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

notes-layout.tsx

55 lines1.8 KB

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;
20​
21const NotesLayoutContext = createContext<NotesLayoutContextValue | null>(null);
22​
23export function NotesLayoutProvider({ children }: { children: ReactNode }) {
24 const [ref, width] = useElementWidth<HTMLDivElement>();
25 const [sidebarVisible, setSidebarVisible] = useState(true);
26​
27 const value = useMemo<NotesLayoutContextValue | null>(
28 () =>
29 width === null
30 ? null
31 : {
32 layout: width < IOS_LAYOUT_MAX_WIDTH ? "ios" : "mac",
33 sidebarVisible,
34 toggleSidebar: () => setSidebarVisible((visible) => !visible),
35 },
36 [width, sidebarVisible],
37 );
38​
39 return (
40 <div ref={ref} className="@container/notes h-full w-full">
41 {value && <NotesLayoutContext value={value}>{children}</NotesLayoutContext>}
42 </div>
43 );
45​
46export function useNotesLayout(): NotesLayoutContextValue {
47 const context = useContext(NotesLayoutContext);
48 if (!context) throw new Error("useNotesLayout must be used inside <NotesLayoutProvider>");
49 return context;
51​
52/** Renders the macOS or the iPhone version of a screen. */
53export function ByLayout({ mac, ios }: { mac: ReactNode; ios: ReactNode }) {
54 return useNotesLayout().layout === "mac" ? mac : ios;