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

TutorialWindow.tsx

591 lines17.6 KB

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