@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-menu",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Components for facilitating reactive and consistent menus.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -37,39 +37,43 @@
37
37
  "src"
38
38
  ],
39
39
  "dependencies": {
40
- "@dxos/effect": "0.16.0",
41
- "@dxos/graph": "0.16.0",
42
- "@dxos/invariant": "0.16.0",
43
- "@dxos/log": "0.16.0",
44
- "@dxos/app-graph": "0.16.0",
45
- "@dxos/react-focus": "0.16.0",
46
- "@dxos/react-ui-attention": "0.16.0",
47
- "@dxos/util": "0.16.0",
48
- "@dxos/ui-types": "0.16.0"
40
+ "@dxos/app-graph": "0.17.0",
41
+ "@dxos/effect": "0.17.0",
42
+ "@dxos/graph": "0.17.0",
43
+ "@dxos/invariant": "0.17.0",
44
+ "@dxos/log": "0.17.0",
45
+ "@dxos/react-focus": "0.17.0",
46
+ "@dxos/react-ui-attention": "0.17.0",
47
+ "@dxos/ui-types": "0.17.0",
48
+ "@dxos/util": "0.17.0"
49
49
  },
50
50
  "devDependencies": {
51
+ "@dxos/random": "0.17.0",
52
+ "@dxos/react-ui": "0.17.0",
53
+ "@dxos/ui-theme": "0.17.0",
51
54
  "@effect/atom-react": "4.0.4",
52
55
  "@storybook/react-vite": "^10.6.0",
53
56
  "@testing-library/react": "^16.3.2",
54
- "@types/react": "~19.2.17",
55
- "@types/react-dom": "~19.2.3",
57
+ "@types/react": "~19.3.0",
58
+ "@types/react-dom": "~19.3.0",
56
59
  "effect": "4.0.4",
57
- "react": "~19.2.7",
58
- "react-dom": "~19.2.7",
59
- "vite": "^8.3.4",
60
- "@dxos/random": "0.16.0",
61
- "@dxos/react-ui": "0.16.0",
62
- "@dxos/ui-theme": "0.16.0"
60
+ "react": "~19.3.1",
61
+ "react-dom": "~19.3.1",
62
+ "typedoc": "0.28.1",
63
+ "vite": "^8.3.4"
63
64
  },
64
65
  "peerDependencies": {
66
+ "@dxos/react-ui": "^0.17.0",
67
+ "@dxos/ui-theme": "^0.17.0",
65
68
  "@effect/atom-react": "4.0.4",
66
69
  "effect": "4.0.4",
67
- "react": "~19.2.7",
68
- "react-dom": "~19.2.7",
69
- "@dxos/react-ui": "^0.16.0",
70
- "@dxos/ui-theme": "^0.16.0"
70
+ "react": "~19.3.1",
71
+ "react-dom": "~19.3.1"
71
72
  },
72
73
  "publishConfig": {
73
74
  "access": "public"
75
+ },
76
+ "scripts": {
77
+ "typedoc": "typedoc --out typedoc"
74
78
  }
75
79
  }
@@ -110,6 +110,34 @@ describe('MenuBuilder', () => {
110
110
  expect(separatorEdge).toEqual({ source: 'root', target: separatorNode!.id, relation: 'child' });
111
111
  });
112
112
 
