@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.
@@ -5,9 +5,10 @@
5
5
  import { RegistryContext } from '@effect/atom-react/RegistryContext';
6
6
  import { type Meta, type StoryObj } from '@storybook/react-vite';
7
7
  import * as Atom from 'effect/reactivity/Atom';
8
- import React, { useCallback, useContext, useMemo, useState } from 'react';
8
+ import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
9
9
  import { expect, userEvent, waitFor, within } from 'storybook/test';
10
10
 
11
+ import { log } from '@dxos/log';
11
12
  import { random } from '@dxos/random';
12
13
  import '@dxos/react-ui/theme.css';
13
14
  import * as Button from '@dxos/react-ui/Button';
@@ -16,10 +17,11 @@ import * as Layout from '@dxos/react-ui/Layout';
16
17
  import { withRegistry, withTheme } from '@dxos/react-ui/testing';
17
18
  import * as Toolbar from '@dxos/react-ui/Toolbar';
18
19
  import * as Typography from '@dxos/react-ui/Typography';
20
+ import { mx } from '@dxos/ui-theme';
19
21
 
20
22
  import { translations } from '#translations';
21
23
 
22
- import { MenuBuilder } from '../builder.ts';
24
+ import { MenuBuilder, TOOLBAR_OVERFLOW_ID } from '../builder.ts';
23
25
  import { type ActionGraphProps, useMenuActions, useMenuBuilder } from '../hooks/index.ts';
24
26
  import { createActions, createNestedActions, createNestedActionsResolver, useMutateActions } from '../testing/index.ts';
25
27
  import { ActionMenu } from './ActionMenu.tsx';
@@ -39,6 +41,15 @@ export default meta;
39
41
 
40
42
  type Story = StoryObj;
41
43
 
