@tangible/ui 0.2.25 → 0.2.27

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.
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
- import type { NavMenuItemProps, NavMenuLabels, NavMenuOrientation, NavMenuSubProps } from './types';
2
+ import type { NavMenuFlyoutTrigger, NavMenuItemProps, NavMenuLabels, NavMenuOrientation, NavMenuSubProps } from './types';
3
3
  /**
4
4
  * Navigation menu rows: groups with headings, the current item, nested items.
5
5
  * Vertical by default (sidebars). `orientation="horizontal"` makes a bar whose
@@ -10,6 +10,7 @@ import type { NavMenuItemProps, NavMenuLabels, NavMenuOrientation, NavMenuSubPro
10
10
  */
11
11
  declare const NavMenuRoot: import("react").ForwardRefExoticComponent<Omit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & {
12
12
  orientation?: NavMenuOrientation;
13
+ flyoutTrigger?: NavMenuFlyoutTrigger;
13
14
  labels?: NavMenuLabels;
14
15
  children: ReactNode;
15
16
  } & import("react").RefAttributes<HTMLDivElement>>;
@@ -6,15 +6,32 @@ import { isDev } from '../../utils/is-dev.js';
6
6
  import { mergeProps } from '../../utils/merge-props.js';
7
7
  import { composeRefs, getElementRef } from '../../utils/compose-refs.js';
8
8
  import { Icon } from '../Icon/index.js';
9
+ import { createHoverWarmth, isWarm, markClosed, markOpen, sampleHoverIntent } from '../../utils/hover-intent.js';
9
10
  import { defaultNavMenuLabels } from './types.js';
11
+ // Hover intent and warmth come from utils/hover-intent (shared with tooltips).
12
+ // A panel opens when the pointer settles, not after a fixed delay; once the
13
+ // bar is warm (a panel open, or one closed within PRIMED_WINDOW) the next
14
+ // opens at once.
15
+ const INTERACTIVE = [
16
+ 'a[href]', 'area[href]', 'button', 'input:not([type=hidden])', 'select', 'textarea', 'summary',
17
+ 'iframe', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable=false])',
18
+ '[tabindex]:not([tabindex="-1"])', '[role=button]', '[role=link]', '[role=checkbox]', '[role=switch]',
19
+ '[role=menuitem]', '[role=tab]', '[aria-haspopup]',
20
+ ].join(', ');
21
+ const PRIMED_WINDOW = 400;
22
+ // Grace period for crossing into the panel.
23
+ const HOVER_CLOSE_DELAY = 300;
10
24
  // Items render <li>, so they're only valid inside a Group or Sub list. The
11
25
  // context exists to warn when one isn't.
12
26
  const ListContext = createContext(false);
13
27
  const RootContext = createContext({
14
28
  orientation: 'vertical',
29
+ flyoutTrigger: 'click',
15
30
  labels: defaultNavMenuLabels,
16
31
  openId: null,
17
32
  setOpenId: () => { },
33
+ rootRef: { current: null },
34
+ warmth: createHoverWarmth(),
18
35
  });
19
36
  // True inside a flyout panel: everything there lays out vertically, and an
20
37
  // item with its own Sub nests inline instead of opening another flyout.
@@ -30,10 +47,13 @@ const FlyoutContext = createContext(false);
30
47
  * hover-to-open. Not a landmark: put it inside `Sidebar.Nav` or a labelled
31
48
  * `<nav>`.
32
49
  */
