Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AppRouteModal.tsx

196 lines8.4 KB

1import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
2import { T, useGT } from "gt-react";
3import { XIcon } from "lucide-react";
4import { useRouter } from "@tanstack/react-router";
5import {
6 useEffect,
7 useRef,
8 useState,
9 type CSSProperties,
10 type ReactNode,
11 type RefObject,
12} from "react";
13​
14import { getCommandPaletteOpener } from "../commandPaletteStore";
15import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay";
16import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../lib/workspaceFocus";
17import { useCloseAppModal } from "./sidebar/mainAppLocation";
18import { GlobalVoiceInputIndicator } from "./chat/GlobalVoiceInputIndicator";
19import { Button } from "./ui/button";
20import { DialogBackdrop } from "./ui/dialog";
21import { closeOpenPopups } from "./ui/open-popups";
22import { SharedTooltipTrigger } from "./ui/shared-tooltip";
23​
24/**
25 * Large modal for the Settings and Usage routes. Esc, the close button, or a press on the
26 * backdrop returns to the page that opened it. Keyboard guards that skip dialogs exempt
27 * `[data-app-modal]`, because these pages own their shortcuts.
28 */
29export function AppRouteModal({
30 label,
31 actionsRef,
32 children,
33}: {
34 label: string;
35 actionsRef?: RefObject<DialogPrimitive.Root.Actions | null>;
36 children: ReactNode;
37}) {
38 const closeAppModal = useCloseAppModal();
39 const [open, setOpen] = useState(true);
40 // Text selection that ends on the backdrop is not a dismissal.
41 const backdropPressRef = useRef(false);
42 const closeReasonRef = useRef<DialogPrimitive.Root.ChangeEventReason | null>(null);
43 // Focus the surface, not its first control: no stray focus ring, no phone keyboard.
44 // On close, return focus to the opener only after a keyboard close (Esc, or a shortcut that
45 // closes through `actionsRef`); after a pointer close it would paint a focus ring.
46 const popupRef = useRef<HTMLDivElement>(null);
47 const [opener] = useState(
48 () =>
49 getCommandPaletteOpener() ??
50 (document.activeElement instanceof HTMLElement ? document.activeElement : null),
51 );
52 // Clear the native window controls (macOS traffic lights, the Windows and Linux caption
53 // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its
54 // 1.5rem inset is shorter than the strip.
55 const nativeTitlebarHeight = useNativeTitlebarHeight();
56 const router = useRouter();
57 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- popups opened before a keyboard shortcut opened the modal would stay drawn above it
58 useEffect(closeOpenPopups, []);
59 // Leaving the page without closing (Navigation: Back) unmounts a focused field during a
60 // commit, when React no longer delivers its blur, so commit-on-blur rows would drop what was
61 // typed. Blur text fields before the navigation renders; other controls keep their focus.
62 // Not onBeforeNavigate: the router skips it while a past redirect is still recorded.
63 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- router listener that blurs a field before navigation unmounts it
64 useEffect(
65 () =>
66 router.subscribe("onBeforeLoad", ({ pathChanged }) => {
67 const focused = document.activeElement;
68 if (pathChanged && focused?.matches("input, textarea, [contenteditable]")) {
69 blurFocusedWithin(popupRef.current);
70 }
71 }),
72 [router],
73 );
74​
75 return (
76 <DialogPrimitive.Root
77 open={open}
78 actionsRef={actionsRef}
79 // Portaled layers outside this tree (toasts, Clerk, confirm dialogs) are not backdrop presses.
80 disablePointerDismissal
81 onOpenChange={(nextOpen, eventDetails) => {
82 if (nextOpen) return;
83 // Base UI's dismiss handler fires on held Esc repeats after a nested popup closes.
84 if (eventDetails.reason === "escape-key" && eventDetails.event.repeat) {
85 return eventDetails.cancel();
86 }
87 // Esc from a layer outside Base UI (Clerk's modals) is that layer's to handle.
88 const target = eventDetails.event.target;
89 if (
90 eventDetails.reason === "escape-key" &&
91 target !== document.body &&
92 target instanceof Node &&
93 !popupRef.current?.contains(target)
94 ) {
95 return eventDetails.cancel();
96 }
97 // Closing unmounts a focused field without a blur, so commit-on-blur rows would
98 // drop what was typed. Blur first so they commit.
99 blurFocusedWithin(popupRef.current);
100 closeReasonRef.current = eventDetails.reason;
101 setOpen(false);
102 }}
103 onOpenChangeComplete={(nextOpen) => {
104 if (!nextOpen) void closeAppModal();
105 }}
106 >
107 <DialogPrimitive.Portal>
108 <DialogBackdrop />
109 <DialogPrimitive.Viewport
110 style={
111 {
112 "--app-modal-titlebar-height": `${nativeTitlebarHeight}px`,
113 "--app-modal-top-inset": `max(env(safe-area-inset-top), ${nativeTitlebarHeight}px)`,
114 "--app-modal-sm-top": `max(1.5rem, ${nativeTitlebarHeight}px)`,
115 } as CSSProperties
116 }
117 // Electron hit-tests drag regions under the backdrop regardless of z-index; without
118 // this, presses above the modal move the window instead of dismissing it.
119 className="fixed inset-0 z-50 flex items-center justify-center [-webkit-app-region:no-drag] sm:p-6 sm:pt-(--app-modal-sm-top) lg:p-10"
120 onPointerDown={(event) => {
121 backdropPressRef.current = event.target === event.currentTarget;
122 }}
123 // A press released inside the popup still clicks the viewport, their common ancestor.
124 onPointerUp={(event) => {
125 if (event.target !== event.currentTarget) backdropPressRef.current = false;
126 }}
127 onClick={(event) => {
128 if (backdropPressRef.current && event.target === event.currentTarget) setOpen(false);
129 backdropPressRef.current = false;
130 }}
131 >
132 <DialogPrimitive.Popup
133 ref={popupRef}
134 initialFocus={popupRef}
135 finalFocus={(closeType) => {
136 const keyboardClose =
137 closeType === "keyboard" || closeReasonRef.current === "imperative-action";
138 if (!keyboardClose) return false;
139 if (!opener?.isConnected || opener === document.body) {
140 // Dismissing a popup on open can remove its focused control.
141 requestWorkspaceContentFocus();
142 return false;
143 }
144 if (!opener.closest("[inert]")) return opener;
145 // The thread behind the modal stays inert until the route closes, so its area
146 // takes focus once it is usable again.
147 const area = opener.closest<HTMLElement>("[data-workspace-area]");
148 if (area?.dataset.workspaceArea)
149 requestWorkspaceFocus({ area: area.dataset.workspaceArea });
150 return false;
151 }}
152 aria-label={label}
153 data-slot="dialog-popup"
154 data-app-modal=""
155 className="relative flex size-full min-h-0 min-w-0 flex-col overflow-hidden bg-background max-sm:pt-(--app-modal-top-inset) max-sm:pb-safe text-foreground outline-none transition-[opacity,scale] duration-150 ease-out [-webkit-app-region:no-drag] data-ending-style:scale-[0.985] data-ending-style:opacity-0 data-starting-style:scale-[0.985] data-starting-style:opacity-0 sm:max-h-[60rem] sm:max-w-[80rem] sm:rounded-2xl sm:border sm:shadow-2xl/40"
156 >
157 {/* The emptied strip still moves the window, as the titlebar it replaces does. */}
158 <div
159 aria-hidden
160 className="absolute inset-x-0 top-0 hidden h-(--app-modal-titlebar-height) [-webkit-app-region:drag] max-sm:block"
161 />
162 {children}
163 <GlobalVoiceInputIndicator />
164 </DialogPrimitive.Popup>
165 </DialogPrimitive.Viewport>
166 </DialogPrimitive.Portal>
167 </DialogPrimitive.Root>
168 );
170​
171function blurFocusedWithin(container: HTMLElement | null) {
172 const focused = document.activeElement;
173 if (focused instanceof HTMLElement && container?.contains(focused)) focused.blur();
175​
176export function AppRouteModalClose() {
177 const gt = useGT();
178 return (
179 <SharedTooltipTrigger
180 render={
181 <DialogPrimitive.Close
182 aria-label={gt("Close")}
183 render={<Button size="icon-sm" variant="ghost" />}
184 />
185 }
186 label={
187 <>
188 <T>Close (Esc)</T>
189 </>
190 }
191 side="bottom"
192 >
193 <XIcon />
194 </SharedTooltipTrigger>
195 );