import { computed, type ComputedRef, type Ref } from "vue"; import type { MenuKey, MenuSelectionMode, MenuSelectionOwner, } from "../menu/context"; export interface UseMenuSelectionOptions { selectionMode: Ref | ComputedRef; selectedKeys: Ref> | ComputedRef>; disabledKeys?: Ref> | ComputedRef>; /** Accepted-value update. Return the accepted keys (may reject the proposal). */ onSelectionChange: (keys: MenuKey[]) => void; } /** * Menu/section selection owner. Proposals are one-shot toggles; the parent * emits the next keys and keeps ownership of the accepted value. */ export function useMenuSelection( options: UseMenuSelectionOptions, ): MenuSelectionOwner { const isItemSelected = (key: MenuKey) => options.selectedKeys.value.some((k) => k === key); const isItemDisabled = (key: MenuKey) => options.disabledKeys?.value.some((k) => k === key) ?? false; const proposeSelection = (key: MenuKey) => { const mode = options.selectionMode.value; if (mode === "none") return; const current = options.selectedKeys.value; const has = isItemSelected(key); if (mode === "single") { options.onSelectionChange(has ? [] : [key]); return; } options.onSelectionChange( has ? current.filter((k) => k !== key) : [...current, key], ); }; return { selectionMode: computed(() => options.selectionMode.value), selectedKeys: computed(() => options.selectedKeys.value), proposeSelection, isItemSelected, isItemDisabled, }; }