33
- const NavMenuRoot = forwardRef(function NavMenu({ orientation = 'vertical', labels, className, children, ...rest }, ref) {
50
+ const NavMenuRoot = forwardRef(function NavMenu({ orientation = 'vertical', flyoutTrigger = 'click', labels, className, children, ...rest }, ref) {
34
51
  const [openId, setOpenId] = useState(null);
35
- const value = useMemo(() => ({ orientation, labels: { ...defaultNavMenuLabels, ...labels }, openId, setOpenId }), [orientation, labels, openId]);
36
- return (_jsx("div", { ref: ref, ...rest, "data-orientation": orientation, className: cx('tui-nav-menu', orientation === 'horizontal' && 'is-horizontal', className), children: _jsx(RootContext.Provider, { value: value, children: children }) }));
52
+ const rootRef = useRef(null);
53
+ // One warmth group per bar, created once (useState's lazy init).
54
+ const [warmth] = useState(createHoverWarmth);
55
+ const value = useMemo(() => ({ orientation, flyoutTrigger, labels: { ...defaultNavMenuLabels, ...labels }, openId, setOpenId, rootRef, warmth }), [orientation, flyoutTrigger, labels, openId, warmth]);
56
+ return (_jsx("div", { ref: composeRefs(ref, rootRef), ...rest, "data-orientation": orientation, className: cx('tui-nav-menu', orientation === 'horizontal' && 'is-horizontal', className), children: _jsx(RootContext.Provider, { value: value, children: children }) }));
37
57
  });
38
58
  // =============================================================================
39
59
  // NavMenu.Group
@@ -79,9 +99,9 @@ function toAriaCurrent(current) {
79
99
  }
80
100
  const isSub = (node) => isValidElement(node) && node.type === NavMenuSub;
81
101
  const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
82
- const { current, icon, disabled, asChild, className, children, ...rest } = props;
102
+ const { current, icon, prefix, suffix, disabled, asChild, className, children, ...rest } = props;
83
103
  const inList = useContext(ListContext);
84
- const { orientation, labels, openId, setOpenId } = useContext(RootContext);
104
+ const { orientation, flyoutTrigger, labels, openId, setOpenId, rootRef, warmth } = useContext(RootContext);
85
105
  const inFlyout = useContext(FlyoutContext);
86
106
  const warned = useRef(false);
87
107
  useEffect(() => {
@@ -90,6 +110,31 @@ const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
90
110
  console.warn('NavMenu.Item renders an <li>: place it inside NavMenu.Group or NavMenu.Sub.');
91
111
  }
92
112
  }, [inList]);
113
+ // The slots render inside the row's <a>/<button>, where interactive content
114
+ // is invalid HTML and unreachable for keyboard users.
115
+ const prefixRef = useRef(null);
116
+ const suffixRef = useRef(null);
117
+ const slotWarned = useRef({ both: false, interactive: false, named: false });
118
+ const restProps = rest;
119
+ const hasSlot = prefix != null || suffix != null;
120
+ const namedOver = hasSlot && (restProps['aria-label'] != null || restProps['aria-labelledby'] != null);
121
+ useEffect(() => {
122
+ if (!isDev())
123
+ return;
124
+ const w = slotWarned.current;
125
+ if (!w.both && prefix != null && icon) {
126
+ w.both = true;
127
+ console.warn('NavMenu.Item: `prefix` replaces `icon`; pass one or the other.');
128
+ }
129
+ if (!w.named && namedOver) {
130
+ w.named = true;
131
+ console.warn('NavMenu.Item: `aria-label`/`aria-labelledby` replaces the whole accessible name, so the `prefix`/`suffix` text is never announced. Let the row be named by its content.');
132
+ }
133
+ if (!w.interactive && [prefixRef.current, suffixRef.current].some((slot) => slot?.querySelector(INTERACTIVE))) {
134
+ w.interactive = true;
135
+ console.warn('NavMenu.Item: `prefix`/`suffix` render inside the row link, so they must not contain interactive content (links, buttons, inputs, tabindex).');
136
+ }
137
+ });
93
138
  // Sub lists render after the link, inside the same <li>.
94
139
  const all = Children.toArray(children);
95
140
  const subs = all.filter(isSub);
@@ -101,42 +146,189 @@ const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
101
146
  const toggleTextId = `${id}-toggle`;
102
147
  const flyout = orientation === 'horizontal' && !inFlyout && subs.length > 0 && !disabled;
103
148
  const open = flyout && openId === id;
149
+ // Close with an updater, never the rendered openId: a timer scheduled while
150
+ // this item was open runs later, when another item may own openId, and a
151
+ // stale `openId === id` check closed that other item (hover A, then B
152
+ // quickly: B opened, then A's close timer shut it).
104
153
  const setOpen = useCallback((next) => {
105
154
  if (next)
106
155
  setOpenId(id);
107
- else if (openId === id)
108
- setOpenId(null);
109
- }, [id, openId, setOpenId]);
156
+ else
157
+ setOpenId((current) => (current === id ? null : current));
158
+ }, [id, setOpenId]);
159
+ // -- Hover (flyoutTrigger="hover") ------------------------------------------
160
+ // Opt-in, mouse only, and built to WCAG 1.4.13 (content on hover):
161
+ // - Hover intent: a short open delay, so sweeping across the bar doesn't
162
+ // flash panels.
163
+ // - Hoverable: a close delay, so the pointer can cross the gap into the
164
+ // panel without it closing.
165
+ // - Dismissible: Escape closes it and it stays closed until the pointer
166
+ // leaves, so it never re-opens under a pointer that's still there.
167
+ // Clicking a hover-opened toggle pins it open rather than yanking it shut,
168
+ // and keyboard behaviour is unchanged.
169
+ const hover = flyout && flyoutTrigger === 'hover';
170
+ const hoverTimer = useRef(null);
171
+ const openedByHover = useRef(false);
172
+ const dismissedWhileHovered = useRef(false);
173
+ const pointerInside = useRef(false);
174
+ // Another panel opening means the pointer (or focus) has moved on, so a
175
+ // pending "dismissed while hovered" no longer applies here.
176
+ // Its pending hover timer is void too: cancelled here so it can't fire into
177
+ // the other item's panel.
178
+ useEffect(() => {
179
+ if (openId !== null && openId !== id) {
180
+ if (hoverTimer.current)
181
+ clearTimeout(hoverTimer.current);
182
+ hoverTimer.current = null;
183
+ openedByHover.current = false;
184
+ dismissedWhileHovered.current = false;
185
+ pointerInside.current = false;
186
+ }
187
+ }, [openId, id]);
188
+ const clearHoverTimer = () => {
189
+ if (hoverTimer.current)
190
+ clearTimeout(hoverTimer.current);
191
+ hoverTimer.current = null;
192
+ };
193
+ useEffect(() => clearHoverTimer, []);
194
+ useEffect(() => () => cancelIntent.current?.(), []);
195
+ // Warmth membership: open counts toward the bar being warm, and closing
196
+ // keeps it warm briefly, so drifting off and straight on to a neighbour
197
+ // isn't a cold start. A dismissal (Escape) cools it instead.
198
+ const dismissed = useRef(false);
199
+ useEffect(() => {
200
+ if (!open)
201
+ return;
202
+ dismissed.current = false;
203
+ markOpen(warmth);
204
+ return () => markClosed(warmth, dismissed.current ? 0 : PRIMED_WINDOW);
205
+ }, [open, warmth]);
206
+ // Intent sampling: the latest pointer position, read by the sampler.
207
+ const pointerPos = useRef({ x: 0, y: 0 });
208
+ const cancelIntent = useRef(null);
209
+ const stopIntent = () => {
210
+ cancelIntent.current?.();
211
+ cancelIntent.current = null;
212
+ };
213
+ const openFromHover = () => {
214
+ clearHoverTimer();
215
+ stopIntent();
216
+ openedByHover.current = true;
217
+ setOpen(true);
218
+ };
219
+ const onEntryPointerEnter = (e) => {
220
+ if (e.pointerType === 'mouse')
221
+ pointerPos.current = { x: e.clientX, y: e.clientY };
222
+ if (e.pointerType === 'mouse')
223
+ pointerInside.current = true;
224
+ if (!hover || e.pointerType !== 'mouse' || dismissedWhileHovered.current)
225
+ return;
226
+ clearHoverTimer();
227
+ stopIntent();
228
+ if (open)
229
+ return;
230
+ // Warm: another panel is open, or one just closed. Open at once, as a bar
231
+ // does; otherwise wait for the pointer to settle.
232
+ if (openId !== null || isWarm(warmth)) {
233
+ openFromHover();
234
+ return;
235
+ }
236
+ cancelIntent.current = sampleHoverIntent({ readPointer: () => pointerPos.current, onIntent: openFromHover });
237
+ };
238
+ const onEntryPointerMove = (e) => {
239
+ if (e.pointerType === 'mouse')
240
+ pointerPos.current = { x: e.clientX, y: e.clientY };
241
+ };
242
+ const onEntryPointerLeave = (e) => {
243
+ if (e.pointerType === 'mouse')
244
+ pointerInside.current = false;
245
+ if (!hover || e.pointerType !== 'mouse')
246
+ return;
247
+ dismissedWhileHovered.current = false;
248
+ clearHoverTimer();
249
+ stopIntent();
250
+ if (!open || !openedByHover.current)
251
+ return;
252
+ // Keyboard presence pins it: closing under focus would strand focus on
253
+ // <body> (SC 2.4.3) when the mouse drifts off a panel the user tabbed into.
254
+ if (entryRef.current?.contains(document.activeElement)) {
255
+ openedByHover.current = false;
256
+ return;
257
+ }
258
+ hoverTimer.current = setTimeout(() => {
259
+ openedByHover.current = false;
260
+ setOpen(false);
261
+ }, HOVER_CLOSE_DELAY);
262
+ };
263
+ const toggleOnClick = (e) => {
264
+ clearHoverTimer();
265
+ // A pointer click on a hover-opened panel pins it. Keyboard activation
266
+ // (detail 0) toggles as always, so Enter never looks like a no-op.
267
+ if (open && openedByHover.current && e.detail > 0) {
268
+ openedByHover.current = false; // pinned
269
+ return;
270
+ }
271
+ openedByHover.current = false;
272
+ setOpen(!open);
273
+ };
110
274
  const entryRef = useRef(null);
