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