@dxos/react-ui-menu 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,11 +2,18 @@
2
2
  // Copyright 2026 DXOS.org
3
3
  //
4
4
 
5
+ import { RegistryContext } from '@effect/atom-react/RegistryContext';
6
+ import * as Atom from 'effect/reactivity/Atom';
7
+ import type * as Registry from 'effect/reactivity/AtomRegistry';
5
8
  import React, {
6
9
  type ButtonHTMLAttributes,
7
- type ReactNode,
10
+ type ForwardedRef,
11
+ Fragment,
12
+ type RefObject,
8
13
  forwardRef,
9
14
  useCallback,
15
+ useContext,
16
+ useLayoutEffect,
10
17
  useMemo,
11
18
  useRef,
12
19
  useState,
@@ -25,16 +32,24 @@ import {
25
32
  type ClassNameValue,
26
33
  type DropdownMenuItemGroupProperties,
27
34
  type ToggleGroupMenuItemGroupProperties,
35
+ TOOLBAR_HOLDS_ATTRIBUTE,
36
+ TOOLBAR_OVERFLOW_TESTID,
37
+ type ToolbarPlacement,
38
+ type ToolbarZone,
28
39
  } from '@dxos/ui-types';
29
40
 
30
41
  import { translationKey } from '#translations';
31
42
 
32
- import { useMenuActions, useMenuItems } from '../hooks/index.ts';
43
+ import { TOOLBAR_OVERFLOW_ID, defaultOverflowGroup } from '../builder.ts';
44
+ import { type ActionGraphProps, useMenuActions, useMenuItems } from '../hooks/index.ts';
33
45
  import {
34
46
  type MenuAction,
35
47
  type MenuActions,
36
48
  type MenuItem,
37
49
  type MenuItemGroup,
50
+ type MenuItemsAccessor,
51
+ type MenuSeparator,
52
+ MenuSeparatorType,
38
53
  isMenuGroup,
39
54
  isSeparator,
40
55
  } from '../types.ts';
@@ -56,6 +71,8 @@ type ActionButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children
56
71
  caretDown?: boolean;
57
72
  classNames?: ClassNameValue;
58
73
  testId?: string;
74
+ /** Shows the icon alone, as the toolbar does for a labelled action it has collapsed. */
75
+ compact?: boolean;
59
76
  };
60
77
 
61
78
  /**
@@ -63,7 +80,7 @@ type ActionButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children
63
80
  * Forwards its ref and remaining props, since a `Menu.Trigger asChild` merges the trigger's onto it.
64
81
  */