111
275
  const toggleRef = useRef(null);
112
- const { refs, floatingStyles } = useFloating({
276
+ const { refs, floatingStyles, isPositioned } = useFloating({
113
277
  open,
114
278
  placement: 'bottom-start',
115
279
  strategy: 'absolute',
116
280
  middleware: [offset(4), flip(), shift({ padding: 8 })],
117
281
  whileElementsMounted: autoUpdate,
118
282
  });
119
- // Click or tap outside closes it. Focus leaving is handled by onBlur below.
283
+ // Moving to another flyout toggle in the same menu is a switch, not a
284
+ // dismissal: its click hands openId over in one update. Closing here on
285
+ // pointerdown or focusout instead left a frame with no panel at all, and
286
+ // set both chevrons animating (Julia: "the menu briefly disappears and the
287
+ // indicator animates back and forth").
288
+ const isSiblingToggle = useCallback((node) => node instanceof Element &&
289
+ !entryRef.current?.contains(node) &&
290
+ (rootRef.current?.contains(node) ?? false) &&
291
+ node.closest('.tui-nav-menu__entry.has-flyout [aria-expanded]') !== null, [rootRef]);
292
+ // While open: a click or tap outside closes it, and Escape closes it from
293
+ // anywhere. Escape is on the document, not the entry, because a
294
+ // hover-opened panel never has focus, and WCAG 1.4.13 needs hover content
295
+ // dismissible without moving focus. Focus returns to the toggle only if it
296
+ // was inside the entry, so a mouse user's focus isn't pulled anywhere.
297
+ // Focus leaving is handled by onBlur below.
120
298
  useEffect(() => {
121
299
  if (!open)
122
300
  return;
123
301
  const onPointerDown = (e) => {
124
- if (!entryRef.current?.contains(e.target))
302
+ if (!entryRef.current?.contains(e.target) && !isSiblingToggle(e.target))
125
303
  setOpen(false);
126
304
  };
127
- document.addEventListener('pointerdown', onPointerDown);
128
- return () => document.removeEventListener('pointerdown', onPointerDown);
129
- }, [open, setOpen]);
130
- const onEntryKeyDown = (e) => {
131
- if (open && e.key === 'Escape') {
305
+ const onKeyDown = (e) => {
306
+ if (e.key !== 'Escape')
307
+ return;
132
308
  e.preventDefault();
309
+ clearHoverTimer();
310
+ // Only "dismissed while hovered" if the pointer really is still there;
311
+ // otherwise there'd be no pointerleave to clear it.
312
+ if (openedByHover.current && pointerInside.current)
313
+ dismissedWhileHovered.current = true;
314
+ openedByHover.current = false;
315
+ dismissed.current = true;
316
+ const focusWasInside = entryRef.current?.contains(document.activeElement) ?? false;
133
317
  setOpen(false);
134
- toggleRef.current?.focus();
135
- }
136
- };
318
+ if (focusWasInside)
319
+ toggleRef.current?.focus();
320
+ };
321
+ document.addEventListener('pointerdown', onPointerDown);
322
+ document.addEventListener('keydown', onKeyDown);
323
+ return () => {
324
+ document.removeEventListener('pointerdown', onPointerDown);
325
+ document.removeEventListener('keydown', onKeyDown);
326
+ };
327
+ }, [open, setOpen, isSiblingToggle]);
137
328
  const onEntryBlur = (e) => {
138
- if (open && !entryRef.current?.contains(e.relatedTarget))
329
+ if (open && !entryRef.current?.contains(e.relatedTarget) && !isSiblingToggle(e.relatedTarget)) {
139
330
  setOpen(false);
331
+ }
140
332
  };
