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

TutorialWindow.tsx

512 lines15.6 KB

1import { Tabs, TabsContent } from "@radix-ui/react-tabs";
2import { useNavigate, useRouter, useSearch } from "@tanstack/react-router";
3import { DatabaseZapIcon, XIcon } from "lucide-react";
4import { AnimatePresence, motion } from "motion/react";
5import {
6 useCallback,
7 useEffect,
8 useLayoutEffect,
9 useRef,
10 useState,
11} from "react";
12import { steps } from "@/data/tutorial";
13import { useScrollShadow } from "@/hooks/use-scroll-shadow";
14import { cn } from "@/lib/utils";
15import {
16 getTutorialDataHandlers,
17 type TutorialData,
18} from "@/utils/getTutorialDataHandlers";
19import { ToggleFloatingWindowButton } from "../ToggleFloatingWindowButton";
20import { Button } from "../ui/button";
21import { ScrollArea } from "../ui/scroll-area";
22import { ScrollShadow } from "../ui/scroll-shadow";
23import { TutorialTableOfContents } from "./TutorialTableOfContents";
24​
25function FloatingWindowHeader({ toggleWindow }: { toggleWindow: () => void }) {
26 return (
27 <div className="text-sm bg-linear-to-r bg-primary text-primary-foreground border-b border-border dark:border-b-primary px-2 py-1 flex items-center">
28 <div className="flex items-center gap-1 font-bold grow">
29 <DatabaseZapIcon className="h-4 w-4" /> TanStack DB Tutorial
30 </div>
31 <Button
32 variant="tutorial"
33 size="icon-xs"
34 className="bg-transparent border-black rounded-full border"
35 onClick={toggleWindow}
36 >
37 <XIcon className="" />
38 </Button>
39 </div>
40 );
42​
43function FloatingWindow({
44 tutorialData,
45 activeStep,
46 setActiveStep,
47 toggleWindow,
48}: {
49 tutorialData: TutorialData;
50 activeStep: string | null;
51 setActiveStep: (step: string) => void;
52 toggleWindow: () => void;
53}) {
54 const navigate = useNavigate();
55​
56 const scrollRef = useRef<HTMLDivElement>(null);
57 const containerRef = useRef<HTMLDivElement>(null);
58​
59 const { canScrollUp, canScrollDown } = useScrollShadow(scrollRef, [
60 activeStep,
61 ]);
62​
63 const [windowSize, setWindowSize] = useState(tutorialData.windowSize);
64​
65 // Store initial limits as constants that never change
66 const INITIAL_MIN_WIDTH = 400;
67 const INITIAL_MAX_WIDTH = 850;
68 const INITIAL_MIN_HEIGHT = 300;
69 const INITIAL_MAX_HEIGHT = 2000;
70​
71 const [
72 { MIN_WIDTH, MAX_WIDTH, MIN_HEIGHT, MAX_HEIGHT },
73 setWindowSizeLimits,
74 ] = useState({
75 MIN_WIDTH: INITIAL_MIN_WIDTH,
76 MAX_WIDTH: INITIAL_MAX_WIDTH,
77 MIN_HEIGHT: INITIAL_MIN_HEIGHT,
78 MAX_HEIGHT: INITIAL_MAX_HEIGHT,
79 });
80​
81 const updateWindowSizeLimits = useCallback(() => {
82 if (typeof window !== "undefined") {
83 // Calculate new limits based on current window size
84 // MIN values: can't be larger than initial values, but can be smaller if window is small
85 // MAX values: can grow and shrink with window size
86 const newMinWidth = Math.min(window.innerWidth - 16, INITIAL_MIN_WIDTH);
87 const newMinHeight = Math.min(
88 window.innerHeight - 65,
89 INITIAL_MIN_HEIGHT,
90 );
91​
92 const newLimits = {
93 MIN_WIDTH: newMinWidth,
94 // MAX_WIDTH should be at least MIN_WIDTH but never exceed what fits in viewport
95 MAX_WIDTH: Math.max(
96 newMinWidth,
97 Math.min(window.innerWidth * 0.9, INITIAL_MAX_WIDTH),
98 ),
99 MIN_HEIGHT: newMinHeight,
100 // MAX_HEIGHT should be at least MIN_HEIGHT but never exceed what fits in viewport
101 MAX_HEIGHT: Math.max(
102 newMinHeight,
103 Math.min(window.innerHeight * 0.75, INITIAL_MAX_HEIGHT),
104 ),
105 };
106​
107 setWindowSizeLimits(newLimits);
108​
109 // Clamp the current window size to fit within new limits
110 // Use a callback to get the current state value, not the saved tutorialData value
111 setWindowSize((currentSize) => ({
112 width: Math.max(
113 newLimits.MIN_WIDTH,
114 Math.min(newLimits.MAX_WIDTH, currentSize.width),
115 ),
116 height: Math.max(
117 newLimits.MIN_HEIGHT,
118 Math.min(newLimits.MAX_HEIGHT, currentSize.height),
119 ),
120 }));
121 }
122 }, []);
123​
124 useEffect(() => {
125 // Make sure the window size is within limits
126 updateWindowSizeLimits();
127 if (typeof window !== "undefined") {
128 window.addEventListener("resize", updateWindowSizeLimits);
129 return () => {
130 window.removeEventListener("resize", updateWindowSizeLimits);
131 };
132 }
133 }, [
134 // Make sure the window size is within limits
135 updateWindowSizeLimits,
136 ]);
137​
138 // Resize state
139 const [isResizing, setIsResizing] = useState(false);
140 const [resizeDirection, setResizeDirection] = useState<
141 "top" | "right" | "corner" | null
142 >(null);
143 const resizeStart = useRef({ x: 0, y: 0, width: 0, height: 0 });
144 const saveTimeoutRef = useRef<number | undefined>(undefined);
145​
146 // Debounced save to localStorage (only save after resize stops)
147 useEffect(() => {
148 if (isResizing) return; // Don't save while actively resizing
149​
150 if (saveTimeoutRef.current) {
151 clearTimeout(saveTimeoutRef.current);
152 }
153​
154 saveTimeoutRef.current = window.setTimeout(() => {
155 getTutorialDataHandlers().then(({ updateTutorialData }) => {
156 updateTutorialData({
157 windowSize,
158 });
159 });
160 }, 100);
161​
162 return () => {
163 if (saveTimeoutRef.current) {
164 clearTimeout(saveTimeoutRef.current);
165 }
166 };
167 }, [windowSize, isResizing]);
168​
169 const handleStepChange = useCallback(
170 async (stepTitle: string) => {
171 // clear all highlights
172 navigate({
173 to: ".",
174 search: ({ highlight: _, ...old }) => {
175 return { ...old };
176 },
177 });
178​
179 const { tutorialData, updateTutorialData } =
180 await getTutorialDataHandlers();
181​
182 tutorialData.tutorialStep = stepTitle;
183​
184 updateTutorialData({
185 tutorialStep: stepTitle,
186 });
187​
188 setActiveStep(stepTitle);
189 },
190 [
191 // clear all highlights
192 navigate,
193 setActiveStep,
194 ],
195 );
196​
197 // Restore scroll position on step change (useLayoutEffect to avoid flicker)
198 useLayoutEffect(() => {
199 if (activeStep) {
200 const saved = tutorialData.scrollPositions[activeStep];
201 if (saved && scrollRef.current) {
202 scrollRef.current.scrollTop = saved;
203 }
204 }
205 }, [activeStep, tutorialData.scrollPositions]);
206​
207 // Save scroll position on scroll
208 const handleScroll = async () => {
209 const { updateTutorialData, tutorialData } =
210 await getTutorialDataHandlers();
211 // get current scroll positions
212 if (scrollRef.current && activeStep) {
213 updateTutorialData({
214 tutorialStep: activeStep,
215 scrollPositions: {
216 ...tutorialData.scrollPositions,
217 [activeStep]: scrollRef.current.scrollTop,
218 },
219 });
220 }
221 };
222​
223 // Resize handlers
224 const handleResizeStart = (
225 e: React.MouseEvent,
226 direction: "top" | "right" | "corner",
227 ) => {
228 e.preventDefault();
229 e.stopPropagation();
230 setIsResizing(true);
231 setResizeDirection(direction);
232 resizeStart.current = {
233 x: e.clientX,
234 y: e.clientY,
235 width: windowSize.width,
236 height: windowSize.height,
237 };
238 };
239​
240 useEffect(() => {
241 if (!isResizing || !containerRef.current) return;
242​
243 const container = containerRef.current;
244​
245 const handleMouseMove = (e: MouseEvent) => {
246 e.preventDefault();
247​
248 const deltaX = e.clientX - resizeStart.current.x;
249 const deltaY = e.clientY - resizeStart.current.y;
250​
251 let newWidth = resizeStart.current.width;
252 let newHeight = resizeStart.current.height;
253​
254 if (resizeDirection === "right" || resizeDirection === "corner") {
255 newWidth = Math.max(
256 MIN_WIDTH,
257 Math.min(MAX_WIDTH, resizeStart.current.width + deltaX),
258 );
259 }
260​
261 if (resizeDirection === "top" || resizeDirection === "corner") {
262 // For top resize, we subtract deltaY because dragging up should increase height
263 newHeight = Math.max(
264 MIN_HEIGHT,
265 Math.min(MAX_HEIGHT, resizeStart.current.height - deltaY),
266 );
267 }
268​
269 // Direct DOM manipulation - no React re-render
270 container.style.width = `${newWidth}px`;
271 container.style.height = `${newHeight}px`;
272 };
273​
274 const handleMouseUp = () => {
275 // Sync final size to React state
276 if (containerRef.current) {
277 const finalWidth = containerRef.current.offsetWidth;
278 const finalHeight = containerRef.current.offsetHeight;
279 setWindowSize({ width: finalWidth, height: finalHeight });
280 }
281​
282 setIsResizing(false);
283 setResizeDirection(null);
284 };
285​
286 document.addEventListener("mousemove", handleMouseMove, { passive: false });
287 document.addEventListener("mouseup", handleMouseUp);
288​
289 return () => {
290 document.removeEventListener("mousemove", handleMouseMove);
291 document.removeEventListener("mouseup", handleMouseUp);
292 };
293 }, [
294 isResizing,
295 resizeDirection,
296 MAX_HEIGHT,
297 MAX_WIDTH,
298 MIN_HEIGHT,
299 MIN_WIDTH,
300 ]);
301​
302 return (
303 <div
304 ref={containerRef}
305 className={cn(
306 "mb-2 drop-shadow-md dark:drop-shadow-lg bg-card rounded-lg border border-border dark:border-primary/50 relative",
307 !isResizing && "transition-all",
308 isResizing && "select-none",
309 )}
310 style={{
311 width: `${windowSize.width}px`,
312 height: `${windowSize.height}px`,
313 willChange: isResizing ? "width, height" : "auto",
314 contain: isResizing ? "layout style paint" : "none",
315 }}
316 >
317 {/* Top resize handle - larger hit area with invisible padding */}
318 <div
319 className="absolute top-0 left-0 right-0 cursor-ns-resize z-50 group h-2 -mt-1"
320 onMouseDown={(e) => handleResizeStart(e, "top")}
321 >
322 <div className="absolute top-1/2 left-0 right-0 h-px -translate-y-1/2 group-hover:bg-orange-500/30 transition-colors" />
323 </div>
324​
325 {/* Right resize handle - larger hit area with invisible padding */}
326 <div
327 className="absolute top-0 right-0 bottom-0 cursor-ew-resize z-50 group -mr-1 w-2"
328 onMouseDown={(e) => handleResizeStart(e, "right")}
329 >
330 <div className="absolute top-0 left-1/2 bottom-0 w-px -translate-x-1/2 group-hover:bg-orange-500/30 transition-colors" />
331 </div>
332​
333 {/* Corner resize handle - larger hit area */}
334 <div
335 className="absolute top-0 right-0 cursor-nesw-resize z-50 group w-4 h-4 -mt-1 -mr-1"
336 onMouseDown={(e) => handleResizeStart(e, "corner")}
337 >
338 <div className="absolute top-1/2 left-1/2 w-1 h-1 -translate-x-1/2 -translate-y-1/2 group-hover:bg-orange-500/50 transition-colors rounded-full" />
339 </div>
340​
341 <div
342 className={cn(
343 "opacity-100 translate-y-0 h-full flex flex-col overflow-hidden rounded-lg",
344 )}
345 >
346 <FloatingWindowHeader toggleWindow={toggleWindow} />
347 <Tabs
348 orientation="vertical"
349 value={activeStep || undefined}
350 onValueChange={handleStepChange}
351 className={cn(
352 "w-full flex-1 flex flex-row p-2 overflow-hidden",
353 isResizing && "pointer-events-none",
354 )}
355 >
356 <ScrollArea type="hover" className="h-full py-2">
357 <TutorialTableOfContents
358 activeStep={activeStep}
359 onStepChange={handleStepChange}
360 />
361 </ScrollArea>
362 <div
363 className={cn(
364 "relative w-full h-full ml-4 min-w-0 overflow-hidden",
365 isResizing && "pointer-events-none",
366 )}
367 >
368 <ScrollShadow
369 position="top"
370 visible={canScrollUp}
371 fromColor="from-card"
372 />
373 <div
374 ref={scrollRef}
375 key={activeStep}
376 onScroll={handleScroll}
377 className={cn(
378 "h-full overflow-y-auto overflow-x-hidden",
379 isResizing ? "contain-strict" : "contain-none",
380 )}
381 >
382 {steps.map((step) => (
383 <TabsContent
384 key={step.title}
385 value={step.title}
386 className="w-full overflow-x-hidden pb-3"
387 >
388 <div className="fade-in animate-in prose dark:prose-invert prose-md prose-neutral prose-base rounded-lg">
389 {<step.file />}
390 {step.nextStepName && (
391 <div className="mt-4">
392 <button
393 type="button"
394 onClick={() =>
395 step.nextStepName &&
396 handleStepChange(step.nextStepName)
397 }
398 className="text-primary underline hover:brightness-75 transition-colors cursor-pointer"
399 >
400 Next: {step.nextStepName}
401 </button>
402 </div>
403 )}
404 </div>
405 </TabsContent>
406 ))}
407 </div>
408 <ScrollShadow
409 position="bottom"
410 visible={canScrollDown}
411 fromColor="from-card"
412 />
413 </div>
414 </Tabs>
415 </div>
416 </div>
417 );
419​
420export function TutorialWindow({
421 tutorialData,
422}: {
423 tutorialData: TutorialData;
424}) {
425 const [isClosed, setIsClosed] = useState(tutorialData.isClosed);
426​
427 const { step: activeStepFromSearch } = useSearch({ strict: false });
428​
429 const [activeStep, setActiveStep] = useState(
430 tutorialData.tutorialStep || steps[0].title,
431 );
432​
433 useEffect(() => {
434 if (activeStepFromSearch && typeof activeStepFromSearch === "string") {
435 const stepInSearch = decodeURIComponent(activeStepFromSearch);
436 if (steps.find((step) => step.title === stepInSearch)) {
437 setActiveStep(stepInSearch);
438 }
439 }
440 }, [activeStepFromSearch]);
441​
442 const router = useRouter();
443​
444 const toggleWindow = useCallback(async () => {
445 setIsClosed((o) => !o);
446 const { updateTutorialData } = await getTutorialDataHandlers();
447​
448 /*
449 We need to invalidate the route so that any components using
450 the `tutorialData` from the loader get the updated data
451 (important for the `tutorialData.windowSize`).
452 */
453 router.invalidate({
454 filter: (route) => route.id === "/_tutorial",
455 });
456​
457 updateTutorialData({
458 isClosed: !isClosed,
459 });
460 }, [isClosed, router]);
461​
462 return (
463 <div className="w-0 h-0">
464 <div
465 className={
466 "absolute bottom-0 left-0 p-2 z-50 overflow-hidden max-w-full"
467 }
468 >
469 <AnimatePresence initial={false}>
470 {!isClosed && (
471 <motion.div
472 key="floating-window"
473 initial={{
474 opacity: 0,
475 translateY: 10,
476 filter: "blur(4px)", // add blur to initial
477 }}
478 animate={{ opacity: 1, translateY: 0, filter: "blur(0px)" }}
479 exit={{ opacity: 0, translateY: 10, filter: "blur(4px)" }} // add blur to exit
480 transition={{
481 translateY: {
482 type: "spring",
483 stiffness: 600,
484 },
485 opacity: {
486 duration: 0.2,
487 ease: "easeInOut",
488 },
489 filter: {
490 duration: 0.2,
491 ease: "easeInOut",
492 },
493 }}
494 >
495 <FloatingWindow
496 tutorialData={tutorialData}
497 activeStep={activeStep}
498 setActiveStep={setActiveStep}
499 toggleWindow={toggleWindow}
500 />
501 </motion.div>
502 )}
503 </AnimatePresence>
504 <ToggleFloatingWindowButton
505 isClosed={isClosed}
506 activeStep={activeStep}
507 toggleWindow={toggleWindow}
508 />
509 </div>
510 </div>
511 );