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

ThreadScreenHost.tsx

170 lines6.3 KB

1import {
2 createContext,
3 useContext,
4 useLayoutEffect,
5 useState,
6 useSyncExternalStore,
7 type ReactNode,
8} from "react";
9import { View } from "react-native";
10​
11import { ScreenContent } from "../../components/ui/ScreenContent";
12import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
13​
14type ThreadScreenContent =
15 | { readonly props: ThreadDetailScreenProps; readonly header?: ReactNode }
16 | { readonly fallback: ReactNode; readonly header?: ReactNode };
17​
18type Handler = (...args: never[]) => unknown;
19​
20function createThreadScreenStore() {
21 let current: ThreadScreenContent | null = null;
22 // One function per handler prop that calls the controller's latest handler, so a handler the
23 // controller recreates does not re-render the thread screen. Each thread gets its own set, so a
24 // send that awaits before calling its handler still reaches the thread it started on.
25 let handlers = {
26 thread: null as string | null,
27 latest: {} as Record<string, unknown>,
28 stable: new Map<string, Handler>(),
29 };
30 const handler = (key: string) => {
31 const set = handlers;
32 let stable = set.stable.get(key);
33 if (stable === undefined) {
34 stable = (...args) => (set.latest[key] as Handler | undefined)?.(...args);
35 set.stable.set(key, stable);
36 }
37 return stable;
38 };
39 const listeners = new Set<() => void>();
40 return {
41 getSnapshot: () => current,
42 subscribe: (listener: () => void) => {
43 listeners.add(listener);
44 return () => {
45 listeners.delete(listener);
46 };
47 },
48 publish: (content: ThreadScreenContent) => {
49 let next = content;
50 if ("props" in content) {
51 const latest = content.props as unknown as Record<string, unknown>;
52 const thread = threadKey(content.props);
53 if (thread !== handlers.thread) handlers = { thread, latest, stable: new Map() };
54 else handlers.latest = latest;
55 const shown = current !== null && "props" in current ? current : null;
56 const shownProps = (shown?.props ?? {}) as Record<string, unknown>;
57 // Controllers rebuild arrays and records with the same contents on most renders; the
58 // screen keeps the ones it has, so its memoized feed and composer skip the update.
59 const props = Object.fromEntries(
60 Object.entries(latest).map(([key, value]) => [
61 key,
62 typeof value === "function"
63 ? handler(key)
64 : sameContents(shownProps[key], value)
65 ? shownProps[key]
66 : value,
67 ]),
68 ) as unknown as ThreadDetailScreenProps;
69 const sameProps = shown !== null && shallowEqual(shown.props, props);
70 // Unchanged props keep their identity, so only the header re-renders when it alone changed.
71 if (sameProps && shown.header === content.header) return;
72 next = { props: sameProps ? shown.props : props, header: content.header };
73 }
74 current = next;
75 for (const listener of listeners) listener();
76 },
77 };
79​
80function threadKey(props: ThreadDetailScreenProps): string | null {
81 const thread = props.selectedThread as ThreadDetailScreenProps["selectedThread"] | undefined;
82 return thread === undefined ? null : `${thread.environmentId}:${thread.id}`;
84​
85function sameContents(previous: unknown, next: unknown): boolean {
86 if (Object.is(previous, next)) return true;
87 if (Array.isArray(previous) && Array.isArray(next)) {
88 return previous.length === next.length && previous.every((item, index) => item === next[index]);
89 }
90 return isPlainRecord(previous) && isPlainRecord(next) && shallowEqual(previous, next);
92​
93function isPlainRecord(value: unknown): value is object {
94 if (typeof value !== "object" || value === null) return false;
95 const prototype = Object.getPrototypeOf(value);
96 return prototype === Object.prototype || prototype === null;
98​
99function shallowEqual(previous: object, next: object): boolean {
100 const previousRecord = previous as Record<string, unknown>;
101 const nextRecord = next as Record<string, unknown>;
102 const keys = Object.keys(nextRecord);
103 return (
104 keys.length === Object.keys(previousRecord).length &&
105 keys.every(
106 (key) =>
107 Object.hasOwn(previousRecord, key) && Object.is(previousRecord[key], nextRecord[key]),
108 )
109 );
111​
112const ThreadScreenContext = createContext<ReturnType<typeof createThreadScreenStore> | null>(null);
113​
114function ThreadScreenOutlet() {
115 const store = useContext(ThreadScreenContext)!;
116 const content = useSyncExternalStore(store.subscribe, store.getSnapshot);
117 if (content === null) return null;
118 const screenProps = "props" in content ? content.props : null;
119 const fallback = "fallback" in content ? content.fallback : null;
120 return (
121 <>
122 {content.header}
123 <ScreenContent surface="canvas">
124 {screenProps === null ? fallback : <ThreadDetailScreen {...screenProps} />}
125 </ScreenContent>
126 </>
127 );
129​
130// Controllers can change from draft to live without replacing the native screen,
131// the keyboard host, or the editor. Publish before paint to avoid an intermediate frame.
132export function ThreadScreenHost({ children }: { readonly children: ReactNode }) {
133 const [store] = useState(createThreadScreenStore);
134 return (
135 <ThreadScreenContext.Provider value={store}>
136 {children}
137 <View className="flex-1 bg-screen android:bg-header">
138 <ThreadScreenOutlet />
139 </View>
140 </ThreadScreenContext.Provider>
141 );
143​
144/** Handler props reach the screen as stable functions; call them from handlers and effects only. */
145export function ThreadScreenBinding({
146 header,
147 ...props
148}: ThreadDetailScreenProps & { readonly header?: ReactNode }) {
149 const store = useContext(ThreadScreenContext)!;
150 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the route's thread screen props to the external store the outlet reads
151 useLayoutEffect(() => {
152 store.publish({ props, header });
153 });
154 return null;
156​
157export function ThreadScreenFallback({
158 children,
159 header,
160}: {
161 readonly children: ReactNode;
162 readonly header?: ReactNode;
163}) {
164 const store = useContext(ThreadScreenContext)!;
165 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the fallback content and header to the external store the outlet reads
166 useLayoutEffect(() => {
167 store.publish({ fallback: children, header });
168 });
169 return null;