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

TutorialWindow.tsx

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