113
+ test('separators added through a subgraph or group keep ids of their own', ({ expect }) => {
114
+ const graph = MenuBuilder.make()
115
+ .root({ label: 'toolbar' })
116
+ .separator()
117
+ .subgraph((sub) => sub.action('bold', { label: 'Bold' }, () => {}).separator())
118
+ .group('more', { label: 'More' }, (group) => group.separator())
119
+ .build();
120
+
121
+ const ids = graph.nodes.filter((node) => node.type === MenuSeparatorType).map((node) => node.id);
122
+ expect(new Set(ids).size).toBe(3);
123
+ });
124
+
125
+ test('separators in a separately built graph are renumbered when merged', ({ expect }) => {
126
+ const extension = MenuBuilder.extend('more', (group) =>
127
+ group.separator().action('save', { label: 'Save' }, () => {}),
128
+ );
129
+ const graph = MenuBuilder.make()
130
+ .root({ label: 'toolbar' })
131
+ .separator()
132
+ .group('more', { label: 'More' }, () => {})
133
+ .subgraph(extension)
134
+ .build();
135
+
136
+ const ids = graph.nodes.filter((node) => node.type === MenuSeparatorType).map((node) => node.id);
137
+ expect(new Set(ids).size).toBe(2);
138
+ expect(graph.edges).toContainEqual({ source: 'more', target: ids[1], relation: 'child' });
139
+ });
140
+
113
141
  test('subgraph callback adds children to current group', ({ expect }) => {
114
142
  const graph = MenuBuilder.make()
115
143
  .root({ label: 'toolbar' })
package/src/builder.ts CHANGED
@@ -2,8 +2,15 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import { type ReactNode } from 'react';
6
+
5
7
  import { invariant } from '@dxos/invariant';
6
- import type { DropdownMenuItemGroupProperties, MenuActionProperties, MenuItemGroupProperties } from '@dxos/ui-types';
8
+ import type {
9
+ CustomRenderProps,
10
+ DropdownMenuItemGroupProperties,
11
+ MenuActionProperties,
12
+ MenuItemGroupProperties,
13
+ } from '@dxos/ui-types';
7
14
 
8
15
  import { translationKey } from '#translations';
9
16
 
@@ -44,6 +51,16 @@ export interface ActionGroupBuilder {
44
51
  /** Add a switch action rendered as a labeled Field.Switch. */
45
52
  switch(id: string, props: Omit<MenuActionProperties, 'variant'> & { checked: boolean }, invoke: () => void): this;
46
53
 
54
+ /** Add a control the caller renders itself (a picker, a field); it stays in the toolbar and never collapses. */
55
+ custom(
56
+ id: string,
57
+ props: Omit<MenuActionProperties, 'variant' | 'render'>,
58
+ render: (props: CustomRenderProps) => ReactNode,
59
+ ): this;
60
+
61
+ /** Add a plain label (e.g. a panel's name) that takes the toolbar's free space. */
62
+ text(id: string, props: Omit<MenuActionProperties, 'variant' | 'render'>): this;
63
+
47
64
  /** Add a nested action group. */
48
65
  group(id: string, props: MenuItemGroupProperties, cb: ActionGroupBuilderFn): this;
49
66
 
@@ -73,8 +90,6 @@ export interface MenuBuilder extends ActionGroupBuilder {
73
90
  }
74
91
 
75
92
  class MenuBuilderImpl implements MenuBuilder {
76
- private _separatorCount = 0;
77
-
78
93
  constructor(
79
94
  private readonly _data: ActionGraphProps,
80
95
  private readonly _rootId: string,
@@ -101,6 +116,18 @@ class MenuBuilderImpl implements MenuBuilder {
101
116
  return this.action(id, { ...props, variant: 'switch' }, invoke);
102
117
  }
103
118
 
119
+ custom(
120
+ id: string,
121
+ props: Omit<MenuActionProperties, 'variant' | 'render'>,
122
+ render: (props: CustomRenderProps) => ReactNode,
123
+ ): this {
124
+ return this.action(id, { ...props, variant: 'custom', render }, () => {});
125
+ }
126
+
127
+ text(id: string, props: Omit<MenuActionProperties, 'variant' | 'render'>): this {
128
+ return this.action(id, { ...props, variant: 'text' }, () => {});
129
+ }
130
+
104
131
  group(id: string, props: MenuItemGroupProperties, cb: ActionGroupBuilderFn): this {
105
132
  this._data.nodes.push(createMenuItemGroup(id, props));
106
133
  this._data.edges.push({ source: this._rootId, target: id, relation: 'child' });
@@ -119,14 +146,30 @@ class MenuBuilderImpl implements MenuBuilder {
119
146
  if (typeof subgraphOrCb === 'function') {
120
147
  subgraphOrCb(new MenuBuilderImpl(this._data, this._rootId));
121
148
  } else {
122
- this._data.nodes.push(...subgraphOrCb.nodes);
123
- this._data.edges.push(...subgraphOrCb.edges);
149
+ // A graph built on its own numbers its separators from one, so they are renumbered into this one.
150
+ const ids = new Map<string, string>();
151
+ for (const node of subgraphOrCb.nodes) {
152
+ if (node.type === MenuSeparatorType) {
153
+ const id = this._nextSeparatorId();
154
+ ids.set(node.id, id);
155
+ this._data.nodes.push({ ...node, id });
156
+ } else {
157
+ this._data.nodes.push(node);
158
+ }
159
+ }
160
+ this._data.edges.push(
161
+ ...subgraphOrCb.edges.map((edge) => ({
162
+ ...edge,
163
+ source: ids.get(edge.source) ?? edge.source,
164
+ target: ids.get(edge.target) ?? edge.target,
165
+ })),
166
+ );
124
167
  }
125
168
  return this;
126
169
  }
127
170
 
128
171
  separator(variant: 'gap' | 'line' = 'gap'): this {
129
- const id = `separator-${++this._separatorCount}`;
172
+ const id = this._nextSeparatorId();
130
173
  this._data.nodes.push({
131
174
  id,
132
175
  type: MenuSeparatorType,
@@ -136,8 +179,30 @@ class MenuBuilderImpl implements MenuBuilder {
136
179
  this._data.edges.push({ source: this._rootId, target: id, relation: 'child' });
137
180
  return this;
138
181
  }
182
+
183
+ // Numbered across the whole graph: a nested group or subgraph builds into the same nodes, so a count of its own
184
+ // would reuse an id and the later separator would replace the earlier one.
185
+ private _nextSeparatorId(): string {
186
+ return `separator-${this._data.nodes.filter((node) => node.type === MenuSeparatorType).length + 1}`;
187
+ }
139
188
  }
140
189
 
190
+ /** Id of the overflow menu (⋮) every toolbar ends with; contributors add to it with {@link MenuBuilder.extend}. */
191
+ export const TOOLBAR_OVERFLOW_ID = 'toolbar-overflow';
192
+
193
+ /** The overflow group a toolbar uses when its owner declares none, so contributors can still add to it. */
194
+ export const defaultOverflowGroup = createMenuItemGroup(TOOLBAR_OVERFLOW_ID, overflowMenuProperties);
195
+
141
196
  export const MenuBuilder = Object.freeze({
142
197
  make: (): MenuBuilder => new MenuBuilderImpl({ nodes: [], edges: [] }, 'root'),
198
+
199
+ /**
200
+ * Builds items into a named group another component declared, so a plugin extends a toolbar or menu it does not own.
201
+ * The result is merged into the owner's graph (e.g. with `subgraph`); its edges hang off `groupId`.
202
+ */
203
+ extend: (groupId: string, cb: ActionGroupBuilderFn): ActionGraphProps => {
204
+ const data: ActionGraphProps = { nodes: [], edges: [] };
205
+ cb(new MenuBuilderImpl(data, groupId));
206
+ return data;
207
+ },
143
208
  });
@@ -43,7 +43,11 @@ const createBaseActionsAtom = (count = 3) => {
43
43
  const openDropdown = async (canvasElement: HTMLElement) => {
44
44
  const canvas = within(canvasElement);
45
45
  await userEvent.click(canvas.getByRole('button', { name: /options/i }));
46
- return within(document.body);
46
+ const body = within(document.body);
47
+ // zag focuses the menu a frame after it opens; a key pressed before then (Escape) goes to the page instead.
48
+ const menu = await body.findByRole('menu');
49
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true));
50
+ return body;
47
51
  };
48
52
 
49
53
  /** A contributor: registers items with a menu it does not own, for as long as it is mounted. */
@@ -198,6 +202,39 @@ export const PriorityOrdering: Story = {
198
202
  },
199
203
  };
200
204
 
205
+ /** Toggles are checkboxes, each pressed on its own; other checked actions in a run are one radio group. */
206
+ export const Toggles: Story = {
207
+ render: () => {
208
+ const menu = useMenuActions();
209
+ const items = useMemo(
210
+ () => [
211
+ createMenuAction('snap', () => {}, { label: 'Snap', variant: 'toggle', checked: true }),
212
+ createMenuAction('axes', () => {}, { label: 'Axes', variant: 'toggle', checked: false }),
213
+ createMenuAction('dots', () => {}, { label: 'Dots', checked: true }),
214
+ createMenuAction('lines', () => {}, { label: 'Lines', checked: false }),
215
+ ],
216
+ [],
217
+ );
218
+ return (
219
+ <>
220
+ <Contributor menu={menu} id='toggles' items={items} />
221
+ <ActionMenu {...menu}>
222
+ <Button.Root icon='ph--list-checks--regular' label='Options' iconOnly />
223
+ </ActionMenu>
224
+ </>
225
+ );
226
+ },
227
+ play: async ({ canvasElement }) => {
228
+ const body = await openDropdown(canvasElement);
229
+ const checkboxes = await body.findAllByRole('menuitemcheckbox');
230
+ await expect(checkboxes.map((el) => [el.textContent, el.getAttribute('aria-checked')])).toEqual([
231
+ ['Snap', 'true'],
232
+ ['Axes', 'false'],
233
+ ]);
234
+ await expect((await body.findAllByRole('menuitemradio')).map((el) => el.textContent)).toEqual(['Dots', 'Lines']);
235
+ },
236
+ };
237
+
201
238
  /** A menu that builds its machine on the trigger's first click; the click both builds and opens it. */
202
239
  export const DeferUntilOpen: Story = {
203
240
  render: () => {
@@ -3,6 +3,8 @@
3
3
  //
4
4
 
5
5
  import React, {
6
+ type CSSProperties,
7
+ Fragment,
6
8
  type MouseEvent,
7
9
  type ReactNode,
8
10
  type RefObject,
@@ -24,6 +26,7 @@ import { resolveKeyBinding } from '@dxos/util';
24
26
 
25
27
  import { translationKey } from '#translations';
26
28
 
29
+ import { TOOLBAR_OVERFLOW_ID } from '../builder.ts';
27
30
  import { useMenuActions, useMenuItems } from '../hooks/index.ts';
28
31
  import {
29
32
  type MenuAction,
@@ -93,12 +96,17 @@ const ItemIcon = ({ menu, action }: { menu: MenuActions; action: MenuAction | Me
93
96
  <Menu.ItemIcon spin={action.properties.spin} size={menu.iconSize} classNames={action.properties.iconClassNames} />
94
97
  ) : null;
95
98
 
99
+ /** A row's indent within a menu listing a tree, added to the row's own inset. */
100
+ const indentStyle = ({ indent }: MenuAction['properties']): CSSProperties | undefined =>
101
+ indent ? { paddingInlineStart: `calc(var(--dx-gap-size) * 1.5 + ${indent}rem)` } : undefined;
102
+
96
103
  const ActionMenuItem = ({ menu, action, group }: ActionItemProps) => {
97
104
  const item = useItemData(action.id, action.properties);
98
105
  const handleClick = useInvoke(menu, action, group);
99
106
  return (
100
107
  <Menu.Item
101
108
  item={item}
109
+ style={indentStyle(action.properties)}
102
110
  onClick={handleClick}
103
111
  // Picking several values from a multi-select group should not close the menu after the first.
104
112
  closeOnSelect={!isMultiSelect(group)}
@@ -117,6 +125,7 @@ const ActionCheckboxItem = ({ menu, action, group }: ActionItemProps) => {
117
125
  return (
118
126
  <Menu.CheckboxItem
119
127
  item={item}
128
+ style={indentStyle(action.properties)}
120
129
  // The graph owns the state: the action flips it and the item re-renders from `checked`.
121
130
  checked={!!action.properties.checked}
122
131
  onClick={handleClick}
@@ -136,6 +145,7 @@ const ActionRadioItem = ({ menu, action, group }: ActionItemProps) => {
136
145
  return (
137
146
  <Menu.RadioItem
138
147
  item={item}
148
+ style={indentStyle(action.properties)}
139
149
  onClick={handleClick}
140
150
  {...(action.properties?.testId && { 'data-testid': action.properties.testId })}
141
151
  >
@@ -168,16 +178,36 @@ const ActionSubMenu = ({ menu, group }: { menu: MenuActions; group: MenuItemGrou
168
178
  );
169
179
  };
170
180
 
181
+ /** A toolbar's named group may be declared for others to extend and left empty; a menu then omits it. */
182
+ const NamedGroupSubMenu = ({ menu, group }: { menu: MenuActions; group: MenuItemGroup<MenuItemChrome> }) => {
183
+ const items = useMenuItems(menu, group);
184
+ return items?.some(isMenuRow) ? <ActionSubMenu menu={menu} group={group} /> : null;
185
+ };
186
+
187
+ /**
188
+ * Whether an item renders as a menu row: a label belongs to a toolbar row (a menu has its own title), and a menu cannot
189
+ * host a control its contributor renders itself.
190
+ */
191
+ const isMenuRow = (item: MenuItem): boolean =>
192
+ isMenuGroup(item) ||
193
+ (!isSeparator(item) &&
194
+ !item.properties?.hidden &&
195
+ item.properties?.variant !== 'text' &&
196
+ item.properties?.variant !== 'custom');
197
+
198
+ /** A toggle group is a set of options, which a menu lists in place, ruled off from its neighbours. */
199
+ const isOptionSet = (item: MenuItem): boolean => isMenuGroup(item) && item.properties.variant === 'toggleGroup';
200
+
171
201
  type Segment = { kind: 'item'; item: MenuItem } | { kind: 'radio'; id: string; actions: MenuAction[] };
172
202
 
173
203
  /**
174
204
  * Runs of checkable items in a single-select group become one radio group (Ark's radio items need one), whose value is
175
- * the member marked `checked`.
205
+ * the member marked `checked`; a `toggle` is pressed on its own (a toolbar's, collapsed into ⋮), so it stays a checkbox.
176
206
  */
177
207
  const segment = (items: MenuItem[], multiple: boolean): Segment[] =>
178
208
  items.reduce<Segment[]>((segments, item) => {
179
209
  const last = segments.at(-1);
180
- if (multiple || !isCheckable(item)) {
210
+ if (multiple || !isCheckable(item) || item.properties.variant === 'toggle') {
181
211
  segments.push({ kind: 'item', item });
182
212
  } else if (last?.kind === 'radio') {
183
213
  last.actions.push(item);
@@ -187,16 +217,29 @@ const segment = (items: MenuItem[], multiple: boolean): Segment[] =>
187
217
  return segments;
188
218
  }, []);
189
219
 
220
+ const isOptionSetSegment = (segment: Segment): boolean => segment.kind === 'item' && isOptionSet(segment.item);
221
+
190
222
  const ActionMenuEntry = ({ menu, item, group }: { menu: MenuActions; item: MenuItem; group?: MenuGroupContext }) => {
191
223
  if (isSeparator(item)) {
192
224
  return <Menu.Separator />;
193
225
  }
194
226
  if (isMenuGroup(item)) {
227
+ // A toolbar's overflow items are already "more" in a menu, so they follow the other items rather than nest.
228
+ if (item.id === TOOLBAR_OVERFLOW_ID) {
229
+ return <OverflowSection menu={menu} group={item} />;
230
+ }
231
+ if (isOptionSet(item)) {
232
+ return <ActionMenuItems menu={menu} group={item} />;
233
+ }
195
234
  // A graph group's properties are an open record, validated by the plugin that contributed them.
196
- return <ActionSubMenu menu={menu} group={item as MenuItemGroup<MenuItemChrome>} />;
235
+ return item.properties.variant ? (
236
+ <ActionSubMenu menu={menu} group={item as MenuItemGroup<MenuItemChrome>} />
237
+ ) : (
238
+ <NamedGroupSubMenu menu={menu} group={item as MenuItemGroup<MenuItemChrome>} />
239
+ );
197
240
  }
198
241
  const action = item as MenuAction;
199
- if (action.properties?.hidden) {
242
+ if (!isMenuRow(action)) {
200
243
  return null;
201
244
  }
202
245
  return isCheckable(action) ? (
@@ -206,6 +249,19 @@ const ActionMenuEntry = ({ menu, item, group }: { menu: MenuActions; item: MenuI
206
249
  );
207
250
  };
208
251
 
252
+ const OverflowSection = ({ menu, group }: { menu: MenuActions; group: MenuItemGroup }) => {
253
+ const items = useMenuItems(menu, group);
254
+ if (!items?.some(isMenuRow)) {
255
+ return null;
256
+ }
257
+ return (
258
+ <>
259
+ <Menu.Separator />
260
+ <ActionMenuItems menu={menu} group={group} />
261
+ </>
262
+ );
263
+ };
264
+
209
265
  const ActionMenuItems = ({
210
266
  menu,
211
267
  group,
@@ -219,7 +275,7 @@ const ActionMenuItems = ({
219
275
  const segments = useMemo(() => segment(items ?? [], isMultiSelect(group)), [items, group]);
220
276
  return (
221
277
  <>
222
- {segments.map((entry) =>
278
+ {segments.map((entry, index) =>
223
279
  entry.kind === 'radio' ? (
224
280
  <Menu.RadioItemGroup
225
281
  key={entry.id}
@@ -232,7 +288,10 @@ const ActionMenuItems = ({
232
288
  ))}
233
289
  </Menu.RadioItemGroup>
234
290
  ) : (
235
- <ActionMenuEntry key={entry.item.id} menu={menu} item={entry.item} group={group} />
291
+ <Fragment key={entry.item.id}>
292
+ {index > 0 && (isOptionSet(entry.item) || isOptionSetSegment(segments[index - 1])) && <Menu.Separator />}
293
+ <ActionMenuEntry menu={menu} item={entry.item} group={group} />
294
+ </Fragment>
236
295
  ),
237
296
  )}
238
297
  </>
@@ -359,7 +418,8 @@ const ActionMenuRoot = ({
359
418
  {children}
360
419
  </Menu.Trigger>
361
420
  )}
362
- <Menu.Content container={containerRef}>
421
+ {/* A menu opened at a point (a right-click) has no trigger for an arrow to point at. */}
422
+ <Menu.Content container={containerRef} arrow={virtualRef ? false : undefined}>
363
423
  <ActionMenuItems menu={menu} group={group} actions={typeof actions === 'function' ? actions() : actions} />
364
424
  </Menu.Content>
365
425
  </Menu.Root>