141
333
  // Safari and Firefox on macOS don't focus a button on click. Without this,
142
334
  // clicking the toggle to close an open flyout blurs the panel first (closing
@@ -152,8 +344,11 @@ const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
152
344
  // Top-level rows of a bar. Rows inside a flyout panel keep the vertical look.
153
345
  const bar = orientation === 'horizontal' && !inFlyout;
154
346
  const itemClass = cx('tui-nav-menu__item', bar && 'is-bar', className);
155
- const iconNode = icon ? (_jsx("span", { className: "tui-nav-menu__icon", "aria-hidden": "true", children: _jsx(Icon, { name: icon }) })) : null;
156
- const content = (inner) => (_jsxs(_Fragment, { children: [iconNode, _jsx("span", { className: "tui-nav-menu__label", id: flyout ? labelId : undefined, children: inner })] }));
347
+ const leading = prefix != null ? (_jsx("span", { className: "tui-nav-menu__prefix", ref: prefixRef, children: prefix })) : icon ? (_jsx("span", { className: "tui-nav-menu__icon", "aria-hidden": "true", children: _jsx(Icon, { name: icon }) })) : null;
348
+ // The ' ' text nodes keep the slots as separate words in the accessible
349
+ // name ("Inbox 3 unread", not "Inbox3 unread"). A flex container doesn't
350
+ // render whitespace-only text, so layout is unaffected.
351
+ const content = (inner) => (_jsxs(_Fragment, { children: [leading, leading && prefix != null && ' ', _jsx("span", { className: "tui-nav-menu__label", id: flyout ? labelId : undefined, children: inner }), suffix != null && (_jsxs(_Fragment, { children: [' ', _jsx("span", { className: "tui-nav-menu__suffix", ref: suffixRef, children: suffix })] }))] }));
157
352
  const chevron = (_jsx("span", { className: "tui-nav-menu__chevron", "aria-hidden": "true", children: _jsx(Icon, { name: "system/chevron-down-small" }) }));
158
353
  let row;
159
354
  // A flyout parent with no destination of its own: the row IS the toggle.
@@ -172,7 +367,7 @@ const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
172
367
  row = (_jsxs("button", { ref: composeRefs(ref, toggleRef), type: "button", ...rest, className: cx(itemClass, 'is-toggle'), "aria-current": ariaCurrent, "aria-expanded": open, "aria-controls": panelId, onPointerDown: focusOnPointerDown, onClick: (e) => {
173
368
  restProps.onClick?.(e);
174
369
  if (!e.defaultPrevented)
175
- setOpen(!open);
370
+ toggleOnClick(e);
176
371
  }, children: [content(label), chevron] }));