65
82
  const ActionButton = forwardRef<HTMLButtonElement, ActionButtonProps>(
66
- ({ action, classNames, testId, ...props }, forwardedRef) => {
83
+ ({ action, classNames, testId, compact, ...props }, forwardedRef) => {
67
84
  const { t } = Hooks.useTranslation(translationKey);
68
85
  const { icon, iconOnly = true, spin } = action.properties;
69
86
  const common = {
@@ -73,7 +90,7 @@ const ActionButton = forwardRef<HTMLButtonElement, ActionButtonProps>(
73
90
  ...(testId && { 'data-testid': testId }),
74
91
  ref: forwardedRef,
75
92
  };
76
- return icon && iconOnly ? (
93
+ return icon && (iconOnly || compact) ? (
77
94
  <Button.Root {...common} icon={icon} label={actionLabel(action, t)} iconOnly />
78
95
  ) : (
79
96
  <Button.Root {...common} icon={icon}>
@@ -83,7 +100,7 @@ const ActionButton = forwardRef<HTMLButtonElement, ActionButtonProps>(
83
100
  },
84
101
  );
85
102
 
86
- const ActionToolbarItem = ({ menu, action }: ItemProps<{ action: MenuAction }>) => {
103
+ const ActionToolbarItem = ({ menu, action, compact }: ItemProps<{ action: MenuAction; compact?: boolean }>) => {
87
104
  const { onAction, caller, iconSize } = menu;
88
105
  const [pending, setPending] = useState(false);
89
106
  const pendingRef = useRef(false);
@@ -120,12 +137,13 @@ const ActionToolbarItem = ({ menu, action }: ItemProps<{ action: MenuAction }>)
120
137
  classNames={classNames}
121
138
  onClick={handleClick}
122
139
  testId={testId}
140
+ compact={compact}
123
141
  />
124
142
  );
125
143
  };
126
144
 
127
145
  /** A `toggle` action is a pressed button whose state is the action's `checked`. */
128
- const ToggleToolbarItem = ({ menu, action }: ItemProps<{ action: MenuAction }>) => {
146
+ const ToggleToolbarItem = ({ menu, action, compact }: ItemProps<{ action: MenuAction; compact?: boolean }>) => {
129
147
  const { onAction, caller, iconSize } = menu;
130
148
  const { t } = Hooks.useTranslation(translationKey);
131
149
  const { icon, iconOnly = true, disabled, testId, hidden, checked, classNames, spin } = action.properties;
@@ -153,7 +171,7 @@ const ToggleToolbarItem = ({ menu, action }: ItemProps<{ action: MenuAction }>)
153
171
  ...(testId && { 'data-testid': testId }),
154
172
  };
155
173
 
156
- return icon && iconOnly ? (
174
+ return icon && (iconOnly || compact) ? (
157
175
  <Button.Toggle {...common} icon={icon} label={actionLabel(action, t)} iconOnly />
158
176
  ) : (
159
177
  <Button.Toggle {...common} icon={icon}>
@@ -200,7 +218,11 @@ const SwitchToolbarItem = ({ menu, action }: ItemProps<{ action: MenuAction }>)
200
218
  );
201
219
  };
202
220
 
203
- const DropdownToolbarItem = ({ menu, group }: ItemProps<{ group: MenuItemGroup<DropdownMenuItemGroupProperties> }>) => {
221
+ const DropdownToolbarItem = ({
222
+ menu,
223
+ group,
224
+ holds,
225
+ }: ItemProps<{ group: MenuItemGroup<DropdownMenuItemGroupProperties>; holds?: string }>) => {
204
226
  const items = useMenuItems(menu, group);
205
227
  const { disabled, testId, applyActive, caretDown = true } = group.properties;
206
228
  const activeItem = items?.find((item) => !!(item as MenuAction).properties.checked) as MenuAction | undefined;
@@ -232,6 +254,7 @@ const DropdownToolbarItem = ({ menu, group }: ItemProps<{ group: MenuItemGroup<D
232
254
  iconSize={menu.iconSize}
233
255
  caretDown={caretDown && !disabled}
234
256
  testId={testId}
257
+ {...(holds && { [TOOLBAR_HOLDS_ATTRIBUTE]: holds })}
235
258
  />
236
259
  );
237
260
 
@@ -313,7 +336,28 @@ const ToggleGroupToolbarItem = ({
313
336
  );
314
337
  };
315
338
 
316
- const ToolbarItem = ({ menu, item }: ItemProps<{ item: MenuItem }>) => {
339
+ const TextToolbarItem = ({ action }: { action: MenuAction }) => {
340
+ const { t } = Hooks.useTranslation(translationKey);
341
+ const { label, hidden, testId, classNames } = action.properties;
342
+ if (hidden) {
343
+ return null;
344
+ }
345
+ return (
346
+ <Toolbar.Text classNames={classNames} {...(testId && { 'data-testid': testId })}>
347
+ {Theme.toLocalizedString(label, t)}
348
+ </Toolbar.Text>
349
+ );
350
+ };
351
+
352
+ /**
353
+ * One menu item rendered as its toolbar control (button, toggle, switch, dropdown, toggle group or custom); `collapsed`
354
+ * renders its compact form.
355
+ */
356
+ export const MenuToolbarItem = ({
357
+ menu,
358
+ item,
359
+ collapsed = false,
360
+ }: ItemProps<{ item: MenuItem; collapsed?: boolean }>) => {
317
361
  if (isSeparator(item)) {
318
362
  return <Toolbar.Separator variant={item.properties.variant === 'line' ? 'line' : 'gap'} />;
319
363
  }
@@ -331,73 +375,434 @@ const ToolbarItem = ({ menu, item }: ItemProps<{ item: MenuItem }>) => {
331
375
  case 'switch':
332
376
  return <SwitchToolbarItem menu={menu} action={action} />;
333
377
  case 'toggle':
334
- return <ToggleToolbarItem menu={menu} action={action} />;
378
+ return <ToggleToolbarItem menu={menu} action={action} compact={collapsed} />;
335
379
  case 'custom':
336
380
  // The contributor owns the rendered element (interactions the action model cannot express).
337
- return action.properties.render ? <>{action.properties.render()}</> : null;
381
+ return action.properties.render ? <>{action.properties.render({ collapsed })}</> : null;
382
+ case 'text':
383
+ return <TextToolbarItem action={action} />;
338
384
  default:
339
- return <ActionToolbarItem menu={menu} action={action} />;
385
+ return <ActionToolbarItem menu={menu} action={action} compact={collapsed} />;
340
386
  }
341
387
  };
342
388
 
343
- const ActionToolbarItems = ({ menu }: { menu: MenuActions }) => {
344
- const items = useMenuItems(menu);
389
+ //
390
+ // Layout (private): zones, rows and the overflow menu.
391
+ //
392
+
393
+ const ZONES: readonly ToolbarZone[] = ['start', 'end'];
394
+
395
+ const placementOf = (item: MenuItem): ToolbarPlacement => (isSeparator(item) ? {} : (item.properties.placement ?? {}));
396
+
397
+ /** A named group without a render variant: inline in a toolbar, a submenu in a menu. */
398
+ const isPlainGroup = (item: MenuItem): item is MenuItemGroup => isMenuGroup(item) && !item.properties.variant;
399
+
400
+ /** Sorts by `placement.order`, an item without one keeping its insertion index. */
401
+ const byOrder = (items: readonly MenuItem[]): MenuItem[] =>
402
+ items
403
+ .map((item, index) => ({ item, order: placementOf(item).order ?? index }))
404
+ .sort((a, b) => a.order - b.order)
405
+ .map(({ item }) => item);
406
+
407
+ /**
408
+ * Drops separators left leading, trailing or doubled once items are placed elsewhere: of a run between two items, a gap
409
+ * stays if there is one, as it lays the row out, else the last.
410
+ */
411
+ const trimSeparators = (items: readonly MenuItem[]): MenuItem[] =>
412
+ items.filter((item, index) => {
413
+ if (!isSeparator(item)) {
414
+ return true;
415
+ }
416
+ const before = items.findLastIndex((other, at) => at < index && !isSeparator(other));
417
+ const after = items.findIndex((other, at) => at > index && !isSeparator(other));
418
+ if (before < 0 || after < 0) {
419
+ return false;
420
+ }
421
+ const run = items.slice(before + 1, after);
422
+ const gap = run.findLastIndex((separator) => isSeparator(separator) && separator.properties.variant === 'gap');
423
+ return index === before + 1 + (gap >= 0 ? gap : run.length - 1);
424
+ });
425
+
426
+ /** A named group laid out inline, its own and contributed items in order; ruled off from what precedes it. */
427
+ const InlineGroup = ({ menu, group, separated }: ItemProps<{ group: MenuItemGroup; separated: boolean }>) => {
428
+ const items = useMenuItems(menu, group);
429
+ const ordered = useMemo(() => byOrder(items ?? []), [items]);
430
+ if (ordered.length === 0) {
431
+ return null;
432
+ }
345
433
  return (
346
434
  <>
347
- {items?.map((item) => (
348
- <ToolbarItem key={item.id} menu={menu} item={item} />
435
+ {separated && <Toolbar.Separator variant='line' />}
436
+ {ordered.map((item) => (
437
+ <MenuToolbarItem key={item.id} menu={menu} item={item} />
349
438
  ))}
350
439
  </>
351
440
  );
352
441
  };
353
442
 
443
+ /** A rule in the ⋮ menu where the rows' items it lists change zone or row, or give way to its own. */
444
+ const menuBreak = (id: string): MenuSeparator => ({
445
+ id: `toolbar-break-${id}`,
446
+ type: MenuSeparatorType,
447
+ properties: { variant: 'gap' },
448
+ data: undefined as never,
449
+ });
450
+
451
+ /**
452
+ * The ⋮ menu: what collapsed out of the rows, in the rows' order and ruled where they are (named groups as submenus),
453
+ * then the overflow group's own and contributed items.
454
+ */
455
+ const OverflowMenu = ({ menu, group, collapsed }: ItemProps<{ group: MenuItemGroup; collapsed: MenuItem[] }>) => {
456
+ const items = useMenuItems(menu, group);
457
+ const actions = useMemo(
458
+ () => trimSeparators([...collapsed, menuBreak('overflow'), ...byOrder(items ?? [])]),
459
+ [collapsed, items],
460
+ );
461
+ return <OverflowMenuTrigger menu={menu} actions={actions} testId={group.properties.testId} />;
462
+ };
463
+
464
+ const OverflowMenuTrigger = ({ menu, actions, testId }: ItemProps<{ actions: MenuItem[]; testId?: string }>) => {
465
+ const { t } = Hooks.useTranslation(translationKey);
466
+ if (actions.length === 0) {
467
+ return null;
468
+ }
469
+ return (
470
+ <ActionMenu {...menu} actions={actions}>
471
+ <Button.Root
472
+ data-testid={testId ?? TOOLBAR_OVERFLOW_TESTID}
473
+ icon='ph--dots-three-vertical--regular'
474
+ iconOnly
475
+ variant='ghost'
476
+ label={t('toolbar-overflow.menu')}
477
+ />
478
+ </ActionMenu>
479
+ );
480
+ };
481
+
482
+ /** The element a row lays out in: the `Toolbar.Root` scroll frame around it, else the row itself. */
483
+ const frameOf = (row: HTMLElement): HTMLElement =>
484
+ row.parentElement?.classList.contains('dx-toolbar-scroll') ? row.parentElement : row;
485
+
486
+ /** A menu cannot show a control the contributor renders itself, or a label, so such items never leave the row. */
487
+ const isMenuable = (item: MenuItem): boolean =>
488
+ !isSeparator(item) && item.properties.variant !== 'custom' && item.properties.variant !== 'text';
489
+
490
+ /**
491
+ * Steps the toolbar takes while a row is too narrow, in order: an item taking its compact form, a group folding in
492
+ * place, or an item moving to ⋮.
493
+ */
494
+ type CollapseStep = { kind: 'compact' | 'fold' | 'move'; item: MenuItem };
495
+
496
+ /** What the collapse has done so far: the items moved into ⋮, the groups folded and the items compacted, by id. */
497
+ type Collapsed = { moved: MenuItem[]; folded: ReadonlySet<string>; compacted: ReadonlySet<string> };
498
+
499
+ /**
500
+ * A ranked item that has a compact form collapses in place to it: a `custom` item renders with `collapsed`, and an
501
+ * action shown with its label and an icon shows the icon alone.
502
+ */
503
+ const isCompactable = (item: MenuItem): boolean => {
504
+ if (isSeparator(item) || isMenuGroup(item) || placementOf(item).collapse === undefined) {
505
+ return false;
506
+ }
507
+ const { variant, icon, iconOnly } = item.properties;
508
+ return variant === 'custom' || (!!icon && iconOnly === false && variant !== 'text' && variant !== 'switch');
509
+ };
510
+
511
+ /**
512
+ * Collapses items while any row is too narrow, so the toolbar fills its container without overflowing it. First each
513
+ * ranked item with a compact form takes it (highest rank first); then groups marked `fold` fold; then ranked items move
514
+ * into the overflow menu, then the rest, last first. Each step is undone once the toolbar is wider than when it was
515
+ * taken, or tried again once an item's content changes, so hidden items are never measured.
516
+ */
517
+ const useCollapse = (
518
+ menu: MenuActions,
519
+ units: MenuItem[],
520
+ rows: RefObject<(HTMLElement | null)[]>,
521
+ bounds: HTMLElement | null | undefined,
522
+ ): Collapsed => {
523
+ const registry = useContext(RegistryContext);
524
+ const steps = useMemo<CollapseStep[]>(() => {
525
+ // A named group collapses as a submenu, which can only hold what a menu shows; an empty one takes no room to free.
526
+ const canCollapse = (item: MenuItem) => {
527
+ if (!isMenuable(item)) {
528
+ return false;
529
+ }
530
+ if (!isPlainGroup(item)) {
531
+ return true;
532
+ }
533
+ // A separator rules a menu as it does a row.
534
+ const children = (registry.get(menu.items(item)) ?? []).filter((child) => !isSeparator(child));
535
+ return children.length > 0 && children.every(isMenuable);
536
+ };
537
+ const ranked = units
538
+ .map((item, index) => ({ item, rank: placementOf(item).collapse, index }))
539
+ .filter(({ rank }) => rank !== undefined)
540
+ .sort((a, b) => (b.rank ?? 0) - (a.rank ?? 0) || b.index - a.index)
541
+ .map(({ item }) => item);
542
+ const rest = units.filter((item) => placementOf(item).collapse === undefined && canCollapse(item)).reverse();
543
+ const order = [...ranked.filter(canCollapse), ...rest];
544
+ return [
545
+ ...ranked.filter(isCompactable).map((item) => ({ kind: 'compact' as const, item })),
546
+ ...order
547
+ .filter((item) => isPlainGroup(item) && placementOf(item).fold)
548
+ .map((item) => ({ kind: 'fold' as const, item })),
549
+ ...order.map((item) => ({ kind: 'move' as const, item })),
550
+ ];
551
+ }, [registry, menu, units]);
552
+
553
+ const [count, setCount] = useState(0);
554
+ const thresholds = useRef<number[]>([]);
555
+ const [width, setWidth] = useState(0);
556
+ // Bumped when an item's own content (a custom item's children) changes.
557
+ const [contentChanges, setContentChanges] = useState(0);
558
+ const measuredChanges = useRef(contentChanges);
559
+ // Ids rather than the items: `steps` is rebuilt whenever a caller passes a fresh `onAction`.
560
+ const stepsKey = steps.map(({ kind, item }) => `${kind}:${item.id}`).join('\n');
561
+
562
+ // Each read forces a layout, so measure only when the items (a new label or icon-only flag yields new items), the
563
+ // steps, the step count, the frame width or an item's content moved.
564
+ useLayoutEffect(() => {
565
+ if (steps.length === 0 && count === 0) {
566
+ return;
567
+ }
568
+ const elements = rows.current.filter((row): row is HTMLElement => !!row);
569
+ if (elements.length === 0) {
570
+ return;
571
+ }
572
+ const width = (bounds ?? frameOf(elements[0])).clientWidth;
573
+ // A toolbar not laid out yet (a closed drawer, a hidden panel) has no width to fit; it is measured once it has one.
574
+ if (width === 0) {
575
+ return;
576
+ }
577
+ // Content that shrank may make room at this width for a step taken, so each step is tried again.
578
+ if (measuredChanges.current !== contentChanges) {
579
+ measuredChanges.current = contentChanges;
580
+ thresholds.current.fill(0);
581
+ }
582
+ const overflowing = elements.some((row) => row.scrollWidth > row.clientWidth + 1);
583
+ if (overflowing && count < steps.length) {
584
+ thresholds.current[count] = width;
585
+ setCount(count + 1);
586
+ } else if (!overflowing && count > 0 && width > (thresholds.current[count - 1] ?? Infinity)) {
587
+ setCount(count - 1);
588
+ }
589
+ }, [units, stepsKey, count, width, bounds, contentChanges]);
590
+
591
+ // Re-render on resize only when something can collapse.
592
+ const observed = steps.length > 0;
593
+ useLayoutEffect(() => {
594
+ const element = rows.current[0];
595
+ if (!observed || !element) {
596
+ return;
597
+ }
598
+ const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
599
+ observer.observe(bounds ?? frameOf(element));
600
+ return () => observer.disconnect();
601
+ }, [observed, rows, bounds]);
602
+
603
+ // Content that changes inside an item leaves the items and the frame as they were, so neither observer above sees it.
604
+ useLayoutEffect(() => {
605
+ const elements = rows.current.filter((row): row is HTMLElement => !!row);
606
+ if (!observed || elements.length === 0) {
607
+ return;
608
+ }
609
+ // A step's own render changes the rows too; this observer is replaced then, which drops those records.
610
+ const observer = new MutationObserver(() => setContentChanges((changes) => changes + 1));
611
+ elements.forEach((row) => observer.observe(row, { childList: true, subtree: true, characterData: true }));
612
+ return () => observer.disconnect();
613
+ }, [observed, rows, units, count]);
614
+
615
+ return useMemo(() => {
616
+ const taken = steps.slice(0, count);
617
+ return {
618
+ moved: taken.filter(({ kind }) => kind === 'move').map(({ item }) => item),
619
+ folded: new Set(taken.filter(({ kind }) => kind === 'fold').map(({ item }) => item.id)),
620
+ compacted: new Set(taken.filter(({ kind }) => kind === 'compact').map(({ item }) => item.id)),
621
+ };
622
+ }, [steps, count]);
623
+ };
624
+
625
+ /** A folded group: its items in a dropdown, under the group's own label and icon. */
626
+ const FoldedGroup = ({ menu, group }: ItemProps<{ group: MenuItemGroup }>) => {
627
+ const registry = useContext(RegistryContext);
628
+ const dropdown = useMemo<MenuItemGroup<DropdownMenuItemGroupProperties>>(() => {
629
+ const { label, icon, ...properties } = group.properties;
630
+ return { ...group, properties: { ...properties, label, icon, variant: 'dropdownMenu' } };
631
+ }, [group]);
632
+ const holds = useMemo(() => heldTestIds(registry, menu, group).join(' '), [registry, menu, group]);
633
+ return <DropdownToolbarItem menu={menu} group={dropdown} holds={holds} />;
634
+ };
635
+
636
+ /** The test ids of a group's items at any depth. */
637
+ const heldTestIds = (registry: Registry.AtomRegistry, menu: MenuActions, group: MenuItemGroup): string[] =>
638
+ (registry.get(menu.items(group)) ?? []).flatMap((item) =>
639
+ isSeparator(item)
640
+ ? []
641
+ : [
642
+ ...(item.properties.testId ? [item.properties.testId as string] : []),
643
+ ...(isMenuGroup(item) ? heldTestIds(registry, menu, item) : []),
644
+ ],
645
+ );
646
+
647
+ const setRef = <T,>(ref: ForwardedRef<T>, value: T | null) => {
648
+ if (typeof ref === 'function') {
649
+ ref(value);
650
+ } else if (ref) {
651
+ ref.current = value;
652
+ }
653
+ };
654
+
354
655
  //
355
656
  // ActionToolbar
356
657
  //
357
658
 
659
+ /** Each group's items from `base`, then from `extra`, so a second graph extends the first group by group. */
660
+ const mergeItems = (base: MenuItemsAccessor, extra: MenuItemsAccessor): MenuItemsAccessor => {
661
+ const atoms = new Map<string, Atom.Atom<MenuItem[] | null>>();
662
+ return (group) => {
663
+ const key = group?.id ?? '';
664
+ let atom = atoms.get(key);
665
+ if (!atom) {
666
+ atom = Atom.make((get) => {
667
+ const own = get(base(group));
668
+ const added = get(extra(group));
669
+ return own || added ? [...(own ?? []), ...(added ?? [])] : null;
670
+ });
671
+ atoms.set(key, atom);
672
+ }
673
+ return atom;
674
+ };
675
+ };
676
+
358
677
  export type ActionToolbarProps = Partial<MenuActions> &
359
- Omit<Toolbar.RootProps, 'disabled'> & {
678
+ Omit<Toolbar.RootProps, 'disabled' | 'children'> & {
360
679
  /** The toolbar is dimmed (still operable) while this attendable lacks attention, unless `alwaysActive`. */
361
680
  attendableId?: string;
362
681
  alwaysActive?: boolean;
363
- /** Hand-written controls before the graph's items (the children follow them). */
364
- start?: ReactNode;
682
+ /**
683
+ * Items another component adds to this toolbar, merged with its own group by group: root items follow the owner's,
684
+ * and `MenuBuilder.extend(groupId, …)` adds to a named group.
685
+ */
686
+ customActions?: Atom.Atom<ActionGraphProps>;
687
+ /**
688
+ * The box whose width the toolbar may fill, measured to decide when collapsed items fit again; by default the
689
+ * toolbar's own frame. A toolbar as wide as its content passes the box it sits in, or it never grows back.
690
+ */
691
+ bounds?: HTMLElement | null;
365
692
  };
366
693
 
367
694
  /**
368
- * A whole `Toolbar.Root` driven from a `MenuActions`: the graph's root items render first, then the toolbar's own
369
- * children. Mix graph and hand-written controls the other way round by dropping an `ActionMenu` into a plain
370
- * `Toolbar.Root`. Without a `MenuActions` it is an empty toolbar until one arrives.
695
+ * A toolbar driven from a `MenuActions`. Each item's `placement` puts it in the start or end zone of a row; a
696
+ * plain named group renders inline and others extend it (`MenuBuilder.extend`); the overflow menu (⋮,
697
+ * `TOOLBAR_OVERFLOW_ID`) ends the first row and takes collapsible items while a row is too narrow. One row renders as a
698
+ * single `Toolbar.Root` (which takes the props and ref); more stack one per row. Hand-written controls join the graph as
699
+ * `custom` items (`MenuBuilder.custom`), labels as `text` items.
371
700
  */
372
701
  export const ActionToolbar = Util.composable<HTMLDivElement, ActionToolbarProps>(
373
702
  (
374
- { items, contributions, onAction, caller, iconSize, attendableId, alwaysActive, start, children, ...props },
703
+ // Controls join the graph as `custom` items, so `children` are dropped rather than rendered.
704
+ {
705
+ items,
706
+ contributions,
707
+ onAction,
708
+ caller,
709
+ iconSize,
710
+ attendableId,
711
+ alwaysActive,
712
+ customActions,
713
+ bounds,
714
+ children: _,
715
+ ...props
716
+ },
375
717
  forwardedRef,
376
718
  ) => {
377
719
  // Called unconditionally (hooks), used only when no source was spread in.
378
720
  const standalone = useMenuActions();
721
+ const custom = useMenuActions(customActions);
379
722
  const menu = useMemo<MenuActions>(
380
723
  () => ({
381
- items: items ?? standalone.items,
724
+ items: customActions ? mergeItems(items ?? standalone.items, custom.items) : (items ?? standalone.items),
382
725
  contributions: contributions ?? standalone.contributions,
383
726
  onAction,
384
727
  caller,
385
728
  iconSize,
386
729
  }),
387
- [items, contributions, onAction, caller, iconSize, standalone],
730
+ [items, contributions, onAction, caller, iconSize, standalone, customActions, custom],
388
731
  );
389
732
  const { hasAttention } = useAttention(attendableId);
390
733
 
391
- return (
392
- <Toolbar.Root
393
- {...Util.composableProps(props, { classNames: attendableId })}
394
- inactive={!alwaysActive && !hasAttention}
395
- ref={forwardedRef}
396
- >
397
- {start}
398
- <ActionToolbarItems menu={menu} />
399
- {children}
400
- </Toolbar.Root>
734
+ const rootItems = useMenuItems(menu);
735
+ const overflow =
736
+ rootItems?.find((item): item is MenuItemGroup => isMenuGroup(item) && item.id === TOOLBAR_OVERFLOW_ID) ??
737
+ defaultOverflowGroup;
738
+ const units = useMemo(() => (rootItems ?? []).filter((item) => item.id !== TOOLBAR_OVERFLOW_ID), [rootItems]);
739
+ const rows = useRef<(HTMLElement | null)[]>([]);
740
+ const { moved: collapsed, folded, compacted } = useCollapse(menu, units, rows, bounds);
741
+
742
+ const rowCount = Math.max(1, ...units.map((item) => (placementOf(item).row ?? 0) + 1));
743
+ // Sorted before `keep` filters, so an item's fallback order is its index in the whole zone.
744
+ const inZone = (row: number, zone: ToolbarZone, keep: (item: MenuItem) => boolean) =>
745
+ byOrder(
746
+ units.filter((item) => {
747
+ const placement = placementOf(item);
748
+ return (placement.row ?? 0) === row && (placement.zone ?? 'start') === zone;
749
+ }),
750
+ ).filter(keep);
751
+ const zone = (row: number, zone: ToolbarZone) =>
752
+ trimSeparators(inZone(row, zone, (item) => !collapsed.includes(item)));
753
+ const moved = Array.from({ length: rowCount }, (_, row) =>
754
+ ZONES.flatMap((name) => [
755
+ menuBreak(`${row}-${name}`),
756
+ ...inZone(row, name, (item) => isSeparator(item) || collapsed.includes(item)),
757
+ ]),
758
+ ).flat();
759
+
760
+ const renderRow = (row: number) => {
761
+ const zones = ZONES.map((name) => ({ name, items: zone(row, name) }));
762
+ const first = row === 0;
763
+ return (
764
+ <Toolbar.Root
765
+ key={row}
766
+ {...(first ? Util.composableProps(props, { classNames: attendableId }) : { classNames: props.classNames })}
767
+ data-row={rowCount > 1 ? row : undefined}
768
+ inactive={!alwaysActive && !hasAttention}
769
+ ref={(element: HTMLDivElement | null) => {
770
+ rows.current[row] = element;
771
+ first && setRef(forwardedRef, element);
772
+ }}
773
+ >
774
+ {zones.map(({ name, items }, index) => (
775
+ <Fragment key={name}>
776
+ {/* A gap pushes the end zone to the far right. */}
777
+ {index > 0 && items.length > 0 && <Toolbar.Separator variant='gap' />}
778
+ {items.map((item, index) =>
779
+ isPlainGroup(item) && folded.has(item.id) ? (
780
+ <FoldedGroup key={item.id} menu={menu} group={item} />
781
+ ) : isPlainGroup(item) ? (
782
+ // A folding group holds the toolbar's own controls, so it is spaced like them rather than ruled off.
783
+ <InlineGroup
784
+ key={item.id}
785
+ menu={menu}
786
+ group={item}
787
+ separated={index > 0 && !placementOf(item).fold}
788
+ />
789
+ ) : (
790
+ <MenuToolbarItem key={item.id} menu={menu} item={item} collapsed={compacted.has(item.id)} />
791
+ ),
792
+ )}
793
+ </Fragment>
794
+ ))}
795
+ {first && <OverflowMenu menu={menu} group={overflow} collapsed={moved} />}
796
+ </Toolbar.Root>
797
+ );
798
+ };
799
+
800
+ return rowCount === 1 ? (
801
+ renderRow(0)
802
+ ) : (
803
+ <div role='none' className='flex flex-col w-full min-w-0 min-h-fit'>
804
+ {Array.from({ length: rowCount }, (_, row) => renderRow(row))}
805
+ </div>
401
806
  );
402
807
  },
403
808
  );
@@ -202,6 +202,12 @@ describe('useMenuBuilder', () => {
202
202
  </RegistryContext.Provider>,
203
203
  );
204
204
  expect(screen.queryByTestId('item-0')).toBeNull();
205
+ // React DEV holds the last fiber that suspended on mount, which reaches its siblings; another suspension replaces it.
206
+ render(
207
+ <Suspense fallback={null}>
208
+ <Suspend />
209
+ </Suspense>,
210
+ );
205
211
  await expect.poll(() => collectedSize(registry)).toBe(0);
206
212
  });
207
213
 
package/src/index.ts CHANGED
@@ -13,6 +13,6 @@ export {
13
13
  executeMenuAction,
14
14
  fallbackIcon,
15
15
  } from './util.ts';
16
- export { type ActionGroupBuilder, type ActionGroupBuilderFn, MenuBuilder } from './builder.ts';
16
+ export { type ActionGroupBuilder, type ActionGroupBuilderFn, MenuBuilder, TOOLBAR_OVERFLOW_ID } from './builder.ts';
17
17
  export { PROMPT_DISPOSITION, TOOLBAR_DISPOSITION, isPromptAction, isToolbarAction } from './toolbar.ts';
18
18
  export { applyPresentation } from './presentation.ts';