@tangible/ui 0.2.17 → 0.2.19

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.
@@ -0,0 +1,234 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
3
+ import { createPortal } from 'react-dom';
4
+ import { cx } from '../../utils/cx.js';
5
+ import { isDev } from '../../utils/is-dev.js';
6
+ import { getPortalRootFor } from '../../utils/portal.js';
7
+ import { Notice } from '../Notice/index.js';
8
+ import { ToastContext } from './ToastContext.js';
9
+ const isBrowser = typeof document !== 'undefined';
10
+ // Safety net for the exit animation: `exit('fade')` resolves on
11
+ // `animationend`, which never fires if the region sits in a hidden/inert
12
+ // subtree (a Fields tab panel) or the stylesheet wasn't loaded. Without a
13
+ // fallback the toast record would accumulate in provider state forever.
14
+ // Comfortably above the 200ms --tui-motion-duration default.
15
+ const EXIT_FALLBACK_MS = 1000;
16
+ /**
17
+ * Presentational toast — an inline-layout Notice dressed for the toast stack
18
+ * (shadow, enter animation, icon | text | actions | × in one row).
19
+ *
20
+ * The toast root is also a nested `.tui-interface` with `data-theme="dark"`:
21
+ * a dark surface by default (following Tooltip's inverted treatment), done as
22
+ * a theme SCOPE rather than a token remap — the toast accepts arbitrary
23
+ * children, and everything inside (action Buttons, the dismiss IconButton,
24
+ * icons, consumer content) resolves dark tokens for free. Pass
25
+ * `data-theme="light"` (or "auto") through rest to opt out.
26
+ *
27
+ * The DOM carries both `tui-toast` and `tui-notice` classes, so Notice's
28
+ * component API tokens (`--tui-notice-bg`, `--tui-notice-padding`, …) can be
29
+ * re-pointed per toast context: `.tui-toast { --tui-notice-bg: …; }`.
30
+ */
31
+ export const Toast = forwardRef(function Toast({ theme = 'neutral', size = 'sm', icon, title, announce, dismissible = true, onDismiss, dismissLabel, actions, className, children, ...rest }, ref) {
32
+ const resolvedAnnounce = announce ?? (theme === 'danger' ? 'assertive' : 'polite');
33
+ return (_jsxs(Notice, { as: "div", ref: ref, className: cx('tui-toast', 'tui-interface', className), "data-theme": "dark", theme: theme, size: size, inline: true, announce: resolvedAnnounce, dismissible: dismissible, onDismiss: onDismiss, dismissLabel: dismissLabel, exitAnimation: "fade", ...rest, children: [icon && _jsx(Notice.Head, { icon: icon }), (title || children != null) && (_jsxs(Notice.Body, { children: [title && _jsx("div", { className: "tui-toast__title", children: title }), children != null && _jsx("div", { className: "tui-toast__description", children: children })] })), actions && _jsx(Notice.Foot, { children: actions })] }));
34
+ });
35
+ let toastCounter = 0;
36
+ export function ToastProvider({ children, placement = 'bottom-end', duration = 5000, regionLabel = 'Notifications', max = 5, container, }) {
37
+ const [toasts, setToasts] = useState([]);
38
+ const anchorRef = useRef(null);
39
+ const [mount, setMount] = useState(null);
40
+ // Once the region has appeared it stays mounted (empty when idle): a live
41
+ // region that already exists announces inserted toasts far more reliably
42
+ // than one created in the same commit as its first content.
43
+ const [everShown, setEverShown] = useState(false);
44
+ const autoMountRef = useRef(null);
45
+ const warnedEmptyRef = useRef(false);
46
+ const warnedUndismissableRef = useRef(false);
47
+ const toast = useCallback((options = {}) => {
48
+ if (isDev() && !warnedEmptyRef.current && !options.title && !options.description) {
49
+ warnedEmptyRef.current = true;
50
+ console.warn('[TUI Toast] toast() called with neither `title` nor `description` — ' +
51
+ 'there is nothing to display or announce.');
52
+ }
53
+ if (isDev() &&
54
+ !warnedUndismissableRef.current &&
55
+ options.dismissible === false &&
56
+ (options.duration === null || (options.duration === undefined && options.actions))) {
57
+ warnedUndismissableRef.current = true;
58
+ console.warn('[TUI Toast] This toast is permanent: `dismissible: false` with no ' +
59
+ 'auto-dismiss (persistent duration). Make sure an action calls ' +
60
+ 'dismiss(id), or the toast can never be removed.');
61
+ }
62
+ const id = options.id ?? `tui-toast-${++toastCounter}`;
63
+ setEverShown(true);
64
+ setToasts((prev) => {
65
+ const existing = prev.find((t) => t.id === id);
66
+ const record = {
67
+ ...options,
68
+ id,
69
+ revision: (existing?.revision ?? 0) + 1,
70
+ dismissed: false,
71
+ };
72
+ const next = existing
73
+ ? prev.map((t) => (t.id === id ? record : t))
74
+ : [...prev, record];
75
+ // Over the cap: dismiss the oldest still-active toasts (animated,
76
+ // onDismiss fires) rather than dropping them cold.
77
+ const active = next.filter((t) => !t.dismissed);
78
+ if (active.length > max) {
79
+ const excess = new Set(active.slice(0, active.length - max).map((t) => t.id));
80
+ return next.map((t) => (excess.has(t.id) ? { ...t, dismissed: true } : t));
81
+ }
82
+ return next;
83
+ });
84
+ return id;
85
+ }, [max]);
86
+ const dismiss = useCallback((id) => {
87
+ setToasts((prev) => prev.map((t) => (t.id === id && !t.dismissed ? { ...t, dismissed: true } : t)));
88
+ }, []);
89
+ const dismissAll = useCallback(() => {
90
+ setToasts((prev) => prev.map((t) => (t.dismissed ? t : { ...t, dismissed: true })));
91
+ }, []);
92
+ // Revision-scoped: a stale removal (an exit that resolved after the same id
93
+ // was re-toasted) must not delete the replacement record.
94
+ const remove = useCallback((id, revision) => {
95
+ setToasts((prev) => prev.filter((t) => !(t.id === id && t.revision === revision)));
96
+ }, []);
97
+ const api = useMemo(() => ({ toast, dismiss, dismissAll }), [toast, dismiss, dismissAll]);
98
+ // Resolve the portal mount from the provider's own position in the tree
99
+ // (the anchor span), never from document.activeElement — see the Modal
100
+ // portal gotcha in CLAUDE.md.
101
+ useLayoutEffect(() => {
102
+ if (!isBrowser || !everShown)
103
+ return;
104
+ if (container) {
105
+ setMount((current) => (current === container ? current : container));
106
+ return;
107
+ }
108
+ if (autoMountRef.current?.isConnected) {
109
+ const auto = autoMountRef.current;
110
+ setMount((current) => (current === auto ? current : auto));
111
+ return;
112
+ }
113
+ const resolved = getPortalRootFor(anchorRef.current);
114
+ autoMountRef.current = resolved;
115
+ setMount(resolved);
116
+ }, [everShown, container]);
117
+ return (_jsxs(ToastContext.Provider, { value: api, children: [children, _jsx("span", { hidden: true, ref: anchorRef }), isBrowser && mount && everShown &&
118
+ createPortal(_jsx(ToastRegion, { placement: placement, label: regionLabel, toasts: toasts, defaultDuration: duration, onRemove: remove }), mount)] }));
119
+ }
120
+ function ToastRegion({ placement, label, toasts, defaultDuration, onRemove }) {
121
+ const regionRef = useRef(null);
122
+ const [hovered, setHovered] = useState(false);
123
+ const [focused, setFocused] = useState(false);
124
+ const [pressed, setPressed] = useState(false);
125
+ const paused = hovered || focused || pressed;
126
+ return (_jsx("div", { ref: regionRef, className: cx('tui-toast-region', `is-placement-${placement}`), role: "region", "aria-label": label, tabIndex: -1, onMouseEnter: () => setHovered(true), onMouseLeave: () => setHovered(false), onPointerDown: () => setPressed(true), onPointerUp: () => setPressed(false), onPointerCancel: () => setPressed(false), onFocusCapture: () => setFocused(true), onBlurCapture: (event) => {
127
+ if (!event.currentTarget.contains(event.relatedTarget)) {
128
+ setFocused(false);
129
+ }
130
+ }, children: toasts.map((record) => (_jsx(ToastItem
131
+ // Keyed on revision too: a re-toast of the same id REMOUNTS the
132
+ // item, resetting Notice's exit state — updating in place could
133
+ // land new content inside an element already faded to nothing.
134
+ , { record: record, paused: paused, defaultDuration: defaultDuration, regionRef: regionRef, onRemove: onRemove }, `${record.id}:${record.revision}`))) }));
135
+ }
136
+ function ToastItem({ record, paused, defaultDuration, regionRef, onRemove }) {
137
+ const handleRef = useRef(null);
138
+ const firedRef = useRef(false);
139
+ const unmountedRef = useRef(false);
140
+ useEffect(() => {
141
+ return () => {
142
+ unmountedRef.current = true;
143
+ };
144
+ }, []);
145
+ // Single exit point: onDismiss fires once no matter which path removed the
146
+ // toast (timer, dismiss(), or the × button). If the removed toast held
147
+ // focus, hand it to the region — unmounting the focused element would
148
+ // silently drop focus to <body> (WCAG 2.4.3; same class of bug as the
149
+ // token-field chip-removal gotcha).
150
+ const finalize = useCallback(() => {
151
+ if (firedRef.current)
152
+ return;
153
+ firedRef.current = true;
154
+ const element = handleRef.current?.element;
155
+ const hadFocus = element ? element.contains(document.activeElement) : false;
156
+ record.onDismiss?.();
157
+ onRemove(record.id, record.revision);
158
+ if (hadFocus)
159
+ regionRef.current?.focus();
160
+ }, [record, onRemove, regionRef]);
161
+ // Programmatic removal (timer expiry, dismiss()): animate, then finalize.
162
+ // The × button path skips this — Notice runs its own fade before calling
163
+ // onDismiss, which lands on finalize directly.
164
+ //
165
+ // The race guards against an `animationend` that never comes (region in a
166
+ // hidden/inert subtree, stylesheet not loaded); the unmounted check drops
167
+ // a resolution that arrives after this instance was superseded by a
168
+ // re-toast of the same id — finalizing then would delete the replacement.
169
+ const dismissNow = useCallback(async () => {
170
+ if (firedRef.current)
171
+ return;
172
+ await Promise.race([
173
+ handleRef.current?.exit('fade'),
174
+ new Promise((resolve) => setTimeout(resolve, EXIT_FALLBACK_MS)),
175
+ ]);
176
+ if (unmountedRef.current)
177
+ return;
178
+ finalize();
179
+ }, [finalize]);
180
+ // `duration: null` persists; a toast with actions persists by default —
181
+ // the user needs time to act on it.
182
+ const effectiveDuration = record.duration !== undefined
183
+ ? record.duration
184
+ : record.actions
185
+ ? null
186
+ : defaultDuration;
187
+ useToastTimer(effectiveDuration, paused, dismissNow);
188
+ useEffect(() => {
189
+ if (record.dismissed)
190
+ void dismissNow();
191
+ }, [record.dismissed, dismissNow]);
192
+ return (_jsx(Toast, { ref: handleRef, theme: record.theme, size: record.size, icon: record.icon, title: record.title, actions: record.actions, announce: record.announce, dismissible: record.dismissible, dismissLabel: record.dismissLabel, className: record.className, style: record.style, "data-testid": record['data-testid'], onDismiss: finalize, children: record.description }));
193
+ }
194
+ /**
195
+ * Countdown that survives pauses: while `paused`, the remaining time is
196
+ * banked and the timeout cleared; on resume it restarts with what's left.
197
+ * A `duration` change resets the countdown in full. (A re-toast of the same
198
+ * id remounts the whole item via its key, so its countdown starts fresh.)
199
+ *
200
+ * Date.now() rather than performance.now() is deliberate: fake-timer suites
201
+ * mock Date but not performance, and the banked arithmetic must move with
202
+ * the mocked clock.
203
+ */
204
+ function useToastTimer(duration, paused, onExpire) {
205
+ const remainingRef = useRef(null);
206
+ const startedAtRef = useRef(0);
207
+ const onExpireRef = useRef(onExpire);
208
+ useEffect(() => {
209
+ onExpireRef.current = onExpire;
210
+ });
211
+ // Reset the bank when the duration changes. Declared before the countdown
212
+ // effect so it runs first in the same commit.
213
+ useEffect(() => {
214
+ remainingRef.current =
215
+ typeof duration === 'number' && Number.isFinite(duration) && duration > 0
216
+ ? duration
217
+ : null;
218
+ }, [duration]);
219
+ useEffect(() => {
220
+ if (paused || remainingRef.current == null)
221
+ return;
222
+ startedAtRef.current = Date.now();
223
+ const timer = setTimeout(() => {
224
+ remainingRef.current = null;
225
+ onExpireRef.current();
226
+ }, remainingRef.current);
227
+ return () => {
228
+ clearTimeout(timer);
229
+ if (remainingRef.current != null) {
230
+ remainingRef.current = Math.max(0, remainingRef.current - (Date.now() - startedAtRef.current));
231
+ }
232
+ };
233
+ }, [paused, duration]);
234
+ }
@@ -0,0 +1,11 @@
1
+ import type { ToastOptions } from './Toast';
2
+ export type ToastContextValue = {
3
+ /** Show a toast. Returns its id. */
4
+ toast: (options?: ToastOptions) => string;
5
+ /** Dismiss one toast by id (plays its exit animation). */
6
+ dismiss: (id: string) => void;
7
+ /** Dismiss all toasts. */
8
+ dismissAll: () => void;
9
+ };
10
+ export declare const ToastContext: import("react").Context<ToastContextValue | null>;
11
+ export declare function useToast(): ToastContextValue;
@@ -0,0 +1,9 @@
1
+ import { createContext, useContext } from 'react';
2
+ export const ToastContext = createContext(null);
3
+ export function useToast() {
4
+ const context = useContext(ToastContext);
5
+ if (!context) {
6
+ throw new Error('[TUI Toast] useToast must be used within a <ToastProvider>.');
7
+ }
8
+ return context;
9
+ }
@@ -0,0 +1,4 @@
1
+ export { Toast, ToastProvider } from './Toast';
2
+ export { useToast } from './ToastContext';
3
+ export type { ToastProps, ToastHandle, ToastTheme, ToastAnnounce, ToastPlacement, ToastOptions, ToastProviderProps, } from './Toast';
4
+ export type { ToastContextValue } from './ToastContext';
@@ -0,0 +1,2 @@
1
+ export { Toast, ToastProvider } from './Toast.js';
2
+ export { useToast } from './ToastContext.js';
@@ -32,7 +32,7 @@ export { RadioGroup, Radio } from './Radio';
32
32
  export { Rating } from './Rating';
