@tangible/ui 0.2.19 → 0.2.21

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 (36) hide show
  1. package/components/Accordion/Accordion.d.ts +1 -1
  2. package/components/Accordion/Accordion.js +40 -12
  3. package/components/Accordion/AccordionContext.d.ts +2 -1
  4. package/components/Accordion/AccordionContext.js +25 -2
  5. package/components/Accordion/index.d.ts +2 -1
  6. package/components/Accordion/index.js +1 -0
  7. package/components/Accordion/types.d.ts +42 -3
  8. package/components/ColorPicker/ColorField.d.ts +25 -1
  9. package/components/ColorPicker/ColorField.js +9 -3
  10. package/components/ColorPicker/index.d.ts +1 -1
  11. package/components/Modal/Modal.d.ts +36 -2
  12. package/components/Modal/Modal.js +40 -11
  13. package/components/Modal/index.d.ts +1 -1
  14. package/components/MoveHandle/MoveHandle.js +25 -11
  15. package/components/MoveHandle/types.d.ts +9 -3
  16. package/components/Toast/Toast.d.ts +14 -0
  17. package/components/Toast/Toast.js +85 -19
  18. package/components/index.d.ts +4 -4
  19. package/components/index.js +1 -1
  20. package/figma-tokens.json +2 -2
  21. package/package.json +9 -1
  22. package/skills/building-with-tui/SKILL.md +29 -2
  23. package/styles/all.css +1 -1
  24. package/styles/all.expanded.css +65 -14
  25. package/styles/all.expanded.unlayered.css +65 -14
  26. package/styles/all.unlayered.css +1 -1
  27. package/styles/components/color-picker.scss +58 -4
  28. package/styles/components/modal.scss +31 -1
  29. package/styles/components/move-handle.scss +20 -4
  30. package/styles/components/toast.scss +16 -0
  31. package/styles/core.css +1 -1
  32. package/styles/core.unlayered.css +1 -1
  33. package/styles/index.scss +7 -1
  34. package/tui-manifest.json +49 -7
  35. package/utils/color/contrast.d.ts +17 -0
  36. package/utils/color/contrast.js +26 -0
