@kolkrabbi/kol-component 0.387.0 → 0.389.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.
@@ -1,10 +1,10 @@
1
- import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
1
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
2
2
  import { IconLoader } from '@kolkrabbi/kol-icons'
3
3
  import Button from '../atoms/Button.jsx'
4
4
  import KolboxGlyph from '../utilities/kolboxGlyph.jsx'
5
5
  import { MenuRow, MenuDivider } from './MenuItem.jsx'
6
6
  import { MenuList, MenuLabel } from './MenuList.jsx'
7
- import { PopoverPanel, PopoverLayer, usePopover } from '../utilities/Popover.jsx'
7
+ import { PopoverPanel, usePopover, spend } from '../utilities/Popover.jsx'
8
8
  import { TONE_VARS } from '../utilities/tone.js'
9
9
 
10
10
  /**
@@ -53,53 +53,12 @@ export const MenuPanel = ({ className = '', children, ...rest }) => (
53
53
  export { MenuLabel }
54
54
 
55
55
 
56
- /* ── the kolbox look (plan-2026-11-18-kolbox-system W31.2 batch 4, 2026-11-18) ──
57
- * kolbox's Menu carried line for line, the chrome in kol-theme `.kol-menu--kolbox` and its rows. Its own API, which no
58
- * other look shares: an `anchor` (an element, a ref, or anything with getBoundingClientRect), controlled `open` with
59
- * `onClose`, `onSelect(row)`, and `groups` `[[row, ...], { title, rows: [...] }]` with a rule between groups; a row is
60
- * `{ label, value, icon, check, shortcut, tag, submenu, disabled, highlighted, inset }`; `highlighted` marks the chosen row
61
- * (where the keys start, the row an `over` list lays on its field), never a lit row: a menu opens with none lit. KOL's words where they are the
62
- * same thing: `aria-label`, `minWidth`, `panelClassName` (the panel's class), `children` (a node above the rows: the
63
- * zoom menu's field). A row's `icon` is the set's name. `placement` is the layer's (`PopoverLayer`): bottom-start, left-start, right-start, beside, over
64
- * (a Dropdown's list lying over its field). */
65
-
66
- /* One row: a leading check or icon, the label, then a shortcut, a tag or a submenu chevron. The active row (the pointer's
67
- or the keys') is solid accent with on-accent ink. The pointer lights a row when it moves on it, so a list that opens
68
- under a resting pointer (a dropdown laid over its field) opens with no row lit.
69
- `inset`: a row with no glyph held in the glyph's column. */
70
- function MenuRowKolbox({ row, index, lead, active, onEnter, onPick }) {
71
- const { label, icon, check, shortcut, tag, submenu, disabled, inset } = row
72
- return (
73
- <div
74
- role={check === undefined ? 'menuitem' : 'menuitemcheckbox'}
75
- aria-checked={check === undefined ? undefined : !!check}
76
- aria-disabled={disabled || undefined}
77
- aria-haspopup={submenu ? 'menu' : undefined}
78
- data-menu-row={index}
79
- data-active={active || undefined}
80
- data-chosen={row.highlighted || undefined}
81
- onPointerMove={disabled || active ? undefined : onEnter}
82
- onClick={disabled ? undefined : onPick}
83
- className={`kol-menu-row--kolbox${disabled ? ' is-disabled' : active ? ' is-active' : ''} flex h-6 shrink-0 cursor-default items-center gap-2 px-2 whitespace-nowrap${disabled ? ' opacity-50' : ''}`}
84
- >
85
- {lead ? (
86
- <span className="flex size-4 shrink-0 items-center justify-center">
87
- {check ? <KolboxGlyph name="check" size={12} /> : icon ? <KolboxGlyph name={icon} /> : null}
88
- </span>
89
- ) : icon ? <KolboxGlyph name={icon} /> : inset && <span className="size-4 shrink-0" />}
90
- <span className="flex-1">{label}</span>
91
- {shortcut && <span className={`shrink-0 ${active ? '' : 'kol-menu-sub--kolbox'}`}>{shortcut}</span>}
92
- {tag && <span className={`kol-menu-tag--kolbox${active ? ' is-active' : ''} px-1`}>{tag}</span>}
93
- {submenu && <KolboxGlyph name="chevron-right" className={active ? '' : 'kol-menu-sub--kolbox'} />}
94
- </div>
95
- )
96
- }
97
-
98
56
  /**
99
- * MenuScroll — the foot of a kolbox menu taller than the window (Menu family, W31.2 batch 4; Figma 288:8017): the full
100
- * panel width, 24 high, the 12 chevron-down centred in oq-64. While the pointer is on it the panel scrolls down, 4 px a
101
- * frame, until the end or the pointer leaves. It sits sticky on the menu's own fill so the rows pass under it.
102
- * `Menu variant="kolbox"` draws it on its own; `panel` is the scrolling panel's ref.
57
+ * MenuScroll — the foot of a menu taller than the window (Menu family, W31.2 batch 4; Figma 288:8017): the full panel
58
+ * width, 24 high, the 12 chevron-down centred in oq-64. While the pointer is on it the panel scrolls down, 4 px a frame,
59
+ * until the end or the pointer leaves. It sits sticky on the menu's own fill so the rows pass under it. `Menu` draws it on
60
+ * its own when its panel scrolls (the theme gives the panel a height cap: kolbox's, the window less 16); `panel` is the
61
+ * scrolling panel's ref.
103
62
  */
