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

keptView.tsx

296 lines9.4 KB

1import { Editor, type EditorOptions } from "@tiptap/core";
2import { PureEditorContent, type EditorContentProps } from "@tiptap/react";
3import {
4 createContext,
5 forwardRef,
6 memo,
7 useContext,
8 useEffect,
9 useEffectEvent,
10 useLayoutEffect,
11 useReducer,
12 useState,
13 type DependencyList,
14 type ReactNode,
15} from "react";
16​
17import { PortalContainerContext, useOwnPortalContainer } from "~/lib/portalContainer";
18​
19export interface KeptViewLifetime {
20 hold(release: () => void): () => void;
22​
23export const KeptViewLifetimeContext = createContext<KeptViewLifetime | null>(null);
24​
25export function createKeptViewLifetime(): KeptViewLifetime & { dispose(): void } {
26 const held = new Set<() => void>();
27 let disposed = false;
28 return {
29 hold(release) {
30 if (disposed) {
31 release();
32 return () => undefined;
33 }
34 held.add(release);
35 return () => {
36 held.delete(release);
37 };
38 },
39 dispose() {
40 disposed = true;
41 const releases = [...held];
42 held.clear();
43 for (const release of releases) release();
44 },
45 };
47​
48export function createKeptViewLifetimes() {
49 const lifetimes = new Map<string, ReturnType<typeof createKeptViewLifetime>>();
50 return {
51 get(key: string): KeptViewLifetime {
52 let lifetime = lifetimes.get(key);
53 if (lifetime === undefined) {
54 lifetime = createKeptViewLifetime();
55 lifetimes.set(key, lifetime);
56 }
57 return lifetime;
58 },
59 retain(keys: ReadonlySet<string>) {
60 for (const [key, lifetime] of lifetimes) {
61 if (keys.has(key)) continue;
62 lifetimes.delete(key);
63 lifetime.dispose();
64 }
65 },
66 };
68​
69// Allow transition renders to commit before freeing abandoned editors.
70const UNCOMMITTED_EDITOR_GRACE_MS = 5_000;
71​
72class KeptEditorInstance {
73 editor: Editor;
74 private options: Partial<EditorOptions>;
75 private deps: DependencyList;
76 private mounted = false;
77 private cancelDestroy: (() => void) | null;
78​
79 constructor(options: Partial<EditorOptions>, deps: DependencyList) {
80 this.options = options;
81 this.deps = deps;
82 this.editor = this.createEditor();
83 this.cancelDestroy = this.destroyAfter(UNCOMMITTED_EDITOR_GRACE_MS);
84 }
85​
86 private createEditor() {
87 return new Editor({
88 ...this.options,
89 onUpdate: (event) => this.options.onUpdate?.(event),
90 onSelectionUpdate: (event) => this.options.onSelectionUpdate?.(event),
91 });
92 }
93​
94 private destroyUnlessMounted() {
95 if (!this.mounted && !this.editor.isDestroyed) this.editor.destroy();
96 }
97​
98 private destroyAfter(delayMs: number) {
99 const timeout = setTimeout(() => this.destroyUnlessMounted(), delayMs);
100 return () => clearTimeout(timeout);
101 }
102​
103 update(options: Partial<EditorOptions>, deps: DependencyList): boolean {
104 this.options = options;
105 if (this.editor.isDestroyed) return false;
106 if (deps.length !== this.deps.length || deps.some((dep, i) => !Object.is(dep, this.deps[i]))) {
107 this.deps = deps;
108 this.editor.destroy();
109 this.editor = this.createEditor();
110 return true;
111 }
112 this.editor.setOptions({ editorProps: options.editorProps ?? {} });
113 return false;
114 }
115​
116 mount(): boolean {
117 this.mounted = true;
118 this.cancelDestroy?.();
119 this.cancelDestroy = null;
120 if (!this.editor.isDestroyed) return false;
121 this.editor = this.createEditor();
122 return true;
123 }
124​
125 unmount(lifetime: KeptViewLifetime | null) {
126 this.mounted = false;
127 // Still in the document means the kept view was hidden, not removed.
128 this.cancelDestroy =
129 lifetime !== null && this.editor.view.dom?.isConnected === true
130 ? lifetime.hold(() => this.destroyUnlessMounted())
131 : this.destroyAfter(1);
132 }
134​
135/** Preserves the editor and undo history across Activity hides; changed deps recreate it. */
136export function useKeptEditor(options: Partial<EditorOptions>, deps: DependencyList): Editor {
137 const lifetime = useContext(KeptViewLifetimeContext);
138 const [, rerender] = useReducer((count: number) => count + 1, 0);
139 const [instance] = useState(() => new KeptEditorInstance(options, deps));
140​
141 useLayoutEffect(() => {
142 if (instance.update(options, deps)) rerender();
143 });
144​
145 useEffect(() => {
146 if (instance.mount()) rerender();
147 return () => instance.unmount(lifetime);
148 }, [instance, lifetime]);
149​
150 return instance.editor;
152​
153class KeptPureEditorContent extends PureEditorContent {
154 static override contextType = KeptViewLifetimeContext;
155 declare context: KeptViewLifetime | null;
156​
157 override componentWillUnmount() {
158 // useKeptEditor owns teardown; Activity hides must preserve node views.
159 if (this.context !== null) return;
160 super.componentWillUnmount();
161 }
163​
164export const KeptEditorContent = memo(
165 forwardRef<HTMLDivElement, Omit<EditorContentProps, "ref" | "innerRef">>(
166 function KeptEditorContent(props, ref) {
167 const [content, setContent] = useState({ editor: props.editor, key: 0 });
168 if (content.editor !== props.editor) {
169 setContent({ editor: props.editor, key: content.key + 1 });
170 }
171 return <KeptPureEditorContent key={content.key} innerRef={ref} {...props} />;
172 },
173 ),
174);
175​
176/** True while a kept view warms up out of sight; it must not act as the shown thread. */
177export const KeptViewWarmingContext = createContext(false);
178​
179/** Warm offscreen for two frames so the list settles before hiding. */
180export function KeptViewFrame({
181 viewKey,
182 warming,
183 onWarm,
184 children,
185}: {
186 viewKey: string;
187 warming: boolean;
188 onWarm: (viewKey: string) => void;
189 children: ReactNode;
190}) {
191 const portalContainer = useOwnPortalContainer(warming, useContext(KeptViewLifetimeContext));
192 const warmed = useEffectEvent(() => onWarm(viewKey));
193 useLayoutEffect(() => {
194 if (!warming) return;
195 let second = 0;
196 const first = requestAnimationFrame(() => {
197 second = requestAnimationFrame(warmed);
198 });
199 return () => {
200 cancelAnimationFrame(first);
201 cancelAnimationFrame(second);
202 };
203 }, [warming]);
204 return (
205 <div
206 className={
207 warming
208 ? "pointer-events-none invisible absolute inset-0 flex min-h-0 flex-col"
209 : "contents"
210 }
211 inert={warming || undefined}
212 aria-hidden={warming || undefined}
213 >
214 <KeptViewWarmingContext value={warming}>
215 <PortalContainerContext value={portalContainer}>{children}</PortalContainerContext>
216 </KeptViewWarmingContext>
217 </div>
218 );
220​
221// ── Keys typed on the way to a kept thread ────────────────────────────────
222​
223/** The route target (`threadRouteTargetKey`) the URL names, as of its last commit. */
224let urlRouteTargetKey: string | null = null;
225let heldText: {
226 readonly targetKey: string;
227 readonly text: string;
228 readonly at: number;
229 readonly pending?: boolean;
230} | null = null;
231const HELD_TEXT_MAX_AGE_MS = 2_000;
232​
233export function setUrlRouteTargetKey(key: string | null): void {
234 urlRouteTargetKey = key;
236​
237/** Printable typing on the sidebar row for the URL's thread. */
238export function isUrlTargetSidebarTextKey(event: KeyboardEvent): boolean {
239 if (event.defaultPrevented || event.isComposing || event.metaKey || event.ctrlKey || event.altKey)
240 return false;
241 // Space and Enter activate the row; only its other text keys join the URL-target buffer.
242 if (event.key.length !== 1 || event.key === " ") return false;
243 const target = event.target;
244 if (
245 !(target instanceof Element) ||
246 !target.matches('[data-testid="sidebar-row-slim"], [data-testid="sidebar-row-card"]')
247 )
248 return false;
249 const threadKey = target.closest("[data-thread-item]")?.getAttribute("data-thread-item");
250 return threadKey !== undefined && urlRouteTargetKey === `server:${threadKey}`;
252​
253/** Holds typing for the URL destination while the previous view finishes its transition. */
254export function holdTextForUrlRouteTarget(viewTargetKey: string, text: string): boolean {
255 const targetKey = urlRouteTargetKey;
256 if (targetKey === null || targetKey === viewTargetKey) return false;
257 const now = performance.now();
258 const earlier =
259 heldText !== null &&
260 heldText.targetKey === targetKey &&
261 (heldText.pending || now - heldText.at < HELD_TEXT_MAX_AGE_MS)
262 ? heldText.text
263 : "";
264 heldText = {
265 targetKey,
266 text: earlier + text,
267 at: now,
268 pending: heldText?.targetKey === targetKey && heldText.pending === true,
269 };
270 return true;
272​
273/** Backspace on the way to a kept thread takes back the last character held for it. */
274export function eraseHeldText(viewTargetKey: string): boolean {
275 if (heldText === null || !isUrlRouteTargetElsewhere(viewTargetKey)) return false;
276 if (heldText.targetKey !== urlRouteTargetKey) return false;
277 heldText = { ...heldText, text: heldText.text.slice(0, -1) };
278 return true;
280​
281/** Text typed for this view while the view the user left was still shown. */
282export function insertHeldText(viewTargetKey: string, insert: (text: string) => boolean): void {
283 const held = heldText;
284 if (held === null || held.targetKey !== viewTargetKey) return;
285 if (!held.pending && performance.now() - held.at >= HELD_TEXT_MAX_AGE_MS) {
286 heldText = null;
287 return;
288 }
289 // Once the destination arrives, readiness can take longer than the navigation grace period.
290 heldText = insert(held.text) || held.text.length === 0 ? null : { ...held, pending: true };
292​
293/** Whether the URL names another route target than this view's. */
294export function isUrlRouteTargetElsewhere(viewTargetKey: string): boolean {
295 return urlRouteTargetKey !== null && urlRouteTargetKey !== viewTargetKey;