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.

8.1 KB
Raw Blame
import { LogicWrapper, MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'

import { FLOW_INITIAL_ROWS, type FlowWindow, fillFlowWindow } from '../utils/flowWindow'

/** Time budget per fill step, under the 50 ms long-task line. */
const FLOW_CHUNK_BUDGET_MS = 40
const FLOW_MIN_CHUNK_ROWS = 4
const FLOW_MAX_CHUNK_ROWS = 256
/** The fill waits this long after input, so a keystroke or a scroll never waits for a fill step. */
const FLOW_INPUT_PAUSE_MS = 200
/** A reader who scrolls this close to the oldest rendered row gets more rows while scrolling, so there is no wall. */
const FLOW_SCROLL_BUFFER_PX = 3000
/**
 * A reader at the top who has not scrolled for this long got there by a jump (Home, the scrollbar) and
 * wants the start of the thread. A reader who scrolled there wants the rows just above.
 */
const FLOW_SCROLL_GESTURE_MS = 500
/** How long after a key that jumps to the start the fill keeps rendering the oldest rows first. */
const FLOW_JUMP_TO_START_MS = 1500
const FLOW_POLL_MS = 50
/** A smooth scroll to the top can stop a little short of it. Within this distance a jump counts as arrived. */
const FLOW_JUMP_ARRIVED_PX = 400
const FLOW_INPUT_EVENTS = ['wheel', 'touchmove', 'keydown', 'pointerdown', 'pointermove'] as const
const FLOW_SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', ' '])

export interface FlowRowsLogicProps {
    flowKey: string
    /** The reader's `scrollTop` in the scroll container, read from the DOM by the component. */
    readerScrollTop?: () => number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface flowRowsLogicValues {
    flowWindow: FlowWindow | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface flowRowsLogicActions {
    chunkCommitted: (committedAt: number) => {
        committedAt: number
    }
    fillChunk: (
        rows: number,
        atStart: boolean
    ) => {
        atStart: boolean
        rows: number
    }
    scheduleNextChunk: () => {
        value: true
    }
    syncWindow: (flowWindow: FlowWindow) => {
        flowWindow: FlowWindow
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface flowRowsLogicMeta {
    key: string
}

export type flowRowsLogicType = MakeLogicType<
    flowRowsLogicValues,
    flowRowsLogicActions,
    FlowRowsLogicProps,
    flowRowsLogicMeta
>

/**
 * The render window of one flow-mode thread. A long thread opens with only its newest rows, then
 * renders the older rows in small steps between frames, so the page never freezes on one huge commit.
 */
export const flowRowsLogic: LogicWrapper<flowRowsLogicType> = kea<flowRowsLogicType>([
    props({} as FlowRowsLogicProps),
    key((props) => props.flowKey),
    path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'flowRowsLogic', key]),
    actions({
        syncWindow: (flowWindow: FlowWindow) => ({ flowWindow }),
        fillChunk: (rows: number, atStart: boolean) => ({ rows, atStart }),
        chunkCommitted: (committedAt: number) => ({ committedAt }),
        scheduleNextChunk: true,
    }),
    reducers({
        flowWindow: [
            null as FlowWindow | null,
            {
                syncWindow: (_, { flowWindow }) => flowWindow,
                fillChunk: (state, { rows, atStart }) => (state ? fillFlowWindow(state, rows, atStart) : state),
            },
        ],
    }),
    listeners(({ actions, values, cache, props }) => ({
        syncWindow: () => {
            actions.scheduleNextChunk()
        },
        chunkCommitted: ({ committedAt }) => {
            if (cache.chunkStartedAt !== null) {
                const elapsed = Math.max(1, committedAt - cache.chunkStartedAt)
                cache.chunkStartedAt = null
                cache.chunkRows = Math.min(
                    FLOW_MAX_CHUNK_ROWS,
                    Math.max(FLOW_MIN_CHUNK_ROWS, Math.round((cache.chunkRows * FLOW_CHUNK_BUDGET_MS) / elapsed))
                )
            }
            actions.scheduleNextChunk()
        },
        scheduleNextChunk: () => {
            if (!values.flowWindow?.holes.length) {
                cache.disposables.dispose('nextChunk')
                return
            }
            cache.disposables.add(() => {
                let timer: ReturnType<typeof setTimeout>
                const renderNextChunk = (): void => {
                    const now = performance.now()
                    const jumping = now - cache.lastJumpToStartAt < FLOW_JUMP_TO_START_MS
                    const scrollTop = props.readerScrollTop?.() ?? null
                    const seekingStart =
                        scrollTop !== null &&
                        (jumping
                            ? scrollTop <= FLOW_JUMP_ARRIVED_PX
                            : scrollTop <= 0 && now - cache.lastScrollGestureAt > FLOW_SCROLL_GESTURE_MS)
                    const typingWait = FLOW_INPUT_PAUSE_MS - (now - cache.lastInputAt)
                    const scrollWait =
                        scrollTop !== null && scrollTop <= FLOW_SCROLL_BUFFER_PX
                            ? 0
                            : FLOW_INPUT_PAUSE_MS - (now - cache.lastScrollGestureAt)
                    // A jump key starts a smooth scroll, and rows added under it cancel it. Wait until it arrives.
                    // While the reader scrolls, check often, so rows arrive soon after they near the oldest one.
                    const wait = seekingStart
                        ? 0
                        : jumping
                          ? FLOW_POLL_MS
                          : Math.max(typingWait, scrollWait > 0 ? Math.min(scrollWait, FLOW_POLL_MS) : 0)
                    if (wait > 0) {
                        timer = setTimeout(renderNextChunk, wait)
                        return
                    }
                    cache.chunkStartedAt = now
                    actions.fillChunk(cache.chunkRows, seekingStart)
                }
                timer = setTimeout(renderNextChunk, 0)
                return () => clearTimeout(timer)
            }, 'nextChunk')
        },
    })),
    afterMount(({ cache }) => {
        cache.chunkRows = FLOW_INITIAL_ROWS
        cache.chunkStartedAt = null
        cache.lastInputAt = -Infinity
        cache.lastScrollGestureAt = -Infinity
        cache.lastJumpToStartAt = -Infinity
        cache.disposables.add(() => {
            const noteInput = (event: Event): void => {
                // A pointer that moves without a pressed button is a hover, not an interaction.
                if (event.type === 'pointermove' && (event as PointerEvent).buttons === 0) {
                    return
                }
                if (event.type === 'keydown') {
                    const { key, metaKey, ctrlKey, target } = event as KeyboardEvent
                    // In a text field these keys move the caret, so they say nothing about the thread.
                    const inTextField =
                        target instanceof HTMLElement &&
                        (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))
                    if (!inTextField && (key === 'Home' || (key === 'ArrowUp' && (metaKey || ctrlKey)))) {
                        cache.lastJumpToStartAt = performance.now()
                        return
                    }
                }
                const scrollGesture =
                    event.type === 'wheel' ||
                    event.type === 'touchmove' ||
                    (event.type === 'keydown' && FLOW_SCROLL_KEYS.has((event as KeyboardEvent).key))
                if (scrollGesture) {
                    cache.lastScrollGestureAt = performance.now()
                } else {
                    cache.lastInputAt = performance.now()
                }
            }
            for (const type of FLOW_INPUT_EVENTS) {
                window.addEventListener(type, noteInput, { capture: true, passive: true })
            }
            return () => {
                for (const type of FLOW_INPUT_EVENTS) {
                    window.removeEventListener(type, noteInput, { capture: true })
                }
            }
        })
    }),
])