:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import { teamLogic } from 'scenes/teamLogic'
import { TodayRecentSection } from './todayRecentOrder'
import { archiveSessions, pinSessions, reportBulkResult, restoreSessions } from './todaySessionBulkRequests'
import {
EMPTY_SELECTION,
TodaySessionSelection,
computeBulkPinDirection,
computeRangeSelection,
isEditableTarget,
isMenuEscape,
orderedVisibleSessionIds,
pruneToVisible,
toggleSelection,
} from './todaySessionSelection'
import { todayShellLogic } from './todayShellLogic'
import { TodayWorkSectionId, todaySpacesLogic } from './todaySpacesLogic'
import { TodayWorkItem, activeCloudRunId } from './todayWorkItems'
export type TodayBulkAction = 'pin' | 'archive'
/** Counted when the confirm opens, so the closing dialog doesn't retitle itself as the selection clears. */
export interface TodayBulkArchiveConfirm {
open: boolean
count: number
running: number
}
export const CLOSED_BULK_ARCHIVE_CONFIRM: TodayBulkArchiveConfirm = { open: false, count: 0, running: 0 }
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionSelectionLogicValues {
currentTeamId: number | null // teamLogic
phoneLayout: boolean // todayShellLogic
collapsedSections: TodayWorkSectionId[] // todaySpacesLogic
pinnedItems: TodayWorkItem[] // todaySpacesLogic
recentGroups: TodayRecentSection[] // todaySpacesLogic
bulkAction: TodayBulkAction | null
bulkArchiveConfirm: TodayBulkArchiveConfirm
bulkPinDirection: 'pin' | 'unpin'
orderedSessionIds: string[]
runningSelectedCount: number
selectedSessionIds: string[]
selectedSessions: TodayWorkItem[]
selection: TodaySessionSelection
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionSelectionLogicActions {
locationChanged: ({
method,
pathname,
search,
searchParams,
hash,
hashParams,
initial,
url,
routerState,
}: LocationChangedPayload) => {
hash: string
hashParams: Record<string, any>
initial: boolean
method: 'POP' | 'PUSH' | 'REPLACE'
pathname: string
routerState: Record<string, any>
search: string
searchParams: Record<string, any>
url: string
} // router
loadPinnedTasks: () => any // todaySpacesLogic
loadRecentTasks: (_?: void | undefined) => void // todaySpacesLogic
archiveSelected: () => {
value: true
}
bulkActionFinished: (failedIds: string[]) => {
failedIds: string[]
}
clearSelection: () => {
value: true
}
closeBulkArchiveConfirm: () => {
value: true
}
openBulkArchiveConfirm: (
count: number,
running: number
) => {
count: number
running: number
}
pinSelected: () => {
value: true
}
requestBulkArchive: () => {
value: true
}
restoreSessions: (sessionIds: string[]) => {
sessionIds: string[]
}
selectSessionRange: (sessionId: string) => {
sessionId: string
}
setSelection: (selection: TodaySessionSelection) => {
selection: TodaySessionSelection
}
toggleSessionSelection: (sessionId: string) => {
sessionId: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todaySessionSelectionLogicMeta {
__keaTypeGenInternalSelectorTypes: {
orderedSessionIds: (
pinnedItems: TodayWorkItem[],
recentGroups: TodayRecentSection[],
collapsedSections: TodayWorkSectionId[],
phoneLayout: boolean
) => string[]
selectedSessionIds: (selection: TodaySessionSelection, orderedSessionIds: string[]) => string[]
selectedSessions: (
selectedSessionIds: string[],
pinnedItems: TodayWorkItem[],
recentGroups: TodayRecentSection[]
) => TodayWorkItem[]
bulkPinDirection: (selectedSessionIds: string[], pinnedItems: TodayWorkItem[]) => 'pin' | 'unpin'
runningSelectedCount: (selectedSessions: TodayWorkItem[]) => number
}
}
export type todaySessionSelectionLogicType = MakeLogicType<
todaySessionSelectionLogicValues,
todaySessionSelectionLogicActions,
Record<string, any>,
todaySessionSelectionLogicMeta
>
export const todaySessionSelectionLogic = kea<todaySessionSelectionLogicType>([
path(['layout', 'today', 'todaySessionSelectionLogic']),
connect(() => ({
values: [
teamLogic,
['currentTeamId'],
todaySpacesLogic,
['collapsedSections', 'pinnedItems', 'recentGroups'],
todayShellLogic,
['phoneLayout'],
],
actions: [router, ['locationChanged'], todaySpacesLogic, ['loadPinnedTasks', 'loadRecentTasks']],
})),
actions({
setSelection: (selection: TodaySessionSelection) => ({ selection }),
toggleSessionSelection: (sessionId: string) => ({ sessionId }),
selectSessionRange: (sessionId: string) => ({ sessionId }),
clearSelection: true,
pinSelected: true,
requestBulkArchive: true,
openBulkArchiveConfirm: (count: number, running: number) => ({ count, running }),
closeBulkArchiveConfirm: true,
archiveSelected: true,
bulkActionFinished: (failedIds: string[]) => ({ failedIds }),
restoreSessions: (sessionIds: string[]) => ({ sessionIds }),
}),
reducers({
selection: [
EMPTY_SELECTION,
{
setSelection: (_, { selection }) => selection,
toggleSessionSelection: (state, { sessionId }) => toggleSelection(state, sessionId),
clearSelection: () => EMPTY_SELECTION,
// Full success clears the selection; a partial one keeps only the failures, so a retry is one click.
bulkActionFinished: (state, { failedIds }) =>
failedIds.length ? { ids: failedIds, anchorId: state.anchorId } : EMPTY_SELECTION,
locationChanged: () => EMPTY_SELECTION,
},
],
bulkAction: [
null as TodayBulkAction | null,
{
pinSelected: () => 'pin',
archiveSelected: () => 'archive',
bulkActionFinished: () => null,
},
],
bulkArchiveConfirm: [
CLOSED_BULK_ARCHIVE_CONFIRM,
{
openBulkArchiveConfirm: (_, { count, running }) => ({ open: true, count, running }),
closeBulkArchiveConfirm: (state) => ({ ...state, open: false }),
bulkActionFinished: (state) => ({ ...state, open: false }),
},
],
}),
selectors({
orderedSessionIds: [
(s) => [s.pinnedItems, s.recentGroups, s.collapsedSections, s.phoneLayout],
(
pinnedItems: TodayWorkItem[],
recentGroups: TodayRecentSection[],
collapsedSections: TodayWorkSectionId[],
phoneLayout: boolean
): string[] =>
orderedVisibleSessionIds(
pinnedItems,
recentGroups.flatMap((group) => group.items),
phoneLayout ? [] : collapsedSections
),
],
// Rows that leave the list, like archived ones or those behind a filter, drop out of the selection.
selectedSessionIds: [
(s) => [s.selection, s.orderedSessionIds],
(selection: TodaySessionSelection, orderedSessionIds: string[]): string[] =>
pruneToVisible(selection.ids, orderedSessionIds),
],
selectedSessions: [
(s) => [s.selectedSessionIds, s.pinnedItems, s.recentGroups],
(
selectedSessionIds: string[],
pinnedItems: TodayWorkItem[],
recentGroups: TodayRecentSection[]
): TodayWorkItem[] => {
const items = new Map(
[...pinnedItems, ...recentGroups.flatMap((group) => group.items)].map((item) => [item.id, item])
)
return selectedSessionIds.flatMap((id) => items.get(id) ?? [])
},
],
bulkPinDirection: [
(s) => [s.selectedSessionIds, s.pinnedItems],
(selectedSessionIds: string[], pinnedItems: TodayWorkItem[]): 'pin' | 'unpin' =>
computeBulkPinDirection(selectedSessionIds, new Set(pinnedItems.map((item) => item.id))),
],
runningSelectedCount: [
(s) => [s.selectedSessions],
(selectedSessions: TodayWorkItem[]): number =>
selectedSessions.filter((item) => activeCloudRunId(item) !== null).length,
],
}),
listeners(({ actions, values }) => ({
selectSessionRange: ({ sessionId }) => {
// With no anchor yet, the range starts at the open session, as it does in Desktop.
const { location, searchParams } = router.values
const openId =
location.pathname.endsWith('/ai') && typeof searchParams.task === 'string' ? searchParams.task : null
actions.setSelection(
computeRangeSelection(
values.selection.anchorId ?? openId,
sessionId,
values.orderedSessionIds,
values.selectedSessionIds
)
)
},
})),
listeners(({ actions, values }) => {
const teamId = (): string => String(values.currentTeamId)
const finish = (failedIds: string[]): void => {
actions.bulkActionFinished(failedIds)
actions.loadPinnedTasks()
actions.loadRecentTasks()
}
return {
pinSelected: async () => {
const ids = values.selectedSessionIds
const pinned = values.bulkPinDirection === 'pin'
const failed = await pinSessions(teamId(), ids, pinned)
reportBulkResult(pinned ? 'pin' : 'unpin', ids.length, failed.length)
finish(failed)
},
requestBulkArchive: () => {
if (values.runningSelectedCount > 0) {
actions.openBulkArchiveConfirm(values.selectedSessionIds.length, values.runningSelectedCount)
} else {
actions.archiveSelected()
}
},
archiveSelected: async () => {
const ids = values.selectedSessions.map((item) => item.id)
const failed = await archiveSessions(teamId(), values.selectedSessions)
const archivedIds = ids.filter((id) => !failed.includes(id))
reportBulkResult('archive', ids.length, failed.length, () => actions.restoreSessions(archivedIds))
finish(failed)
},
restoreSessions: async ({ sessionIds }) => {
const failed = await restoreSessions(teamId(), sessionIds)
if (failed.length) {
reportBulkResult('restore', sessionIds.length, failed.length)
}
actions.loadPinnedTasks()
actions.loadRecentTasks()
},
}
}),
afterMount(({ actions, values, cache }) => {
cache.disposables.add(() => {
const onKeyDown = (event: KeyboardEvent): void => {
// The archive confirm answers Escape itself, and the selection it names has to stay.
if (
event.key === 'Escape' &&
!isEditableTarget(event.target) &&
!isMenuEscape(event) &&
!values.bulkArchiveConfirm.open &&
values.selection.ids.length
) {
actions.clearSelection()
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, 'clearSelectionOnEscape')
}),
])