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

notes-layout.tsx

74 lines2.5 KB

1import { createContext, useContext, useMemo, useState } from "react";
2import type { ReactNode } from "react";
3​
4import { useRevealForSpotlight } from "@/components/spotlight/spotlight-reveal";
5import { useElementWidth } from "@/hooks/use-element-width";
6​
7/**
8 * The Notes clone has two looks: the three-column macOS app, and the iPhone
9 * app (one screen at a time). Which one we show depends on the width of the
10 * app pane, so dragging the divider or opening the page on a phone both work.
11 */
12export const IOS_LAYOUT_MAX_WIDTH = 640;
13​
14export type NotesLayout = "mac" | "ios";
15​
16interface NotesLayoutContextValue {
17 layout: NotesLayout;
18 sidebarVisible: boolean;
19 toggleSidebar: () => void;
21​
22const NotesLayoutContext = createContext<NotesLayoutContextValue | null>(null);
23const FixedLayoutContext = createContext<NotesLayout | null>(null);
24​
25/**
26 * Pins the layout regardless of width (`null`: pick by width). The app sheet
27 * on small screens always shows the iPhone app, even on a phone in landscape.
28 */
29export function FixedNotesLayout({
30 layout,
31 children,
32}: {
33 layout: NotesLayout | null;
34 children: ReactNode;
35}) {
36 return <FixedLayoutContext value={layout}>{children}</FixedLayoutContext>;
38​
39export function NotesLayoutProvider({ children }: { children: ReactNode }) {
40 const [ref, width] = useElementWidth<HTMLDivElement>();
41 const [sidebarVisible, setSidebarVisible] = useState(true);
42 const fixedLayout = useContext(FixedLayoutContext);
43 // The guide's "Show me the folder counts" brings the sidebar back.
44 useRevealForSpotlight("folder-counts", () => setSidebarVisible(true));
45​
46 const value = useMemo<NotesLayoutContextValue | null>(
47 () =>
48 width === null
49 ? null
50 : {
51 layout: fixedLayout ?? (width < IOS_LAYOUT_MAX_WIDTH ? "ios" : "mac"),
52 sidebarVisible,
53 toggleSidebar: () => setSidebarVisible((visible) => !visible),
54 },
55 [width, fixedLayout, sidebarVisible],
56 );
57​
58 return (
59 <div ref={ref} className="@container/notes h-full w-full">
60 {value && <NotesLayoutContext value={value}>{children}</NotesLayoutContext>}
61 </div>
62 );
64​
65export function useNotesLayout(): NotesLayoutContextValue {
66 const context = useContext(NotesLayoutContext);
67 if (!context) throw new Error("useNotesLayout must be used inside <NotesLayoutProvider>");
68 return context;
70​
71/** Renders the macOS or the iPhone version of a screen. */
72export function ByLayout({ mac, ios }: { mac: ReactNode; ios: ReactNode }) {
73 return useNotesLayout().layout === "mac" ? mac : ios;