Skip to content

: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.

13.0 KB
Raw Blame
import {
    LogicWrapper,
    MakeLogicType,
    actions,
    afterMount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'

import {
    archiveSessions,
    pinSessions,
    reportBulkResult,
    restoreSessions,
} from '~/layout/today/todaySessionBulkRequests'
import {
    EMPTY_SELECTION,
    TodaySessionSelection,
    computeBulkPinDirection,
    computeRangeSelection,
    isEditableTarget,
    isMenuEscape,
    pruneToVisible,
    toggleSelection,
} from '~/layout/today/todaySessionSelection'
import {
    CLOSED_BULK_ARCHIVE_CONFIRM,
    TodayBulkAction,
    TodayBulkArchiveConfirm,
} from '~/layout/today/todaySessionSelectionLogic'
import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
import { TodayWorkItem, activeCloudRunId } from '~/layout/today/todayWorkItems'

import { SpaceFeedFilters, SpaceFeedSection, SpaceFeedType, SpaceFeedView } from './spaceFeedEntries'
import { SpaceFeedSelectAllState, selectAllState, spaceFeedSessions, toggleAllSelection } from './spaceFeedSelection'
import { spaceFeedViewLogic } from './spaceFeedViewLogic'
import { spaceSceneLogic } from './spaceSceneLogic'

export interface SpaceFeedSelectionLogicProps {
    id: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceFeedSelectionLogicValues {
    currentTeamId: number | null // spaceSceneLogic
    feedSections: SpaceFeedSection[] // spaceSceneLogic
    pinnedItems: TodayWorkItem[] // todaySpacesLogic
    bulkAction: TodayBulkAction | null
    bulkArchiveConfirm: TodayBulkArchiveConfirm
    bulkPinDirection: 'pin' | 'unpin'
    feedSessions: TodayWorkItem[]
    orderedSessionIds: string[]
    runningSelectedCount: number
    selectAll: SpaceFeedSelectAllState
    selectedSessionIds: string[]
    selectedSessions: TodayWorkItem[]
    selection: TodaySessionSelection
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceFeedSelectionLogicActions {
    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
    clearFilters: () => {
        value: true
    } // spaceFeedViewLogic
    setFilters: (filters: SpaceFeedFilters) => {
        filters: SpaceFeedFilters
    } // spaceFeedViewLogic
    setTypes: (types: SpaceFeedType[]) => {
        types: SpaceFeedType[]
    } // spaceFeedViewLogic
    setView: (view: SpaceFeedView) => {
        view: SpaceFeedView
    } // spaceFeedViewLogic
    loadSessions: () => any // spaceSceneLogic
    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
    }
    toggleSelectAll: () => {
        value: true
    }
    toggleSessionSelection: (sessionId: string) => {
        sessionId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceFeedSelectionLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        feedSessions: (feedSections: SpaceFeedSection[]) => TodayWorkItem[]
        orderedSessionIds: (feedSessions: TodayWorkItem[]) => string[]
        selectedSessionIds: (selection: TodaySessionSelection, orderedSessionIds: string[]) => string[]
        selectedSessions: (selectedSessionIds: string[], feedSessions: TodayWorkItem[]) => TodayWorkItem[]
        selectAll: (selectedSessionIds: string[], orderedSessionIds: string[]) => SpaceFeedSelectAllState
        bulkPinDirection: (selectedSessionIds: string[], pinnedItems: TodayWorkItem[]) => 'pin' | 'unpin'
        runningSelectedCount: (selectedSessions: TodayWorkItem[]) => number
    }
}

export type spaceFeedSelectionLogicType = MakeLogicType<
    spaceFeedSelectionLogicValues,
    spaceFeedSelectionLogicActions,
    SpaceFeedSelectionLogicProps,
    spaceFeedSelectionLogicMeta
>

/** The sessions picked in a space's feed for a bulk change. Separate from the sidebar's pick, which spans spaces. */
export const spaceFeedSelectionLogic: LogicWrapper<spaceFeedSelectionLogicType> = kea<spaceFeedSelectionLogicType>([
    props({} as SpaceFeedSelectionLogicProps),
    key((props) => props.id),
    path((id) => ['products', 'tasks', 'spaces', 'spaceFeedSelectionLogic', id]),
    connect((props: SpaceFeedSelectionLogicProps) => ({
        values: [spaceSceneLogic(props), ['currentTeamId', 'feedSections'], todaySpacesLogic, ['pinnedItems']],
        actions: [
            router,
            ['locationChanged'],
            spaceSceneLogic(props),
            ['loadSessions'],
            spaceFeedViewLogic,
            ['clearFilters', 'setFilters', 'setTypes', 'setView'],
            todaySpacesLogic,
            ['loadPinnedTasks', 'loadRecentTasks'],
        ],
    })),
    actions({
        setSelection: (selection: TodaySessionSelection) => ({ selection }),
        toggleSessionSelection: (sessionId: string) => ({ sessionId }),
        selectSessionRange: (sessionId: string) => ({ sessionId }),
        toggleSelectAll: true,
        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,
                // A partial failure keeps only the failures selected, so a retry is one click.
                bulkActionFinished: (state, { failedIds }) =>
                    failedIds.length ? { ids: failedIds, anchorId: state.anchorId } : EMPTY_SELECTION,
                locationChanged: () => EMPTY_SELECTION,
                setView: () => EMPTY_SELECTION,
                setTypes: () => EMPTY_SELECTION,
                setFilters: () => EMPTY_SELECTION,
                clearFilters: () => 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({
        feedSessions: [
            (s) => [s.feedSections],
            (feedSections: SpaceFeedSection[]): TodayWorkItem[] => spaceFeedSessions(feedSections),
        ],
        orderedSessionIds: [
            (s) => [s.feedSessions],
            (feedSessions: TodayWorkItem[]): string[] => feedSessions.map((item) => item.id),
        ],
        // Sessions that leave the feed, like archived ones, 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.feedSessions],
            (selectedSessionIds: string[], feedSessions: TodayWorkItem[]): TodayWorkItem[] => {
                const items = new Map(feedSessions.map((item) => [item.id, item]))
                return selectedSessionIds.flatMap((id) => items.get(id) ?? [])
            },
        ],
        selectAll: [
            (s) => [s.selectedSessionIds, s.orderedSessionIds],
            (selectedSessionIds: string[], orderedSessionIds: string[]): SpaceFeedSelectAllState =>
                selectAllState(selectedSessionIds, orderedSessionIds),
        ],
        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 }) => {
        const teamId = (): string => String(values.currentTeamId)

        const finish = (failedIds: string[]): void => {
            actions.bulkActionFinished(failedIds)
            actions.loadSessions()
            actions.loadPinnedTasks()
            actions.loadRecentTasks()
        }

        return {
            selectSessionRange: ({ sessionId }) => {
                actions.setSelection(
                    computeRangeSelection(
                        values.selection.anchorId,
                        sessionId,
                        values.orderedSessionIds,
                        values.selectedSessionIds
                    )
                )
            },
            toggleSelectAll: () => {
                actions.setSelection(toggleAllSelection(values.selectedSessionIds, values.orderedSessionIds))
            },
            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.loadSessions()
                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')
    }),
])