Open History to see the last commit
1import { useLocation } from "@tanstack/react-router";
2import { useEffect, useLayoutEffect, useRef } from "react";
3import type { ReactNode } from "react";
4
5import { AppSheet } from "@/components/app-sheet/app-sheet";
6import {
7 rememberSheetLocation,
8 useIsAppSheetOpen,
9 useOpenAppSheet,
10} from "@/components/app-sheet/app-sheet-store";
11import { GuideDocument } from "@/components/guide/guide-document";
12import { MobileGuideHeader } from "@/components/guide/mobile-guide-header";
13import { TryItProvider } from "@/components/guide/try-it";
14import { useReadingPosition } from "@/components/guide/use-reading-position";
15import { captureScrollAnchor, restoreScrollAnchor } from "@/lib/scroll-anchor";
16import { setRecordSheetState } from "@/lib/sheet-aware-history";
17import type { ScrollAnchor } from "@/lib/scroll-anchor";
18
19/**
20 * Small screens: the guide fills the screen, and each hands-on section's
21 * "Try it" slides the app up as a sheet, already on the screen the section is
22 * about. Whether the sheet is open follows browser history (Back closes it);
23 * closing it puts the guide back exactly where it was.
24 */
25export function MobileWorkspace({ appSlot }: { appSlot: ReactNode }) {
26 const open = useIsAppSheetOpen();
27 const openAppSheet = useOpenAppSheet();
28 const href = useLocation({ select: (location) => location.href });
29 const scrollRef = useRef<HTMLDivElement>(null);
30 const savedScroll = useRef<ScrollAnchor | null>(null);
31
32 // While this layout shows, history entries record whether the sheet is open.
33 useLayoutEffect(() => {
34 setRecordSheetState(true);
35 return () => setRecordSheetState(false);
36 }, []);
37
38 // Same place in the guide as before a layout change…
39 useReadingPosition(scrollRef);
40
41 // …and as before the sheet opened, once it closes.
42 useLayoutEffect(() => {
43 const container = scrollRef.current;
44 if (!container) return;
45 if (open) {
46 savedScroll.current = captureScrollAnchor(container);
47 } else if (savedScroll.current) {
48 restoreScrollAnchor(container, savedScroll.current);
49 savedScroll.current = null;
50 }
51 }, [open]);
52
53 // Where the app was, so the next "Try it" for this screen picks up there.
54 useEffect(() => {
55 if (open) rememberSheetLocation(href);
56 }, [open, href]);
57
58 return (
59 <TryItProvider onTryIt={openAppSheet}>
60 <div className="flex h-dvh flex-col bg-background" inert={open}>
61 <MobileGuideHeader scrollRef={scrollRef} />
62 <div
63 ref={scrollRef}
64 data-wrap-code
65 className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-[env(safe-area-inset-bottom)]"
66 >
67 <GuideDocument />
68 </div>
69 </div>
70 <AppSheet app={appSlot} />
71 </TryItProvider>
72 );
73}