@@ -10,7 +10,7 @@ declare function AccordionItem({ value, disabled, headingLevel, children, classN
10
10
  declare namespace AccordionItem {
11
11
  var displayName: string;
12
12
  }
13
- declare function AccordionTrigger({ asChild, 'aria-label': ariaLabel, children, className }: AccordionTriggerProps): import("react/jsx-runtime").JSX.Element;
13
+ declare function AccordionTrigger({ asChild, unstyled, 'aria-label': ariaLabel, children, className, }: AccordionTriggerProps): import("react/jsx-runtime").JSX.Element;
14
14
  declare namespace AccordionTrigger {
15
15
  var displayName: string;
16
16
  }
@@ -26,8 +26,13 @@ function AccordionRoot(props) {
26
26
  }
27
27
  function AccordionSingle({ value: controlledValue, defaultValue, onValueChange, collapsible = false, variant, children, className, registerTrigger, getTriggers, }) {
28
28
  const [internalValue, setInternalValue] = useState(defaultValue);
29
- const isControlled = controlledValue !== undefined;
30
- const currentValue = isControlled ? controlledValue : internalValue;
29
+ // `null` is the controlled "nothing open" — `undefined` is uncontrolled.
30
+ // Locked at mount (the controlled→uncontrolled gotcha): `onValueChange`
31
+ // reports `undefined` on collapse, so a consumer wiring it straight into
32
+ // `useState<string | null>` feeds `undefined` back here. After mount that
33
+ // must read as "controlled, nothing open", not as a silent mode switch.
34
+ const isControlled = useRef(controlledValue !== undefined).current;
35
+ const currentValue = isControlled ? (controlledValue ?? undefined) : internalValue;
31
36
  const isOpen = useCallback((itemValue) => currentValue === itemValue, [currentValue]);
32
37
  const toggle = useCallback((itemValue) => {
33
38
  let newValue;
@@ -56,10 +61,16 @@ function AccordionSingle({ value: controlledValue, defaultValue, onValueChange,
56
61
  }), [collapsible, isOpen, toggle, registerTrigger, getTriggers]);
57
62
  return (_jsx(AccordionContext.Provider, { value: contextValue, children: _jsx("div", { className: cx('tui-accordion', `is-variant-${variant}`, className), "data-type": "single", children: children }) }));
58
63
  }
64
+ // -----------------------------------------------------------------------------
65
+ // Multiple Mode
66
+ // -----------------------------------------------------------------------------
67
+ const EMPTY_VALUES = [];
59
68
  function AccordionMultiple({ value: controlledValue, defaultValue, onValueChange, variant, children, className, registerTrigger, getTriggers, }) {
60
69
  const [internalValue, setInternalValue] = useState(defaultValue ?? []);
61
- const isControlled = controlledValue !== undefined;
62
- const currentValue = isControlled ? controlledValue : internalValue;
70
+ // Locked at mount, as in single mode. A stable empty array, not `?? []`,
71
+ // so the memoised callbacks below don't re-create every render.
72
+ const isControlled = useRef(controlledValue !== undefined).current;
73
+ const currentValue = isControlled ? (controlledValue ?? EMPTY_VALUES) : internalValue;
63
74
  const isOpen = useCallback((itemValue) => currentValue.includes(itemValue), [currentValue]);
64
75
  const toggle = useCallback((itemValue) => {
65
76
  const newValue = currentValue.includes(itemValue)
@@ -103,7 +114,7 @@ function AccordionItem({ value, disabled = false, headingLevel, children, classN
103
114
  // =============================================================================
104
115
  // Accordion Trigger
105
116
  // =============================================================================
106
- function AccordionTrigger({ asChild = false, 'aria-label': ariaLabel, children, className }) {
117
+ function AccordionTrigger({ asChild = false, unstyled = false, 'aria-label': ariaLabel, children, className, }) {
107
118
  const { toggle, registerTrigger, getTriggers } = useAccordionContext();
108
119
  const { value, disabled, headingLevel, triggerId, panelId, isOpen } = useAccordionItemContext();
109
120
  const triggerRef = useRef(null);
@@ -137,13 +148,25 @@ function AccordionTrigger({ asChild = false, 'aria-label': ariaLabel, children,
137
148
  // check is only needed for asChild.)
138
149
  if (asChild && event.target !== event.currentTarget)
139
150
  return;
140
- // Enter/Space activation for asChild mode. Native <button> elements fire
141
- // click on Enter/Space automatically; role="button" elements do not.
151
+ // Enter/Space activation for asChild mode. A native <button> child fires
152
+ // click on Enter/Space itself, and that click already reaches handleClick
153
+ // — so it is left to the browser. Synthesising here too would toggle
154
+ // twice, and the old version only avoided that because preventDefault
155
+ // happened to cancel the native activation. Non-button children
156
+ // (role="button" on a div) get the synthetic activation.
142
157
  if (asChild && (event.key === 'Enter' || event.key === ' ')) {
143
- event.preventDefault();
144
- if (!disabled) {
145
- toggle(value);
158
+ // Disabled first, for every child type: the child only carries
159
+ // aria-disabled (it may not be a <button>), so a native button child
160
+ // would otherwise still turn Enter/Space into a real click — handleClick
161
+ // guards toggle(), but the child's own composed onClick would fire.
162
+ if (disabled) {
163
+ event.preventDefault();
164
+ return;
146
165
  }
166
+ if (event.currentTarget instanceof HTMLButtonElement)
167
+ return;
168
+ event.preventDefault();
169
+ toggle(value);
147
170
  return;
148
171
  }
149
172
  const triggers = getTriggers();
@@ -218,7 +241,12 @@ function AccordionTrigger({ asChild = false, 'aria-label': ariaLabel, children,
218
241
  'aria-label': ariaLabel,
219
242
  'data-state': state,
220
243
  'data-disabled': disabled || undefined,
221
- className: cx('tui-accordion__trigger', className),
244
+ // Behaviour hook without paint: always present, so a consumer can key
245
+ // styles off it whether or not the paint class is applied.
246
+ 'data-tui-accordion-trigger': '',
247
+ // `unstyled` drops the row paint (flex, width 100%, padding, hover bg,
248
+ // inset focus ring) for a child that is already a styled control.
249
+ className: cx(!unstyled && 'tui-accordion__trigger', className),
222
250
  onClick: handleClick,
223
251
  onKeyDown: handleKeyDown,
224
252
  };
@@ -233,7 +261,7 @@ function AccordionTrigger({ asChild = false, 'aria-label': ariaLabel, children,
233
261
  return element;
234
262
  }
235
263
  // Default: render as button with built-in chevron indicator
236
- const button = (_jsxs("button", { ref: triggerRef, type: "button", id: triggerId, className: cx('tui-accordion__trigger', className), "aria-expanded": isOpen, "aria-controls": panelId, "aria-label": ariaLabel, disabled: disabled, "data-state": state, "data-disabled": disabled || undefined, onClick: handleClick, onKeyDown: handleKeyDown, children: [children && _jsx("span", { className: "tui-accordion__trigger-content", children: children }), _jsx(Icon, { name: "system/chevron-down", className: "tui-accordion__indicator", "aria-hidden": "true" })] }));
264
+ const button = (_jsxs("button", { ref: triggerRef, type: "button", id: triggerId, className: cx('tui-accordion__trigger', className), "aria-expanded": isOpen, "aria-controls": panelId, "aria-label": ariaLabel, disabled: disabled, "data-state": state, "data-disabled": disabled || undefined, "data-tui-accordion-trigger": "", onClick: handleClick, onKeyDown: handleKeyDown, children: [children && _jsx("span", { className: "tui-accordion__trigger-content", children: children }), _jsx(Icon, { name: "system/chevron-down", className: "tui-accordion__indicator", "aria-hidden": "true" })] }));
237
265
  // Wrap in heading if headingLevel is specified
238
266
  if (headingLevel) {
239
267
  const Heading = `h${headingLevel}`;
@@ -1,5 +1,6 @@
1
- import type { AccordionContextValue, AccordionItemContextValue } from './types';
1
+ import type { AccordionContextValue, AccordionItemContextValue, AccordionItemState } from './types';
2
2
  export declare const AccordionContext: import("react").Context<AccordionContextValue | null>;
3
3
  export declare function useAccordionContext(): AccordionContextValue;
4
4
  export declare const AccordionItemContext: import("react").Context<AccordionItemContextValue | null>;
5
5
  export declare function useAccordionItemContext(): AccordionItemContextValue;
6
+ export declare function useAccordionItem(): AccordionItemState;
@@ -1,4 +1,4 @@
1
- import { createContext, useContext } from 'react';
1
+ import { createContext, useContext, useMemo } from 'react';
2
2
  // =============================================================================
3
3
  // Accordion Root Context
4
4
  // =============================================================================
@@ -17,7 +17,30 @@ export const AccordionItemContext = createContext(null);
17
17
  export function useAccordionItemContext() {
18
18
  const context = useContext(AccordionItemContext);
19
19
  if (!context) {
20
- throw new Error('Accordion.Trigger and Accordion.Panel must be used within an Accordion.Item');
20
+ throw new Error('Accordion.Trigger, Accordion.Panel and useAccordionItem() must be used within an Accordion.Item');
21
21
  }
22
22
  return context;
23
23
  }
24
+ // =============================================================================
25
+ // Public: useAccordionItem
26
+ // =============================================================================
27
+ //
28
+ // For a secondary control inside an Accordion.Item that toggles the same item
29
+ // — an Edit/Close link beside the chevron — and wants aria-expanded /
30
+ // aria-controls of its own. Deliberately a narrow, read-mostly handle rather
31
+ // than the raw contexts: the item's ids and open state, plus a bound toggle.
32
+ export function useAccordionItem() {
33
+ const { toggle } = useAccordionContext();
34
+ const { value, disabled, triggerId, panelId, isOpen } = useAccordionItemContext();
35
+ return useMemo(() => ({
36
+ value,
37
+ isOpen,
38
+ disabled,
39
+ triggerId,
40
+ panelId,
41
+ toggle: () => {
42
+ if (!disabled)
43
+ toggle(value);
44
+ },
45
+ }), [value, isOpen, disabled, triggerId, panelId, toggle]);
46
+ }
@@ -1,2 +1,3 @@
1
1
  export { Accordion } from './Accordion';
2
- export type { AccordionProps, AccordionSingleProps, AccordionMultipleProps, AccordionItemProps, AccordionTriggerProps, AccordionPanelProps, AccordionVariant, } from './types';
2
+ export { useAccordionItem } from './AccordionContext';
3
+ export type { AccordionItemState, AccordionProps, AccordionSingleProps, AccordionMultipleProps, AccordionItemProps, AccordionTriggerProps, AccordionPanelProps, AccordionVariant, } from './types';
@@ -1 +1,2 @@
1
1
  export { Accordion } from './Accordion.js';
2
+ export { useAccordionItem } from './AccordionContext.js';
@@ -12,11 +12,21 @@ type AccordionBaseProps = {
12
12
  };
13
13
  export type AccordionSingleProps = AccordionBaseProps & {
14
14
  type: 'single';
15
- /** Controlled: currently open item value */
16
- value?: string;
15
+ /**
16
+ * Controlled: currently open item value. `null` means "controlled, nothing
17
+ * open". Controlled vs uncontrolled is decided once, at mount, from whether
18
+ * `value` is `undefined` — so pass `null` (not `undefined`) for "all closed",
19
+ * and if `undefined` does leak back in later (`onValueChange` reports it on
20
+ * collapse), it reads as "nothing open" rather than switching modes.
21
+ */
22
+ value?: string | null;
17
23
  /** Uncontrolled: initially open item */
18
24
  defaultValue?: string;
19
- /** Callback when open item changes (undefined when all closed in collapsible mode) */
25
+ /**
26
+ * Callback when open item changes. Receives `undefined` when all items are
27
+ * closed (collapsible mode) — store it as `value ?? null` if your state is
28
+ * `string | null`.
29
+ */
20
30
  onValueChange?: (value: string | undefined) => void;
21
31
  /** Allow closing all items (otherwise one stays open) */
22
32
  collapsible?: boolean;
@@ -55,6 +65,16 @@ export type AccordionTriggerProps = {
55
65
  * @default false
56
66
  */
57
67
  asChild?: boolean;
68
+ /**
69
+ * `asChild` only. Skip the `tui-accordion__trigger` class — the full-width
70
+ * row paint (flex, width 100%, padding, hover background, inset focus ring)
71
+ * — and leave the child's own styling alone. The behaviour hook
72
+ * (`data-tui-accordion-trigger`, `data-state`, ARIA, handlers) still lands.
73
+ * For a child that is already a styled control (an `IconButton`), not for a
74
+ * custom row that wants the accordion's look.
75
+ * @default false
76
+ */
77
+ unstyled?: boolean;
58
78
  /** Accessible label for the trigger. Required when children is empty (e.g. icon-only triggers). */
59
79
  'aria-label'?: string;
60
80
  children?: ReactNode;
@@ -82,4 +102,23 @@ export type AccordionItemContextValue = {
82
102
  panelId: string;
83
103
  isOpen: boolean;
84
104
  };
105
+ /**
106
+ * What `useAccordionItem()` hands a secondary control rendered inside an
107
+ * `Accordion.Item` — enough to wire `aria-expanded`/`aria-controls` and toggle
108
+ * the same item from a second button (an Edit/Close link beside the chevron).
109
+ */
110
+ export type AccordionItemState = {
111
+ /** The item's `value`. */
112
+ value: string;
113
+ /** Whether the item is currently open. */
114
+ isOpen: boolean;
115
+ /** Whether the item is disabled — a secondary control should disable too. */
116
+ disabled: boolean;
117
+ /** `id` of the item's trigger (the built-in one, or the `asChild` element). */
118
+ triggerId: string;
119
+ /** `id` of the item's panel — the value for a secondary control's `aria-controls`. */
120
+ panelId: string;
121
+ /** Toggle this item, honouring `type`/`collapsible` and `disabled`. */
122
+ toggle: () => void;
123
+ };
85
124
  export {};
@@ -25,6 +25,13 @@ export type ColorFieldLabels = ColorPickerLabels & {
25
25
  /** Strings for the embedded GradientPicker (gradient mode only). */
26
26
  gradientPicker?: GradientPickerLabels;
27
27
  };
28
+ /**
29
+ * Trigger chrome. `field` is the default bordered pill; `bare` drops the field
30
+ * box (border, background, padding) so the swatch itself is the control —
31
+ * sized like an IconButton of the same `size`, for colour-ladder strips and
32
+ * swatch grids.
33
+ */
34
+ export type ColorFieldVariant = 'field' | 'bare';
28
35
  export type ColorFieldProps = {
29
36
  /**
30
37
  * Controlled value — a CSS colour, a `var(--x[, fallback])` reference, or
@@ -58,6 +65,23 @@ export type ColorFieldProps = {
58
65
  label?: React.ReactNode;
59
66
  /** Show the label text beside the swatch. @default true */
60
67
  showLabel?: boolean;
68
+ /**
69
+ * Show the icon-swatch before the label. Opt out for a text-only trigger
70
+ * (a dense settings row where the value text is the affordance). Hiding the
71
+ * swatch also hides the `dynamic` bolt and any `icon` — the accessible name
72
+ * still carries the dynamic state. With both this and `showLabel` off the
73
+ * trigger would be empty, so the label is kept and a dev warning fires.
74
+ * @default true
75
+ */
76
+ showSwatch?: boolean;
77
+ /**
78
+ * Trigger chrome. `bare` removes the field box and sizes the swatch to the
79
+ * control height (an IconButton-shaped tile), keeping the focus ring and the
80
+ * swatch's own edge. Composes with `showLabel={false}` for a swatch-only
81
+ * tile, or with a label for a chrome-less swatch + text row.
82
+ * @default 'field'
83
+ */
84
+ variant?: ColorFieldVariant;
61
85
  /**
62
86
  * Dynamic-data treatment — a neutral swatch with a bolt icon, for values
63
87
  * bound to dynamic sources rather than a fixed colour.
@@ -85,4 +109,4 @@ export type ColorFieldProps = {
85
109
  * and a label that opens a {@link ColorPicker} in a dialog popover. This is the
86
110
  * reusable field-level control for colour inputs; the picker itself is the panel.
87
111
  */
88
- export declare function ColorField({ value: controlledValue, defaultValue, onValueChange, format: controlledFormat, defaultFormat, onFormatChange, formats, alpha, gradient, disabled, label, showLabel, dynamic, icon, size, side, align, open, defaultOpen, onOpenChange, labels, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, className, id, ...rest }: ColorFieldProps): import("react/jsx-runtime").JSX.Element;
112
+ export declare function ColorField({ value: controlledValue, defaultValue, onValueChange, format: controlledFormat, defaultFormat, onFormatChange, formats, alpha, gradient, disabled, label, showLabel, showSwatch, variant, dynamic, icon, size, side, align, open, defaultOpen, onOpenChange, labels, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, className, id, ...rest }: ColorFieldProps): import("react/jsx-runtime").JSX.Element;
@@ -67,7 +67,7 @@ function nodeToText(node) {
67
67
  * and a label that opens a {@link ColorPicker} in a dialog popover. This is the
68
68
  * reusable field-level control for colour inputs; the picker itself is the panel.
69
69
  */
70
- export function ColorField({ value: controlledValue, defaultValue = '#000000', onValueChange, format: controlledFormat, defaultFormat = 'hex', onFormatChange, formats, alpha = true, gradient = false, disabled, label, showLabel = true, dynamic = false, icon, size = 'md', side = 'bottom', align = 'start', open, defaultOpen, onOpenChange, labels, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, className, id, ...rest }) {
70
+ export function ColorField({ value: controlledValue, defaultValue = '#000000', onValueChange, format: controlledFormat, defaultFormat = 'hex', onFormatChange, formats, alpha = true, gradient = false, disabled, label, showLabel = true, showSwatch = true, variant = 'field', dynamic = false, icon, size = 'md', side = 'bottom', align = 'start', open, defaultOpen, onOpenChange, labels, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, className, id, ...rest }) {
71
71
  const triggerRef = useRef(null);
72
72
  const isValueControlled = useRef(controlledValue !== undefined).current;
73
73
  const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
@@ -142,6 +142,12 @@ export function ColorField({ value: controlledValue, defaultValue = '#000000', o
142
142
  !ariaLabelledby) {
143
143
  console.warn('[ColorField] `label` is a node with no derivable text — pass `aria-label` so the control has an accessible name.');
144
144
  }
145
+ // An empty trigger is never right: with both content slots opted out, keep
146
+ // the label — the value text is the least a colour control must show.
147
+ const hasLabel = showLabel || !showSwatch;
148
+ if (isDev() && !showLabel && !showSwatch) {
149
+ console.warn('[ColorField] `showLabel={false}` and `showSwatch={false}` together would render an empty trigger — the label is kept.');
150
+ }
145
151
  // Name context includes the value/label and the dynamic state, so both the
146
152
  // trigger and the (focus-trapped) popover dialog identify which field this is.
147
153
  const nameContext = (labelText ? `${triggerBase}: ${labelText}` : triggerBase) +
@@ -155,7 +161,7 @@ export function ColorField({ value: controlledValue, defaultValue = '#000000', o
155
161
  if (!next)
156
162
  lastGradientRef.current = null;
157
163
  onOpenChange?.(next);
158
- }, children: [_jsx(Popover.Trigger, { asChild: true, children: _jsxs("button", { ref: triggerRef, type: "button", id: id, className: cx('tui-color-field', size !== 'md' && `is-size-${size}`, !showLabel && 'is-swatch-only', disabled && 'is-disabled', className), disabled: disabled, "aria-label": computedAriaLabel, "aria-labelledby": ariaLabelledby, ...rest, children: [_jsx("span", { className: "tui-color-field__swatch", "aria-hidden": "true", style: {
164
+ }, children: [_jsx(Popover.Trigger, { asChild: true, children: _jsxs("button", { ref: triggerRef, type: "button", id: id, className: cx('tui-color-field', size !== 'md' && `is-size-${size}`, variant !== 'field' && `is-variant-${variant}`, showSwatch && !hasLabel && 'is-swatch-only', !showSwatch && 'is-label-only', disabled && 'is-disabled', className), disabled: disabled, "aria-label": computedAriaLabel, "aria-labelledby": ariaLabelledby, ...rest, children: [showSwatch && (_jsx("span", { className: "tui-color-field__swatch", "aria-hidden": "true", style: {
159
165
  '--_swatch': swatchBg,
160
166
  '--_swatch-icon': iconColor,
161
167
  // A gradient paints the whole swatch; solid values keep the
@@ -165,7 +171,7 @@ export function ColorField({ value: controlledValue, defaultValue = '#000000', o
165
171
  ...(isGradient && !dynamic
166
172
  ? { '--_swatch-image': formatGradient(parsedGradient.gradient) }
167
173
  : null),
168
- }, children: _jsx(Icon, { name: swatchIcon, className: "tui-color-field__swatch-icon" }) }), showLabel && _jsx("span", { className: "tui-color-field__label", children: labelNode })] }) }), _jsx(Popover.Content, { side: side, align: align, modal: true, "aria-label": popoverLabel, className: "tui-color-field__popover", children: gradient ? (_jsxs(Tabs
174
+ }, children: _jsx(Icon, { name: swatchIcon, className: "tui-color-field__swatch-icon" }) })), hasLabel && _jsx("span", { className: "tui-color-field__label", children: labelNode })] }) }), _jsx(Popover.Content, { side: side, align: align, modal: true, "aria-label": popoverLabel, className: "tui-color-field__popover", children: gradient ? (_jsxs(Tabs
169
175
  // The tab derives from the value; switching CONVERTS the value
170
176
  // (matching the reference design): solid → a two-stop gradient of
171
177
  // itself, gradient → its first stop's colour. Because switching is
@@ -1,7 +1,7 @@
1
1
  export { ColorPicker } from './ColorPicker';
2
2
  export type { ColorPickerProps } from './ColorPicker';
3
3
  export { ColorField } from './ColorField';
4
- export type { ColorFieldProps, ColorFieldLabels } from './ColorField';
4
+ export type { ColorFieldProps, ColorFieldLabels, ColorFieldVariant } from './ColorField';
5
5
  export type { Side as ColorFieldSide, Align as ColorFieldAlign } from '../Popover';
6
6
  export { defaultColorPickerLabels } from './labels';
7
7
  export type { ColorPickerLabels } from './labels';
@@ -1,6 +1,10 @@
1
1
  import React from 'react';
2
2
  import type { SizeStandard } from '../../types';
3
3
  type Size = SizeStandard | 'xl';
4
+ /** ARIA role of the dialog element. See `ModalProps['role']`. */
5
+ export type ModalRole = 'dialog' | 'alertdialog';
6
+ /** Distribution of `Modal.Foot`'s actions along the row. See `ModalFootProps['justify']`. */
7
+ export type ModalFootJustify = 'start' | 'end' | 'between';
4
8
  export type ModalProps = Omit<React.HTMLAttributes<HTMLDivElement>, 'role' | 'aria-modal' | 'tabIndex' | 'children'> & {
5
9
  open: boolean;
6
10
  onClose: () => void;
@@ -11,10 +15,29 @@ export type ModalProps = Omit<React.HTMLAttributes<HTMLDivElement>, 'role' | 'ar
11
15
  * without an accessible name, which violates WCAG 4.1.2 (Name, Role, Value). */
12
16
  'aria-labelledby'?: string;
13
17
  'aria-describedby'?: string;
18
+ /** ARIA role of the dialog element. Default `'dialog'`.
19
+ *
20
+ * `'alertdialog'` is for a dialog that interrupts the user's workflow to demand a response —
21
+ * a destructive-action confirm is the textbook case. Focus trap, `aria-modal`, Escape and
22
+ * focus restore behave identically for both roles; what changes is the contract around them:
23
+ * the APG alert dialog pattern expects BOTH `aria-labelledby` (the heading) and
24
+ * `aria-describedby` (the message) — a dev warning fires if either is missing — and the
25
+ * backdrop stops dismissing on click unless `closeOnBackdropClick` says otherwise, since a
26
+ * stray click outside is not a response. Escape still closes: it is the keyboard "cancel".
27
+ *
28
+ * Initial focus lands on the first focusable element in DOM order (unless
29
+ * `initialFocusSelector` says otherwise), and the APG wants that to be the safest action —
30
+ * so put Cancel before the destructive action in `Modal.Foot`. If the visual order must
31
+ * differ (`Modal.Foot justify="between"` with a destructive action first), point
32
+ * `initialFocusSelector` at the safe one.
33
+ * https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/ */
34
+ role?: ModalRole;
14
35
  initialFocusSelector?: string;
15
36
  container?: Element | null;
16
37
  showCloseButton?: boolean;
17
38
  closeLabel?: string;
39
+ /** Close when clicking the backdrop. Default `true` for `role="dialog"`, `false` for
40
+ * `role="alertdialog"` (see `role`). Passing it explicitly always wins. */
18
41
  closeOnBackdropClick?: boolean;
19
42
  closeOnEscape?: boolean;
20
43
  /** When true, prevents the browser from scrolling to the trigger element
@@ -26,7 +49,7 @@ export type ModalProps = Omit<React.HTMLAttributes<HTMLDivElement>, 'role' | 'ar
26
49
  className?: string;
27
50
  children?: React.ReactNode;
28
51
  };
29
- declare function ModalRoot({ open, onClose, size, stickyHead, stickyFoot, 'aria-labelledby': labelledBy, 'aria-describedby': describedBy, initialFocusSelector, container, showCloseButton, closeLabel, closeOnBackdropClick, closeOnEscape, preventScrollOnRestore, className, children, ...rest }: ModalProps): import("react/jsx-runtime").JSX.Element | null;
52
+ declare function ModalRoot({ open, onClose, size, stickyHead, stickyFoot, 'aria-labelledby': labelledBy, 'aria-describedby': describedBy, role, initialFocusSelector, container, showCloseButton, closeLabel, closeOnBackdropClick, closeOnEscape, preventScrollOnRestore, className, children, ...rest }: ModalProps): import("react/jsx-runtime").JSX.Element | null;
30
53
  type ModalCloseProps = {
31
54
  label?: string;
32
55
  className?: string;
@@ -59,7 +82,18 @@ declare function ModalBody({ className, children, scrollLabel, ...rest }: ModalB
59
82
  declare namespace ModalBody {
60
83
  var displayName: string;
61
84
  }
62
- declare function ModalFoot({ className, children, ...rest }: ModalSlotProps): import("react/jsx-runtime").JSX.Element;
85
+ export type ModalFootProps = ModalSlotProps & {
86
+ /** How the actions distribute along the row. `'end'` (default) keeps them together at the
87
+ * inline end, so reading order is visual order and the primary action comes last; `'start'`
88
+ * keeps them together at the inline start; `'between'` separates the first action from the
89
+ * rest, which stay grouped at the end — the place for a destructive or tertiary action you
90
+ * want visibly apart from the primary. Visual order follows DOM order, and so does the
91
+ * dialog's initial focus: a destructive action placed first will be focused first unless
92
+ * the Modal's `initialFocusSelector` points at a safer one.
93
+ * Published as `data-justify` on `.tui-modal__foot`. */
94
+ justify?: ModalFootJustify;
95
+ };
96
+ declare function ModalFoot({ className, children, justify, ...rest }: ModalFootProps): import("react/jsx-runtime").JSX.Element;
63
97
  declare namespace ModalFoot {
64
98
  var displayName: string;
65
99
  }
@@ -8,13 +8,18 @@ import { useFocusTrap, getInitialFocus } from '../../utils/focus-trap.js';
8
8
  import { ModalContext, useModalContext } from './context.js';
9
9
  import { IconButton } from '../IconButton/index.js';
10
10
  const isBrowser = typeof document !== 'undefined';
11
- function ModalRoot({ open, onClose, size = 'md', stickyHead, stickyFoot, 'aria-labelledby': labelledBy, 'aria-describedby': describedBy, initialFocusSelector, container, showCloseButton, closeLabel = 'Close', closeOnBackdropClick = true, closeOnEscape = true, preventScrollOnRestore = false, className, children, ...rest }) {
11
+ function ModalRoot({ open, onClose, size = 'md', stickyHead, stickyFoot, 'aria-labelledby': labelledBy, 'aria-describedby': describedBy, role = 'dialog', initialFocusSelector, container, showCloseButton, closeLabel = 'Close', closeOnBackdropClick, closeOnEscape = true, preventScrollOnRestore = false, className, children, ...rest }) {
12
12
  const dialogRef = useRef(null);
13
13
  const anchorRef = useRef(null);
14
14
  const restoreRef = useRef(null);
15
15
  const warnedRef = useRef(false);
16
16
  const warnedAriaLabelRef = useRef(false);
17
+ const warnedAlertRef = useRef(false);
17
18
  const [mount, setMount] = useState(null);
19
+ // An alert dialog interrupts to demand a response; a click that lands outside
20
+ // it is not one, so the backdrop shortcut is off by default for that role.
21
+ // Escape stays on for both — it is the keyboard "cancel", not a stray click.
22
+ const backdropDismisses = closeOnBackdropClick ?? role === 'dialog';
18
23
  // Dev warning: aria-label via ...rest silently competes with aria-labelledby
19
24
  // (labelledby wins per AccName 1.2 step 2B, leaving aria-label dead code).
20
25
  useEffect(() => {
@@ -25,14 +30,34 @@ function ModalRoot({ open, onClose, size = 'md', stickyHead, stickyFoot, 'aria-l
25
30
  'Remove one. Prefer `aria-labelledby` referencing a visible heading.');
26
31
  }
27
32
  }, [open, labelledBy, rest]);
28
- // Dev warning: Modal should have an accessible name
33
+ // Dev warning: Modal should have an accessible name. The alertdialog warning
34
+ // below covers a missing label for that role, so this one is dialog-only.
29
35
  useEffect(() => {
30
- if (isDev() && !warnedRef.current && open && !labelledBy) {
36
+ if (isDev() && !warnedRef.current && open && !labelledBy && role === 'dialog') {
31
37
  warnedRef.current = true;
32
38
  console.warn('[TUI Modal] Missing `aria-labelledby` prop. Dialogs should reference a visible heading ' +
33
39
  'to provide an accessible name (WCAG 4.1.2).');
34
40
  }
35
- }, [open, labelledBy]);
41
+ }, [open, labelledBy, role]);
42
+ // Dev warning: an alert dialog needs BOTH a name and a description. The APG
43
+ // pattern is explicit — the heading names it, the message it interrupts with
44
+ // is what `aria-describedby` reads out on focus. Without the description, AT
45
+ // announces "Delete item, dialog" and nothing about what is being deleted.
46
+ useEffect(() => {
47
+ if (!isDev() || warnedAlertRef.current || !open || role !== 'alertdialog')
48
+ return;
49
+ const missing = [
50
+ !labelledBy && '`aria-labelledby`',
51
+ !describedBy && '`aria-describedby`',
52
+ ].filter(Boolean);
53
+ if (missing.length === 0)
54
+ return;
55
+ warnedAlertRef.current = true;
56
+ console.warn(`[TUI Modal] role="alertdialog" is missing ${missing.join(' and ')}. An alert dialog ` +
57
+ 'needs both: `aria-labelledby` pointing at its heading and `aria-describedby` pointing ' +
58
+ 'at the message it interrupts with, so the response it demands is announced together ' +
59
+ 'with its name. See https://www.w3.org/WAI/ARIA/apg/patterns/alertdialog/');
60
+ }, [open, role, labelledBy, describedBy]);
36
61
  // Compute portal mount point and capture the focus-restore target on open.
37
62
  // Uses useLayoutEffect to run before paint — both renders complete before
38
63
  // the browser shows anything, so no visible delay.
@@ -171,7 +196,14 @@ function ModalRoot({ open, onClose, size = 'md', stickyHead, stickyFoot, 'aria-l
171
196
  `Ensure an element with id="${labelledBy}" exists inside the modal.`);
172
197
  }
173
198
  }
174
- }, [open, mount, initialFocusSelector, labelledBy]);
199
+ // Same for describedBy. A phantom id is silently ignored by AccName (unlike
200
+ // aria-labelledby, which would blank the name), so the only symptom is a
201
+ // description that never announces — worth a line in dev.
202
+ if (isDev() && describedBy && !document.getElementById(describedBy)) {
203
+ console.warn(`Modal: aria-describedby="${describedBy}" references a non-existent element. ` +
204
+ `Ensure an element with id="${describedBy}" exists inside the modal.`);
205
+ }
206
+ }, [open, mount, initialFocusSelector, labelledBy, describedBy]);
175
207
  // Memoize context value to prevent unnecessary re-renders
176
208
  const contextValue = useMemo(() => ({ onClose }), [onClose]);
177
209
  if (!open)
@@ -181,7 +213,7 @@ function ModalRoot({ open, onClose, size = 'md', stickyHead, stickyFoot, 'aria-l
181
213
  // Unmounts on the very next render (pre-paint), so it never lays anything out.
182
214
  if (!mount)
183
215
  return _jsx("span", { ref: anchorRef, hidden: true });
184
- return createPortal(_jsx(ModalContext.Provider, { value: contextValue, children: _jsxs("div", { className: "tui-modal", "data-state": "open", style: { pointerEvents: 'auto' }, children: [_jsx("div", { className: "tui-modal__backdrop", "aria-hidden": "true", onClick: closeOnBackdropClick ? onClose : undefined }), _jsxs("div", { ref: dialogRef, role: "dialog", "aria-modal": "true", "aria-labelledby": labelledBy, "aria-describedby": describedBy, className: cx('tui-modal__dialog', `is-size-${size}`, stickyHead && 'is-sticky-head', stickyFoot && 'is-sticky-foot', className), tabIndex: -1, ...rest, children: [showCloseButton && (_jsx(IconButton, { icon: "system/close", label: closeLabel, variant: "ghost", size: "sm", onClick: onClose, className: "tui-modal__close", showTooltip: true })), children] })] }) }), mount);
216
+ return createPortal(_jsx(ModalContext.Provider, { value: contextValue, children: _jsxs("div", { className: "tui-modal", "data-state": "open", style: { pointerEvents: 'auto' }, children: [_jsx("div", { className: "tui-modal__backdrop", "aria-hidden": "true", onClick: backdropDismisses ? onClose : undefined }), _jsxs("div", { ref: dialogRef, role: role, "aria-modal": "true", "aria-labelledby": labelledBy, "aria-describedby": describedBy, className: cx('tui-modal__dialog', `is-size-${size}`, stickyHead && 'is-sticky-head', stickyFoot && 'is-sticky-foot', className), tabIndex: -1, ...rest, children: [showCloseButton && (_jsx(IconButton, { icon: "system/close", label: closeLabel, variant: "ghost", size: "sm", onClick: onClose, className: "tui-modal__close", showTooltip: true })), children] })] }) }), mount);
185
217
  }
186
218
  function ModalClose({ label = 'Close', className }) {
187
219
  const { onClose } = useModalContext();
@@ -197,11 +229,8 @@ function ModalBody({ className, children, scrollLabel, ...rest }) {
197
229
  return (_jsx("div", { className: cx('tui-modal__body', className), ...rest, children: _jsx("div", { className: "tui-modal__body-inner", "aria-label": scrollLabel, tabIndex: scrollLabel ? 0 : undefined, role: scrollLabel ? 'region' : undefined, children: children }) }));
198
230
  }
199
231
  ModalBody.displayName = 'Modal.Body';
200
- // =============================================================================
201
- // Modal.Foot — Footer slot
202
- // =============================================================================
203
- function ModalFoot({ className, children, ...rest }) {
204
- return (_jsx("div", { className: cx('tui-modal__foot', className), ...rest, children: children }));
232
+ function ModalFoot({ className, children, justify = 'end', ...rest }) {
233
+ return (_jsx("div", { ...rest, className: cx('tui-modal__foot', className), "data-justify": justify, children: children }));
205
234
  }
206
235
  ModalFoot.displayName = 'Modal.Foot';
207
236
  export const Modal = ModalRoot;
@@ -1,2 +1,2 @@
1
1
  export { Modal } from './Modal';
2
- export type { ModalProps } from './Modal';
2
+ export type { ModalProps, ModalRole, ModalFootProps, ModalFootJustify } from './Modal';
@@ -18,10 +18,12 @@ import { Icon } from '../Icon/index.js';
18
18
  // Modes:
19
19
  // full — Background panel with arrows, index, lock (default)
20
20
  // handle — Bare drag icon button, no chrome
21
- // arrows — Panel with up/down chevrons only, no drag handle or index.
22
- // For items reordered exclusively by explicit moves (e.g.
23
- // top-level containers that aren't drag targets). Locked renders
24
- // as disabled chevrons (described via aria-describedby), no icon.
21
+ // arrows — Panel with up/down chevrons and no drag handle. For items
22
+ // reordered exclusively by explicit moves (top-level containers,
23
+ // lists without a drag library). `index` renders between the
24
+ // chevrons as a static badge — no hover swap, nothing to swap to.
25
+ // Locked renders as disabled chevrons (described via
26
+ // aria-describedby), no lock icon; the index stays put.
25
27
  //
26
28
  // CSS token API (never defined, read via fallback):
27
29
  // --tui-move-handle-size Override container size
@@ -63,11 +65,19 @@ export const MoveHandle = memo(forwardRef(function MoveHandle({ mode = 'full', s
63
65
  if (active instanceof HTMLButtonElement &&
64
66
  active.disabled &&
65
67
  group.contains(active)) {
68
+ // Arrows mode has no drag handle to fall back to, so the group itself
69
+ // (tabIndex -1 in that mode) catches focus rather than <body> — the
70
+ // same rule as Sidebar's collapse and Toast's removal: any state change
71
+ // that can disable the focused element needs an explicit refocus target.
66
72
  const fallback = group.querySelector('[data-direction="up"]:not(:disabled), [data-direction="down"]:not(:disabled)') ??
67
- group.querySelector('[data-role="drag-handle"]');
73
+ group.querySelector('[data-role="drag-handle"]') ??
74
+ (group.hasAttribute('tabindex') ? group : null);
68
75
  fallback?.focus();
69
76
  }
70
- }, [mode, canMoveUp, canMoveDown]);
77
+ // `locked` disables the chevrons too (disabled={locked || !canMoveUp}),
78
+ // so it must re-run this — a row locking during a save is the likeliest
79
+ // way to disable a focused chevron.
80
+ }, [mode, canMoveUp, canMoveDown, locked]);
71
81
  // Debounce the lock icon — prevents visual jitter when `locked` flashes
72
82
  // briefly (e.g. during a save). Behaviour (disabled buttons) applies
73
83
  // immediately; only the icon swap is delayed.
@@ -91,13 +101,17 @@ export const MoveHandle = memo(forwardRef(function MoveHandle({ mode = 'full', s
91
101
  }
92
102
  // ----- Full / arrows mode -----
93
103
  const isArrows = mode === 'arrows';
94
- const hasIndex = !isArrows && index != null;
104
+ const hasIndex = index != null;
95
105
  const hasArrows = !!(onMoveUp || onMoveDown);
96
106
  const resolvedLockedDesc = locked
97
107
  ? (labels?.locked ?? 'This item is locked and cannot be reordered')
98
108
  : undefined;
99
- // Arrows mode has no center — locked reads as disabled chevrons (plus the
100
- // aria-describedby explanation), not a lock icon swap.
101
- const showCenter = !isArrows;
102
- return (_jsxs("div", { ref: mergedRef, role: "group", "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-describedby": locked ? lockedDescId : undefined, "aria-disabled": locked || undefined, className: cx('tui-move-handle', `is-size-${size}`, isArrows && 'is-arrows', locked && 'is-locked', hasIndex && 'has-index', className), children: [locked && (_jsx("span", { id: lockedDescId, className: "tui-visually-hidden", children: resolvedLockedDesc })), onMoveUp && (_jsx("button", { type: "button", className: "tui-move-handle__up", "data-direction": "up", "aria-label": labels?.moveUp ?? 'Move up', disabled: locked || !canMoveUp, onClick: onMoveUp, children: _jsx(Icon, { name: "system/chevron-up" }) })), showCenter && (_jsx("div", { className: "tui-move-handle__center", children: showLockIcon ? (_jsx("span", { className: "tui-move-handle__lock", "aria-hidden": "true", children: _jsx(Icon, { name: "system/lock" }) })) : (_jsxs(_Fragment, { children: [hasIndex && (_jsx("span", { className: "tui-move-handle__index", "aria-hidden": "true", children: index })), _jsx("button", { type: "button", className: "tui-move-handle__handle", "data-role": "drag-handle", "aria-label": resolvedDragLabel, tabIndex: hasArrows ? -1 : 0, ...restDragProps, children: _jsx(Icon, { name: "system/handle-alt" }) })] })) })), onMoveDown && (_jsx("button", { type: "button", className: "tui-move-handle__down", "data-direction": "down", "aria-label": labels?.moveDown ?? 'Move down', disabled: locked || !canMoveDown, onClick: onMoveDown, children: _jsx(Icon, { name: "system/chevron-down" }) }))] }));
109
+ // Arrows mode only has a center when there is an index to show. Locked
110
+ // reads as disabled chevrons (plus the aria-describedby explanation), not
111
+ // a lock icon swap — the index is still true information, so it stays.
112
+ const showCenter = !isArrows || hasIndex;
113
+ return (_jsxs("div", { ref: mergedRef, role: "group", "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-describedby": locked ? lockedDescId : undefined, "aria-disabled": locked || undefined,
114
+ // Focus-recovery target for arrows mode (see the effect above). Not in
115
+ // the tab order; only reached programmatically.
116
+ tabIndex: isArrows ? -1 : undefined, className: cx('tui-move-handle', `is-size-${size}`, isArrows && 'is-arrows', locked && 'is-locked', hasIndex && 'has-index', className), children: [locked && (_jsx("span", { id: lockedDescId, className: "tui-visually-hidden", children: resolvedLockedDesc })), onMoveUp && (_jsx("button", { type: "button", className: "tui-move-handle__up", "data-direction": "up", "aria-label": labels?.moveUp ?? 'Move up', disabled: locked || !canMoveUp, onClick: onMoveUp, children: _jsx(Icon, { name: "system/chevron-up" }) })), showCenter && isArrows && (_jsx("div", { className: "tui-move-handle__center", children: _jsx("span", { className: "tui-move-handle__index", "aria-hidden": "true", children: index }) })), showCenter && !isArrows && (_jsx("div", { className: "tui-move-handle__center", children: showLockIcon ? (_jsx("span", { className: "tui-move-handle__lock", "aria-hidden": "true", children: _jsx(Icon, { name: "system/lock" }) })) : (_jsxs(_Fragment, { children: [hasIndex && (_jsx("span", { className: "tui-move-handle__index", "aria-hidden": "true", children: index })), _jsx("button", { type: "button", className: "tui-move-handle__handle", "data-role": "drag-handle", "aria-label": resolvedDragLabel, tabIndex: hasArrows ? -1 : 0, ...restDragProps, children: _jsx(Icon, { name: "system/handle-alt" }) })] })) })), onMoveDown && (_jsx("button", { type: "button", className: "tui-move-handle__down", "data-direction": "down", "aria-label": labels?.moveDown ?? 'Move down', disabled: locked || !canMoveDown, onClick: onMoveDown, children: _jsx(Icon, { name: "system/chevron-down" }) }))] }));
103
117
  }));
@@ -18,13 +18,19 @@ export interface MoveHandleProps {
18
18
  /**
19
19
  * Structural mode. 'full' (default) shows background panel with arrows/index.
20
20
  * 'handle' shows only the bare drag icon button. 'arrows' shows the panel
21
- * with only the up/down chevron buttons — no drag handle or index — for
22
- * items reordered exclusively by explicit moves (e.g. top-level containers).
21
+ * with the up/down chevron buttons and no drag handle — for items reordered
22
+ * exclusively by explicit moves (top-level containers, lists without a drag
23
+ * library). Pass `index` to show the position between the chevrons.
23
24
  */
24
25
  mode?: MoveHandleMode;
25
26
  /** Component scale. Full mode: sm = 32px, md = 40px. Handle mode: sm = 24px, md = 32px. */
26
27
  size?: MoveHandleSize;
27
- /** Position index. When provided, shows number at rest, drag handle on hover. Ignored in 'arrows' mode. */
28
+ /**
29
+ * Position index. In 'full' mode, shows the number at rest and swaps to the
30
+ * drag handle on hover/focus-within. In 'arrows' mode, shows the number
31
+ * between the chevrons with no swap — there is no handle to swap to.
32
+ * Ignored in 'handle' mode.
33
+ */
28
34
  index?: number;
29
35
  /** When true, shows lock icon and disables all interaction. */
30
36
  locked?: boolean;