@openartifactsai/ui 0.0.0-stage → 0.23.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +82 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +29 -0
  7. package/src/clicks.d.ts +63 -0
  8. package/src/clicks.js +75 -0
  9. package/src/cn.d.ts +3 -0
  10. package/src/cn.js +5 -0
  11. package/src/color-picker.d.ts +98 -0
  12. package/src/color-picker.js +395 -0
  13. package/src/color.d.ts +150 -0
  14. package/src/color.js +543 -0
  15. package/src/crash-boundary.d.ts +29 -0
  16. package/src/crash-boundary.js +32 -0
  17. package/src/data/google-fonts.json +1775 -0
  18. package/src/drag-cover.d.ts +48 -0
  19. package/src/drag-cover.js +41 -0
  20. package/src/effect-editors.d.ts +48 -0
  21. package/src/effect-editors.js +230 -0
  22. package/src/effects.d.ts +118 -0
  23. package/src/effects.js +425 -0
  24. package/src/escape-to-popup.d.ts +53 -0
  25. package/src/escape-to-popup.js +78 -0
  26. package/src/field-announce.d.ts +28 -0
  27. package/src/field-announce.js +43 -0
  28. package/src/fields.d.ts +176 -0
  29. package/src/fields.js +377 -0
  30. package/src/focusables.d.ts +50 -0
  31. package/src/focusables.js +61 -0
  32. package/src/font-picker.d.ts +62 -0
  33. package/src/font-picker.js +242 -0
  34. package/src/fonts.d.ts +121 -0
  35. package/src/fonts.js +273 -0
  36. package/src/history-diff.d.ts +64 -0
  37. package/src/history-diff.js +151 -0
  38. package/src/history.d.ts +95 -0
  39. package/src/history.js +160 -0
  40. package/src/index.d.ts +38 -0
  41. package/src/index.js +38 -0
  42. package/src/key-chord.d.ts +74 -0
  43. package/src/key-chord.js +228 -0
  44. package/src/keys.d.ts +142 -0
  45. package/src/keys.js +172 -0
  46. package/src/layout.d.ts +74 -0
  47. package/src/layout.js +173 -0
  48. package/src/link-card-view.d.ts +97 -0
  49. package/src/link-card-view.js +175 -0
  50. package/src/link-card.d.ts +136 -0
  51. package/src/link-card.js +158 -0
  52. package/src/menu-shortcuts.d.ts +31 -0
  53. package/src/menu-shortcuts.js +91 -0
  54. package/src/menu.d.ts +120 -0
  55. package/src/menu.js +100 -0
  56. package/src/number-entry.d.ts +140 -0
  57. package/src/number-entry.js +202 -0
  58. package/src/number-limits.d.ts +2 -0
  59. package/src/number-limits.js +2 -0
  60. package/src/number-wheel.d.ts +29 -0
  61. package/src/number-wheel.js +27 -0
  62. package/src/numbers.d.ts +28 -0
  63. package/src/numbers.js +124 -0
  64. package/src/overlays.d.ts +71 -0
  65. package/src/overlays.js +131 -0
  66. package/src/pressed.d.ts +5 -0
  67. package/src/pressed.js +10 -0
  68. package/src/scroll.d.ts +24 -0
  69. package/src/scroll.js +111 -0
  70. package/src/scrub-number-field.d.ts +79 -0
  71. package/src/scrub-number-field.js +254 -0
  72. package/src/select-announce.d.ts +50 -0
  73. package/src/select-announce.js +71 -0
  74. package/src/slider-session.d.ts +43 -0
  75. package/src/slider-session.js +39 -0
  76. package/src/styles.css +96 -0
  77. package/src/tab-strip-layout.d.ts +76 -0
  78. package/src/tab-strip-layout.js +111 -0
  79. package/src/tab-strip.d.ts +73 -0
  80. package/src/tab-strip.js +498 -0
  81. package/src/text-area-view.d.ts +35 -0
  82. package/src/text-area-view.js +142 -0
  83. package/src/text-area.d.ts +38 -0
  84. package/src/text-area.js +51 -0
  85. package/src/theme.css +34 -0
  86. package/src/toast-fit.d.ts +21 -0
  87. package/src/toast-fit.js +30 -0
  88. package/src/toast-tone.d.ts +27 -0
  89. package/src/toast-tone.js +22 -0
  90. package/src/tooltip.d.ts +23 -0
  91. package/src/tooltip.js +18 -0
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Number text for {@link ScrubNumberField}: reading what was typed (a
3
+ * number, a unit, simple arithmetic) and rounding to a step. No DOM.
4
+ */
5
+ /** A typed number and the unit typed after it, if any. */
6
+ export interface TypedNumber {
7
+ value: number;
8
+ /** The unit written after the number (`px`, `%`…), or undefined. */
9
+ unit?: string;
10
+ }
11
+ /**
12
+ * Reads typed text: `12`, `12px`, `-4.5`, `.5`, or arithmetic with `+ - * /`
13
+ * and parentheses (`10 + 4`, `100/3`, `(8+2)*2px`). A unit may follow the
14
+ * whole expression or its first number. Null when the text is not that.
15
+ */
16
+ export declare function evaluateNumberInput(text: string): TypedNumber | null;
17
+ /** Decimals needed to show multiples of `step` (0.25 → 2). */
18
+ export declare function stepDecimals(step: number): number;
19
+ /** Rounds `value` to `decimals` places, without `-0`. */
20
+ export declare function roundTo(value: number, decimals: number): number;
21
+ /** Clamps into `[min, max]` (either bound optional). */
22
+ export declare function clampNumber(value: number, min?: number, max?: number): number;
23
+ /** The nearest multiple of `step` (no snapping for a step that is not a positive number). */
24
+ export declare function snapToStep(value: number, step: number): number;
25
+ /** Where stepping starts in an empty (or mixed) field: 0, kept inside `[min, max]`. */
26
+ export declare function stepStart(min?: number, max?: number): number;
27
+ /** Formats a value for a number field: rounded, no trailing zeros. */
28
+ export declare function formatNumber(value: number, decimals: number): string;
package/src/numbers.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Number text for {@link ScrubNumberField}: reading what was typed (a
3
+ * number, a unit, simple arithmetic) and rounding to a step. No DOM.
4
+ */
5
+ /**
6
+ * Reads typed text: `12`, `12px`, `-4.5`, `.5`, or arithmetic with `+ - * /`
7
+ * and parentheses (`10 + 4`, `100/3`, `(8+2)*2px`). A unit may follow the
8
+ * whole expression or its first number. Null when the text is not that.
9
+ */
10
+ export function evaluateNumberInput(text) {
11
+ const source = text.trim().replace(/,/g, '.');
12
+ if (!source)
13
+ return null;
14
+ // Units: letters or % after a number; all of them must be the same.
15
+ let unit;
16
+ const bare = source.replace(/(\d|\.)\s*([a-z]+|%)/gi, (_match, digit, u) => {
17
+ const lower = u.toLowerCase();
18
+ if (unit !== undefined && unit !== lower)
19
+ unit = '\u0000';
20
+ else
21
+ unit = lower;
22
+ return digit;
23
+ });
24
+ if (unit === '\u0000')
25
+ return null;
26
+ if (!/^[\d.\s+\-*/()]+$/.test(bare))
27
+ return null;
28
+ let at = 0;
29
+ const peek = () => {
30
+ while (bare[at] === ' ')
31
+ at++;
32
+ return bare[at];
33
+ };
34
+ const number = () => {
35
+ const match = /^(?:\d+\.?\d*|\.\d+)/.exec(bare.slice(at));
36
+ if (!match)
37
+ return null;
38
+ at += match[0].length;
39
+ return Number(match[0]);
40
+ };
41
+ const factor = () => {
42
+ const ch = peek();
43
+ if (ch === '-' || ch === '+') {
44
+ at++;
45
+ const inner = factor();
46
+ return inner === null ? null : ch === '-' ? -inner : inner;
47
+ }
48
+ if (ch === '(') {
49
+ at++;
50
+ const inner = sum();
51
+ if (inner === null || peek() !== ')')
52
+ return null;
53
+ at++;
54
+ return inner;
55
+ }
56
+ return number();
57
+ };
58
+ const product = () => {
59
+ let left = factor();
60
+ while (left !== null && (peek() === '*' || peek() === '/')) {
61
+ const op = bare[at++];
62
+ const right = factor();
63
+ if (right === null)
64
+ return null;
65
+ left = op === '*' ? left * right : left / right;
66
+ }
67
+ return left;
68
+ };
69
+ const sum = () => {
70
+ let left = product();
71
+ while (left !== null && (peek() === '+' || peek() === '-')) {
72
+ const op = bare[at++];
73
+ const right = product();
74
+ if (right === null)
75
+ return null;
76
+ left = op === '+' ? left + right : left - right;
77
+ }
78
+ return left;
79
+ };
80
+ const value = sum();
81
+ if (value === null || peek() !== undefined || !Number.isFinite(value))
82
+ return null;
83
+ return unit === undefined ? { value } : { value, unit };
84
+ }
85
+ /** Decimals needed to show multiples of `step` (0.25 → 2). */
86
+ export function stepDecimals(step) {
87
+ if (!Number.isFinite(step) || step <= 0)
88
+ return 0;
89
+ const text = String(step);
90
+ const exp = /e-(\d+)$/.exec(text);
91
+ if (exp)
92
+ return Number(exp[1]);
93
+ const dot = text.indexOf('.');
94
+ return dot < 0 ? 0 : text.length - dot - 1;
95
+ }
96
+ /** Rounds `value` to `decimals` places, without `-0`. */
97
+ export function roundTo(value, decimals) {
98
+ const factor = 10 ** decimals;
99
+ const out = Math.round(value * factor) / factor;
100
+ return Object.is(out, -0) ? 0 : out;
101
+ }
102
+ /** Clamps into `[min, max]` (either bound optional). */
103
+ export function clampNumber(value, min, max) {
104
+ let out = value;
105
+ if (min !== undefined && out < min)
106
+ out = min;
107
+ if (max !== undefined && out > max)
108
+ out = max;
109
+ return out;
110
+ }
111
+ /** The nearest multiple of `step` (no snapping for a step that is not a positive number). */
112
+ export function snapToStep(value, step) {
113
+ if (!Number.isFinite(step) || step <= 0)
114
+ return value;
115
+ return Math.round(value / step) * step;
116
+ }
117
+ /** Where stepping starts in an empty (or mixed) field: 0, kept inside `[min, max]`. */
118
+ export function stepStart(min, max) {
119
+ return clampNumber(0, min, max);
120
+ }
121
+ /** Formats a value for a number field: rounded, no trailing zeros. */
122
+ export function formatNumber(value, decimals) {
123
+ return String(roundTo(value, decimals));
124
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Popover and dialog wrappers.
3
+ */
4
+ import { Dialog as BaseDialog } from '@base-ui/react/dialog';
5
+ import { type KeyboardEvent, type ReactElement, type ReactNode } from 'react';
6
+ /** Props of {@link Popover}. */
7
+ export interface PopoverProps {
8
+ trigger: ReactElement<Record<string, unknown>>;
9
+ children: ReactNode;
10
+ side?: 'top' | 'bottom' | 'left' | 'right';
11
+ align?: 'start' | 'center' | 'end';
12
+ open?: boolean;
13
+ onOpenChange?: (open: boolean) => void;
14
+ className?: string;
15
+ }
16
+ /** A floating panel anchored to a trigger, on any of its four sides. A held Enter opens it once. */
17
+ export declare function Popover({ trigger, children, side, align, open, onOpenChange, className }: PopoverProps): import("react/jsx-runtime").JSX.Element;
18
+ /** Marks the part of a dialog that Select All selects (the whole dialog when none does). */
19
+ export declare const SELECT_ALL_ATTRIBUTE = "data-select-all";
20
+ /** Props of {@link Dialog}. */
21
+ export interface DialogProps {
22
+ open: boolean;
23
+ onOpenChange: (open: boolean) => void;
24
+ title: ReactNode;
25
+ description?: ReactNode;
26
+ children?: ReactNode;
27
+ /** Footer buttons; defaults to none. */
28
+ footer?: ReactNode;
29
+ className?: string;
30
+ /** Called once the dialog has finished appearing or disappearing. */
31
+ onOpenChangeComplete?: (open: boolean) => void;
32
+ /** Sees every keydown and keyup inside the dialog first (capture phase). */
33
+ onKeyCapture?: (event: KeyboardEvent<HTMLElement>) => void;
34
+ /** The element focused when the dialog opens; by default the first one that takes focus. */
35
+ initialFocus?: BaseDialog.Popup.Props['initialFocus'];
36
+ /** The element focused when the dialog closes; by default the one focused before it opened. */
37
+ finalFocus?: BaseDialog.Popup.Props['finalFocus'];
38
+ }
39
+ /**
40
+ * A modal dialog. Closed by a held Enter, the Enter's repeats don't press
41
+ * what gets the focus next. With a menu or popover open in it, Escape closes
42
+ * that first, wherever the focus is.
43
+ */
44
+ export declare function Dialog({ open, onOpenChange, title, description, children, footer, className, onOpenChangeComplete, onKeyCapture, initialFocus, finalFocus }: DialogProps): import("react/jsx-runtime").JSX.Element;
45
+ /** Props of {@link ConfirmDialog}. */
46
+ export interface ConfirmDialogProps {
47
+ open: boolean;
48
+ onOpenChange: (open: boolean) => void;
49
+ title: ReactNode;
50
+ description?: ReactNode;
51
+ confirmLabel?: string;
52
+ /** The Cancel button's words (default `Cancel`): the page's language. */
53
+ cancelLabel?: string;
54
+ danger?: boolean;
55
+ /**
56
+ * With `danger`: while the dialog appears, Enter and Space from the
57
+ * keyboard do nothing in it, so the press that opened it (a held Enter or
58
+ * Delete) can't also confirm. Pointer clicks and Escape work as usual.
59
+ */
60
+ guardEarlyPress?: boolean;
61
+ /**
62
+ * The element focused when it opens: `'cancel'` for the Cancel button; `'confirm'` for the confirm button, or the
63
+ * dialog itself while that button is scrolled out of view; else as {@link DialogProps.initialFocus}.
64
+ */
65
+ initialFocus?: 'cancel' | 'confirm' | DialogProps['initialFocus'];
66
+ /** The element focused when it closes, as {@link DialogProps.finalFocus}. */
67
+ finalFocus?: DialogProps['finalFocus'];
68
+ onConfirm: () => void;
69
+ }
70
+ /** A yes/no dialog. */
71
+ export declare function ConfirmDialog({ open, onOpenChange, title, description, confirmLabel, cancelLabel, danger, guardEarlyPress, initialFocus, finalFocus, onConfirm }: ConfirmDialogProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,131 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * Popover and dialog wrappers.
4
+ */
5
+ import { Dialog as BaseDialog } from '@base-ui/react/dialog';
6
+ import { Popover as BasePopover } from '@base-ui/react/popover';
7
+ import { X } from 'lucide-react';
8
+ import { useCallback, useEffect, useRef, useState } from 'react';
9
+ import { Button } from "./button.js";
10
+ import { cn } from "./cn.js";
11
+ import { fullyInView } from "./focusables.js";
12
+ import { createEscapeHandoff, EscapeHandoffContext, handEscapeToPopup, useEscapeHandoffRef } from "./escape-to-popup.js";
13
+ import { blocksEarlyPress, guardHeldActivation, isSelectAllLetter, preventRepeatedActivation } from "./keys.js";
14
+ import { POPUP_CLASS } from "./menu.js";
15
+ /** A floating panel anchored to a trigger, on any of its four sides. A held Enter opens it once. */
16
+ export function Popover({ trigger, children, side = 'bottom', align = 'center', open, onOpenChange, className }) {
17
+ return (_jsxs(BasePopover.Root, { open: open, onOpenChange: onOpenChange ? (next) => onOpenChange(next) : undefined, children: [_jsx(BasePopover.Trigger, { render: trigger, onKeyDown: preventRepeatedActivation }), _jsx(BasePopover.Portal, { children: _jsx(BasePopover.Positioner, { side: side, align: align, sideOffset: 8, className: "z-[1000]", children: _jsx(PopoverPopup, { className: className, children: children }) }) })] }));
18
+ }
19
+ /** A popover's panel: inside a dialog, it takes the Escapes typed outside it while it is open. */
20
+ function PopoverPopup({ className, children }) {
21
+ const handoffRef = useEscapeHandoffRef();
22
+ return (_jsx(BasePopover.Popup, { ref: handoffRef, className: cn(POPUP_CLASS, 'p-3', className), children: children }));
23
+ }
24
+ /** Marks the part of a dialog that Select All selects (the whole dialog when none does). */
25
+ export const SELECT_ALL_ATTRIBUTE = 'data-select-all';
26
+ /**
27
+ * Select All in an open dialog selects the dialog, not the page behind it: a selection that would start on the page
28
+ * body is replaced by the dialog's `[data-select-all]` part (or all of it), and a selection left outside the dialog
29
+ * is cleared before ⌘A / Ctrl+A. Only the topmost dialog (no nested one open over it) does this.
30
+ */
31
+ function useDialogSelectAll(popupRef, open) {
32
+ useEffect(() => {
33
+ const popup = popupRef.current;
34
+ if (!open || popup === null)
35
+ return;
36
+ const doc = popup.ownerDocument;
37
+ const topmost = () => popup.isConnected && popup.hasAttribute('data-open') && !popup.hasAttribute('data-nested-dialog-open');
38
+ const onSelectStart = (event) => {
39
+ if (event.target !== doc.body || !topmost())
40
+ return;
41
+ event.preventDefault();
42
+ doc.getSelection()?.selectAllChildren(popup.querySelector(`[${SELECT_ALL_ATTRIBUTE}]`) ?? popup);
43
+ };
44
+ const onKeyDown = (event) => {
45
+ if (!(event.metaKey || event.ctrlKey) || !isSelectAllLetter(event) || !topmost())
46
+ return;
47
+ const selection = doc.getSelection();
48
+ const anchor = selection?.anchorNode ?? null;
49
+ const anchorElement = anchor === null ? null : anchor.nodeType === Node.ELEMENT_NODE ? anchor : anchor.parentElement;
50
+ if (anchorElement !== null && !popup.contains(anchorElement))
51
+ selection?.removeAllRanges();
52
+ };
53
+ doc.addEventListener('selectstart', onSelectStart);
54
+ doc.addEventListener('keydown', onKeyDown, true);
55
+ return () => {
56
+ doc.removeEventListener('selectstart', onSelectStart);
57
+ doc.removeEventListener('keydown', onKeyDown, true);
58
+ };
59
+ }, [popupRef, open]);
60
+ }
61
+ /**
62
+ * A modal dialog. Closed by a held Enter, the Enter's repeats don't press
63
+ * what gets the focus next. With a menu or popover open in it, Escape closes
64
+ * that first, wherever the focus is.
65
+ */
66
+ export function Dialog({ open, onOpenChange, title, description, children, footer, className, onOpenChangeComplete, onKeyCapture, initialFocus, finalFocus }) {
67
+ const enterHeld = useRef(false);
68
+ const wasOpen = useRef(open);
69
+ const [handoff] = useState(createEscapeHandoff);
70
+ const popupRef = useRef(null);
71
+ const [mounted, setMounted] = useState(false);
72
+ const popupMounted = useCallback((element) => {
73
+ popupRef.current = element;
74
+ setMounted(element !== null);
75
+ }, []);
76
+ useDialogSelectAll(popupRef, open && mounted);
77
+ useEffect(() => {
78
+ if (open === wasOpen.current)
79
+ return;
80
+ wasOpen.current = open;
81
+ if (!open && enterHeld.current)
82
+ guardHeldActivation(window, 'Enter', () => false);
83
+ enterHeld.current = false;
84
+ }, [open]);
85
+ const keyCapture = (event) => {
86
+ onKeyCapture?.(event);
87
+ if (event.key === 'Enter')
88
+ enterHeld.current = event.type === 'keydown';
89
+ };
90
+ return (_jsx(EscapeHandoffContext.Provider, { value: handoff, children: _jsx(BaseDialog.Root, { open: open, onOpenChange: (next, details) => {
91
+ if (!handEscapeToPopup(handoff, details))
92
+ onOpenChange(next);
93
+ }, onOpenChangeComplete: onOpenChangeComplete, children: _jsxs(BaseDialog.Portal, { children: [_jsx(BaseDialog.Backdrop, { className: "fixed inset-0 z-[900] bg-black/30 transition-opacity data-[starting-style]:opacity-0 data-[ending-style]:opacity-0" }), _jsxs(BaseDialog.Popup, { ref: popupMounted, className: cn('fixed left-1/2 top-1/2 z-[901] max-h-[calc(100dvh-2rem)] w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto overscroll-contain rounded-xl bg-surface p-5 text-fg shadow-popup outline-none', 'transition-[opacity,transform] data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0', className), onKeyDownCapture: keyCapture, onKeyUpCapture: keyCapture, initialFocus: initialFocus, finalFocus: finalFocus, children: [_jsxs("div", { className: "mb-3 flex items-start gap-3", children: [_jsxs("div", { className: "flex-1", children: [_jsx(BaseDialog.Title, { className: "text-[15px] font-semibold", children: title }), description ? _jsx(BaseDialog.Description, { className: "mt-1 text-fg-muted", children: description }) : null] }), _jsx(BaseDialog.Close, { "aria-label": "Close", className: "rounded-md p-1 text-fg-muted hover:bg-hover", children: _jsx(X, { className: "size-4" }) })] }), children, footer ? _jsx("div", { className: "mt-4 flex justify-end gap-2", children: footer }) : null] })] }) }) }));
94
+ }
95
+ /** The nearest box between `el` and `dialog` (the dialog included) that scrolls up and down. */
96
+ function verticalScroller(el, dialog) {
97
+ for (let at = el.parentElement; at && at !== dialog; at = at.parentElement) {
98
+ const { overflowY } = getComputedStyle(at);
99
+ if ((overflowY === 'auto' || overflowY === 'scroll') && at.scrollHeight > at.clientHeight)
100
+ return at;
101
+ }
102
+ return dialog;
103
+ }
104
+ /** The confirm button, or its dialog while the button is not wholly in view there (the dialog shows no focus ring). */
105
+ function confirmFocusTarget(button) {
106
+ const dialog = button?.closest('[role="dialog"], [role="alertdialog"]');
107
+ if (!button || !dialog)
108
+ return true;
109
+ return fullyInView(button.getBoundingClientRect(), verticalScroller(button, dialog).getBoundingClientRect()) ? button : dialog;
110
+ }
111
+ /** A yes/no dialog. */
112
+ export function ConfirmDialog({ open, onOpenChange, title, description, confirmLabel = 'Confirm', cancelLabel = 'Cancel', danger, guardEarlyPress, initialFocus, finalFocus, onConfirm }) {
113
+ const times = useRef(null);
114
+ const cancel = useRef(null);
115
+ const confirm = useRef(null);
116
+ const guarded = Boolean(danger && guardEarlyPress);
117
+ if (!open)
118
+ times.current = null;
119
+ else if (guarded && !times.current)
120
+ times.current = { opened: performance.now(), shown: null };
121
+ return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, title: title, description: description, initialFocus: initialFocus === 'cancel' ? cancel : initialFocus === 'confirm' ? () => confirmFocusTarget(confirm.current) : initialFocus, finalFocus: finalFocus, onOpenChangeComplete: guarded ? (shown) => {
122
+ if (shown && times.current && times.current.shown === null)
123
+ times.current = { ...times.current, shown: performance.now() };
124
+ } : undefined, onKeyCapture: guarded ? (event) => {
125
+ if (times.current && blocksEarlyPress(times.current, performance.now(), { key: event.key, repeat: event.repeat, isTrusted: event.nativeEvent.isTrusted }))
126
+ event.preventDefault();
127
+ } : undefined, footer: _jsxs(_Fragment, { children: [_jsx(Button, { ref: cancel, onClick: () => onOpenChange(false), children: cancelLabel }), _jsx(Button, { ref: confirm, variant: danger ? 'danger' : 'primary', onClick: () => {
128
+ onConfirm();
129
+ onOpenChange(false);
130
+ }, children: confirmLabel })] }) }));
131
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The `aria-pressed` a button writes. A button that opens a popup and is not pressed writes none: `aria-pressed="false"`
3
+ * would make it a toggle to screen readers, which then read "not pressed" on a plain menu or dialog button.
4
+ */
5
+ export declare function ariaPressed(pressed: boolean | undefined, hasPopup: boolean | string | undefined): boolean | undefined;
package/src/pressed.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The `aria-pressed` a button writes. A button that opens a popup and is not pressed writes none: `aria-pressed="false"`
3
+ * would make it a toggle to screen readers, which then read "not pressed" on a plain menu or dialog button.
4
+ */
5
+ export function ariaPressed(pressed, hasPopup) {
6
+ if (pressed !== false)
7
+ return pressed;
8
+ const opensPopup = hasPopup !== undefined && hasPopup !== false && hasPopup !== 'false';
9
+ return opensPopup ? undefined : false;
10
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Scrolling regions that keyboard users can reach.
3
+ */
4
+ import { type HTMLAttributes, type RefObject } from 'react';
5
+ /**
6
+ * Whether the element's content overflows an axis that scrolls, kept current
7
+ * as the element or its children resize and as children come and go.
8
+ */
9
+ export declare function useHasScrollOverflow(ref: RefObject<HTMLElement | null>): boolean;
10
+ /** Props of {@link ScrollBody}. */
11
+ export interface ScrollBodyProps extends HTMLAttributes<HTMLDivElement> {
12
+ /**
13
+ * Accessible name used when the region becomes a tab stop. Defaults to the
14
+ * enclosing dialog's title, else "Panel content".
15
+ */
16
+ label?: string;
17
+ }
18
+ /**
19
+ * A scrolling region (give it a max height and `overflow-auto`). When its
20
+ * content overflows and holds no tab stop of its own, it becomes a named,
21
+ * focusable group so keyboard users can Tab to it and scroll it; otherwise
22
+ * it stays out of the tab order.
23
+ */
24
+ export declare const ScrollBody: import("react").ForwardRefExoticComponent<ScrollBodyProps & import("react").RefAttributes<HTMLDivElement>>;
package/src/scroll.js ADDED
@@ -0,0 +1,111 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * Scrolling regions that keyboard users can reach.
4
+ */
5
+ import { forwardRef, useCallback, useLayoutEffect, useRef, useState } from 'react';
6
+ import { cn } from "./cn.js";
7
+ import { scrollsOverflow, tabbableElements } from "./focusables.js";
8
+ /**
9
+ * Whether the element's content overflows an axis that scrolls, kept current
10
+ * as the element or its children resize and as children come and go.
11
+ */
12
+ export function useHasScrollOverflow(ref) {
13
+ const [overflowing, setOverflowing] = useState(false);
14
+ useLayoutEffect(() => {
15
+ const element = ref.current;
16
+ const view = element?.ownerDocument.defaultView;
17
+ if (!element || !view)
18
+ return;
19
+ const measure = () => {
20
+ const style = view.getComputedStyle(element);
21
+ setOverflowing(scrollsOverflow({
22
+ scrollWidth: element.scrollWidth,
23
+ clientWidth: element.clientWidth,
24
+ scrollHeight: element.scrollHeight,
25
+ clientHeight: element.clientHeight,
26
+ overflowX: style.overflowX,
27
+ overflowY: style.overflowY,
28
+ }));
29
+ };
30
+ measure();
31
+ if (typeof view.ResizeObserver !== 'function')
32
+ return;
33
+ const resize = new view.ResizeObserver(measure);
34
+ const watched = new Set();
35
+ const watch = (node) => {
36
+ if (node.nodeType !== 1)
37
+ return;
38
+ const child = node;
39
+ // `display: contents` boxes have no size of their own; watch what they hold.
40
+ if (view.getComputedStyle(child).display === 'contents') {
41
+ child.childNodes.forEach(watch);
42
+ return;
43
+ }
44
+ if (!watched.has(child)) {
45
+ watched.add(child);
46
+ resize.observe(child);
47
+ }
48
+ };
49
+ resize.observe(element);
50
+ element.childNodes.forEach(watch);
51
+ const mutations = new view.MutationObserver((records) => {
52
+ for (const record of records)
53
+ record.addedNodes.forEach(watch);
54
+ for (const child of watched) {
55
+ if (!element.contains(child)) {
56
+ resize.unobserve(child);
57
+ watched.delete(child);
58
+ }
59
+ }
60
+ measure();
61
+ });
62
+ mutations.observe(element, { childList: true, subtree: true, characterData: true });
63
+ return () => {
64
+ resize.disconnect();
65
+ mutations.disconnect();
66
+ };
67
+ }, [ref]);
68
+ return overflowing;
69
+ }
70
+ /**
71
+ * A scrolling region (give it a max height and `overflow-auto`). When its
72
+ * content overflows and holds no tab stop of its own, it becomes a named,
73
+ * focusable group so keyboard users can Tab to it and scroll it; otherwise
74
+ * it stays out of the tab order.
75
+ */
76
+ export const ScrollBody = forwardRef(function ScrollBody({ label, className, ...rest }, forwardedRef) {
77
+ const ref = useRef(null);
78
+ const setRef = useCallback((node) => {
79
+ ref.current = node;
80
+ if (typeof forwardedRef === 'function')
81
+ forwardedRef(node);
82
+ else if (forwardedRef)
83
+ forwardedRef.current = node;
84
+ }, [forwardedRef]);
85
+ const overflowing = useHasScrollOverflow(ref);
86
+ const [needsStop, setNeedsStop] = useState(false);
87
+ const [labelledBy, setLabelledBy] = useState(null);
88
+ useLayoutEffect(() => {
89
+ const body = ref.current;
90
+ const view = body?.ownerDocument.defaultView;
91
+ if (!overflowing || !body || !view)
92
+ return;
93
+ const update = () => {
94
+ setNeedsStop(tabbableElements(body).length === 0);
95
+ setLabelledBy(body.closest('[role="dialog"], [role="alertdialog"]')?.getAttribute('aria-labelledby') ?? null);
96
+ };
97
+ update();
98
+ const observer = new view.MutationObserver(update);
99
+ observer.observe(body, { childList: true, subtree: true, attributes: true, attributeFilter: ['tabindex', 'disabled', 'hidden', 'href', 'contenteditable'] });
100
+ return () => observer.disconnect();
101
+ }, [overflowing]);
102
+ const focusable = overflowing && needsStop;
103
+ return (_jsx("div", { ref: setRef, ...(focusable
104
+ ? {
105
+ role: 'group',
106
+ tabIndex: 0,
107
+ 'aria-labelledby': label === undefined ? (labelledBy ?? undefined) : undefined,
108
+ 'aria-label': label ?? (labelledBy === null ? 'Panel content' : undefined),
109
+ }
110
+ : {}), className: cn(focusable && 'focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent', className), ...rest }));
111
+ });
@@ -0,0 +1,79 @@
1
+ /**
2
+ * {@link ScrubNumberField}: a number field whose label is dragged sideways
3
+ * to change the value, the way design tools do it.
4
+ */
5
+ import { type ReactNode } from 'react';
6
+ import { type NumberLimit } from './number-entry.js';
7
+ /** Props of {@link ScrubNumberField}. */
8
+ export interface ScrubNumberFieldProps {
9
+ /** The value; null shows the field empty (with `placeholder`). */
10
+ value: number | null;
11
+ /** Several selected things differ: show "Mixed" until a value is entered. */
12
+ mixed?: boolean;
13
+ /** Live value while scrubbing or stepping with held keys. */
14
+ onChange?: (value: number) => void;
15
+ /**
16
+ * Final value: typed and committed (Enter or blur), stepped with a key, or
17
+ * at the end of a scrub. `unit` is set when the user typed one of `units`.
18
+ */
19
+ onCommit: (value: number, unit?: string) => void;
20
+ /** Accessible name (required: the label may be an icon). */
21
+ 'aria-label': string;
22
+ /** The drag handle at the start: a letter (`W`, `X`) or an icon. Without it the field has no scrub handle. */
23
+ label?: ReactNode;
24
+ /** Unit shown after the number (`px`, `%`, `°`). Typing it is allowed. */
25
+ unit?: string;
26
+ /** Other units the user may type (`em`, `rem`); a typed one is passed to `onCommit`. */
27
+ units?: readonly string[];
28
+ min?: number;
29
+ max?: number;
30
+ /** Arrow-key and scrub step (default 1). */
31
+ step?: number;
32
+ /** Shift + arrow and Page Up/Down step (default 10 × step). */
33
+ largeStep?: number;
34
+ /** Alt + arrow step (default step / 10). */
35
+ smallStep?: number;
36
+ /** Decimals kept (default: those of the smallest step). */
37
+ precision?: number;
38
+ /** Pixels of drag per step (default 2). */
39
+ pixelsPerStep?: number;
40
+ placeholder?: string;
41
+ disabled?: boolean;
42
+ className?: string;
43
+ /** Tooltip of the drag handle. */
44
+ title?: string;
45
+ /**
46
+ * Told when the field changed what the user typed: held it at a bound, or
47
+ * (in a field whose minimum is zero or more) dropped a leading minus sign.
48
+ * Called once per commit or key with every change, in order, instead of
49
+ * the field saying it.
50
+ */
51
+ onLimit?: (limits: readonly NumberLimit[]) => void;
52
+ /**
53
+ * Typed text that is no number, or carries a unit the field does not take,
54
+ * changes nothing and the field says so ("takes a number in px", naming
55
+ * `unit` or else the first of `units`). Without it such text is put back
56
+ * silently.
57
+ */
58
+ strict?: boolean;
59
+ }
60
+ /**
61
+ * A number field with a drag-to-scrub label.
62
+ *
63
+ * - Drag the label sideways to scrub (Shift: large steps, Alt: small
64
+ * steps); values land on multiples of `step` unless Alt is held. Escape
65
+ * during a drag puts the value back; the end of a drag leaves the field
66
+ * focused with its text selected. Pressing the label commits any other
67
+ * field being typed in first.
68
+ * - Arrow Up/Down step (Shift ×10, Alt ÷10), Page Up/Down take large
69
+ * steps, Home/End go to `min`/`max`. An empty or mixed field steps
70
+ * from 0 (kept within `min`/`max`).
71
+ * - Typing accepts arithmetic (`12*2`, `100/3`) and a unit; Enter or blur
72
+ * commits, Escape reverts. ⌘S / Ctrl+S commits before the page saves.
73
+ * - When `min` is zero or more, a minus sign can't start the number: the
74
+ * key does nothing there, and typed text that starts with one keeps its
75
+ * number without it. The field says that, and typed values held at
76
+ * `min` or `max`, to screen readers, unless `onLimit` takes them over.
77
+ * - `mixed` shows "Mixed" until something is entered.
78
+ */
79
+ export declare function ScrubNumberField({ value, mixed, onChange, onCommit, label, unit, units, min, max, step, largeStep, smallStep, precision, pixelsPerStep, placeholder, disabled, className, title, onLimit, strict, ...aria }: ScrubNumberFieldProps): import("react/jsx-runtime").JSX.Element;