177
372
  }
178
373
  else if (asChild) {
@@ -206,11 +401,18 @@ const NavMenuItem = forwardRef(function NavMenuItem(props, ref) {
206
401
  if (!flyout) {
207
402
  return (_jsxs("li", { className: "tui-nav-menu__entry", children: [row, !(disabled && bar) && subs] }));
208
403
  }
209
- return (_jsxs("li", { ref: composeRefs(entryRef, refs.setReference), className: cx('tui-nav-menu__entry', 'has-flyout', !rowIsToggle && 'is-split'), onKeyDown: onEntryKeyDown, onBlur: onEntryBlur, children: [row, !rowIsToggle && (
404
+ return (_jsxs("li", { ref: composeRefs(entryRef, refs.setReference), className: cx('tui-nav-menu__entry', 'has-flyout', !rowIsToggle && 'is-split'), onBlur: onEntryBlur, onPointerEnter: onEntryPointerEnter, onPointerMove: hover ? onEntryPointerMove : undefined, onPointerLeave: onEntryPointerLeave, children: [row, !rowIsToggle && (
210
405
  // A link can't also toggle, so a parent with a destination gets its own
211
406
  // toggle. It's named "<label> <submenu>", so the bar never has a row
212
407
  // of identical "toggle" buttons.
213
- _jsxs("button", { ref: toggleRef, type: "button", className: cx('tui-nav-menu__toggle', 'is-bar'), "aria-expanded": open, "aria-controls": panelId, "aria-labelledby": `${labelId} ${toggleTextId}`, onPointerDown: focusOnPointerDown, onClick: () => setOpen(!open), children: [chevron, _jsx("span", { id: toggleTextId, hidden: true, children: labels.submenu })] })), _jsx("div", { id: panelId, ref: refs.setFloating, style: floatingStyles, className: "tui-nav-menu__flyout", hidden: !open,
408
+ _jsxs("button", { ref: toggleRef, type: "button", className: cx('tui-nav-menu__toggle', 'is-bar'), "aria-expanded": open, "aria-controls": panelId, "aria-labelledby": `${labelId} ${toggleTextId}`, onPointerDown: focusOnPointerDown, onClick: toggleOnClick, children: [chevron, _jsx("span", { id: toggleTextId, hidden: true, children: labels.submenu })] })), _jsx("div", { id: panelId, ref: refs.setFloating,
409
+ // While hidden the panel has no size, so its last position is stale.
410
+ // Until Floating UI has placed it for this opening it's transparent,
411
+ // or it paints a frame at the stale spot (past the viewport edge, at
412
+ // the bar's end) before jumping into place. Opacity, not visibility:
413
+ // it must stay focusable and in the accessibility tree, so Enter then
414
+ // an immediate Tab still lands inside.
415
+ style: { ...floatingStyles, opacity: open && !isPositioned ? 0 : undefined }, className: "tui-nav-menu__flyout", hidden: !open,
214
416
  // Following a link inside closes the panel (APG): in a single-page
215
417
  // app nothing else would, and it would sit over the new page. Enter
216
418
  // on a link fires click too. Router onClicks compose: this runs after
@@ -1,3 +1,3 @@
1
1
  export { NavMenu } from './NavMenu';
2
2
  export { defaultNavMenuLabels } from './types';
3
- export type { NavMenuProps, NavMenuOrientation, NavMenuLabels, NavMenuGroupProps, NavMenuGroupLabelElement, NavMenuItemProps, NavMenuItemAsLink, NavMenuItemAsButton, NavMenuItemAsChild, NavMenuCurrent, NavMenuSubProps, } from './types';
3
+ export type { NavMenuProps, NavMenuOrientation, NavMenuFlyoutTrigger, NavMenuLabels, NavMenuGroupProps, NavMenuGroupLabelElement, NavMenuItemProps, NavMenuItemAsLink, NavMenuItemAsButton, NavMenuItemAsChild, NavMenuCurrent, NavMenuSubProps, } from './types';
@@ -1,6 +1,7 @@
1
1
  import type { ComponentPropsWithoutRef, ReactNode } from 'react';
2
2
  import type { IconName } from '../../icons/registry';
3
3
  export type NavMenuOrientation = 'vertical' | 'horizontal';
4
+ export type NavMenuFlyoutTrigger = 'click' | 'hover';
4
5
  /** Visually hidden strings, for localisation. */
5
6
  export type NavMenuLabels = {
6
7
  /**
@@ -27,6 +28,18 @@ export type NavMenuProps = ComponentPropsWithoutRef<'div'> & {
27
28
  * @default 'vertical'
28
29
  */
29
30
  orientation?: NavMenuOrientation;
31
+ /**
32
+ * How a horizontal bar's flyouts open. `click` (default): click or
33
+ * Enter/Space. `hover`: also opens for a mouse once the pointer settles on
34
+ * an item (hover intent, as in WordPress's Toolbar: under 6px of movement in
35
+ * 100ms), so sweeping across the bar opens nothing. Once primed (a panel is
36
+ * open, or one just closed), the next opens at once. There's a grace period
37
+ * for crossing into the panel. Escape dismisses it until the pointer leaves
38
+ * (WCAG 1.4.13); clicking pins it open. Touch and keyboard behave as `click`
39
+ * either way.
40
+ * @default 'click'
41
+ */
42
+ flyoutTrigger?: NavMenuFlyoutTrigger;
30
43
  /** Visually hidden strings. */
31
44
  labels?: NavMenuLabels;
32
45
  children: ReactNode;
@@ -60,6 +73,28 @@ type NavMenuItemBaseProps = {
60
73
  current?: NavMenuCurrent;
61
74
  /** Leading icon, from the registry. Sized by `--tui-nav-menu-icon-size`. */
62
75
  icon?: IconName;
76
+ /**
77
+ * Custom leading content in the icon's place (an avatar, a glyph not in the
78
+ * registry). Replaces `icon` when both are set. Unlike `icon`, it isn't
79
+ * hidden from assistive tech: mark decorative content `aria-hidden`
80
+ * yourself, or its text joins the name. A shape drawn with CSS `background`
81
+ * disappears in forced colors; give it a border if it carries meaning.
82
+ */
83
+ prefix?: ReactNode;
84
+ /**
85
+ * Trailing content pushed to the row's inline end: a badge, a count. It sits
86
+ * inside the row, so its text joins the accessible name: give a bare number
87
+ * context, so `3 <span class="tui-visually-hidden">unread</span>` reads
88
+ * "Inbox 3 unread" (put the space outside the hidden span). Must not be
89
+ * interactive (no buttons or links): a control nested in a link is invalid.
90
+ *
91
+ * Both slots reach the name only through the row's content, so don't pass
92
+ * `aria-label`/`aria-labelledby` to an item with a slot: either replaces
93
+ * the whole name. On a row that is itself the flyout's disclosure button,
94
+ * the suffix is part of the button's name; on a split row it belongs to the
95
+ * link (the destination), and the toggle stays "Reports submenu".
96
+ */
97
+ suffix?: ReactNode;
63
98
  /**
64
99
  * Inert item: rendered as a disabled link (`role="link"`, `aria-disabled`,
65
100
  * no href), out of the tab order. For destinations that exist but aren't
@@ -78,12 +113,12 @@ type NavMenuItemBaseProps = {
78
113
  children: ReactNode;
79
114
  };
80
115
  /** Link item: renders an `<a>`. */
81
- export type NavMenuItemAsLink = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'a'>, 'children' | 'aria-current'> & {
116
+ export type NavMenuItemAsLink = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'a'>, 'children' | 'aria-current' | 'prefix'> & {
82
117
  href: string;
83
118
  asChild?: never;
84
119
  };
85
120
  /** Action item: renders a `<button type="button">`. */
86
- export type NavMenuItemAsButton = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'button'>, 'children' | 'aria-current' | 'disabled'> & {
121
+ export type NavMenuItemAsButton = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'button'>, 'children' | 'aria-current' | 'prefix' | 'disabled'> & {
87
122
  href?: never;
88
123
  asChild?: never;
89
124
  };
@@ -92,7 +127,7 @@ export type NavMenuItemAsButton = NavMenuItemBaseProps & Omit<ComponentPropsWith
92
127
  * `<Link>`, say). It receives the item's class, `aria-current`, the icon and
93
128
  * a label wrapper. It must render a real `<a href>`.
94
129
  */
95
- export type NavMenuItemAsChild = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'a'>, 'children' | 'aria-current' | 'href'> & {
130
+ export type NavMenuItemAsChild = NavMenuItemBaseProps & Omit<ComponentPropsWithoutRef<'a'>, 'children' | 'aria-current' | 'prefix' | 'href'> & {
96
131
  asChild: true;
97
132
  href?: never;
98
133
  };
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import React, { useCallback, useEffect, useRef, cloneElement, isValidElement, } from 'react';
3
3
  import { cx } from '../../utils/cx.js';
4
+ import { TooltipWarmthScope } from '../Tooltip/TooltipWarmthScope.js';
4
5
  import { isDev } from '../../utils/is-dev.js';
5
6
  // =============================================================================
6
7
  // Toolbar Component
@@ -204,7 +205,7 @@ function ToolbarRoot({ 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledB
204
205
  return (_jsx("div", { ref: containerRef, role: "toolbar", "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-orientation": orientation, className: cx('tui-toolbar', className), style: style,
205
206
  // Capture phase catches focus on inner elements (SVG icons, spans) before
206
207
  // they handle it, allowing us to update roving tabindex correctly
207
- onFocusCapture: handleFocusIn, onKeyDown: handleKeyDown, children: children }));
208
+ onFocusCapture: handleFocusIn, onKeyDown: handleKeyDown, children: _jsx(TooltipWarmthScope, { children: children }) }));
208
209
  }
209
210
  // =============================================================================
210
211
  // Toolbar Group
@@ -1,5 +1,5 @@
1
1
  import type { TooltipProviderProps, TooltipProps, TooltipTriggerProps, TooltipContentProps } from './types';
2
- declare function TooltipProviderComponent({ delayDuration, closeDelayDuration, children, }: TooltipProviderProps): import("react/jsx-runtime").JSX.Element;
2
+ declare function TooltipProviderComponent({ delayDuration, closeDelayDuration, skipDelayDuration, children, }: TooltipProviderProps): import("react/jsx-runtime").JSX.Element;
3
3
  declare function TooltipRoot({ open: controlledOpen, onOpenChange, defaultOpen, delayDuration: localDelay, children, }: TooltipProps): import("react/jsx-runtime").JSX.Element;
4
4
  declare function TooltipTriggerComponent({ asChild, 'aria-label': ariaLabel, children, }: TooltipTriggerProps): import("react/jsx-runtime").JSX.Element;
5
5
  declare function TooltipContentComponent(props: TooltipContentProps): import("react/jsx-runtime").JSX.Element | null;
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import React, { useCallback, useEffect, useId, useMemo, useRef, useState, cloneElement, isValidElement, } from 'react';
3
+ import { createHoverWarmth, isWarm, markClosed, markOpen } from '../../utils/hover-intent.js';
3
4
  import { isDev } from '../../utils/is-dev.js';
4
5
  import { useFloating, offset, flip, shift, arrow, autoUpdate, FloatingPortal, FloatingArrow, } from '@floating-ui/react';
5
6
  import { cx } from '../../utils/cx.js';
@@ -10,8 +11,10 @@ import { toPlacement } from './types.js';
10
11
  // =============================================================================
11
12
  // TooltipProvider
12
13
  // =============================================================================
13
- function TooltipProviderComponent({ delayDuration = 400, closeDelayDuration = 150, children, }) {
14
- const value = useMemo(() => ({ delayDuration, closeDelayDuration }), [delayDuration, closeDelayDuration]);
14
+ function TooltipProviderComponent({ delayDuration = 400, closeDelayDuration = 150, skipDelayDuration = 300, children, }) {
15
+ const [warmth] = useState(createHoverWarmth);
16
+ const [activeClose] = useState(() => ({ current: null }));
17
+ const value = useMemo(() => ({ delayDuration, closeDelayDuration, skipDelayDuration, warmth, activeClose }), [delayDuration, closeDelayDuration, skipDelayDuration, warmth, activeClose]);
15
18
  return (_jsx(TooltipProviderContext.Provider, { value: value, children: children }));
16
19
  }
17
20
  // =============================================================================
@@ -52,10 +55,52 @@ function TooltipRoot({ open: controlledOpen, onOpenChange, defaultOpen = false,
52
55
  closeTimeoutRef.current = null;
53
56
  }
54
57
  }, []);
58
+ const { warmth, skipDelayDuration, activeClose } = providerContext;
55
59
  const handleOpen = useCallback(() => {
56
60
  clearAllTimeouts();
61
+ // Warm group: a tooltip is showing, or one just closed. Open at once.
62
+ if (warmth && isWarm(warmth)) {
63
+ setOpen(true);
64
+ return;
65
+ }
57
66
  openTimeoutRef.current = setTimeout(() => setOpen(true), resolvedDelay);
58
- }, [clearAllTimeouts, resolvedDelay, setOpen]);
67
+ }, [clearAllTimeouts, resolvedDelay, setOpen, warmth]);
68
+ // Warmth membership. Open counts toward the group being warm; closing keeps
69
+ // it warm for skipDelayDuration, unless it was dismissed. One at a time: a
70
+ // tooltip opening in a warm group closes the previous one at once, rather
71
+ // than both showing through its close delay.
72
+ const dismissedRef = useRef(false);
73
+ // Read through a ref: an inline onOpenChange makes setOpen a new function
74
+ // every render, and the membership effect must not re-run (and churn the
75
+ // warm window) for that.
76
+ const setOpenRef = useRef(setOpen);
77
+ setOpenRef.current = setOpen;
78
+ useEffect(() => {
79
+ if (!open || !warmth)
80
+ return;
81
+ dismissedRef.current = false;
82
+ markOpen(warmth);
83
+ const closeNow = () => {
84
+ clearAllTimeouts();
85
+ setOpenRef.current(false);
86
+ };
87
+ if (activeClose) {
88
+ const previous = activeClose.current;
89
+ activeClose.current = closeNow;
90
+ if (previous)
91
+ previous();
92
+ }
93
+ return () => {
94
+ markClosed(warmth, dismissedRef.current ? 0 : skipDelayDuration);
95
+ if (activeClose?.current === closeNow)
96
+ activeClose.current = null;
97
+ };
98
+ }, [open, warmth, activeClose, skipDelayDuration, clearAllTimeouts]);
99
+ const dismiss = useCallback(() => {
100
+ dismissedRef.current = true;
101
+ clearAllTimeouts();
102
+ setOpen(false);
103
+ }, [clearAllTimeouts, setOpen]);
59
104
  const handleClose = useCallback(() => {
60
105
  clearAllTimeouts();
61
106
  if (resolvedCloseDelay > 0) {
@@ -79,7 +124,8 @@ function TooltipRoot({ open: controlledOpen, onOpenChange, defaultOpen = false,
79
124
  handleOpen,
80
125
  handleClose,
81
126
  cancelClose,
82
- }), [open, setOpen, contentId, resolvedDelay, resolvedCloseDelay, handleOpen, handleClose, cancelClose]);
127
+ dismiss,
128
+ }), [open, setOpen, contentId, resolvedDelay, resolvedCloseDelay, handleOpen, handleClose, cancelClose, dismiss]);
83
129
  return (_jsx(TooltipContext.Provider, { value: contextValue, children: children }));
84
130
  }
85
131
  // =============================================================================
@@ -132,7 +178,7 @@ function TooltipContentComponent(props) {
132
178
  }
133
179
  // Inner component: only mounted when open. All Floating UI hooks live here.
134
180
  function TooltipContentInner({ side = 'top', align = 'center', sideOffset = 8, theme = 'dark', className, children, }) {
135
- const { setOpen, triggerRef, contentId, cancelClose, handleClose } = useTooltipContext();
181
+ const { triggerRef, contentId, cancelClose, handleClose, dismiss } = useTooltipContext();
136
182
  const arrowRef = useRef(null);
137
183
  const { refs, floatingStyles, context } = useFloating({
138
184
  placement: toPlacement(side, align),
@@ -161,7 +207,7 @@ function TooltipContentInner({ side = 'top', align = 'center', sideOffset = 8, t
161
207
  const activeEl = document.activeElement;
162
208
  const trigger = triggerRef.current;
163
209
  const focusIsOnTrigger = trigger && (trigger === activeEl || trigger.contains(activeEl));
164
- setOpen(false);
210
+ dismiss();
165
211
  if (focusIsOnTrigger) {
166
212
  e.stopPropagation(); // Prevent bubbling to modal's Escape handler
167
213
  }
@@ -169,7 +215,7 @@ function TooltipContentInner({ side = 'top', align = 'center', sideOffset = 8, t
169
215
  };
170
216
  document.addEventListener('keydown', handleKeyDown);
171
217
  return () => document.removeEventListener('keydown', handleKeyDown);
172
- }, [setOpen, triggerRef]);
218
+ }, [dismiss, triggerRef]);
173
219
  // Get portal root inside .tui-interface
174
220
  const portalRoot = getPortalRootFor(triggerRef.current);
175
221
  // Dev warning: tooltips should not contain interactive content (WCAG 1.4.13)
@@ -1,3 +1,4 @@
1
+ import type { HoverWarmth } from '../../utils/hover-intent';
1
2
  import type { TooltipContextValue } from './types';
2
3
  /**
3
4
  * Context for Tooltip compound components.
@@ -10,6 +11,17 @@ export declare function useTooltipContext(): TooltipContextValue;
10
11
  export type TooltipProviderContextValue = {
11
12
  delayDuration: number;
12
13
  closeDelayDuration: number;
14
+ skipDelayDuration: number;
15
+ /**
16
+ * The warmth group (utils/hover-intent), or null with no provider: bare
17
+ * tooltips stay independent, as before. Scoped rather than global so warmth
18
+ * never leaks between unrelated regions (or test cases).
19
+ */
20
+ warmth: HoverWarmth | null;
21
+ /** Closes the group's currently open tooltip: one at a time when warm. */
22
+ activeClose: {
23
+ current: (() => void) | null;
24
+ } | null;
13
25
  };
14
26
  export declare const TooltipProviderContext: import("react").Context<TooltipProviderContextValue>;
15
27
  export declare function useTooltipProviderContext(): TooltipProviderContextValue;
@@ -19,6 +19,9 @@ export function useTooltipContext() {
19
19
  export const TooltipProviderContext = createContext({
20
20
  delayDuration: 400,
21
21
  closeDelayDuration: 0,
22
+ skipDelayDuration: 300,
23
+ warmth: null,
24
+ activeClose: null,
22
25
  });
23
26
  export function useTooltipProviderContext() {
24
27
  return useContext(TooltipProviderContext);
@@ -0,0 +1,13 @@
1
+ import { type ReactNode } from 'react';
2
+ /**
3
+ * @internal Gives the tooltips inside a warmth group. Toolbar wraps its
4
+ * items in this, so toolbar tooltips warm up with no setup.
5
+ *
6
+ * Under an outer TooltipProvider it changes nothing: that provider's group
7
+ * and delays apply. Without one, it supplies the provider's defaults too, not
8
+ * the bare-tooltip fallback, whose 0ms close delay would make a toolbar's
9
+ * tooltips close before the pointer can cross into them (WCAG 1.4.13).
10
+ */
11
+ export declare function TooltipWarmthScope({ children }: {
12
+ children: ReactNode;
13
+ }): import("react/jsx-runtime").JSX.Element;