Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

spotlight.tsx

227 lines8.0 KB

1import { useRouter } from "@tanstack/react-router";
2import { useCallback, useEffect, useRef, useState } from "react";
3import { flushSync } from "react-dom";
4import { toast } from "sonner";
5​
6import { useShowInAppSheet } from "@/components/app-sheet/app-sheet-store";
7import { useIsAppInSheet } from "@/components/guide/try-it";
8import { setInspectorOpen } from "@/components/network/inspector-store";
9import { queryOnce } from "@tanstack/react-db";
10​
11import { newestNoteQuery } from "@/db/queries";
12import { createStore, useStore } from "@/lib/store";
13​
14import { revealSpotlightTarget } from "./spotlight-reveal";
15​
16import {
17 SPOTLIGHT_TARGETS,
18 findSpotlightElement,
19 folderIdFromPath,
20 isNetworkTarget,
21 routeForTarget,
22} from "./spotlight-targets";
23import type { SpotlightTarget } from "./spotlight-targets";
24​
25/** How long a spotlight stays up if the reader doesn't dismiss it. */
26const SPOTLIGHT_DURATION_MS = 8000;
27/** How long to wait for the target to show up (a route change, the sheet opening). */
28const FIND_TIMEOUT_MS = 2000;
29​
30const spotlightStore = createStore<{ target: SpotlightTarget; id: number } | null>(null);
31let nextId = 1;
32​
33export function dismissSpotlight() {
34 spotlightStore.set(null);
36​
37/** Spotlights `target` as soon as it's on screen (the caller brings it there). */
38export function startSpotlight(target: SpotlightTarget) {
39 spotlightStore.set({ target, id: nextId++ });
41​
42/** Says why nothing lit up, instead of failing silently. */
43function showMissingTarget(target: SpotlightTarget) {
44 const { label, hint } = SPOTLIGHT_TARGETS[target];
45 toast(`Couldn't show the ${label.toLowerCase()}`, { id: "spotlight-missing", description: hint });
47​
48/** A note to open for the editor: the newest in the folder you're in, or anywhere. */
49async function noteToOpen(pathname: string) {
50 for (const folderId of new Set([folderIdFromPath(pathname), "all"])) {
51 const [note] = await queryOnce(newestNoteQuery(folderId));
52 if (note) return { folderId, noteId: note.id };
53 }
54 return undefined;
56​
57/**
58 * Points the reader at a part of the app: brings it on screen (opens the
59 * sheet on phones, the request inspector, the right route) and spotlights it.
60 */
61export function useShowSpotlight() {
62 const router = useRouter();
63 const inSheet = useIsAppInSheet();
64 const showInAppSheet = useShowInAppSheet();
65​
66 return useCallback(
67 async (target: SpotlightTarget) => {
68 // Un-hide it first (a hidden sidebar, a collapsed section), and render
69 // that now, so the check below sees it.
70 flushSync(() => revealSpotlightTarget(target));
71 const { pathname } = router.state.location;
72 const onScreen = document.querySelector(`[data-spotlight="${target}"]`) !== null;
73 const route = onScreen
74 ? null
75 : routeForTarget(
76 target,
77 pathname,
78 target === "editor" ? await noteToOpen(pathname) : undefined,
79 );
80 if (inSheet) {
81 showInAppSheet(route, isNetworkTarget(target) ? "network" : "app");
82 } else {
83 if (target === "request-inspector") setInspectorOpen(true);
84 if (route) void router.navigate(route);
85 }
86 startSpotlight(target);
87 },
88 [router, inSheet, showInAppSheet],
89 );
91​
92interface Box {
93 top: number;
94 left: number;
95 width: number;
96 height: number;
98​
99const PADDING = 6;
100​
101/**
102 * The spotlight: a ring around the target with the rest of the page dimmed.
103 * It never takes focus or blocks the page (it ignores the pointer); Escape,
104 * any click or tap, or a few seconds dismiss it. It follows the target while
105 * it moves (the sheet sliding up, the page scrolling).
106 */
107export function SpotlightOverlay({
108 onMissing = showMissingTarget,
109}: {
110 /** The target didn't show up in time. */
111 onMissing?: (target: SpotlightTarget) => void;
112}) {
113 const onMissingRef = useRef(onMissing);
114 onMissingRef.current = onMissing;
115 const spotlight = useStore(spotlightStore);
116 const [box, setBox] = useState<Box | null>(null);
117 const scrolledFor = useRef<number | null>(null);
118​
119 // Track the target's position every frame while the spotlight is up.
120 useEffect(() => {
121 setBox(null);
122 if (!spotlight) return;
123 let found = false;
124 let frame = 0;
125 let lastTop = Number.NaN;
126 // Nothing to point at in time: say so, instead of failing silently.
127 const missing = window.setTimeout(() => {
128 if (found) return;
129 dismissSpotlight();
130 onMissingRef.current(spotlight.target);
131 }, FIND_TIMEOUT_MS);
132 const track = () => {
133 const element = findSpotlightElement(spotlight.target);
134 if (!element) {
135 setBox(null);
136 // It was there and went away (the reader navigated): just end.
137 if (found) return dismissSpotlight();
138 } else {
139 found = true;
140 const rect = element.getBoundingClientRect();
141 // Bring it on screen once, and only if none of it shows. Wait until
142 // it stops moving: the sheet may still be sliding up.
143 const settled = rect.top === lastTop;
144 lastTop = rect.top;
145 if (settled && scrolledFor.current !== spotlight.id) {
146 scrolledFor.current = spotlight.id;
147 const offScreen =
148 rect.bottom <= 0 ||
149 rect.top >= window.innerHeight ||
150 rect.right <= 0 ||
151 rect.left >= window.innerWidth;
152 if (offScreen) element.scrollIntoView({ block: "nearest", inline: "nearest" });
153 }
154 // Clip to the viewport, so a long list's ring stays on screen.
155 const top = Math.max(rect.top, 0) - PADDING;
156 const bottom = Math.min(rect.bottom, window.innerHeight) + PADDING;
157 const left = Math.max(rect.left, 0) - PADDING;
158 const right = Math.min(rect.right, window.innerWidth) + PADDING;
159 setBox((previous) =>
160 previous &&
161 previous.top === top &&
162 previous.left === left &&
163 previous.width === right - left &&
164 previous.height === bottom - top
165 ? previous
166 : { top, left, width: right - left, height: bottom - top },
167 );
168 }
169 frame = requestAnimationFrame(track);
170 };
171 frame = requestAnimationFrame(track);
172 const timeout = window.setTimeout(dismissSpotlight, SPOTLIGHT_DURATION_MS);
173 return () => {
174 cancelAnimationFrame(frame);
175 window.clearTimeout(missing);
176 window.clearTimeout(timeout);
177 };
178 }, [spotlight]);
179​
180 // Escape or any press dismisses it. Escape is taken here, so it doesn't
181 // also close the app sheet behind the spotlight.
182 useEffect(() => {
183 if (!spotlight) return;
184 const onKeyDown = (event: KeyboardEvent) => {
185 if (event.key !== "Escape") return;
186 event.preventDefault();
187 dismissSpotlight();
188 };
189 window.addEventListener("keydown", onKeyDown, { capture: true });
190 window.addEventListener("pointerdown", dismissSpotlight, { capture: true });
191 return () => {
192 window.removeEventListener("keydown", onKeyDown, { capture: true });
193 window.removeEventListener("pointerdown", dismissSpotlight, { capture: true });
194 };
195 }, [spotlight]);
196​
197 const label = spotlight ? SPOTLIGHT_TARGETS[spotlight.target].label : null;
198​
199 return (
200 <>
201 <p role="status" className="sr-only">
202 {spotlight && box
203 ? `Showing the ${label?.toLowerCase()} in the app. Press Escape to dismiss.`
204 : ""}
205 </p>
206 {spotlight && box && (
207 <div aria-hidden className="pointer-events-none fixed inset-0 z-[70]">
208 <div
209 key={spotlight.id}
210 className="spotlight-ring absolute rounded-xl"
211 style={{ top: box.top, left: box.left, width: box.width, height: box.height }}
212 />
213 <span
214 className="spotlight-label absolute rounded-full bg-guide-accent px-2.5 py-1 text-[12px] font-semibold whitespace-nowrap text-white shadow-md"
215 style={
216 box.top > 40
217 ? { top: box.top - 30, left: Math.max(8, box.left) }
218 : { top: box.top + box.height + 6, left: Math.max(8, box.left) }
219 }
220 >
221 {label}
222 </span>
223 </div>
224 )}
225 </>
226 );