104
63
  export function MenuScroll({ panel }) {
105
64
  const run = useRef(0)
@@ -113,224 +72,126 @@ export function MenuScroll({ panel }) {
113
72
  useEffect(() => stop, [])
114
73
  return (
115
74
  <div data-menu-more="" aria-hidden onPointerEnter={go} onPointerLeave={stop}
116
- className="kol-menu-scroll--kolbox sticky -bottom-2 -mx-2 -mb-2 flex h-6 shrink-0 items-center justify-center">
75
+ className="kol-menu-scroll sticky flex h-6 shrink-0 items-center justify-center">
117
76
  <KolboxGlyph name="chevron-down" />
118
77
  </div>
119
78
  )
120
79
  }
121
80
 
122
- /* Flyouts: a row whose `submenu` holds groups (the same shape) opens a second Menu, on hover, a click, ArrowRight or
123
- Enter; ArrowLeft in the flyout closes it and gives the keys back. A pick in a flyout runs this Menu's onSelect and
124
- closes every level. The child is a panel beside this whole panel, not hung from its row; the row stays lit in the
125
- accent while its child is open. A list taller than the window scrolls and ends in MenuScroll while there is more below.
126
- The keys: the arrows move the lit row, Enter picks, a letter jumps to the next row that starts with it, Escape (the
127
- layer's) closes. */
128
- function MenuKolbox({ anchor, open, onClose, onSelect, groups = [], 'aria-label': label, placement = 'bottom-start', panelClassName = '', minWidth, nested = false, accent, children }) {
129
- const all = groups.map((g) => (Array.isArray(g) ? { rows: g } : g))
130
- const rows = all.flatMap((g) => g.rows)
131
- /* the lead column is kept for checks only, so a checked list lines up; a row's icon sits in its row */
132
- const lead = rows.some((r) => r.check !== undefined)
133
- /* no row is lit on open (the accent is the pointer's and the keys'); the chosen row (`highlighted`) is where the keys
134
- start and, under `placement="over"`, the row laid on the field */
135
- const chosen = rows.findIndex((r) => r.highlighted)
136
- const [active, setActive] = useState(-1)
137
- const [flyout, setFlyout] = useState(null)
138
- useEffect(() => { if (open) setActive(-1); else setFlyout(null) }, [open])
139
-
140
- /* focus once, when the panel mounts: a flyout takes the keys while it is open */
141
- const panel = useRef(null)
142
- const [more, setMore] = useState(false)
143
- const measure = useCallback(() => { const p = panel.current; if (p) setMore(p.scrollHeight - p.scrollTop - p.clientHeight > 1) }, [])
144
- const mount = useCallback((node) => { panel.current = node; node?.focus({ preventScroll: true }); if (node) requestAnimationFrame(measure) }, [measure])
145
- const refocus = () => panel.current?.focus({ preventScroll: true })
146
- /* the keys move the lit row; a long list follows it */
147
- useEffect(() => { panel.current?.querySelector(`[data-menu-row="${active}"]`)?.scrollIntoView({ block: 'nearest' }) }, [active])
148
-
149
- const pick = (row) => { onSelect?.(row); onClose?.() }
150
- const show = (i) => { if (flyout !== null && flyout !== i) refocus(); setFlyout(i !== null && rows[i]?.submenu && !rows[i].disabled ? i : null) }
151
- const press = (i) => (rows[i].submenu ? show(i) : pick(rows[i]))
152
- const key = (e) => {
153
- /* the page's own shortcuts never see a key meant for the menu; Escape goes on to the layer's listener */
154
- if (e.key !== 'Escape') e.stopPropagation()
155
- if (e.key === 'ArrowLeft' && nested) { e.preventDefault(); onClose?.(); return }
156
- const live = rows.map((r, i) => (r.disabled ? -1 : i)).filter((i) => i >= 0)
157
- if (!live.length) return
158
- const at = live.indexOf(active)
159
- if (e.key === 'ArrowDown') { e.preventDefault(); show(null); setActive(at < 0 && live.includes(chosen) ? chosen : live[(at + 1) % live.length]) }
160
- if (e.key === 'ArrowUp') { e.preventDefault(); show(null); setActive(live[at < 0 ? live.length - 1 : (at - 1 + live.length) % live.length]) }
161
- if (e.key === 'ArrowRight' && rows[active]?.submenu) { e.preventDefault(); show(active) }
162
- /* preventDefault: else the Enter's keypress lands on the trigger that takes focus back, and opens it again */
163
- if (e.key === 'Enter' && rows[active] && !rows[active].disabled) { e.preventDefault(); press(active) }
164
- /* a letter jumps to the next live row that starts with it */
165
- if (e.key.length === 1 && /\S/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey && e.target.tagName !== 'INPUT') {
166
- const k = e.key.toLowerCase()
167
- const next = [...live.slice(at + 1), ...live.slice(0, at + 1)].find((i) => String(rows[i].label).toLowerCase().startsWith(k))
168
- if (next !== undefined) { show(null); setActive(next) }
169
- }
170
- }
171
-
172
- let n = -1
173
- const sub = flyout !== null ? rows[flyout] : null
174
- return (
175
- <>
176
- <PopoverLayer anchor={anchor} open={open} onClose={onClose} placement={placement} kind="menu">
177
- <div
178
- data-accent={accent === 'secondary' ? accent : undefined}
179
- role="menu"
180
- aria-label={label}
181
- tabIndex={-1}
182
- ref={mount}
183
- onKeyDown={key}
184
- onScroll={measure}
185
- data-kolbox-menu=""
186
- style={minWidth != null ? { minWidth } : undefined}
187
- className={`kol-menu--kolbox kol-kolbox-surface flex min-w-40 flex-col overflow-y-auto p-2 outline-none ${panelClassName}`}
188
- >
189
- {children}
190
- {all.map((g, gi) => (
191
- <Fragment key={gi}>
192
- {gi > 0 && <div role="separator" className="kol-menu-rule--kolbox -mx-2 my-1 h-px shrink-0" />}
193
- {g.title && <div className="kol-menu-heading--kolbox flex h-6 shrink-0 items-center px-2">{g.title}</div>}
194
- {g.rows.map((row) => {
195
- const i = ++n
196
- return <MenuRowKolbox key={i} row={row} index={i} lead={lead} active={i === active || i === flyout} onEnter={() => { setActive(i); show(i) }} onPick={() => press(i)} />
197
- })}
198
- </Fragment>
199
- ))}
200
- {more && <MenuScroll panel={panel} />}
201
- </div>
202
- </PopoverLayer>
203
- {sub?.submenu && (
204
- <MenuKolbox
205
- key={flyout}
206
- nested
207
- anchor={panel.current}
208
- open={open}
209
- placement="beside"
210
- aria-label={sub.label}
211
- groups={sub.submenu}
212
- accent={accent}
213
- onSelect={pick}
214
- onClose={() => { setFlyout(null); refocus() }}
215
- />
216
- )}
217
- </>
218
- )
219
- }
220
-
221
- /* Menu's own rows under the kolbox look (Folio on kolbox, 2026-11-22), so a host that passes `items` switches by the
222
- variant alone: `{ label, onClick, kbd, checked, disabled, icon, items }`, `{ divider: true }` (a new group) and
223
- `{ heading }` (a titled group) become kolbox's groups; a row's `onClick` runs as it is picked. `anchor` may also be a
224
- point `{ x, y }` (a right-click list): the list opens at it. */
225
- const kolboxGroupsOf = (items) => {
226
- const groups = [{ rows: [] }]
227
- for (const it of items) {
228
- if (it.divider || it.heading) { if (groups.at(-1).rows.length || groups.at(-1).title) groups.push({ rows: [] }); if (it.heading) groups.at(-1).title = it.heading; continue }
229
- groups.at(-1).rows.push({ label: it.label, check: it.checked, shortcut: it.kbd || undefined, disabled: it.disabled, icon: typeof it.icon === 'string' ? it.icon : undefined, submenu: it.items?.length ? kolboxGroupsOf(it.items) : undefined, run: it.onClick })
230
- }
231
- return groups.filter((g) => g.rows.length)
232
- }
233
- function MenuKolboxItems({ items, anchor, onSelect, ...props }) {
234
- const point = anchor != null && !('current' in anchor) && typeof anchor.getBoundingClientRect !== 'function' && anchor.x != null
235
- const { x, y } = point ? anchor : {}
236
- const at = useMemo(() => (point ? { getBoundingClientRect: () => ({ x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 }) } : anchor), [point, x, y, point ? null : anchor]) // eslint-disable-line react-hooks/exhaustive-deps
237
- return <MenuKolbox {...props} anchor={at} groups={kolboxGroupsOf(items)} onSelect={(row) => { onSelect?.(row); row.run?.() }} />
238
- }
239
-
240
- /* ── the folio look (Folio migration batch B, 2026-11-22) ──
241
- * Folio's menu list (apps/folio EditorChrome `Items`) carried class for class, the chrome in kol-theme `.kol-menu--folio`.
242
- * The host owns the trigger, as kolbox's does; the list is drawn in place, never portalled, so it keeps the frame's
243
- * `data-folio-*` switches. KOL's words: `open`, `onClose`, `items` (`{ label, onClick, kbd, checked, disabled }` or
244
- * `{ divider: true }`), `aria-label`, `minWidth`, `panelClassName` (where the list sits: the host's `absolute ...`).
245
- * `anchor` a point `{ x, y }`: a right-click list, fixed at the point and kept on screen, closed by any press, a scroll or
246
- * the window's blur. Without one a press outside the host's wrapper (the list's parent) closes it. Escape closes either.
247
- * The check column is drawn when any row says `checked`; the key column when a row says `kbd`. A row's click closes
248
- * the list, then runs. */
249
- function MenuFolioCheck({ checked }) {
250
- return <span aria-hidden className="kol-menu-check--folio inline-flex size-[16px] shrink-0 items-center justify-center">{checked ? '✓' : ''}</span>
251
- }
252
- function MenuFolio({ open, onClose, items = [], anchor, 'aria-label': label, minWidth, panelClassName = '', accent }) {
253
- const panel = useRef(null)
254
- useEffect(() => {
255
- if (!open) return undefined
256
- const esc = (e) => e.key === 'Escape' && onClose?.()
257
- if (anchor) {
258
- const shut = () => onClose?.()
259
- addEventListener('mousedown', shut); addEventListener('keydown', esc); addEventListener('scroll', shut, true); addEventListener('blur', shut)
260
- return () => { removeEventListener('mousedown', shut); removeEventListener('keydown', esc); removeEventListener('scroll', shut, true); removeEventListener('blur', shut) }
261
- }
262
- const off = (e) => { if (!panel.current?.parentElement?.contains(e.target)) onClose?.() }
263
- addEventListener('mousedown', off); addEventListener('keydown', esc)
264
- return () => { removeEventListener('mousedown', off); removeEventListener('keydown', esc) }
265
- }, [open, onClose, anchor])
266
- if (!open) return null
267
- const lead = items.some((it) => it.checked !== undefined)
268
- const rows = items.filter((it) => !it.divider).length, seps = items.length - rows
269
- const at = anchor ? { left: Math.min(anchor.x, innerWidth - 260), top: Math.max(8, Math.min(anchor.y, innerHeight - (rows * 32 + seps * 13 + 16) - 8)) } : null
270
- return (
271
- <span data-accent={accent === 'secondary' ? accent : undefined} ref={panel} role="menu" aria-label={label} style={{ ...at, ...(minWidth != null ? { minWidth } : null) }} onMouseDown={(e) => e.stopPropagation()}
272
- className={`kol-menu--folio z-50 flex min-w-[240px] flex-col rounded-[4px] border py-[6px] ${anchor ? 'fixed' : ''} ${panelClassName}`}>
273
- {items.map((it, i) => (it.divider ? <span key={i} className="kol-menu-rule--folio my-[6px] h-px" /> : (
274
- <button key={`${it.label}${i}`} type="button" role="menuitem" disabled={it.disabled} onMouseDown={(e) => e.preventDefault()} onClick={() => { onClose?.(); it.onClick?.() }}
275
- className="kol-menu-row--folio flex h-[32px] items-center gap-[16px] px-[14px] text-left">
276
- {lead && <MenuFolioCheck checked={it.checked} />}{it.label}{it.kbd !== undefined && <span className="kol-menu-kbd--folio ml-auto">{it.kbd}</span>}
277
- </button>
278
- )))}
279
- </span>
280
- )
281
- }
81
+ /* `groups` (kolbox's word, kept): `[[row, ...], { title, rows: [...] }]`, a rule between groups, a title a heading; a row
82
+ `{ label, value, icon, check, shortcut, tag, submenu, disabled, highlighted, inset }` becomes a Menu row (`shortcut` the
83
+ key cap, `submenu` a flyout of the same groups), and a pick hands `onSelect` the row as it was given */
84
+ const itemsOfGroups = (groups) => groups.flatMap((g, gi) => {
85
+ const { title, rows = [] } = Array.isArray(g) ? { rows: g } : g
86
+ return [
87
+ ...(gi > 0 ? [{ divider: true, key: `d${gi}` }] : []),
88
+ ...(title ? [{ heading: title, key: `h${gi}` }] : []),
89
+ ...rows.map((r, ri) => ({ key: `${gi}.${ri}`, label: r.label, icon: r.icon, check: r.check, kbd: r.shortcut || undefined, tag: r.tag, disabled: r.disabled, highlighted: r.highlighted, inset: r.inset, items: r.submenu ? itemsOfGroups(r.submenu) : undefined, row: r })),
90
+ ]
91
+ })
92
+ const anchorOf = (anchor) => (anchor && typeof anchor === 'object' && 'current' in anchor ? anchor.current : anchor)
93
+ const pointRect = (x, y) => ({ getBoundingClientRect: () => ({ x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 }) })
94
+ const later = (a, b) => !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING)
95
+ /* a number the theme sets on the panel (`--kol-menu-flyout-*`), or the default */
96
+ const themeNum = (el, name, d) => { const v = parseFloat(getComputedStyle(el).getPropertyValue(name)); return Number.isFinite(v) ? v : d }
97
+ const PLACE = { 'bottom-start': 'bottom-start', 'bottom-end': 'bottom-end', 'left-start': 'left-start', 'right-start': 'right-start', over: 'bottom-start', flyout: 'right-start' }
98
+ const GAP = { 'left-start': 8, 'right-start': 8 }
282
99
 
