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