44
+ export const Default: Story = {
45
+ render: () => {
46
+ const registry = useContext(RegistryContext);
47
+ const menu = useMemo(() => createNestedActionsResolver({ registry }), [registry]);
48
+
49
+ return <ActionToolbar {...menu} alwaysActive />;
50
+ },
51
+ };
52
+
42
53
  export const DropdownMenu: Story = {
43
54
  render: () => {
44
55
  const actions = useMemo(() => {
@@ -60,15 +71,6 @@ export const DropdownMenu: Story = {
60
71
  },
61
72
  };
62
73
 
63
- export const Default: Story = {
64
- render: () => {
65
- const registry = useContext(RegistryContext);
66
- const menu = useMemo(() => createNestedActionsResolver({ registry }), [registry]);
67
-
68
- return <ActionToolbar {...menu} alwaysActive />;
69
- },
70
- };
71
-
72
74
  /** Reactive toolbar driven by an atom-backed actions hook; the menu structure is data, not JSX. */
73
75
  export const UseMenuActionsToolbar: Story = {
74
76
  render: () => {
@@ -114,17 +116,58 @@ export const SwitchToolbar: Story = {
114
116
  },
115
117
  };
116
118
 
117
- /** `ActionToolbar` renders its own children after the graph items: here a filter input trails the actions. */
118
- export const TrailingChildren: Story = {
119
+ /**
120
+ * Another component extends a toolbar it does not own through `customActions`: a label, its own control (`custom`), an
121
+ * action in the owner's named group, and an item in the overflow menu.
122
+ */
123
+ export const CustomActions: Story = {
119
124
  render: () => {
120
- const registry = useContext(RegistryContext);
121
- const menu = useMemo(() => createNestedActionsResolver({ registry }), [registry]);
125
+ const menu = useMenuBuilder(
126
+ () =>
127
+ MenuBuilder.make()
128
+ .group('edit', { label: 'Edit' }, (group) =>
129
+ group.action('undo', { label: 'Undo', icon: 'ph--arrow-counter-clockwise--regular' }, () => {}),
130
+ )
131
+ .build(),
132
+ [],
133
+ );
134
+ const customActions = useMemo(
135
+ () =>
136
+ Atom.make(() =>
137
+ MenuBuilder.make()
138
+ .text('title', { label: 'Document', testId: 'title' })
139
+ .subgraph(
140
+ MenuBuilder.extend('edit', (group) =>
141
+ group.action('redo', { label: 'Redo', icon: 'ph--arrow-clockwise--regular' }, () => {}),
142
+ ),
143
+ )
144
+ .custom('filter', { label: 'Filter', placement: { zone: 'end' } }, () => (
145
+ <Input.Root placeholder='Filter…' aria-label='Filter' />
146
+ ))
147
+ .subgraph(
148
+ MenuBuilder.extend(TOOLBAR_OVERFLOW_ID, (group) =>
149
+ group.action('export', { label: 'Export', icon: 'ph--export--regular' }, () => {}),
150
+ ),
151
+ )
152
+ .build(),
153
+ ),
154
+ [],
155
+ );
122
156
 
123
- return (
124
- <ActionToolbar {...menu} alwaysActive>
125
- <Input.Root placeholder='Filter…' aria-label='Filter' />
126
- </ActionToolbar>
157
+ return <ActionToolbar {...menu} customActions={customActions} alwaysActive />;
158
+ },
159
+ play: async ({ canvasElement }) => {
160
+ const canvas = within(canvasElement);
161
+ await waitFor(() => expect(canvas.getByTestId('title')).toHaveTextContent('Document'));
162
+ const buttons = [...canvas.getByRole('toolbar').querySelectorAll('button')].map((button) =>
163
+ button.getAttribute('aria-label'),
127
164
  );
165
+ await expect(buttons.slice(0, 2)).toEqual(['Undo', 'Redo']);
166
+ await expect(canvas.getByRole('textbox', { name: 'Filter' })).toBeVisible();
167
+ await userEvent.click(canvas.getByTestId('toolbar.overflow'));
168
+ await expect(await within(document.body).findByRole('menuitem', { name: 'Export' })).toBeVisible();
169
+ await userEvent.keyboard('{Escape}');
170
+ await waitFor(() => expect(within(document.body).queryByRole('menu')).toBeNull());
128
171
  },
129
172
  };
130
173
 
@@ -148,10 +191,14 @@ export const EmbeddedMenu: Story = {
148
191
  const canvas = within(canvasElement);
149
192
  await userEvent.click(canvas.getByRole('button', { name: 'More' }));
150
193
  const body = within(document.body);
151
- // Every root item of the nested fixture is a group, so each is a submenu trigger.
152
- const triggers = await body.findAllByRole('menuitem');
194
+ // Every root item of the nested fixture is a group, so each enabled one is a submenu trigger.
195
+ const triggers = (await body.findAllByRole('menuitem')).filter(
196
+ (trigger) => trigger.getAttribute('aria-disabled') !== 'true',
197
+ );
153
198
  await expect(triggers.length).toBeGreaterThan(0);
154
- await expect(triggers[0]).toHaveAttribute('aria-haspopup', 'menu');
199
+ for (const trigger of triggers) {
200
+ await expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
201
+ }
155
202
  },
156
203
  };
157
204
 
@@ -344,3 +391,467 @@ export const Attention: Story = {
344
391
  await expect(canvas.getByTestId('add')).toBeEnabled();
345
392
  },
346
393
  };
394
+
395
+ //
396
+ // Layout: named groups, contributions from other components, rows and the overflow menu.
397
+ //
398
+
399
+ /** Story fixtures: an owner's toolbar (a document editor) and the components that extend it. */
400
+ type Log = (id: string) => void;
401
+
402
+ const record: Log = (id) => log.info('action', { id });
403
+
404
+ /** The owner declares named groups and the overflow menu; it knows nothing of its contributors. */
405
+ const ownerGraph = (log: Log, fold = false): ActionGraphProps =>
406
+ MenuBuilder.make()
407
+ .group(
408
+ 'formatting',
409
+ { label: 'Formatting', icon: 'ph--text-aa--regular', placement: { zone: 'start', collapse: 2, fold } },
410
+ (group) =>
411
+ group
412
+ .action('heading', { label: 'Heading', icon: 'ph--text-h--regular', placement: { order: 10 } }, () =>
413
+ log('heading'),
414
+ )
415
+ .action('bold', { label: 'Bold', icon: 'ph--text-b--regular', placement: { order: 20 } }, () => log('bold'))
416
+ .action('italic', { label: 'Italic', icon: 'ph--text-italic--regular', placement: { order: 30 } }, () =>
417
+ log('italic'),
418
+ )
419
+ .action('link', { label: 'Link', icon: 'ph--link--regular', placement: { order: 40 } }, () => log('link')),
420
+ )
421
+ .group(
422
+ 'blocks',
423
+ { label: 'Blocks', icon: 'ph--list-bullets--regular', placement: { zone: 'start', collapse: 3, fold } },
424
+ (group) =>
425
+ group
426
+ .action('list', { label: 'List', icon: 'ph--list-bullets--regular', placement: { order: 10 } }, () =>
427
+ log('list'),
428
+ )
429
+ .action('quote', { label: 'Quote', icon: 'ph--quotes--regular', placement: { order: 20 } }, () =>
430
+ log('quote'),
431
+ ),
432
+ )
433
+ .group('view', { label: 'View', icon: 'ph--eye--regular', placement: { zone: 'end', collapse: 1 } }, (group) =>
434
+ group.action('preview', { label: 'Preview', icon: 'ph--eye--regular' }, () => log('preview')),
435
+ )
436
+ .group('tools', { label: 'Tools', icon: 'ph--wrench--regular', placement: { zone: 'end' } }, (group) =>
437
+ group.action('search', { label: 'Search', icon: 'ph--magnifying-glass--regular', placement: { order: 10 } }, () =>
438
+ log('search'),
439
+ ),
440
+ )
441
+ .menu(TOOLBAR_OVERFLOW_ID, (group) =>
442
+ group.action('export', { label: 'Export', icon: 'ph--export--regular' }, () => log('export')),
443
+ )
444
+ .build();
445
+
446
+ type Contributor = 'review' | 'transcription' | 'presenter';
447
+
448
+ /** What other components add: each extends a named group, or adds its own group with a placement. */
449
+ const contributions: Record<Contributor, (log: Log) => ActionGraphProps[]> = {
450
+ // Beside the formatting it relates to (after Link).
451
+ review: (log) => [
452
+ MenuBuilder.extend('formatting', (group) =>
453
+ group.action(
454
+ 'comment',
455
+ { label: 'Comment', icon: 'ph--chat-text--regular', testId: 'toolbar.comment', placement: { order: 45 } },
456
+ () => log('comment'),
457
+ ),
458
+ ),
459
+ ],
460
+ // Ahead of Search in the owner's tools group.
461
+ transcription: (log) => [
462
+ MenuBuilder.extend('tools', (group) =>
463
+ group.action(
464
+ 'microphone',
465
+ { label: 'Dictate', icon: 'ph--microphone--regular', testId: 'toolbar.microphone', placement: { order: 5 } },
466
+ () => log('microphone'),
467
+ ),
468
+ ),
469
+ ],
470
+ // Editing actions join the blocks group; slide-level controls take a second row; Print joins the overflow menu.
471
+ presenter: (log) => [
472
+ MenuBuilder.extend('blocks', (group) =>
473
+ group
474
+ .action(
475
+ 'column',
476
+ {
477
+ label: 'Start next column',
478
+ icon: 'ph--columns--regular',
479
+ testId: 'toolbar.column',
480
+ placement: { order: 30 },
481
+ },
482
+ () => log('column'),
483
+ )
484
+ .action(
485
+ 'object',
486
+ {
487
+ label: 'Insert object',
488
+ icon: 'ph--squares-four--regular',
489
+ testId: 'toolbar.object',
490
+ placement: { order: 40 },
491
+ },
492
+ () => log('object'),
493
+ ),
494
+ ),
495
+ MenuBuilder.make()
496
+ .group(
497
+ 'slide',
498
+ { label: 'Slide', icon: 'ph--presentation--regular', placement: { row: 1, zone: 'start', collapse: 4 } },
499
+ (group) =>
500
+ group
501
+ .action('layout', { label: 'Layout', icon: 'ph--layout--regular' }, () => log('layout'))
502
+ .action('background', { label: 'Background', icon: 'ph--image--regular' }, () => log('background')),
503
+ )
504
+ .group(
505
+ 'deck',
506
+ { label: 'Deck', icon: 'ph--projector-screen--regular', placement: { row: 1, zone: 'end' } },
507
+ (group) => group.action('present', { label: 'Present', icon: 'ph--play--regular' }, () => log('present')),
508
+ )
509
+ .build(),
510
+ MenuBuilder.extend(TOOLBAR_OVERFLOW_ID, (group) =>
511
+ group.action('print', { label: 'Print', icon: 'ph--printer--regular' }, () => log('print')),
512
+ ),
513
+ ],
514
+ };
515
+
516
+ type StoryProps = { contributors?: Contributor[]; narrow?: boolean; fold?: boolean; asMenu?: boolean };
517
+
518
+ const LayoutStory = ({ contributors = [], narrow, fold, asMenu }: StoryProps) => {
519
+ const menu = useMenuBuilder(
520
+ () =>
521
+ contributors
522
+ .flatMap((contributor) => contributions[contributor](record))
523
+ .reduce((builder, graph) => builder.subgraph(graph), MenuBuilder.make().subgraph(ownerGraph(record, fold)))
524
+ .build(),
525
+ [contributors, fold],
526
+ );
527
+
528
+ return (
529
+ <div className='p-8'>
530
+ {asMenu ? (
531
+ // The same graph as a menu: named groups become submenus, the overflow group one more.
532
+ <ActionMenu {...menu}>
533
+ <Button.Root data-testid='menu.trigger' icon='ph--list--regular' label='Menu' />
534
+ </ActionMenu>
535
+ ) : (
536
+ // Fills the story frame; resize the window and groups move into ⋮ by collapse rank, coming back as it widens.
537
+ <ActionToolbar {...menu} alwaysActive classNames={mx('_border border-separator', narrow && 'max-w-[20rem]')} />
538
+ )}
539
+ </div>
540
+ );
541
+ };
542
+
543
+ /** The labels of a row's buttons, in DOM order. */
544
+ const labels = (canvasElement: HTMLElement, row = 0) => {
545
+ const rows = canvasElement.querySelectorAll<HTMLElement>('[role=toolbar]');
546
+ return [...(rows[row]?.querySelectorAll('button') ?? [])].map((button) => button.getAttribute('aria-label'));
547
+ };
548
+
549
+ /** The owner's named groups across the start and end zones, with Export in the overflow menu. */
550
+ export const Groups: Story = {
551
+ render: () => <LayoutStory />,
552
+ play: async ({ canvasElement }) => {
553
+ await waitFor(() =>
554
+ expect(labels(canvasElement)).toEqual([
555
+ 'Heading',
556
+ 'Bold',
557
+ 'Italic',
558
+ 'Link',
559
+ 'List',
560
+ 'Quote',
561
+ 'Preview',
562
+ 'Search',
563
+ 'More',
564
+ ]),
565
+ );
566
+ await userEvent.click(within(canvasElement).getByTestId('toolbar.overflow'));
567
+ await expect(await within(document.body).findByRole('menuitem', { name: 'Export' })).toBeVisible();
568
+ },
569
+ };
570
+
571
+ /** Other components extend the owner's named groups (interleaved by order), add a second row, and extend ⋮. */
572
+ export const Extended: Story = {
573
+ render: () => <LayoutStory contributors={['review', 'transcription', 'presenter']} />,
574
+ play: async ({ canvasElement }) => {
575
+ await waitFor(() =>
576
+ expect(labels(canvasElement)).toEqual([
577
+ 'Heading',
578
+ 'Bold',
579
+ 'Italic',
580
+ 'Link',
581
+ 'Comment',
582
+ 'List',
583
+ 'Quote',
584
+ 'Start next column',
585
+ 'Insert object',
586
+ 'Preview',
587
+ 'Dictate',
588
+ 'Search',
589
+ 'More',
590
+ ]),
591
+ );
592
+ await expect(labels(canvasElement, 1)).toEqual(['Layout', 'Background', 'Present']);
593
+ await userEvent.click(within(canvasElement).getByTestId('toolbar.overflow'));
594
+ await expect(await within(document.body).findByRole('menuitem', { name: 'Print' })).toBeVisible();
595
+ },
596
+ };
597
+
598
+ /** At a narrow width whole groups move into ⋮ by collapse rank, each as a submenu; unranked groups stay. */
599
+ export const Narrow: Story = {
600
+ render: () => <LayoutStory contributors={['review', 'transcription', 'presenter']} narrow />,
601
+ play: async ({ canvasElement }) => {
602
+ const canvas = within(canvasElement);
603
+ await waitFor(() => expect(labels(canvasElement)).not.toContain('List'));
604
+ await expect(canvas.getByTestId('toolbar.microphone')).toBeVisible();
605
+ await userEvent.click(canvas.getByTestId('toolbar.overflow'));
606
+ const body = within(document.body);
607
+ await userEvent.click(await body.findByRole('menuitem', { name: 'Blocks' }));
608
+ await expect(await body.findByRole('menuitem', { name: 'Insert object' })).toBeVisible();
609
+ },
610
+ };
611
+
612
+ /** Groups that fold do so in place, into a dropdown in the row, before any item moves into ⋮. */
613
+ export const Folding: Story = {
614
+ render: () => <LayoutStory contributors={['review', 'transcription', 'presenter']} narrow fold />,
615
+ play: async ({ canvasElement }) => {
616
+ await waitFor(() => expect(labels(canvasElement)).not.toContain('List'));
617
+ await expect(labels(canvasElement)).toEqual(expect.arrayContaining(['Formatting', 'Blocks', 'Preview']));
618
+ await userEvent.click(within(canvasElement).getByRole('button', { name: 'Blocks' }));
619
+ await expect(await within(document.body).findByRole('menuitem', { name: 'Insert object' })).toBeVisible();
620
+ },
621
+ };
622
+
623
+ const SeparatorsStory = () => {
624
+ const menu = useMenuBuilder(
625
+ () =>
626
+ MenuBuilder.make()
627
+ .action('snap', { label: 'Snap', icon: 'ph--magnet--regular', placement: { collapse: 1 } }, () => {})
628
+ .separator('line')
629
+ .action('axes', { label: 'Axes', icon: 'ph--vector-two--regular', placement: { collapse: 1 } }, () => {})
630
+ .separator('line')
631
+ .custom('zoom', { label: 'Zoom' }, () => <Toolbar.Text classNames='flex-none'>Zoom</Toolbar.Text>)
632
+ .separator('line')
633
+ .action('grid', { label: 'Grid', icon: 'ph--grid-four--regular', placement: { collapse: 1 } }, () => {})
634
+ .separator('gap')
635
+ .action('guides', { label: 'Guides', icon: 'ph--squares-four--regular', placement: { collapse: 1 } }, () => {})
636
+ .separator('line')
637
+ .custom('theme', { label: 'Theme' }, () => <Toolbar.Text classNames='flex-none'>Theme</Toolbar.Text>)
638
+ .build(),
639
+ [],
640
+ );
641
+ return (
642
+ <div className='p-8 w-[8rem]'>
643
+ <ActionToolbar {...menu} alwaysActive data-testid='separators' />
644
+ </div>
645
+ );
646
+ };
647
+
648
+ /**
649
+ * Collapsing the items between rules leaves none of them: a rule stays only between two items, and of the rules left
650
+ * between two, the gap. The ⋮ menu lists them in the row's order, ruled where the row is.
651
+ */
652
+ export const Separators: Story = {
653
+ render: () => <SeparatorsStory />,
654
+ play: async ({ canvasElement }) => {
655
+ const row = within(canvasElement).getByTestId('separators');
656
+ await waitFor(() => expect(labels(canvasElement)).toEqual(['More']));
657
+ await expect(row.querySelector('[data-scope=separator]')).toBeNull();
658
+ await expect(row.querySelectorAll('[data-part=gap]')).toHaveLength(1);
659
+ await userEvent.click(within(row).getByTestId('toolbar.overflow'));
660
+ const menu = await within(document.body).findByRole('menu');
661
+ const entries = Array.from(menu.querySelectorAll('[role=menuitem], [role=separator]')).map((entry) =>
662
+ entry.getAttribute('role') === 'separator' ? '|' : entry.textContent?.trim(),
663
+ );
664
+ await expect(entries).toEqual(['Snap', '|', 'Axes', '|', 'Grid', '|', 'Guides']);
665
+ },
666
+ };
667
+
668
+ const OverflowOrderStory = () => {
669
+ const menu = useMenuBuilder(
670
+ () =>
671
+ MenuBuilder.make()
672
+ .custom('zoom', { label: 'Zoom' }, () => <Toolbar.Text classNames='flex-none'>Zoom</Toolbar.Text>)
673
+ .action('a', { label: 'A', icon: 'ph--circle--regular', placement: { collapse: 1 } }, () => {})
674
+ .action('b', { label: 'B', icon: 'ph--square--regular', placement: { collapse: 1, order: 0.5 } }, () => {})
675
+ .build(),
676
+ [],
677
+ );
678
+ return (
679
+ <div className='p-8 w-[8rem]'>
680
+ <ActionToolbar {...menu} alwaysActive data-testid='overflow-order' />
681
+ </div>
682
+ );
683
+ };
684
+
685
+ /** The ⋮ menu keeps the row's order when an item that stays in the row sets the others' fallback order. */
686
+ export const OverflowOrder: Story = {
687
+ render: () => <OverflowOrderStory />,
688
+ play: async ({ canvasElement }) => {
689
+ const row = within(canvasElement).getByTestId('overflow-order');
690
+ await waitFor(() => expect(labels(canvasElement)).toEqual(['More']));
691
+ await userEvent.click(within(row).getByTestId('toolbar.overflow'));
692
+ const menu = await within(document.body).findByRole('menu');
693
+ const entries = Array.from(menu.querySelectorAll('[role=menuitem]')).map((entry) => entry.textContent?.trim());
694
+ await expect(entries).toEqual(['B', 'A']);
695
+ },
696
+ };
697
+
698
+ /** The same graph rendered as a menu: named groups are submenus. */
699
+ export const AsMenu: Story = {
700
+ render: () => <LayoutStory contributors={['review']} asMenu />,
701
+ play: async ({ canvasElement }) => {
702
+ await userEvent.click(within(canvasElement).getByTestId('menu.trigger'));
703
+ const body = within(document.body);
704
+ await userEvent.click(await body.findByRole('menuitem', { name: 'Formatting' }));
705
+ await expect(await body.findByRole('menuitem', { name: 'Comment' })).toBeVisible();
706
+ },
707
+ };
708
+
709
+ const useCompactMenu = () =>
710
+ useMenuBuilder(
711
+ () =>
712
+ MenuBuilder.make()
713
+ .root({ label: 'Document' })
714
+ .custom('title', { label: 'Title', placement: { collapse: 1 } }, ({ collapsed }) => (
715
+ <Button.Root variant='ghost' icon='ph--file-text--regular' data-testid='story.title'>
716
+ {!collapsed && 'A rather long document title'}
717
+ </Button.Root>
718
+ ))
719
+ .action(
720
+ 'share',
721
+ {
722
+ label: 'Share',
723
+ icon: 'ph--user-plus--regular',
724
+ iconOnly: false,
725
+ testId: 'story.share',
726
+ placement: { collapse: 2 },
727
+ },
728
+ () => log('share'),
729
+ )
730
+ .action('search', { label: 'Search', icon: 'ph--magnifying-glass--regular', testId: 'story.search' }, () =>
731
+ log('search'),
732
+ )
733
+ .build(),
734
+ [],
735
+ );
736
+
737
+ const CompactStory = () => {
738
+ const menu = useCompactMenu();
739
+ return (
740
+ <div className='p-8'>
741
+ <ActionToolbar {...menu} alwaysActive classNames='_border border-separator max-w-[12rem]' />
742
+ </div>
743
+ );
744
+ };
745
+
746
+ /** Too narrow for the labels, ranked items take their compact form in place, in rank order, before anything moves. */
747
+ export const Compact: Story = {
748
+ render: () => <CompactStory />,
749
+ play: async ({ canvasElement }) => {
750
+ const canvas = within(canvasElement);
751
+ await waitFor(() =>
752
+ expect(canvas.getByTestId('story.title')).not.toHaveTextContent('A rather long document title'),
753
+ );
754
+ await expect(canvas.getByTestId('story.share')).toHaveAttribute('aria-label', 'Share');
755
+ await expect(canvas.getByTestId('story.search')).toBeVisible();
756
+ await expect(canvas.queryByTestId('toolbar.overflow')).toBeNull();
757
+ },
758
+ };
759
+
760
+ const GrowBackStory = () => {
761
+ const menu = useCompactMenu();
762
+ const [box, setBox] = useState<HTMLDivElement | null>(null);
763
+ return (
764
+ <div ref={setBox} className='flex p-8 w-[16rem]' data-testid='story.box'>
765
+ {/* As wide as its content, so its own width says nothing of the room it has. */}
766
+ <div role='none' className='flex min-w-0'>
767
+ <ActionToolbar {...menu} alwaysActive bounds={box} classNames='border border-separator' />
768
+ </div>
769
+ </div>
770
+ );
771
+ };
772
+
773
+ /** A toolbar as wide as its content takes its full form again once the box it measures has room. */
774
+ export const GrowBack: Story = {
775
+ render: () => <GrowBackStory />,
776
+ play: async ({ canvasElement }) => {
777
+ const canvas = within(canvasElement);
778
+ const title = canvas.getByTestId('story.title');
779
+ await waitFor(() => expect(title).not.toHaveTextContent('A rather long document title'));
780
+ canvas.getByTestId('story.box').style.width = '48rem';
781
+ await waitFor(() => expect(title).toHaveTextContent('A rather long document title'));
782
+ await expect(canvas.getByTestId('story.share')).toHaveTextContent('Share');
783
+ },
784
+ };
785
+
786
+ // Read by the item itself, so a change reaches its content without rebuilding the menu.
787
+ const NamesContext = createContext<string[]>([]);
788
+
789
+ // Like a list of viewers: it never collapses, so the items beside it make room for it.
790
+ const People = () => {
791
+ const names = useContext(NamesContext);
792
+ return (
793
+ <Button.Root variant='ghost' icon='ph--users--regular' data-testid='story.people'>
794
+ {names.join(', ')}
795
+ </Button.Root>
796
+ );
797
+ };
798
+
799
+ const ChangingContentStory = () => {
800
+ const [names, setNames] = useState(['Ada']);
801
+ const [box, setBox] = useState<HTMLDivElement | null>(null);
802
+ const menu = useMenuBuilder(
803
+ () =>
804
+ MenuBuilder.make()
805
+ .root({ label: 'Document' })
806
+ .custom('people', { label: 'People' }, () => <People />)
807
+ .action(
808
+ 'share',
809
+ {
810
+ label: 'Share',
811
+ icon: 'ph--user-plus--regular',
812
+ iconOnly: false,
813
+ testId: 'story.share',
814
+ placement: { collapse: 1 },
815
+ },
816
+ () => log('share'),
817
+ )
818
+ .build(),
819
+ [],
820
+ );
821
+ return (
822
+ <div className='flex flex-col gap-4 p-8'>
823
+ <div className='flex gap-2'>
824
+ <Button.Root data-testid='story.join' onClick={() => setNames((names) => [...names, 'Ben', 'Charlotte'])}>
825
+ Join
826
+ </Button.Root>
827
+ <Button.Root data-testid='story.leave' onClick={() => setNames((names) => names.slice(0, 1))}>
828
+ Leave
829
+ </Button.Root>
830
+ </div>
831
+ <div ref={setBox} className='flex w-[16rem]'>
832
+ <div role='none' className='flex min-w-0'>
833
+ <NamesContext.Provider value={names}>
834
+ <ActionToolbar {...menu} alwaysActive bounds={box} classNames='border border-separator' />
835
+ </NamesContext.Provider>
836
+ </div>
837
+ </div>
838
+ </div>
839
+ );
840
+ };
841
+
842
+ /**
843
+ * An item whose content grows past the box it measures makes the items beside it collapse, though menu and box are
844
+ * unchanged; once its content shrinks back, they take their full form again.
845
+ */
846
+ export const ChangingContent: Story = {
847
+ render: () => <ChangingContentStory />,
848
+ play: async ({ canvasElement }) => {
849
+ const canvas = within(canvasElement);
850
+ await expect(canvas.getByTestId('story.share')).toHaveTextContent('Share');
851
+ await userEvent.click(canvas.getByTestId('story.join'));
852
+ await waitFor(() => expect(canvas.getByTestId('story.share')).not.toHaveTextContent('Share'));
853
+ await expect(canvas.getByTestId('story.people')).toHaveTextContent('Charlotte');
854
+ await userEvent.click(canvas.getByTestId('story.leave'));
855
+ await waitFor(() => expect(canvas.getByTestId('story.share')).toHaveTextContent('Share'));
856
+ },
857
+ };