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

AppRouteModal.tsx

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