Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useIncrementalTimelineEntries.ts

42 lines1.4 KB

1import { useState } from "react";
2import {
3 deriveTimelineEntriesFromVisibleTurnItemsWithState,
4 type TimelineEntriesInput,
5 type TimelineEntriesProjection,
6} from "../session-logic";
7​
8function sameInput(left: TimelineEntriesInput, right: TimelineEntriesInput): boolean {
9 return (
10 left.visibleTurnItems === right.visibleTurnItems &&
11 left.optimisticMessages === right.optimisticMessages &&
12 left.anchoredMessages === right.anchoredMessages &&
13 left.attachmentUrlById === right.attachmentUrlById &&
14 left.attempts === right.attempts &&
15 left.nodes === right.nodes &&
16 left.plans === right.plans
17 );
19​
20/**
21 * Timeline entries for a thread, derived from the previous projection so
22 * unchanged rows keep their identity and memoized rows skip rendering. A new
23 * thread starts from scratch.
24 */
25export function useIncrementalTimelineEntries(
26 threadKey: string | null,
27 input: TimelineEntriesInput,
28): TimelineEntriesProjection["entries"] {
29 const [state, setState] = useState(() => ({
30 threadKey,
31 projection: deriveTimelineEntriesFromVisibleTurnItemsWithState(input),
32 }));
33 if (state.threadKey === threadKey && sameInput(state.projection.input, input)) {
34 return state.projection.entries;
35 }
36 const projection = deriveTimelineEntriesFromVisibleTurnItemsWithState(
37 input,
38 state.threadKey === threadKey ? state.projection : null,
39 );
40 setState({ threadKey, projection });
41 return projection.entries;