283
100
  /**
284
- * Menu — THE menu engine (plan-2026-10-31-menu-engine W1). Every list that floats over a trigger is this: the Menu*
285
- * menus, Dropdown (a `fused` select), MultiSelect (columns), MenuItem (a menubar entry), ContextMenu (a point).
101
+ * Menu — THE menu (plan-2026-10-31-menu-engine W1; one menu since plan-2026-11-29-one-set-fold W3). Every list that floats
102
+ * over a trigger or an anchor is this: the Menu* menus, Dropdown (a `fused` select, and its field's list), MultiSelect
103
+ * (columns), MenuItem (a menubar entry), ContextMenu (a point), MenuBar, the kolbox menus. Its look is the theme's
104
+ * (`--kol-menu-*`, kol-theme `.kol-menu-panel` and its rows): the default theme draws KOL's panel, `data-theme-variant=
105
+ * "kolbox"` kolbox's (rows 24 touching, the lit row solid accent, the check in the leading column, plain shortcuts).
286
106
  *
287
107
  * trigger render prop `({ open, props })` — any trigger: MenuTrigger chip, a select, the ⋮, a menubar button
288
- * anchor `{ x, y }` instead of a trigger — the panel opens at a point (right-click)
289
- * align 'start' | 'end' — the panel's edge flush with the trigger's
108
+ * anchor instead of a trigger: an element, a ref, anything with getBoundingClientRect, or a point `{ x, y }` (a
109
+ * right-click). With neither, the panel hangs under the element it is rendered in (Folio's in-place list)
110
+ * placement anchored: bottom-start (unset), bottom-end, left-start, right-start, over (the list over its field, the
111
+ * `highlighted` row lying on it). With a trigger: `align` 'start' | 'end', the panel's edge flush with it
112
+ * items rows as data (MenuList's keys); or `groups` (kolbox's: `[[row], { title, rows }]`, rows `{ label, value,
113
+ * icon, check, shortcut, tag, submenu, disabled, highlighted, inset }`); `onSelect(row)` on any pick
290
114
  * fused the panel continues the trigger: no gap, its width, top corners squared, never flips
291
- * tone nothing to pass: the trigger's resolved `--kol-tone-*` ride onto the portalled panel, so a menu in a
292
- * `kol-tone-*` wrapper floats on that tone's surface
115
+ * tone nothing to pass: the trigger's resolved `--kol-tone-*` ride onto the portalled panel
293
116
  * closeOnSelect false keeps the panel open while rows toggle (a multiselect)
294
- * open / onOpenChange controlled, when the caller needs the state
295
- * offset the gap under the trigger (default 4; a fused panel sits at -1, a point anchor at 2 — pass one to override)
296
- * variant 'kolbox' (plan-2026-11-18-kolbox-system W31.2 batch 4): kolbox's menu, its own API — see `MenuKolbox` above;
297
- * it also reads `items` and a point `anchor` (Folio on kolbox, 2026-11-22) — see `MenuKolboxItems`
298
- * variant 'folio' (Folio migration batch B): Folio's list, drawn in place, the host's trigger — see `MenuFolio` above
117
+ * open / defaultOpen / onOpenChange / onClose controlled or not; `onClose` runs on every close
118
+ * offset the gap (default 4; a fused panel -1, a point anchor 4, beside 8)
119
+ * search · minWidth · panelClassName (the panel's class) · panelStyle · aria-label · accent · children (above the rows;
120
+ * a function gets `{ close }`)
121
+ * variant 'kolbox' | 'folio' are accepted and do nothing: the theme draws the look (on the retirement ledger)
122
+ *
123
+ * The keys, every menu (kolbox's): the panel takes focus on open; the arrows move the lit row, Enter picks (or opens a
124
+ * flyout), ArrowRight opens and ArrowLeft closes a flyout, a letter jumps to the next row that starts with it, Escape
125
+ * closes the topmost menu only. No row is lit on open; the pointer lights the row it moves on. Closed from a trigger, the
126
+ * focus goes back to it. A press outside closes, except one inside a menu or layer opened later (a child, a field's
127
+ * list); a press on the canvas (`[data-canvas]`) that closes it is spent there.
299
128
  */
