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