-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdesign.tsx
More file actions
809 lines (729 loc) · 29.7 KB
/
Copy pathdesign.tsx
File metadata and controls
809 lines (729 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
import { clsx } from 'clsx';
import { tv, type VariantProps } from 'tailwind-variants';
import { XIcon } from '@phosphor-icons/react';
import { forwardRef, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import type { ButtonHTMLAttributes, ComponentProps, CSSProperties, HTMLAttributes, InputHTMLAttributes, ReactNode, RefObject } from 'react';
import { stepFocus } from './focus-step';
import { OVERLAY_VIEWPORT_MARGIN_PX } from '../lib/ui-geometry';
// App-wide type scale, color strategy, and chrome conventions: see
// docs/specs/theme.md and AGENTS.md.
/** Desktop pane-header height. Geometry derived from the header (such as the
* elevated zoom inset) must use this constant so the chrome stays proportional. */
export const PANE_HEADER_HEIGHT_PX = 30;
// Pane headers/doors own the top corners; terminal bodies own the bottom.
// All terminal-radius constants derive from this single source so the CSS
// class, the SVG-friendly px value, and the inline-style rem string can't
// drift apart. Tailwind's `lg` step is 0.5rem; if that ever changes, both
// the class names and BASE_REM must move together.
// Keep the class names as literals so Tailwind's scanner emits them.
const TERMINAL_BORDER_RADIUS_REM = 0.5;
export const TERMINAL_BORDER_RADIUS_PX = TERMINAL_BORDER_RADIUS_REM * 16;
export const TERMINAL_TOP_RADIUS_CLASS = 'rounded-t-lg';
export const TERMINAL_BOTTOM_RADIUS_CLASS = 'rounded-b-lg';
export const TERMINAL_SELECTION_BORDER_RADIUS = `${TERMINAL_BORDER_RADIUS_REM}rem`;
/** Shared shape, size bounds, and type for Baseboard Doors and Workspace tabs. */
export const DOOR_TAB_CLASS = clsx(
'relative flex h-6 max-w-[220px] min-w-[68px] items-center overflow-hidden text-sm font-medium font-mono',
TERMINAL_TOP_RADIUS_CLASS,
);
/** The `max-w-` / `h-` bounds of `DOOR_TAB_CLASS`, for the host code that has to
* reason about a tab's size without a rendered element (the cross-window tab
* drag). Tailwind needs the arbitrary values spelled literally above, so these
* two are a mirror — keep them in sync. */
export const DOOR_TAB_MAX_WIDTH_PX = 220;
export const DOOR_TAB_HEIGHT_PX = 24;
/** The surface an alarm inset is drawn on, which is what picks its token: each
* `--color-alarm-vs-*` is contrast-picked against one background. */
export type AlertRingGround = 'door' | 'header-active' | 'header-inactive';
export const ALERT_RING_INSET_CLASS = 'pointer-events-none absolute inset-0';
/** Spelled out per ground, never built from a template — Tailwind's scanner
* reads source text, so a composed arbitrary value would never be emitted. */
export const ALERT_RING_INSET_BY_GROUND: Record<AlertRingGround, string> = {
door: 'shadow-[inset_0_0_0_2px_var(--color-alarm-vs-door)]',
'header-active': 'shadow-[inset_0_0_0_2px_var(--color-alarm-vs-header-active)]',
'header-inactive': 'shadow-[inset_0_0_0_2px_var(--color-alarm-vs-header-inactive)]',
};
// The Workspace strip's two halves of one idea: the selected tab is seated
// against the Wall, and the rest recede into the app ground. Keep them
// together so a palette change can't move one endpoint without the other.
export const TAB_WALL_JOIN_GRADIENT = 'linear-gradient(to bottom, var(--color-header-active-bg), var(--color-app-bg))';
// The inactive tab's fade, starting at 70% of the 24px tab — just below the
// label's baseline — and ending at 70% app background, i.e. a 30/70 sRGB mix
// with the header color under it. Deliberately TRANSLUCENT rather than a
// gradient between the two tokens: it composites over the `bg-header-*` class,
// so HEADER_PALETTE_TRANSITION_CLASS still crossfades beneath it. A gradient
// naming the header token would paint over that crossfade, which
// `transition-colors` cannot tween.
export const TAB_INACTIVE_FADE_STYLE = {
backgroundImage: 'linear-gradient(to bottom, transparent 70%, color-mix(in srgb, var(--color-app-bg) 70%, transparent))',
} as const;
// The gutter between panes (and around the wall's top/sides — the baseboard
// side stays a tight 2px). Deliberately ODD: the passthrough ring is a 1px
// stroke, and a 1px stroke can only sit dead-center of a gutter on whole
// device pixels when the gutter is odd. Consumed by LATH_LAYOUT_OPTS.gap and
// mirrored by the Tailwind inset classes in Wall.tsx / Baseboard.tsx
// (`*-1.75` = 7px) — keep them in sync.
export const PANE_GUTTER_PX = 7;
/** Pointer travel before a press becomes a drag; below it the element's own
* click behavior (select / enter passthrough / rename / activate) is untouched.
* Shared by the pane/Door drag and the Workspace strip's reorder, so both feel
* like one gesture vocabulary. */
export const DRAG_THRESHOLD_PX = 5;
// Concentric-corners rule: when a rounded outline wraps a rounded edge, both
// arcs must share a corner center — outer radius = inner radius + offset.
// Never tighten the inner radius to compensate. The pane focus ring draws on
// a rect inflated by SELECTION_RING_INFLATE_PX, so its radius grows by the
// same amount; rings at zero offset (doors, the Lath drop preview) keep the
// pane radius as-is.
//
// The inflate is derived so the ring is CENTERED in the gutter: the 1px
// passthrough border draws just inside the inflated rect, spanning
// [INFLATE-1, INFLATE] from the pane edge, so its center sits at
// INFLATE - 0.5 = PANE_GUTTER_PX / 2. (Both selection-ring strokes center on
// the same line via their path inset — see SelectionRing.)
export const SELECTION_RING_INFLATE_PX = (PANE_GUTTER_PX + 1) / 2;
export const PANE_SELECTION_RING_RADIUS_PX = TERMINAL_BORDER_RADIUS_PX + SELECTION_RING_INFLATE_PX;
// Focus-ring motion. The selection ring's travel between panes/doors, the pane
// header's active/inactive palette crossfade, and the ring's unfocus-saturate
// fade all run on this single duration so they resolve as one gesture. Half the
// Lath layout motion (LATH_MOTION_MS = 440) — the ring is a light overlay chasing
// geometry the wall has already committed, so it settles quicker. The ring travel
// itself is a JS tween on a pointer-events-none overlay (WorkspaceSelectionOverlay
// + rect-tween.ts), the same per-frame carve-out the Lath animator holds against
// DESIGN.md's "don't animate layout properties" rule.
export const FOCUS_MOTION_MS = 220;
// The pane-header palette crossfade, as a complete Tailwind literal so the
// scanner emits it (a template built from FOCUS_MOTION_MS would be invisible to
// it). The duration + house curve are asserted against FOCUS_MOTION_MS in
// design.test.ts so this literal can't silently drift from the ring's timing.
export const HEADER_PALETTE_TRANSITION_CLASS =
'transition-colors duration-[220ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none';
// Letter-spacing for the small semibold TODO pill — wider tracking keeps the
// tiny label legible. Shared so both pill sites stay in sync.
export const TODO_PILL_TRACKING_CLASS = 'tracking-[0.08em]';
// Letter-spacing for the alarm overlay's `SPEAKING` / `SPOKEN` labels — wider
// tracking keeps the small all-caps label legible over the wash.
export const ALERT_SPEECH_TRACKING_CLASS = 'tracking-[0.12em]';
// Chrome for small anchored popovers (title candidates, TODO preview, pane
// context menu, rename warning). Text size and padding vary per popover and
// stay at the call site; the surface recipe is shared so they can't drift.
export const POPUP_SURFACE_CLASS = 'z-[1000] rounded border border-border bg-surface-raised font-mono text-foreground shadow-md';
// Message-only panes use the terminal ground because they stand in for a
// Surface, not chrome. PaneMessage pairs this scrollable root with content that
// stays centered when it fits and fully reachable when the pane is small.
const PANE_MESSAGE_CLASS = 'flex h-full min-h-0 w-full min-w-0 flex-col overflow-auto bg-terminal-bg px-6 py-6 text-center text-sm';
export function PaneMessage({
children,
className,
contentClassName,
...props
}: ComponentProps<'div'> & { contentClassName?: string }) {
return (
<div {...props} className={clsx(PANE_MESSAGE_CLASS, className)}>
{/* Auto margins center only spare space; overflowing content starts at the
scroll origin instead of being centered beyond its reachable bounds. */}
<div className={clsx('my-auto w-full min-w-0 max-w-[30rem] shrink-0 self-center [overflow-wrap:anywhere]', contentClassName)}>
{children}
</div>
</div>
);
}
// `ComponentProps<'div'>` rather than `HTMLAttributes<HTMLDivElement>` so `ref`
// is among the props (React 19 ref-as-prop): an anchored menu needs the row
// itself measured, not a wrapper around it.
export function PopupButtonRow({
className,
...props
}: ComponentProps<'div'>) {
return (
<div
className={clsx(
'flex items-stretch overflow-hidden rounded border border-border bg-surface-raised font-mono text-sm text-foreground shadow-md',
className,
)}
{...props}
/>
);
}
export const popupButton = tv({
base: 'm-0 px-1.5 py-0.5',
variants: {
flashed: {
true: 'animate-copy-flash bg-header-active-bg/25 text-header-active-bg',
false: 'hover:bg-foreground/10',
},
},
defaultVariants: { flashed: false },
});
export type PopupButtonVariants = VariantProps<typeof popupButton>;
export interface ModalRect {
top: number;
left: number;
width: number;
height: number;
}
/** The selection ring's z-index. Under `WorkspaceWindow` it paints from
* `document.body`, where every modal layer must sit above it
* (docs/specs/layout.md → "Selection overlay"). */
export const SELECTION_RING_Z_INDEX = 50;
export const MODAL_LAYERS = {
app: 60,
pane: 100,
critical: 9999,
} as const;
export type ModalLayer = keyof typeof MODAL_LAYERS;
export const modalOverlay = tv({
base: 'flex items-center justify-center',
variants: {
scope: {
viewport: 'fixed inset-0',
// The target veil covers the target's exact rect (zero offset), so the
// Concentric-Corners Rule (DESIGN.md) makes its radius EQUAL the target's
// — panes round at rounded-lg (TERMINAL_*_RADIUS_CLASS above).
target: 'rounded-lg',
},
backdrop: {
standard: 'bg-app-bg/50',
strong: 'bg-app-bg/55',
},
},
defaultVariants: { scope: 'viewport', backdrop: 'standard' },
});
export type ModalOverlayVariants = VariantProps<typeof modalOverlay>;
/**
* The inset a modal overlay reserves around its surface. Hoisted because
* `OVERLAY_MAX_HEIGHT.modal` below is derived from it — `py-6`, doubled — and
* Tailwind needs both as literals, so the pair can only be kept honest by
* living side by side.
*/
export const MODAL_OVERLAY_INSET = 'px-4 py-6';
/**
* The custom properties viewport-bounded overlays read for their height caps.
*
* These exist so a bound can be *narrowed* by an ancestor: a story overrides one
* to snapshot the short-viewport layout deterministically, which no `dvh` value
* can (Chromatic controls snapshot width, never height). Unset everywhere in the
* app, so each entry below falls through to the real viewport.
*
* One property per kind, not one shared: inside the Settings dialog the popover
* is a DOM descendant of the modal surface, and custom properties inherit
* through `position: fixed` — so a single knob narrowed to constrain the
* dropdown would silently cap the dialog containing it too.
*/
export const OVERLAY_MAX_HEIGHT_VAR = {
modal: '--overlay-max-h-modal',
popover: '--overlay-max-h-popover',
} as const;
/**
* Height caps for things that float over the viewport. One spelling per kind of
* inset, rather than the six hand-rolled `vh`/`dvh` literals these replaced.
*
* `dvh` rather than `vh` so a mobile browser's collapsing chrome counts. Written
* as whole literals because Tailwind scans source statically and cannot see a
* value assembled from a constant — `design.test.ts` pins `popover` to
* `OVERLAY_VIEWPORT_MARGIN_PX` so the two cannot drift.
*/
export const OVERLAY_MAX_HEIGHT = {
/** A `ModalFrame` surface: the viewport minus `MODAL_OVERLAY_INSET` doubled. */
modal: 'max-h-[var(--overlay-max-h-modal,calc(100dvh-3rem))]',
/** An anchored popover, matching `clampOverlayPosition`'s viewport margin. */
popover: 'max-h-[var(--overlay-max-h-popover,calc(100dvh-24px))]',
} as const;
/**
* The same caps as `OVERLAY_MAX_HEIGHT`, for an inline `style` rather than a
* class. Assembled from the constants — only Tailwind needs whole literals, so
* an inline consumer has no excuse to hand-roll a second copy.
*/
export const OVERLAY_MAX_HEIGHT_CSS = {
popover: `var(${OVERLAY_MAX_HEIGHT_VAR.popover}, calc(100dvh - ${OVERLAY_VIEWPORT_MARGIN_PX * 2}px))`,
} as const;
export const modalSurface = tv({
base: 'rounded-lg border border-border bg-surface-raised font-mono text-foreground shadow-lg',
variants: {
padding: {
none: 'p-0',
compact: 'p-3',
default: 'p-4',
spacious: 'px-6 py-4',
},
align: {
start: 'text-left',
center: 'text-center',
},
elevation: {
raised: 'shadow-lg',
modal: 'shadow-2xl',
},
},
defaultVariants: { padding: 'default', align: 'start', elevation: 'raised' },
});
export type ModalSurfaceVariants = VariantProps<typeof modalSurface>;
/** The terminal context floats over its source pane: the modal surface with an
* edge that stays visible in dark themes. Its exit length is mirrored into CSS
* as `--context-exit-duration` (docs/specs/layout.md → "Header context menu"). */
export const TERMINAL_CONTEXT_SURFACE_CLASS = modalSurface({ padding: 'none', elevation: 'modal', class: 'z-[1000] border-foreground/20' });
export const TERMINAL_CONTEXT_EXIT_MS = 180;
export const modalActionButton = tv({
base: 'rounded px-2 py-1.5 text-xs transition-colors focus-visible:outline focus-visible:outline-1 focus-visible:outline-focus-ring disabled:cursor-not-allowed disabled:opacity-45',
variants: {
tone: {
primary: 'bg-header-active-bg text-header-active-fg',
secondary: 'border border-border text-muted hover:bg-header-inactive-bg hover:text-foreground',
},
},
defaultVariants: { tone: 'secondary' },
});
export type ModalActionButtonVariants = VariantProps<typeof modalActionButton>;
export const modalReviewBlock = tv({
base: 'block rounded border border-border bg-app-bg font-mono text-foreground whitespace-pre-wrap',
variants: {
density: {
compact: 'p-2 text-xs',
default: 'px-2.5 py-2 text-sm leading-relaxed',
},
overflow: {
short: 'max-h-32 overflow-auto',
medium: 'max-h-40 overflow-auto',
},
wrap: {
breakAll: 'break-all',
breakWords: 'break-words',
},
},
defaultVariants: {
density: 'default',
overflow: 'medium',
wrap: 'breakWords',
},
});
export type ModalReviewBlockVariants = VariantProps<typeof modalReviewBlock>;
export type ModalReviewBlockProps = HTMLAttributes<HTMLDivElement> & ModalReviewBlockVariants;
export function ModalReviewBlock({
density,
overflow,
wrap,
className,
...props
}: ModalReviewBlockProps) {
return (
<div
className={clsx(modalReviewBlock({ density, overflow, wrap }), className)}
{...props}
/>
);
}
export const modalIconButton = tv({
base: 'shrink-0 rounded p-0.5 text-muted transition-colors hover:bg-foreground/10 hover:text-foreground focus-visible:outline focus-visible:outline-1 focus-visible:outline-focus-ring',
});
export type ModalCloseButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;
export const ModalCloseButton = forwardRef<HTMLButtonElement, ModalCloseButtonProps>(
function ModalCloseButton({
children,
className,
type = 'button',
...props
}, ref) {
const ariaLabel = props['aria-label'] ?? 'Close';
return (
<button
ref={ref}
type={type}
{...props}
aria-label={ariaLabel}
className={clsx(modalIconButton(), className)}
>
{children ?? <XIcon size={13} weight="bold" />}
</button>
);
},
);
// Form controls. The app has no checkbox anywhere: a boolean is an OnOffSwitch,
// and a number is a NumericInput. Both live here so dialogs share one vocabulary
// rather than each restyling a bare <input> (DESIGN.md -> Inputs).
export type NumericInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type' | 'value'> & {
value: string;
onChange: (next: string) => void;
/** Max digits the field holds — sizes the box so rows stay compact. */
chars?: number;
};
/**
* A compact underlined number field. Filters non-numeric input at the keystroke
* rather than relying on `type="number"`, whose spinners and locale parsing do
* not fit the app's chrome.
*/
export const NumericInput = forwardRef<HTMLInputElement, NumericInputProps>(
function NumericInput({ value, onChange, chars = 4, className, style, ...props }, ref) {
return (
<input
ref={ref}
type="text"
inputMode="numeric"
value={value}
onChange={(e) => onChange(e.target.value.replace(/[^0-9.]/g, ''))}
style={{ width: `calc(${chars}ch + 0.5rem)`, ...style }}
className={clsx(
'border-0 border-b border-border bg-transparent px-0.5 py-0.5 font-mono text-foreground outline-none focus:border-focus-ring',
className,
)}
{...props}
/>
);
},
);
export type TextInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'> & {
value: string;
onChange: (next: string) => void;
};
/**
* A full-width underlined text field — the string counterpart to
* {@link NumericInput}, sharing its underline so a dialog mixing the two reads
* as one form. Unlike NumericInput it filters nothing and sets no `type`, so a
* caller passes `type="password"` for a credential.
*/
export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
function TextInput({ value, onChange, className, ...props }, ref) {
return (
<input
ref={ref}
value={value}
onChange={(e) => onChange(e.target.value)}
className={clsx(
'w-full border-0 border-b border-border bg-transparent px-0.5 py-0.5 font-mono text-foreground outline-none placeholder:text-muted focus:border-focus-ring',
className,
)}
{...props}
/>
);
},
);
/**
* Left margin that lines content up under an `OnOffSwitch`'s label rather than
* its control: the switch's `w-15` plus the usual `gap-3` between them. Lives here
* so it moves with the switch's own geometry.
*/
export const UNDER_SWITCH_INDENT = 'ml-18';
/**
* Quiet action tint and interaction treatment, shared by switches and context actions.
* Hover is gated on `not-aria-disabled` as well as `:enabled`, because a button that
* drops its clicks via `aria-disabled` (an in-flight `ContextAction`) is still `:enabled`.
* `focus-visible` is deliberately ungated: such a button keeps focus and must keep its ring.
*/
export const SUBTLE_ACTION_REST_COLOR_CLASS = 'text-[color:color-mix(in_srgb,var(--color-link)_35%,var(--color-muted))]';
export const SUBTLE_ACTION_COLOR_CLASS = `${SUBTLE_ACTION_REST_COLOR_CLASS} enabled:not-aria-disabled:hover:text-link enabled:focus-visible:text-link`;
export const SUBTLE_ACTION_INTERACTION_CLASS = 'enabled:not-aria-disabled:hover:bg-current/10 focus-visible:outline focus-visible:outline-focus-ring';
/**
* The app's boolean control: compact track (off left, on right) and one state
* label. Keep its width fixed across states and in sync with UNDER_SWITCH_INDENT.
* Native button behavior handles Space/Enter and surrounding disabled fieldsets.
*/
export function OnOffSwitch({
on,
onEnable,
onDisable,
label,
}: {
on: boolean;
onEnable: () => void;
onDisable: () => void;
/** Describes what is being switched; announced with the current position. */
label: string;
}) {
return (
<button
type="button"
role="switch"
aria-checked={on}
aria-label={`${label} ${on ? 'on' : 'off'}`}
onClick={() => (on ? onDisable() : onEnable())}
className={clsx(
'inline-flex h-6 w-15 shrink-0 items-center gap-1.5 rounded px-1 font-mono text-sm font-normal disabled:cursor-not-allowed disabled:opacity-45',
SUBTLE_ACTION_COLOR_CLASS,
SUBTLE_ACTION_INTERACTION_CLASS,
)}
>
<span
aria-hidden
className={clsx('relative h-3.5 w-6 shrink-0 rounded-full', on ? 'bg-link/25' : 'bg-foreground/10')}
>
<span className={clsx('absolute top-0.5 h-2.5 w-2.5 rounded-full', on ? 'left-3 bg-link' : 'left-0.5 bg-muted')} />
</span>
<span className={clsx('w-[3ch] shrink-0 text-left', !on && 'text-muted')}>{on ? 'On' : 'Off'}</span>
</button>
);
}
export function useMeasuredElementRect(element: HTMLElement | null): ModalRect | null {
const [rect, setRect] = useState<ModalRect | null>(null);
useLayoutEffect(() => {
if (!element) {
setRect(null);
return;
}
// `resize` fires tens of times during a window drag and `ResizeObserver`
// reports every intermediate frame; keeping the previous object when the
// numbers match spares every consumer a re-render per event.
const update = () => {
const next = element.getBoundingClientRect();
setRect((previous) =>
previous
&& previous.top === next.top
&& previous.left === next.left
&& previous.width === next.width
&& previous.height === next.height
? previous
: { top: next.top, left: next.left, width: next.width, height: next.height },
);
};
update();
const ro = new ResizeObserver(update);
ro.observe(element);
window.addEventListener('resize', update);
return () => {
ro.disconnect();
window.removeEventListener('resize', update);
};
}, [element]);
return rect;
}
export function ModalOverlay({
children,
targetElement,
layer = 'pane',
zIndex,
backdrop = 'standard',
className,
style,
...props
}: HTMLAttributes<HTMLDivElement> & ModalOverlayVariants & {
targetElement?: HTMLElement | null;
layer?: ModalLayer;
zIndex?: number;
}) {
const rect = useMeasuredElementRect(targetElement ?? null);
const resolvedZIndex = zIndex ?? MODAL_LAYERS[layer];
const overlayStyle: CSSProperties = rect
? {
position: 'fixed',
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
zIndex: resolvedZIndex,
...style,
}
: { zIndex: resolvedZIndex, ...style };
const overlay = (
<div
className={clsx(modalOverlay({ scope: rect ? 'target' : 'viewport', backdrop }), className)}
style={overlayStyle}
{...props}
>
{children}
</div>
);
// In `document.body`, so no Workspace's stacking context or presentation
// transform holds it under the selection ring (docs/specs/layout.md ->
// "Selection overlay"). The server renderer has no portals.
return typeof document === 'undefined' ? overlay : createPortal(overlay, document.body);
}
export type ModalSurfaceProps = HTMLAttributes<HTMLDivElement> & ModalSurfaceVariants;
export const ModalSurface = forwardRef<HTMLDivElement, ModalSurfaceProps>(function ModalSurface({
children,
padding,
align,
elevation,
className,
...props
}, ref) {
return (
<div
ref={ref}
className={clsx(modalSurface({ padding, align, elevation }), className)}
{...props}
>
{children}
</div>
);
});
export type ModalFrameProps = HTMLAttributes<HTMLDivElement> & ModalSurfaceVariants & {
titleId: string;
targetElement?: HTMLElement | null;
layer?: ModalLayer;
backdrop?: ModalOverlayVariants['backdrop'];
overlayClassName?: string;
initialFocusRef?: RefObject<HTMLElement | null>;
onEscape?: () => void;
};
export function ModalFrame({
children,
titleId,
targetElement,
layer,
backdrop,
overlayClassName,
initialFocusRef,
onEscape,
padding,
align,
elevation,
className,
...props
}: ModalFrameProps) {
const surfaceRef = useRef<HTMLDivElement>(null);
useModalFocusTrap(surfaceRef, { initialFocusRef, onEscape });
return (
<ModalOverlay
targetElement={targetElement}
layer={layer}
backdrop={backdrop}
className={overlayClassName}
>
<ModalSurface
ref={surfaceRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
padding={padding}
align={align}
elevation={elevation}
className={className}
{...props}
>
{children}
</ModalSurface>
</ModalOverlay>
);
}
const MODAL_FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
function useModalFocusTrap<TModal extends HTMLElement, TInitial extends HTMLElement>(
modalRef: RefObject<TModal | null>,
{
initialFocusRef,
onEscape,
}: {
initialFocusRef?: RefObject<TInitial | null>;
onEscape?: () => void;
} = {},
): void {
useEffect(() => {
initialFocusRef?.current?.focus();
}, [initialFocusRef]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const modal = modalRef.current;
if (!modal) return;
if (event.key !== 'Escape' && event.key !== 'Tab') return;
// A native modal <dialog> (ThemeStoreDialog, ThemeDebuggerDialog) sits in
// the browser's top layer and owns the keyboard with its own Tab/Escape
// handling. This listener is on window in the capture phase, so without
// this bail it would preventDefault every Tab and cycle focus back into
// the modal underneath — leaving the dialog's own fields untabbable.
// Kept below the key filter: it is a full-document query, and this
// handler runs for every keystroke while any modal is mounted.
if (document.querySelector('dialog[open]')) return;
if (event.key === 'Escape') {
if (onEscape) {
event.preventDefault();
event.stopPropagation();
onEscape();
}
return;
}
if (event.key !== 'Tab') return;
event.preventDefault();
stepFocus(
Array.from(modal.querySelectorAll<HTMLElement>(MODAL_FOCUSABLE_SELECTOR)),
event.shiftKey ? -1 : 1,
);
};
window.addEventListener('keydown', handleKeyDown, true);
return () => window.removeEventListener('keydown', handleKeyDown, true);
}, [modalRef, onEscape]);
}
// Chrome buttons: icon-only and labeled triggers used in the standalone app
// bar, plus the Windows/Linux native-style window controls. All inherit text
// color from the surrounding chrome so they tint with the active/inactive
// header palette — except `windowClose`, whose hover red matches the native
// OS close button across themes.
export const chromeButton = tv({
base: 'flex items-center transition-colors',
variants: {
kind: {
icon: 'h-5 min-w-5 justify-center rounded hover:bg-current/10',
labeled: 'h-5 min-w-5 gap-1 rounded px-1.5 text-xs text-inherit hover:bg-current/10',
window: 'w-11 justify-center text-inherit hover:bg-current/10',
windowClose: 'w-11 justify-center text-inherit hover:bg-[#b92a1b] hover:text-white',
},
},
defaultVariants: { kind: 'icon' },
});
export type ChromeButtonVariants = VariantProps<typeof chromeButton>;
// Buttons that sit on a previewed theme rather than the host's: every theme
// picker surface paints a *candidate* palette, so these inherit `currentColor`
// where `modalIconButton` would reach for `text-muted`,
// `hover:bg-foreground/10`, or `outline-focus-ring` — host tokens that would
// read as a foreign color on the preview. Hover feedback is the label
// underline, not a fill, for the same reason (docs/specs/theme.md).
export const themePreviewButton = tv({
base: 'flex min-w-0 items-center rounded transition-colors focus-visible:outline-2 focus-visible:outline-current',
variants: {
kind: {
trigger: 'gap-2 px-2 py-1 font-mono text-sm',
// Inset so the ring stays inside the entry's own clipped corners.
entry: 'min-h-8 flex-1 py-1 pl-2 text-left text-sm pointer-coarse:min-h-11 focus-visible:-outline-offset-3',
uninstall: 'mx-1 min-h-8 shrink-0 justify-center px-1.5 pointer-coarse:min-h-11 hover:opacity-65 focus-visible:-outline-offset-3',
},
},
});
export type ThemePreviewButtonVariants = VariantProps<typeof themePreviewButton>;
/** Pane-header zoom control. The zoomed pane swaps its header foreground and
* background tokens so Unzoom reads as the active escape hatch in every theme. */
export function paneZoomButtonClass(zoomed: boolean, activeHeader: boolean): string {
return clsx(
// The zoom pill's tokens flip with the header palette, so it rides the same
// crossfade timing as the header background instead of the default transition.
`flex h-5 min-w-5 items-center justify-center rounded ${HEADER_PALETTE_TRANSITION_CLASS}`,
zoomed
? activeHeader
? 'bg-header-active-fg text-header-active-bg'
: 'bg-header-inactive-fg text-header-inactive-bg'
: 'hover:bg-current/10',
);
}
/** Keyboard shortcut rendered as `[keys]` in muted color. Use everywhere key
* bindings appear in UI text so the bracket convention is consistent. */
export function Shortcut({
children,
className,
}: {
children: ReactNode;
className?: string;
}) {
return <span className={clsx('text-muted', className)}>[{children}]</span>;
}
/** Render a string with any `[...]` segments replaced by <Shortcut>. */
export function renderShortcuts(text: string): ReactNode[] {
const parts: ReactNode[] = [];
const regex = /\[([^\]]+)\]/g;
let lastIndex = 0;
let idx = 0;
let match: RegExpExecArray | null;
while ((match = regex.exec(text)) !== null) {
if (match.index > lastIndex) {
parts.push(text.slice(lastIndex, match.index));
}
parts.push(<Shortcut key={idx++}>{match[1]}</Shortcut>);
lastIndex = regex.lastIndex;
}
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts;
}