Skip to content

[Feature]: eventDetails on state-change emits — typed reason + cancel(), v-model pairing investigation #2828

Closed

Description

@zernonia

Part of the v3 roadmap — #2721
Phase 3 — Component contract · pairs with the controlled-state work in #2723

Problem

State-change emits carry a bare value. To know why something closed — Escape vs outside-press vs selection — users listen to scattered granular events (escapeKeyDown, pointerDownOutside, interactOutside, focusOutside) on content parts and call .preventDefault() there. "Close on Escape but not on outside-press", confirm-before-close, and dismissal analytics are all hand-rolled per family.

Drawer already ships the better contract: 'update:open': [value: boolean, details?: DrawerOpenChangeDetails] with a typed reason union ('swipe' | 'escape-key' | 'outside-press' | 'click' | 'cancel' | 'trigger-press' | 'close-press') — packages/core/src/Drawer/DrawerRoot.vue:12-23,52. Every other family emits a bare value.

Prior art: Base UI's every change handler is (value, eventDetails) where eventDetails = { reason, event, cancel(), allowPropagation(), … } with a per-component typed reason union.

Goal

  • A shared ChangeEventDetails shape in shared/types.ts: { reason, originalEvent?, cancel(), allowPropagation()? }, with per-family reason unions (Drawer's becomes the first instance, not a special case).
  • Thread reasons through DismissableLayer / FocusScope / trigger handlers so every update:open (and value emits where it makes sense) carries details.
  • details.cancel() prevents the state change while staying uncontrolled — replacing most @escapeKeyDown.prevent-style usage; decide whether the granular events survive as deprecated escape hatches.
  • Imperative APIs (handles, composables) surface as reason: 'imperative-action'.

Investigation: pairing with Vue v-model

v-model sugar compiles to @update:x="$event => (x = $event)" — it consumes only the first argument, so a second details arg is invisible to v-model users (fine for writes, but the details are only reachable via an explicit extra listener). Before committing, evaluate:

  1. Second emit arg (Drawer's current pattern): zero breakage, v-model keeps working, explicit @update:open="(v, d) => …" opts into details. Does an extra listener alongside v-model fire reliably in all cases (it should — same event)?
  2. Parallel semantic event (@open-change="(v, details) => …" next to update:open): keeps the model emit pristine, closer to Base UI naming, but duplicates every emit.
  3. Details via state, not event: expose lastChangeDetails on the family's useX() composable / root slot props (feat: headless logic composables for every component #2723), so v-model users read the reason reactively without touching listeners.
  4. Controlled-state primitive interplay: the shared controllable-state composable (part of the feat: headless logic composables for every component #2723 foundation) must forward details through its emit path so this lands once, not ~50 times; check defineModel compatibility (its set path has no channel for extra args).

Likely answer is a combination of 1 + 3, but the investigation should settle it with real SFC playground tests before the pattern is propagated.

Why it matters

It's the single highest-value additive API change available (Drawer already proved the ergonomics), it unblocks confirm-before-close and analytics use cases cleanly, and it must be designed before #2723 freezes the composable emit contracts.

Activity

  1. added this to the v3 milestone on Jul 29, 2026
  2. added
    enhancement
    v3
    on Jul 29, 2026
  3. changed the title [-]feat: `eventDetails` on state-change emits — typed reason + `cancel()`, `v-model` pairing investigation[/-] [+][Feature]: `eventDetails` on state-change emits — typed reason + `cancel()`, `v-model` pairing investigation[/+] on Jul 29, 2026
  4. zernonia commented on Sep 4, 2026

    @zernonia
    MemberAuthor

    Proposal for decision

    Drafted against the v3 head so the emit channel can be settled before #2723 freezes more composable signatures. It also covers a case the investigation list above misses: cancel() ordering under v-model. Recommendations are marked; amend freely.

    1. Recommendation

    Adopt option 1 (second emit arg, Drawer's existing shape at Drawer/DrawerRoot.vue:52) for reporting, option 3 (lastChangeDetails on useX() and root slot props) for reading back, and implement both once via option 4: a new shared/useControllableState.ts replacing the per-root useVModel call. For cancellation, use a cancellable pre-change event beforeUpdate:<name> emitted before update:<name>. It is the only mechanic that is correct in uncontrolled, v-model, defineModel-parent and composable modes without a double emit (analysis in §3). The DOM ships this exact pair (beforetoggle cancelable → toggle), and it matches the codebase's .prevent idiom. update:<name> details keep reason/event for analytics; its cancel() is a dev-warn no-op.

    2. Types

    // packages/core/src/shared/types.ts
    export type BaseChangeReason = 'imperative-action' | 'none'
    
    export interface ChangeEventDetails<Reason extends string = string, E extends Event = Event> {
      readonly reason: Reason | BaseChangeReason
      /** Native event that caused the change, if any. */
      readonly event?: E
      /** Prevent the change. Must be called synchronously; only honoured on `beforeUpdate:*`. */
      cancel: () => void
      readonly isCanceled: boolean
    }
    
    // Emits shape per root (Dialog shown; every family follows suit)
    export type DialogRootEmits = {
      'beforeUpdate:open': [value: boolean, details: ChangeEventDetails<DialogOpenChangeReason>]
      'update:open': [value: boolean, details: ChangeEventDetails<DialogOpenChangeReason>]
    }

    Starter reason unions (additive; Drawer's at DrawerRoot.vue:12-19 becomes ChangeEventDetails<DrawerOpenChangeReason>, no rename):

    Family Reasons
    Dialog / AlertDialog trigger-press, close-press, escape-key, outside-press, focus-outside (AlertDialog never emits outside-press)
    Popover same as Dialog
    Menu family (Dropdown/Context/Menubar/Sub) trigger-press, trigger-hover, item-press, list-navigation, sibling-open, escape-key, outside-press, focus-outside
    Select / Combobox open trigger-press, input-change, list-navigation, item-press, escape-key, outside-press, focus-outside
    Select / Combobox modelValue item-press, list-navigation, clear-press, input-clear
    Tooltip trigger-hover, trigger-focus, trigger-press, escape-key, outside-press, sibling-open
    HoverCard trigger-hover, trigger-focus, escape-key, outside-press, focus-outside
    Drawer (first instance) existing union unchanged
    Toast timeout, swipe, close-press, escape-key

    'imperative-action' is appended everywhere: slot-prop close() (Dialog/DialogRoot.vue:104), context onOpenChange called without a reason, and useX().setOpen(). 'none' is never emitted; it is the initial lastChangeDetails.reason. Parent prop writes (:open changing) emit nothing, as today.

    3. Ordering analysis and the chosen mechanic

    <DialogRoot v-model:open="open" @update:open="(v, d) => cond && d.cancel()"> compiles (compiler-core buildProps → dedupeProperties, which merges duplicate on* keys into an array in source order) to:

    _createVNode(DialogRoot, {
      open: _ctx.open,
      "onUpdate:open": [
        $event => (_ctx.open = $event),   // v-model writer, consumes arg 1 only
        (v, d) => cond && d.cancel(),     // explicit listener
      ],
    })

    At runtime emit() calls an array handler in order, synchronously; mergeProps (used by v-bind="forwarded" in AlertDialog/AlertDialogRoot.vue) also concatenates existing before incoming. So the writer runs first if v-model is written first, the listener first otherwise, but the writer is unconditional. Whichever order, _ctx.open is already false when emit() returns. With useVModel({ passive: false }) (Dialog/DialogRoot.vue:71-74) the emit is the computed setter, so this all happens inside the component's own open.value = false. A flag checked after emit() cannot stop the parent write; the component sees props.open flip on the next pre-flush regardless.

    Mechanics rejected: a revert re-emit works but fires every update:open listener twice, delivers a bogus (true, …) to analytics and composable onUpdate, and is visible to flush: 'sync' watchers. Documenting cancel() as uncontrolled-only makes it a silent no-op in the mode the docs recommend (guides/controlled-state.md).

    The pre-event mechanic, step by step, inside setState(value, reason, event):

    1. Bail if value === state.value.
    2. Build one details object; emit('beforeUpdate:open', value, details), synchronous.
    3. If details.isCanceled: record it in lastChangeDetails, return false. Nothing else runs.
    4. Else write the uncontrolled ref (only when props.open === undefined), emit('update:open', value, details), set lastChangeDetails, return true.
    • Uncontrolled: step 3 leaves the internal ref untouched; no paint.
    • v-model parent: the writer lives on update:open, which is never emitted on cancel; parent ref untouched, no re-render.
    • defineModel parent: the parent's v-model:open="model" compiles to the identical writer; its own update:open to its grandparent is never triggered. Note defineModel cannot be used inside reka roots: useModel's setter emits with one argument, so details would be dropped. Reka is on useVModel/own state, so this only constrains us from ever switching, and it argues for owning the composable (§5).
    • Composable channel: useDialog({ open?: Ref, onBeforeUpdate?, onUpdate? }); with a caller-owned ref, a cancelled request simply never writes it.

    Fixed for free: today's uncontrolled emits are asynchronous (vueuse passive path emits from a watcher), while Drawer's manual path is sync (DrawerRoot.vue:117-122). The shared composable makes both sync.

    4. Granular events

    Keep them, unchanged, as the low-level layer. DismissableLayer.vue already gates dismiss on event.defaultPrevented, so .prevent keeps working. One additive change: dismiss: [] becomes dismiss: [details: { reason: 'escape-key' | 'outside-press' | 'focus-outside', event }], and content parts forward it (Dialog, Popover, Menu, Select, Combobox ContentImpl). That deletes the pendingDismissReason capture hack at Drawer/DrawerContentImpl.vue:219-225. No deprecation; document beforeUpdate:* as the recommended entry point and the granular events as the escape hatch.

    5. Where it lands once

    New packages/core/src/shared/useControllableState.ts, exported from shared/index.ts:

    export function useControllableState<T, R extends string>(options: {
      prop: () => T | undefined
      defaultValue: T
      emit: (name: any, ...args: any[]) => void
      name: string // 'open' → 'beforeUpdate:open' / 'update:open'
      onBeforeUpdate?: (value: T, details: ChangeEventDetails<R>) => void // composable channel
      onUpdate?: (value: T, details: ChangeEventDetails<R>) => void
      isEqual?: (a: T, b: T) => boolean
    }): {
      state: Readonly<Ref<T>>
      setState: (value: T, reason?: R | 'imperative-action', event?: Event) => boolean
      lastChangeDetails: Readonly<Ref<ChangeEventDetails<R>>>
    }

    Roots swap useVModel(props, 'open', emit, { passive }) (Dialog, Popover, Menu, Tooltip, HoverCard, Select, Combobox, Toast roots) for one call; useSingleOrMultipleValue.ts:47-51 wraps it so Accordion/ToggleGroup/Listbox inherit it; useEmitAsProps.ts:33 already spreads all args, so AlertDialog forwarding needs no change. Contexts gain a reason parameter (onOpenChange(value, reason?, event?)), the pattern DrawerRoot.vue:71 already uses.

    The #2723 composables must change: useSwitch.ts:45,52 and useTabs.ts:138,146-148 write straight into the passed ref with no emit channel, and the recipe pins useVModel in the shell. Amend the recipe so the composable owns useControllableState and takes onBeforeUpdate/onUpdate options; useMenuRoot's onOpenChange (Menu/useMenu.ts:74-79) is the first to gain a reason.

    6. Decision checklist

    Decision Recommended
    Details as second arg on update:* (Drawer's shape), not a parallel @open-change Yes
    Cancellation via a beforeUpdate:<name> pre-event; cancel() on update:* is a no-op Yes
    dismiss on DismissableLayer carries { reason, event } Yes
    Deprecate escapeKeyDown / pointerDownOutside / interactOutside / focusOutside No
    Introduce shared/useControllableState and migrate roots off useVModel (sync emit in uncontrolled mode) Yes
    Ship allowPropagation() (Base UI nested-popup semantics) in this pass No; the stack manager already routes Escape to the top layer only

    Unverified

    • Compiled output shape and source-order merging in compiler-core's dedupeProperties; no Vue compiler available to run here.
    • useModel (defineModel) emitting a single argument.
    • That @before-update:open compiles to onBeforeUpdate:open and is not misclassified by isModelListener (prefix is onUpdate:, so it should not be).
    • Whether any consumer relies on the current asynchronous uncontrolled emit timing.

    Generated by Claude Code

  5. zernonia commented on Sep 4, 2026

    @zernonia
    MemberAuthor

    Decisions

    The proposal above is accepted as written. For the record:

    1. Details as the second argument on update:*, Drawer's existing shape; no parallel @open-change event: yes.
    2. Cancellation via a cancellable beforeUpdate:<name> pre-event; on cancel, update:* never fires, so the v-model writer never runs. cancel() on the update:* details is a dev-warn no-op: yes.
    3. dismiss on DismissableLayer carries { reason, event }, forwarded by the content parts; Drawer's pendingDismissReason capture goes away: yes.
    4. escapeKeyDown / pointerDownOutside / interactOutside / focusOutside stay, undeprecated, as the low-level layer: yes.
    5. New shared/useControllableState; every root migrates off vueuse useVModel. Accepted side effect: uncontrolled update:* emits become synchronous, matching Drawer today: yes.
    6. allowPropagation(): no, not in this pass; the layer stack already routes Escape to the top layer only.

    Sequencing: useControllableState plus the ChangeEventDetails type is the first PR. The #2723 recipe is amended in the same PR so composables take onBeforeUpdate / onUpdate options and own the controllable state. Per-family reason unions and the dismiss details follow family by family, Dialog and Popover first.


    Generated by Claude Code

  6. zernonia commented on Oct 28, 2026

    @zernonia
    MemberAuthor

    Done on v3 in #2910 → #3086.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementv3

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions