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