// // Copyright 2026 DXOS.org // import React, { forwardRef } from 'react'; import { type Size } from '../../sizes.ts'; import { Button, type ButtonProps } from '../Button/Button.tsx'; import * as Menu from '../Menu/Menu.tsx'; /** * One entry in a {@link MenuButton}'s menu: a caller describes the menu it wants instead of assembling the Menu parts. */ export type MenuButtonItem = /** Heading over the entries that follow, up to the next heading or separator; not selectable. */ | { type: 'group'; label: string } | { type: 'separator' } /** Single-select entry; consecutive options form one radio group, checked while `selected`. */ | { type: 'option'; label: string; selected: boolean; onSelect: () => void; testId?: string } | { type: 'checkbox'; label: string; checked: boolean; onCheckedChange: (checked: boolean) => void; testId?: string }; type OptionItem = Extract; type CheckboxItem = Extract; /** A run of the menu between separators: its optional heading, then runs of options and single checkboxes. */ type Section = { label?: string; entries: ( | { type: 'options'; options: OptionItem[]; start: number } | { type: 'checkbox'; item: CheckboxItem; index: number } )[]; }; /** Splits the flat item list into sections, so headings and option runs become Ark groups (and zag owns their ARIA). */ const toSections = (items: MenuButtonItem[]): Section[] => { const sections: Section[] = []; let section: Section | undefined; const current = () => { section ??= { entries: [] }; return section; }; const close = () => { if (section) { sections.push(section); section = undefined; } }; items.forEach((item, index) => { switch (item.type) { case 'separator': close(); sections.push({ entries: [] }); break; case 'group': close(); section = { label: item.label, entries: [] }; break; case 'option': { const entries = current().entries; const last = entries.at(-1); if (last?.type === 'options') { last.options.push(item); } else { entries.push({ type: 'options', options: [item], start: index }); } break; } case 'checkbox': current().entries.push({ type: 'checkbox', item, index }); break; } }); close(); return sections; }; export type MenuButtonProps = Omit & { items: MenuButtonItem[]; /** The menu's size; `md` by default. */ menuSize?: Size; }; /** * A Button that opens a menu of options and checkboxes: the composite behind every "options" caret in the app. The * button is the trigger and nothing else; a caller that wants a primary action pairs it with a Button of its own. */ export const MenuButton = forwardRef( ({ items, menuSize, ...props }, forwardedRef) => (