33
33
  export { SegmentedControl } from './SegmentedControl';
34
34
  export { Slider } from './Slider';
35
- export { Sidebar } from './Sidebar';
35
+ export { Sidebar, defaultSidebarToggleLabels } from './Sidebar';
36
36
  export { StepIndicator } from './StepIndicator';
37
37
  export { StepList } from './StepList';
38
38
  export { DataTable } from './Table';
@@ -43,6 +43,7 @@ export { Switch } from './Switch';
43
43
  export { Tabs } from './Tabs';
44
44
  export { Textarea } from './Textarea';
45
45
  export { TextInput } from './TextInput';
46
+ export { Toast, ToastProvider, useToast } from './Toast';
46
47
  export { Toolbar } from './Toolbar';
47
48
  export { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from './Tooltip';
48
49
  export type { AccordionProps, AccordionSingleProps, AccordionMultipleProps, AccordionItemProps, AccordionTriggerProps, AccordionPanelProps, } from './Accordion';
@@ -75,7 +76,7 @@ export type { ProgressProps } from './Progress';
75
76
  export type { RadioGroupProps, RadioProps } from './Radio';
76
77
  export type { RatingProps } from './Rating';
77
78
  export type { SegmentedControlProps, SegmentedControlItemProps, SegmentedControlValue, SegmentedControlVariant, SegmentedControlSize, SegmentedControlOrientation, } from './SegmentedControl';
78
- export type { SidebarProps, SidebarHeaderProps, SidebarNavProps } from './Sidebar';
79
+ export type { SidebarProps, SidebarHeaderProps, SidebarFooterProps, SidebarNavProps, SidebarToggleProps, SidebarToggleLabels, } from './Sidebar';
79
80
  export type { StepIndicatorProps, StepStatus } from './StepIndicator';
80
81
  export type { StepListProps, StepListItemProps } from './StepList';
81
82
  export type { DataTableProps } from './Table';
@@ -86,6 +87,7 @@ export type { SearchSelectProps, SearchSelectTriggerProps, SearchSelectContentPr
86
87
  export type { SwitchProps } from './Switch';
87
88
  export type { TextareaProps, TextareaResize } from './Textarea';
88
89
  export type { TextInputProps, TextInputType } from './TextInput';
90
+ export type { ToastProps, ToastHandle, ToastTheme, ToastAnnounce, ToastPlacement, ToastOptions, ToastContextValue, ToastProviderProps, } from './Toast';
89
91
  export type { ToolbarProps, ToolbarGroupProps, ToolbarItemProps, ToolbarOrientation } from './Toolbar';
90
92
  export type { TooltipProps, TooltipProviderProps, TooltipTriggerProps, TooltipContentProps } from './Tooltip';
91
93
  export { GENERATIVE_COLORS, stringToGenerativeColor } from '../utils/generative';
@@ -30,7 +30,7 @@ export { RadioGroup, Radio } from './Radio/index.js';
30
30
  export { Rating } from './Rating/index.js';
31
31
  export { SegmentedControl } from './SegmentedControl/index.js';
32
32
  export { Slider } from './Slider/index.js';
33
- export { Sidebar } from './Sidebar/index.js';
33
+ export { Sidebar, defaultSidebarToggleLabels } from './Sidebar/index.js';
34
34
  export { StepIndicator } from './StepIndicator/index.js';
35
35
  export { StepList } from './StepList/index.js';
36
36
  export { DataTable } from './Table/index.js';
@@ -41,6 +41,7 @@ export { Switch } from './Switch/index.js';
41
41
  export { Tabs } from './Tabs/index.js';
42
42
  export { Textarea } from './Textarea/index.js';
43
43
  export { TextInput } from './TextInput/index.js';
44
+ export { Toast, ToastProvider, useToast } from './Toast/index.js';
44
45
  export { Toolbar } from './Toolbar/index.js';
45
46
  export { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from './Tooltip/index.js';
46
47
  // Generative colors (The Jellybean Bag) — deterministic identity colors
package/figma-tokens.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.2.17",
2
+ "version": "0.2.19",
3
3
  "source": "publish/styles/all.expanded.css",
4
4
  "prefix": "tui-",
5
5
  "note": "Layer 1 primitives only. Component API tokens (--tui-{component}-*) are never defined in CSS — they exist only as fallback reads — so they have no Figma representation.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangible/ui",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "description": "Tangible Design System",
5
5
  "type": "module",
6
6
  "main": "./components/index.js",
@@ -218,6 +218,10 @@
218
218
  "import": "./components/Textarea/index.js",
219
219
  "types": "./components/Textarea/index.d.ts"
220
220
  },
221
+ "./components/Toast": {
222
+ "import": "./components/Toast/index.js",
223
+ "types": "./components/Toast/index.d.ts"
224
+ },
221
225
  "./components/Toolbar": {
222
226
  "import": "./components/Toolbar/index.js",
223
227
  "types": "./components/Toolbar/index.d.ts"
@@ -80,7 +80,8 @@ their full `--tui-<component>-*` API — the only shipped listing, since consume
80
80
  0.2.12.)
81
81
  - **Most union / variant aliases**: `AccordionVariant`, `ContentIndicatorSize`,
82
82
  `ComboboxFilterMode`, `IconButton`'s `Shape`/`Variant`, `NoticeHandle`, `ProgressSegment`,
83
- `OptionValue`, `SidebarFooterProps`, `TooltipTheme`, …
83
+ `OptionValue`, `TooltipTheme`, … (`SidebarFooterProps` was on this list until 0.2.18, which
84
+ also exported the new `SidebarToggleProps`.)
84
85
  - **All of DatePicker** — the barrel exports zero DatePicker types: `DatePickerProps`,
85
86
  `DateRangePickerProps`, `CalendarProps`, `DateRange`, `DateRangePreset`, `WeekStart`.
86
87
  - **`SliderProps`**, which is missing entirely.