Skip to content

Commit ec355c9

Browse files
zernoniaclaude
andauthored
feat(Menu): headless composables for the Menu overlay family (#2723) (#2796)
* feat(Menu): headless composables for the Menu overlay family Converts the core Menu parts to compose a useMenu.ts module, validating the overlay archetype for #2723 (after Switch + Tabs). Public API unchanged. - useMenuRoot() — state-only overlay root: returns { open, onOpenChange, onClose } + the MenuContext/MenuRootContext objects the SFC provides. No PartSurface (the root renders no attrs). MenuRoot.vue composes it. - getMenuItemBaseSurface() — the attr-bearing item render surface (role/aria/highlight handlers). A context-SCOPED factory (creates per-instance isFocused, needs the item element) — the Tabs pure-builder axiom does not hold for overlays. MenuItemImpl.vue. - getMenuItemSelectSurface() — the close-on-select protocol via an onSelect callback channel (the CustomEvent token, never a merged DOM listener). MenuItem.vue. - useMenuContent() — the overlay brain: typeahead, arrow-nav, the pointer-grace machine, highlightedElement ownership. Returns the role=menu surface + the content context; the four component wrappers and the two mount side-effects stay in the SFC. Cuts MenuContentImpl.vue from 405 to 191 lines; the only un-extractable seam is RovingFocusGroup.getItems() (a template-instance ref), injected as a getItems option. Surfaces bind via mergeProps so consumer listeners chain; functional data-* selectors (data-reka-menu-content) live in props, not stateToDataAttrs. useFocusGuards stays scoped to the content root (#2794). Menu + DropdownMenu + ContextMenu + Menubar 56/56 green; full suite 2075 green; type-check clean; 19 useMenu unit tests. Refs #2723 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(Menu): overlay-family findings + recipe overlay section Refs #2723 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 82172de commit ec355c9

8 files changed

Lines changed: 1060 additions & 386 deletions

File tree

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Headless composables for an OVERLAY family (Menu) — #2723
2+
3+
> **Status: overlay archetype validated + core Menu parts converted** (parity-gated,
4+
> 51 consumer tests green). Began as a spike; graduated to a real conversion. This
5+
> establishes the overlay contract that the deferred overlay work (**joint with
6+
> #2724**) should build on. Scope: `MenuRoot`/`MenuItem`/`MenuItemImpl`/
7+
> `MenuContentImpl`; `MenuSubTrigger`/`Checkbox`/`Radio`/`Sub` reuse the same builders
8+
> as follow-ups (see "Scope NOT covered").
9+
10+
## TL;DR
11+
12+
The pattern extends — but overlays **bend two axioms** from the Switch/Tabs recipe,
13+
and the recipe's stated reason for deferring overlays ("overlay logic lives in
14+
Content-part wrappers") is **wrong by half**. The wrappers are a thin shell; the
15+
overlay *brain* (typeahead, arrow-nav, the pointer-grace machine, highlight
16+
ownership) is plain state+handlers and extracts cleanly — **now demonstrated, not
17+
just argued**: `useMenuContent()` pulls ~215 lines out of `MenuContentImpl.vue`
18+
(**405 → 191 lines**), leaving the SFC as the four wrappers + positioning props.
19+
The single thing that couldn't move is `RovingFocusGroup.getItems()` (a template-
20+
instance ref), injected as one `getItems` option. That reframe is the most useful
21+
input to #2724.
22+
23+
## What was built
24+
25+
In `packages/core/src/Menu/useMenu.ts`:
26+
27+
1. **`useMenuRoot()`** — the state-only overlay root. Renders no attrs, so **no
28+
`PartSurface`**; returns `{ open, onOpenChange, onClose, menuContext, menuRootContext }`
29+
— the two context objects the SFC provides verbatim. `MenuRoot.vue` now composes it.
30+
2. **`getMenuItemBaseSurface(contentContext, { disabled, currentElement })`** — the
31+
attr-bearing item render surface (role/tabindex/aria-disabled + the
32+
pointermove/leave/focus/blur hover-highlight). `MenuItemImpl.vue` composes it.
33+
3. **`getMenuItemSelectSurface(rootContext, { disabled, currentElement, onSelect, searchRef })`**
34+
— the select protocol (click/pointerdown/pointerup/keydown + close-on-select).
35+
`MenuItem.vue` composes it.
36+
4. **`useMenuContent(options)`** — the overlay **brain**: typeahead, arrow-nav
37+
(`handleKeyDown`/`onKeydownNavigation`), the pointer-grace/direction machine, and
38+
`highlightedElement` ownership. Returns the `role=menu` `PartSurface` + the
39+
`MenuContentContext` value. `MenuContentImpl.vue` composes it, keeping the four
40+
wrappers + the two mount side-effects. **Extracted ~215 lines (405 → 191).**
41+
42+
**Verification:** `Menu` + `DropdownMenu` + `ContextMenu` + `Menubar` suites (the
43+
compatibility oracle for these SFCs) **51/51 green**; full suite **2042 green**;
44+
`type-check` clean; **19** POC unit tests across the four shapes.
45+
46+
## Findings — the questions overlays force
47+
48+
### 1. Overlay-root contract: `{ state, context }`, no surface
49+
`useMenuRoot()` returns state + the context objects, no `PartSurface`. **The family
50+
is not surface-free — only the root is.** `DropdownMenuTrigger`/`Content` have real
51+
surfaces; the surfaces just begin one level below the root. Recipe addition (one line):
52+
53+
> *Overlay roots are state-only (`{ state, context }`, no surface); positioning
54+
> (`PopperRoot`) and portal stay wrappers, so a standalone overlay `useX()` yields
55+
> the state machine and the trigger/item surfaces but not placement.*
56+
57+
The two-context shape (`MenuContext` keyed `['MenuRoot','MenuSub']` + `MenuRootContext`)
58+
is reused by `MenuSub` — a future `useMenuSub()` returns a `MenuContext`-shaped
59+
object, so the contract is symmetric.
60+
61+
### 2. HEADLINE: the item builder is a context-SCOPED FACTORY, not a pure builder
62+
Tabs' per-item builders are **pure, idempotent derivations** of `(context, value)` —
63+
safe to call many times. `getMenuItemBaseSurface` **cannot** be: it creates
64+
per-instance state (`isFocused`) and closes over the item's own `currentElement`
65+
(the highlight identity check + pointer handlers compare against it). So it must be
66+
called **exactly once per item instance**, and callers pass an element ref they
67+
populate after mount.
68+
69+
> **The "context-pure builder" axiom does not survive contact with overlays.**
70+
> Overlay item builders are *context-scoped factories*: `state`/`props` computeds
71+
> stay pure derivations, but the factory itself instantiates state. If both the
72+
> standalone `useMenu().getItemSurface` path and the SFC inject-and-call path
73+
> instantiated it, you'd get two divergent `isFocused` states — so memoize one
74+
> factory call per instance.
75+
76+
### 3. The select protocol moves — as a callback channel
77+
`MenuItem`'s close-on-select is **not** a DOM dispatch — it builds
78+
`new CustomEvent(ITEM_SELECT, { cancelable: true })` as a cancelable **token**, emits
79+
it, `await nextTick()`, and closes unless `defaultPrevented`. That whole flow lives
80+
in the composable behind an **`onSelect: (event) => void`** option; the SFC passes
81+
`e => emits('select', e)`. `onSelect` stays a callback — it is never a merged DOM
82+
listener. The async `defaultPrevented`-after-`nextTick` veto survives `mergeProps`
83+
binding as long as surface handlers come first in the merge.
84+
85+
### 4. base + variant layering (so SubTrigger can reuse)
86+
The SFC split (`MenuItemImpl` = render/highlight; `MenuItem` = select) maps to two
87+
builders. **Base** (`getMenuItemBaseSurface`) is what every item variant renders
88+
through, so `MenuSubTrigger`/`MenuCheckboxItem`/`MenuRadioItem` can reuse it and add
89+
their own layer. Not layering the base would strand SubTrigger.
90+
91+
### 5. What CANNOT move (stays wrapper/SFC)
92+
- **`CollectionItem` registration** — vnode-bound provide/inject; the `<CollectionItem>`
93+
wrapper stays in the SFC. The composable documents it as a required host.
94+
- **`RovingFocusGroup.getItems()`** — a template-instance-ref call (typeahead
95+
candidates); a standalone `useMenuContent()` must **accept an injected `getItems`**.
96+
- **The pointer-grace machine** — CAN move, but only into a **content** composable,
97+
never the item's. Items already consume it purely via the `onItemEnter`/`onItemLeave`/
98+
`onTriggerLeave` closure trio on `MenuContentContext` — that trio IS the contract,
99+
keep it verbatim. It's pinned near the DOM only by lazy `getBoundingClientRect()`/
100+
`dataset.side` reads (SSR-safe as-is).
101+
- **`highlightedElement` is an `HTMLElement`** — the stale-leave guard, `isHighlighted`,
102+
and arrow-nav all depend on **element identity**. Do NOT normalize it to an id/index
103+
in a refactor — that's a behavior rewrite.
104+
- **Mount-lifecycle composables** (`useBodyScrollLock`, `useFocusGuards`,
105+
`useIsUsingKeyboard`) — must run inside the mounted content/root, so an overlay
106+
`useX()` is **not callable outside `setup()`** (unlike Switch/Tabs). Expected for
107+
overlays; test in a mount harness.
108+
109+
### 6. Two recipe amendments overlays require
110+
- **Functional `data-*` selectors are exempt from the no-`data-*` rule.**
111+
`data-reka-menu-content` (submenu-scoping `closest()` check), `data-reka-collection-item`,
112+
and `[data-disabled]` (read by `useArrowNavigation`'s selector) are *functional
113+
selectors*, not semantic state — they belong in `props`, not routed through
114+
`stateToDataAttrs`. Silently dropping one degrades UX with no test failure.
115+
- **Overlay item builders are context-scoped factories** (finding #2) — the recipe's
116+
"pure builder" wording needs the factory caveat for overlays.
117+
118+
## The reframe for #2724 (most valuable output) — now PROVEN
119+
120+
The deferral said "overlay logic lives in Content-part component wrappers." Reality
121+
for Menu: `MenuContentImpl` composes **4** wrappers (FocusScope/DismissableLayer/
122+
RovingFocusGroup/PopperContent), but the **majority** of its logic — typeahead,
123+
`onKeydownNavigation`, `handleKeyDown`, `handleBlur`, the pointer-direction tracker,
124+
the grace machine (`isPointerMovingToSubmenu`, `pointerGraceIntentRef`,
125+
`pointerDirRef`, `lastPointerXRef`), and `highlightedElement` ownership — is
126+
**wrapper-independent**. `useMenuContent()` extracts it: it returns the `role=menu`
127+
surface and the `MenuContentContext` value, and **`MenuContentImpl.vue` drops from
128+
405 to 191 lines** — the residue is the 4 wrappers, the positioning props, and the
129+
two mount side-effects (`useFocusGuards`/`useBodyScrollLock`).
130+
131+
**The wrappers are the shell; the overlay brain is the composable.** The only piece
132+
that resisted extraction is `RovingFocusGroup.getItems()` (a template-instance ref
133+
for typeahead candidates), injected as a single `getItems` option — a clean,
134+
named seam. That is exactly the boundary #2724 should build the overlay contract on.
135+
136+
## Scope NOT covered (recommended next depth)
137+
- Reuse `getMenuItemBaseSurface` in **`MenuSubTrigger`/`MenuCheckboxItem`/`MenuRadioItem`**
138+
(proves the base+variant layering end-to-end; SubTrigger adds the open-timer +
139+
grace-polygon layer).
140+
- **`useMenuSub()`** — the `MenuContext` symmetry (`MenuSub` re-provides a
141+
`MenuContext`-shaped object).
142+
- Fold `useFocusGuards`/`useBodyScrollLock` into `useMenuContent` behind a flag, so a
143+
standalone consumer opts into the mount side-effects (kept in the SFC here so the
144+
brain stays side-effect-free).
145+
- `PartSurface` is imported from `@/shared` (relocated there by #2795).
146+
147+
## Bottom line
148+
`useX()` works for overlays. It costs two axiom amendments (state-only root;
149+
context-scoped factories) and one exemption (functional `data-*`). The real prize
150+
isn't the item surface — it's that the overlay brain in the Content part extracts,
151+
and this POC **proves it**: `useMenuContent()` takes 405→191 lines out of the SFC
152+
with one named seam (`getItems`), all 51 consumer tests still green. That is the
153+
concrete evidence #2724 needs before it rewrites overlay internals — the overlay
154+
contract can be "state-only root + brain composable + wrappers stay wrappers."

‎docs/superpowers/recipes/2723-headless-composable-recipe.md‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,21 +103,56 @@ computed from `(context, itemValue)`. What converting Tabs settled:
103103
to a literal so it stays callable outside `setup()` (Tabs is computed-only — no
104104
watchers/lifecycle in the composable). Never call `useId` inside the composable.
105105

106+
## Overlay families (validated on Menu)
107+
108+
Overlays (Menu/DropdownMenu, Dialog, Popover, Select, Combobox) differ again: the
109+
ROOT renders no attrs, and the behavior lives in a Content part wrapped by component
110+
families (FocusScope/DismissableLayer/Presence/Popper/RovingFocus). Converting the
111+
core Menu parts settled the overlay contract:
112+
113+
- **The root is state-only: `{ state, context }`, no `PartSurface`.** `useMenuRoot()`
114+
returns `open`/`onOpenChange`/`onClose` + the context object(s) the SFC provides.
115+
The family is not surface-free — surfaces begin at Trigger/Content. Positioning
116+
(`PopperRoot`) and portal stay wrappers.
117+
- **Per-item overlay builders are context-SCOPED FACTORIES, not pure builders.**
118+
Unlike Tabs' idempotent `(context, value)` derivations, `getMenuItemBaseSurface`
119+
creates per-instance state (`isFocused`) and closes over the item's `currentElement`
120+
— call it EXACTLY ONCE per instance. `state`/`props` computeds stay pure; the
121+
factory instantiates. **This is the Tabs axiom that does NOT survive overlays.**
122+
- **Functional `data-*` selectors are exempt from the no-`data-*` rule.**
123+
`data-reka-menu-content` (submenu `closest()` scoping), `data-reka-collection-item`,
124+
and `[data-disabled]` (read by `useArrowNavigation`) are selectors, not semantic
125+
state — put them in `props`, not through `stateToDataAttrs`. Dropping one degrades
126+
UX with no test failure.
127+
- **Close-on-select is a callback channel, not a merged listener.** The item's
128+
`CustomEvent(ITEM_SELECT, { cancelable })` is a token: emit it, `await nextTick()`,
129+
close unless `defaultPrevented`. Expose it as an `onSelect(event)` option; the SFC
130+
passes `e => emits('select', e)`. Never bind it as a DOM listener.
131+
- **The Content "brain" extracts; the wrappers are the shell.** Typeahead, arrow-nav,
132+
the pointer-grace machine, and `highlightedElement` ownership are wrapper-independent
133+
— `useMenuContent()` took `MenuContentImpl` from 405→191 lines, returning the
134+
`role=menu` surface + the content context; FocusScope/DismissableLayer/
135+
RovingFocusGroup/PopperContent + `useFocusGuards`/`useBodyScrollLock` stay in the
136+
SFC. The one seam that can't move is `RovingFocusGroup.getItems()` (a template-
137+
instance ref) — inject it as a `getItems` option.
138+
- **Overlay composables are mount-lifecycle-bound** (`useIsUsingKeyboard`, the content
139+
watchers/`onUnmounted`) — NOT callable outside `setup()`; test in a mount harness.
140+
106141
## Dependency- and structure-ordered migration (not size)
107142

108-
- **Overlays are deferred.** Dialog/Popover/Tooltip/HoverCard/DropdownMenu/Select/
109-
Combobox render **no root attrs** (`PopoverRoot` is `<PopperRoot><slot/></PopperRoot>`);
110-
their logic lives in Content-part component wrappers. Define the overlay contract
111-
**jointly with #2724** (which rewrites overlay internals) — converting them here
112-
first is double churn.
143+
- **Overlays: contract validated on Menu (see above).** The remaining overlays
144+
(Dialog/Popover/Tooltip/HoverCard/Select/Combobox) render **no root attrs**
145+
(`PopoverRoot` is `<PopperRoot><slot/></PopperRoot>`) and share Menu's shape. Convert
146+
them **jointly with #2724** (which rewrites overlay internals) so the state-only-root
147+
+ brain-composable + wrappers-stay-wrappers contract lands once, not twice.
113148
- **Convert dependencies first.** Families that snapshot a child's `exposed`
114149
(`ComboboxRoot` reads `ListboxRoot`'s exposed methods) require the dependency
115150
converted first: **Listbox → Combobox → Select**.
116151
- **Tiers:** (1) form/toggle: Checkbox, RadioGroup, ToggleGroup, Toggle; (2)
117152
collection/disclosure: Tabs ✓(gate), Accordion, Collapsible; (3) delegation
118-
chains: Listbox → Combobox → Select; (4) overlays — deferred (joint with #2724);
119-
(5) date/calendar family last (heavy generics; `useDateField` is already
120-
composable-shaped — the house prior art for this whole effort).
153+
chains: Listbox → Combobox → Select; (4) overlays — Menu ✓(contract), rest joint
154+
with #2724; (5) date/calendar family last (heavy generics; `useDateField` is
155+
already composable-shaped — the house prior art for this whole effort).
121156

122157
## Footguns
123158

0 commit comments

Comments
 (0)