import { computed, toValue, type MaybeRefOrGetter } from "vue"; import { keyIndexOf, type DisclosureKey } from "../disclosure-group/context"; export interface UseDisclosureGroupNavigationProps { expandedKeys: MaybeRefOrGetter; itemIds: MaybeRefOrGetter; onExpandedChange: (keys: DisclosureKey[]) => void; allowsMultipleExpanded?: boolean; } export interface UseDisclosureGroupNavigationReturn { currentIndex: number; isPrevDisabled: boolean; isNextDisabled: boolean; onPrevious: () => void; onNext: () => void; } const EMPTY_ITEM_IDS: DisclosureKey[] = []; /** * Vue port of HeroUI useDisclosureGroupNavigation. * `expandedKeys` / `onExpandedChange` use arrays instead of Set; * the source collection is never mutated. */ export function useDisclosureGroupNavigation({ allowsMultipleExpanded = false, expandedKeys, itemIds = EMPTY_ITEM_IDS, onExpandedChange, }: UseDisclosureGroupNavigationProps): UseDisclosureGroupNavigationReturn { const currentIndex = computed(() => { const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; const keys = toValue(expandedKeys) ?? []; const expandedItems = ids.filter((id) => keyIndexOf(keys, id) !== -1); const currentItem = expandedItems.length > 0 ? expandedItems[0] : ids[0]; if (currentItem === undefined) return -1; return keyIndexOf(ids, currentItem); }); function handlePrevious() { const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; const keys = toValue(expandedKeys) ?? []; const index = currentIndex.value; if (index <= 0) return; const prevItem = ids[index - 1]; if (prevItem === undefined) return; if (allowsMultipleExpanded) { if (keyIndexOf(keys, prevItem) === -1) { onExpandedChange([...keys, prevItem]); } } else { onExpandedChange([prevItem]); } } function handleNext() { const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; const keys = toValue(expandedKeys) ?? []; const index = currentIndex.value; if (index >= ids.length - 1) return; const nextItem = ids[index + 1]; if (nextItem === undefined) return; if (allowsMultipleExpanded) { if (keyIndexOf(keys, nextItem) === -1) { onExpandedChange([...keys, nextItem]); } } else { onExpandedChange([nextItem]); } } const isPrevDisabled = computed(() => currentIndex.value <= 0); const isNextDisabled = computed(() => { const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; return currentIndex.value >= ids.length - 1; }); return { get currentIndex() { return currentIndex.value; }, get isPrevDisabled() { return isPrevDisabled.value; }, get isNextDisabled() { return isNextDisabled.value; }, onPrevious: handlePrevious, onNext: handleNext, }; }