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

ThreadScreenHost.tsx

88 lines2.8 KB

1import {
2 createContext,
3 useContext,
4 useLayoutEffect,
5 useState,
6 useSyncExternalStore,
7 type ReactNode,
8} from "react";
9import { Platform, View } from "react-native";
10import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
11​
12type ThreadScreenContent =
13 | { readonly props: ThreadDetailScreenProps }
14 | { readonly fallback: ReactNode; readonly header?: ReactNode };
15​
16function createThreadScreenStore() {
17 let current: ThreadScreenContent | null = null;
18 const listeners = new Set<() => void>();
19 return {
20 getSnapshot: () => current,
21 subscribe: (listener: () => void) => {
22 listeners.add(listener);
23 return () => {
24 listeners.delete(listener);
25 };
26 },
27 publish: (content: ThreadScreenContent) => {
28 current = content;
29 for (const listener of listeners) listener();
30 },
31 };
33const ThreadScreenContext = createContext<ReturnType<typeof createThreadScreenStore> | null>(null);
34​
35function ThreadScreenOutlet() {
36 const store = useContext(ThreadScreenContext)!;
37 const content = useSyncExternalStore(store.subscribe, store.getSnapshot);
38 if (content === null) return null;
39 const body = "props" in content ? <ThreadDetailScreen {...content.props} /> : content.fallback;
40 return (
41 <>
42 {"props" in content ? content.props.header : content.header}
43 {Platform.OS === "android" ? (
44 <View className="flex-1 overflow-hidden rounded-t-[28px] bg-thread-canvas">{body}</View>
45 ) : (
46 body
47 )}
48 </>
49 );
51​
52// Controllers can change from draft to live without replacing the native screen,
53// the keyboard host, or the editor. Publish before paint to avoid an intermediate frame.
54export function ThreadScreenHost({ children }: { readonly children: ReactNode }) {
55 const [store] = useState(createThreadScreenStore);
56 return (
57 <ThreadScreenContext.Provider value={store}>
58 {children}
59 <View className="flex-1 bg-screen android:bg-header">
60 <ThreadScreenOutlet />
61 </View>
62 </ThreadScreenContext.Provider>
63 );
65​
66export function ThreadScreenBinding(props: ThreadDetailScreenProps) {
67 const store = useContext(ThreadScreenContext)!;
68 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the route's thread screen props to the external store the outlet reads
69 useLayoutEffect(() => {
70 store.publish({ props });
71 });
72 return null;
74​
75export function ThreadScreenFallback({
76 children,
77 header,
78}: {
79 readonly children: ReactNode;
80 readonly header?: ReactNode;
81}) {
82 const store = useContext(ThreadScreenContext)!;
83 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the fallback content and header to the external store the outlet reads
84 useLayoutEffect(() => {
85 store.publish({ fallback: children, header });
86 });
87 return null;