diff --git a/src/components/forms/auto-complete/RuiAutoComplete.vue b/src/components/forms/auto-complete/RuiAutoComplete.vue index 75931a8..32a4c1d 100644 --- a/src/components/forms/auto-complete/RuiAutoComplete.vue +++ b/src/components/forms/auto-complete/RuiAutoComplete.vue @@ -95,6 +95,16 @@ const slots = useSlots(); const { dense, variant, disabled, options } = toRefs(props); +const { + getText, + getIdentifier, +} = useDropdownOptionProperty( + { + keyAttr: props.keyAttr, + textAttr: props.textAttr, + }, +); + const textInput = ref(); const activator = ref(); const noDataContainer = ref(); @@ -237,8 +247,6 @@ const { renderedData, isOpen, menuWidth, - getText, - getIdentifier, isActiveItem, itemIndexInValue, highlightedIndex, diff --git a/src/composables/dropdown-menu.ts b/src/composables/dropdown-menu.ts index f668011..8f8b222 100644 --- a/src/composables/dropdown-menu.ts +++ b/src/composables/dropdown-menu.ts @@ -1,12 +1,15 @@ import type { Ref } from 'vue'; -export interface DropdownOptions { +export interface DropdownItemAttr { + keyAttr?: K; + textAttr?: K | ((item: T) => string); +} + +export interface DropdownOptions extends DropdownItemAttr { options: Ref; dense?: Ref; value: Ref; menuRef: Ref; - keyAttr?: K; - textAttr?: K | ((item: T) => string); appendWidth?: number; prependWidth?: number; itemHeight?: number; @@ -17,6 +20,35 @@ export interface DropdownOptions { hideSelected?: boolean; } +export function useDropdownOptionProperty({ + keyAttr, + textAttr, +}: DropdownItemAttr) { + function getText(item: T): T[K] | T | string { + if (textAttr) { + if (typeof textAttr === 'function') + return textAttr(item); + + else + return item[textAttr]; + } + + return item; + } + + function getIdentifier(item: T): T[K] | T { + if (keyAttr) + return item[keyAttr]; + + return item; + } + + return { + getIdentifier, + getText, + }; +}; + export function useDropdownMenu({ appendWidth, autoFocus, @@ -41,6 +73,11 @@ export function useDropdownMenu({ return options.filter(item => !isActiveItem(item)); }); + const { getIdentifier, getText } = useDropdownOptionProperty({ + keyAttr, + textAttr, + }); + const { containerProps, list, scrollTo, wrapperProps } = useVirtualList( options, { @@ -99,25 +136,6 @@ export function useDropdownMenu({ set(isOpen, state); } - function getText(item: T): T[K] | T | string { - if (textAttr) { - if (typeof textAttr === 'function') - return textAttr(item); - - else - return item[textAttr]; - } - - return item; - } - - function getIdentifier(item: T): T[K] | T { - if (keyAttr) - return item[keyAttr]; - - return item; - } - function itemIndexInValue(item: T): number { const val = get(value); const selected: T[] = Array.isArray(val) ? val : (val ? [val] : []);