300
- export function Menu(props) {
301
- if (props.variant === 'kolbox') return props.items ? <MenuKolboxItems {...props} /> : <MenuKolbox {...props} />
302
- if (props.variant === 'folio') return <MenuFolio {...props} />
303
- return <MenuOn {...props} />
304
- }
305
-
306
- function MenuOn({
307
- items, trigger, anchor, align = 'start', minWidth, offset, defaultOpen = false, open: openProp, onOpenChange,
308
- stayOpen = false, closeOnSelect = true, fused = false, search, role = 'menu',
309
- panelClassName = '', panelStyle, rootClassName, className = '', accent, children,
129
+ export function Menu({
130
+ items, groups, onSelect, trigger, anchor, placement, align = 'start', minWidth, offset, defaultOpen = false,
131
+ open: openProp, onOpenChange, onClose, stayOpen = false, closeOnSelect = true, fused = false, search, role = 'menu',
132
+ panelClassName = '', panelStyle, rootClassName, className = '', accent, 'aria-label': ariaLabel, nested = false,
133
+ variant, children, // eslint-disable-line no-unused-vars
310
134
  }) {
311
135
  const [own, setOwn] = useState(defaultOpen)
312
136
  const controlled = openProp !== undefined
313
137
  const open = controlled ? openProp : own
314
- const setOpen = (v) => { if (!controlled) setOwn(v); onOpenChange?.(v) }
138
+ const setOpen = (v) => { if (!controlled) setOwn(v); onOpenChange?.(v); if (!v) onClose?.() }
139
+ const rows = useMemo(() => (groups ? itemsOfGroups(groups) : items), [groups, items])
140
+
141
+ const a = anchorOf(anchor)
142
+ const point = !trigger && a && typeof a === 'object' && !(a instanceof Element) && typeof a.getBoundingClientRect !== 'function' && a.x != null
143
+ const where = trigger ? (align === 'end' ? 'bottom-end' : 'bottom-start') : placement ?? 'bottom-start'
144
+ const panel = useRef(null)
315
145
  const popover = usePopover({
316
146
  open,
317
147
  onOpenChange: setOpen,
318
- placement: anchor ? 'right-start' : align === 'end' ? 'bottom-end' : 'bottom-start',
319
- offset: offset ?? (fused ? -1 : anchor ? 2 : 4),
320
- flip: !fused,
148
+ placement: PLACE[where] ?? where,
149
+ offset: where === 'over' ? (({ rects, elements }) => {
150
+ /* the list over its field: the chosen row's middle on the field's middle, or the list's top on the field's top */
151
+ const row = elements.floating.querySelector('[data-chosen]')
152
+ if (!row) return -rects.reference.height
153
+ const top = row.getBoundingClientRect().top - elements.floating.getBoundingClientRect().top
154
+ return -rects.reference.height / 2 - (top + row.offsetHeight / 2)
155
+ }) : where === 'flyout' ? (({ placement: side }) => {
156
+ /* a child menu beside its parent's PANEL, `--kol-menu-flyout-gap` off its edge; its top on the row less
157
+ `--kol-menu-flyout-dy` (`--kol-menu-flyout-on-row` 1), or level with the panel's top (0) */
158
+ const p = a?.closest?.('[data-menu-panel]')
159
+ if (!p) return 4
160
+ const pr = p.getBoundingClientRect(), rr = a.getBoundingClientRect()
161
+ const onRow = themeNum(p, '--kol-menu-flyout-on-row', 1)
162
+ return {
163
+ mainAxis: (side.startsWith('right') ? pr.right - rr.right : rr.left - pr.left) + themeNum(p, '--kol-menu-flyout-gap', 0),
164
+ crossAxis: (onRow ? 0 : pr.top - rr.top) + themeNum(p, '--kol-menu-flyout-dy', -5),
165
+ }
166
+ }) : offset ?? (fused ? -1 : GAP[where] ?? 4),
167
+ flip: !fused && where !== 'over',
321
168
  matchReferenceWidth: fused,
322
- click: !anchor,
169
+ click: !!trigger,
323
170
  role,
324
- dismiss: stayOpen ? { outsidePress: false } : true,
171
+ /* Escape is ours (below); the press outside skips a menu or layer opened after this one, and spends a canvas press */
172
+ dismiss: {
173
+ escapeKey: false,
174
+ outsidePress: stayOpen ? false : (e) => {
175
+ const me = panel.current, t = e.target
176
+ const hit = t?.closest?.('[data-kolbox-overlay]')
177
+ if (me && hit && hit !== me && later(me, hit)) return false
178
+ if (t?.closest?.('[data-canvas]')) spend(e)
179
+ return true
180
+ },
181
+ },
325
182
  })
326
183
 
327
- /* a point anchor is a zero-size virtual rect — `setPositionReference`, never `elements.reference` (ContextMenu) */
328
- const { setPositionReference } = popover.refs
329
- useEffect(() => {
330
- if (!anchor) return
331
- const { x, y } = anchor
332
- setPositionReference({ getBoundingClientRect: () => ({ width: 0, height: 0, x, y, top: y, left: x, right: x, bottom: y }) })
333
- }, [anchor?.x, anchor?.y, setPositionReference]) // eslint-disable-line react-hooks/exhaustive-deps
184
+ /* the anchor: an element is the reference (a press on it is the caller's toggle, never outside); a point or a box is
185
+ a virtual one; with neither, the element the Menu is rendered in */
186
+ const { setReference, setPositionReference } = popover.refs
187
+ const here = useRef(null)
188
+ useLayoutEffect(() => {
189
+ if (trigger || !open) return
190
+ if (!a) { const host = here.current?.parentElement; if (host) setReference(host); return }
191
+ if (a instanceof Element) setReference(a)
192
+ else if (point) setPositionReference(pointRect(a.x, a.y))
193
+ else setPositionReference(a)
194
+ }, [open, trigger, a, point ? a.x : null, point ? a.y : null]) // eslint-disable-line react-hooks/exhaustive-deps
334
195
 
335
196
  /* THE PANEL IS PORTALLED, so a tone the trigger inherits never reaches it through the cascade — copy it on open */
336
197
  const rootRef = useRef(null)
@@ -345,24 +206,93 @@ function MenuOn({
345
206
  setAmbient(vars)
346
207
  }, [open])
347
208
 
209
+ /* closed from a trigger, the focus goes back to it when it was in the panel */
210
+ const wasOpen = useRef(open)
211
+ useLayoutEffect(() => {
212
+ if (wasOpen.current && !open && trigger) {
213
+ const f = document.activeElement
214
+ if (!f || f === document.body) rootRef.current?.querySelector('button, [href], [tabindex]:not([tabindex="-1"])')?.focus({ preventScroll: true })
215
+ }
216
+ wasOpen.current = open
217
+ }, [open, trigger])
218
+
219
+ /* Escape closes the topmost menu or layer only */
220
+ useEffect(() => {
221
+ if (!open) return undefined
222
+ const esc = (e) => {
223
+ if (e.key !== 'Escape' || !panel.current) return
224
+ const all = document.querySelectorAll('[data-kolbox-overlay]')
225
+ if (all[all.length - 1] === panel.current) setOpen(false)
226
+ }
227
+ document.addEventListener('keydown', esc)
228
+ return () => document.removeEventListener('keydown', esc)
229
+ }) // eslint-disable-line react-hooks/exhaustive-deps
230
+
231
+ /* the panel's scroll foot, when it scrolls */
232
+ const [more, setMore] = useState(false)
233
+ const measure = useCallback(() => { const p = panel.current; if (p) setMore(p.scrollHeight - p.scrollTop - p.clientHeight > 1) }, [])
234
+ const mount = useCallback((node) => { panel.current = node; if (node) { node.focus({ preventScroll: true }); requestAnimationFrame(measure) } }, [measure])
235
+
236
+ /* the lit row: the pointer's or the keys' (`data-active`, on the DOM, so composed rows light too) */
237
+ const lit = useRef(null)
238
+ const light = (el, keys) => {
239
+ if (lit.current && lit.current !== el) lit.current.removeAttribute('data-active')
240
+ lit.current = el
241
+ if (el) { el.setAttribute('data-active', ''); if (keys) el.scrollIntoView({ block: 'nearest' }) }
242
+ panel.current?.toggleAttribute('data-keys', !!keys)
243
+ }
244
+ const liveRows = () => [...(panel.current?.querySelectorAll('[data-menu-row]') ?? [])].filter((el) => !el.disabled && el.getAttribute('aria-disabled') !== 'true' && el.closest('[data-menu-panel]') === panel.current)
245
+ const onPointerMove = (e) => {
246
+ const row = e.target.closest?.('[data-menu-row]')
247
+ if (row && row !== lit.current && liveRows().includes(row)) light(row, false)
248
+ }
249
+ const onKeyDown = (e) => {
250
+ /* the page's own shortcuts never see a key meant for the menu; Escape goes on to the listener above */
251
+ if (e.key === 'Escape') return
252
+ e.stopPropagation()
253
+ if (e.key === 'ArrowLeft' && nested) { e.preventDefault(); setOpen(false); return }
254
+ const live = liveRows()
255
+ if (!live.length) return
256
+ const at = live.indexOf(lit.current)
257
+ const chosen = live.find((el) => el.hasAttribute('data-chosen'))
258
+ if (e.key === 'ArrowDown') { e.preventDefault(); light(at < 0 && chosen ? chosen : live[(at + 1) % live.length], true) }
259
+ if (e.key === 'ArrowUp') { e.preventDefault(); light(live[at < 0 ? live.length - 1 : (at - 1 + live.length) % live.length], true) }
260
+ const row = live[at]
261
+ if (row && e.key === 'ArrowRight' && row.getAttribute('aria-haspopup')) { e.preventDefault(); if (row.getAttribute('aria-expanded') !== 'true') row.click() }
262
+ /* preventDefault: else the Enter's keypress lands on the trigger that takes focus back, and opens it again */
263
+ if (row && e.key === 'Enter' && e.target.tagName !== 'INPUT') { e.preventDefault(); if (row.getAttribute('aria-expanded') !== 'true') row.click() }
264
+ /* a letter jumps to the next live row that starts with it */
265
+ if (e.key.length === 1 && /\S/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey && e.target.tagName !== 'INPUT') {
266
+ const k = e.key.toLowerCase()
267
+ const next = [...live.slice(at + 1), ...live.slice(0, at + 1)].find((el) => el.textContent.trim().toLowerCase().startsWith(k))
268
+ if (next) light(next, true)
269
+ }
270
+ }
271
+
272
+ const close = () => setOpen(false)
348
273
  /* the wrapper takes the ref (a Button need not forward one); the trigger takes the handlers and the aria —
349
274
  * `aria-pressed` cleared, an open menu is `aria-expanded`, its fill is the trigger's `pressed` */
350
275
  return (
351
276
  <>
352
- {trigger && (
277
+ {trigger ? (
353
278
  <span data-accent={accent === 'secondary' ? accent : undefined} ref={(el) => { rootRef.current = el; popover.refs.setReference(el) }} className={rootClassName ?? `inline-flex align-middle ${className}`.trim()}>
354
279
  {trigger({ open, props: { ...popover.getReferenceProps(), 'aria-pressed': undefined } })}
355
280
  </span>
356
- )}
281
+ ) : !a && <span ref={here} hidden />}
357
282
  {open && (
358
- <PopoverPanel popover={popover} panel={false} focus={false}
359
- className={`kol-menu-panel${fused ? ' kol-menu-panel--fused' : ' w-max'} ${panelClassName}`.replace(/\s+/g, ' ').trim()}
360
- style={{ ...ambient, ...(minWidth ? { minWidth } : null), ...panelStyle }}>
361
- {/* a row's click closes the menu (it bubbles from `[data-menu-item]`); a flyout row only toggles */}
362
- <div data-accent={accent === 'secondary' ? accent : undefined} role="none" className="flex flex-col gap-[var(--kol-spacing-0-5)] min-h-0" onClick={(e) => { if (closeOnSelect && e.target.closest('[data-menu-item]')) setOpen(false) }}>
363
- <MenuList items={items} search={search}>
364
- {typeof children === 'function' ? children({ close: () => setOpen(false) }) : children}
283
+ <PopoverPanel popover={popover} panel={false} focus={false} panelRef={mount}
284
+ className={`kol-menu-panel${fused ? ' kol-menu-panel--fused' : ' w-max'} outline-none ${panelClassName}`.replace(/\s+/g, ' ').trim()}
285
+ style={{ ...ambient, ...(minWidth ? { minWidth } : null), ...panelStyle }}
286
+ floatingProps={{
287
+ tabIndex: -1, 'aria-label': ariaLabel, 'data-menu-panel': '', 'data-kolbox-overlay': 'menu', 'data-kolbox-menu': '',
288
+ 'data-accent': accent === 'secondary' ? accent : undefined, onKeyDown, onPointerMove, onScroll: measure,
289
+ }}>
290
+ {/* a row's click closes the menu (it bubbles from `[data-menu-item]`, a child menu's too); a flyout row only opens */}
291
+ <div data-accent={accent === 'secondary' ? accent : undefined} role="none" className="flex flex-col gap-[var(--kol-menu-gap,var(--kol-spacing-0-5))] min-h-0" onClick={(e) => { if (closeOnSelect && e.target.closest('[data-menu-item]')) close() }}>
292
+ <MenuList items={rows} search={search} onSelect={onSelect}>
293
+ {typeof children === 'function' ? children({ close }) : children}
365
294
  </MenuList>
295
+ {more && <MenuScroll panel={panel} />}
366
296
  </div>
367
297
  </PopoverPanel>
368
298
  )}
@@ -393,7 +323,7 @@ export function MenuFilter({ groups = [], onPick, active = [], onRemove, onClear
393
323
  })
394
324
  const rowCls = 'kol-menu-row kol-helper-12'
395
325
  return (
396
- <Menu align={align} minWidth={minWidth} offset={8} items={items} variant={variant}
326
+ <Menu align={align} minWidth={minWidth} offset={8} items={items}
397
327
  trigger={({ open, props }) => <MenuTrigger open={open || active.length > 0} icon={icon} variant={variant} {...props}>{label}</MenuTrigger>}>
398
328
  {active.length > 0 && (
399
329
  <>
@@ -431,7 +361,7 @@ export function MenuDatePicker({ groups = [], value, onChange, label, icon = 'ca
431
361
  ...(compare ? [{ divider: true }, { key: 'compare', label: compare.label, kbd: compare.kbd, onClick: compare.onClick }] : []),
432
362
  ]
433
363
  return (
434
- <Menu align={align} minWidth={minWidth} offset={8} items={items} variant={variant}
364
+ <Menu align={align} minWidth={minWidth} offset={8} items={items}
435
365
  trigger={({ open, props }) => <MenuTrigger open={open} icon={icon} iconComponent={iconComponent} variant={variant} {...props}>{label}</MenuTrigger>} />
436
366
  )
437
367
  }
@@ -439,7 +369,12 @@ export function MenuDatePicker({ groups = [], value, onChange, label, icon = 'ca
439
369
  /** MenuMore — the ⋮ chip and its rows (`items`, as `Menu`'s); `label` names it for a screen reader. */
440
370
  export function MenuMore({ label, items = [], align = 'end', minWidth = 224, defaultOpen, stayOpen, variant }) {
441
371
  return (
442
- <Menu align={align} minWidth={minWidth} offset={8} items={items} defaultOpen={defaultOpen} stayOpen={stayOpen} variant={variant}
372
+ <Menu align={align} minWidth={minWidth} offset={8} items={items} defaultOpen={defaultOpen} stayOpen={stayOpen}
443
373
  trigger={({ open, props }) => <MenuTrigger open={open} iconOnly aria-label={label} variant={variant} {...props} />} />
444
374
  )
445
375
  }
376
+
377
+ /** @deprecated 2026-11-29 → Menu (plan-2026-11-29-one-set-fold W3): kolbox's menu is the one Menu, its look the theme's */
378
+ export const MenuKolbox = Menu
379
+ /** @deprecated 2026-11-29 → Menu (plan-2026-11-29-one-set-fold W3): Folio wears the kolbox theme */
380
+ export const MenuFolio = Menu