import { type AnyObject, type AnyValue, type ModelValue, type Size, } from '@squirrel/components/p-select-list/p-select-list.types'; import { createInternalItems, createInternalValue } from '@squirrel/components/p-select-list/p-select-list.utils'; import { type ListKeyboardNavigationInstance, setupListKeyboardNavigation, } from '@squirrel/utils/listKeyboardNavigation'; import { toString } from '@squirrel/utils/string'; import { useVirtualizer } from '@tanstack/vue-virtual'; import { cloneDeep, difference, intersection, uniqBy } from 'lodash-es'; import { type ComponentPublicInstance, computed, nextTick, onUnmounted, type Ref, ref, watch } from 'vue'; type Emits = { (e: 'update:modelValue', modelValue: ModelValue): void; (e: 'select', value: AnyValue): void; }; type Props = { modelValue: ModelValue; valueIsObject: boolean; items: AnyValue[] | AnyObject[]; size: Size; itemText: string; itemValue: string | number; itemSize: number; itemsVisible: number; searchable: boolean; multiple: boolean; selectedTopShown: boolean; disabledBy: string; }; type InputSearch = Ref; type VirtualizerRef = Ref; // Async helpers const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const nextLoop = (ms?: number) => new Promise((resolve) => setTimeout(resolve, ms || 0)); // Constants const LIST_ITEM_SIZES = { sm: 32, md: 40, lg: 48 }; const LIST_ITEM_CLASS = 'clear-both block w-full whitespace-nowrap py-1 px-3 text-left text-sm font-medium hover:bg-p-blue-10'; const LIST_ITEM_ACTIVE_CLASS = 'selected'; const LIST_ITEM_DISABLED_CLASS = 'opacity-30 cursor-default'; export const useSelectList = (props: Props, inputSearch: InputSearch, virtualizerRef: VirtualizerRef, emit: Emits) => { // Data let navigationSvc: ListKeyboardNavigationInstance | null = null; const internalItems = ref([]); // Instead of having two modes one for multiple and one for single select, // we always operate in "multiple" mode by using an internal array value instead of this.value const internalValue = ref([]); const search = ref(''); // Computed const selectedItems = computed(() => { return internalItems.value.filter((item) => internalValue.value.includes(item[props.itemValue])); }); const deselectedItems = computed(() => { return internalItems.value.filter((item) => !internalValue.value.includes(item[props.itemValue])); }); const computedItems = computed(() => { return cloneDeep(internalItems.value).filter((item) => { return String(item[props.itemText]).toLocaleLowerCase().includes(String(search.value).toLocaleLowerCase()); }); }); const computedItemSize = computed(() => (props.itemSize ? props.itemSize : LIST_ITEM_SIZES[props.size])); // Whether all filtered (i.e. currently visible) items are selected const computedInsideSelected = computed(() => { const filteredItems = computedItems.value.map((item) => item[props.itemValue]); return filteredItems.every((item) => internalValue.value.includes(item)); }); // Virtualizer const rowVirtualizer = useVirtualizer( computed(() => { return { count: computedItems.value.length, getScrollElement: () => virtualizerRef.value, getItemKey: (index: number) => toString(computedItems.value[index][props.itemValue]), estimateSize: () => { return props.itemSize ? props.itemSize : LIST_ITEM_SIZES[props.size]; }, overscan: 10, }; }) ); const getValue = (index: number) => computedItems.value[index]?.[props.itemValue]; const getText = (index: number) => computedItems.value[index]?.[props.itemText]; // Watch // Makes sure internalValue is always an Array watch( () => props.modelValue, (nV) => { internalValue.value = createInternalValue( nV, props.valueIsObject, props.multiple, props.itemValue, internalItems.value ); }, { immediate: true, deep: true, } ); watch(search, async (nV) => { await scrollScrollerToTop(); await nextFrame(); if (!navigationSvc) { return; } const firstItem = navigationSvc.getItems().filter((item) => item.style.transform.includes('translateY(0px)'))[0]; if (nV) { navigationSvc.setFocusedItem(firstItem); } else { if (props.multiple) { navigationSvc.setFocusedItem(firstItem); } else { getActiveItemIndex() > -1 ? scrollToActiveItem() : navigationSvc.clearFocusedState(); } } }); // Lifecycle onUnmounted(() => { navigationSvc?.destroy(); navigationSvc = null; }); // Methods // Sorts internalItems putting the selected ones first const putSelectedItemsOnTop = () => { if (props.selectedTopShown) { // Split between selected and not selected, so that we can sort the selected ones const arr = internalItems.value.reduce( (acc: [AnyObject[], AnyObject[]], curr: AnyObject) => { internalValue.value.includes(curr[props.itemValue] as string | number) ? acc[0].push(curr) : acc[1].push(curr); return acc; }, [[], []] ); internalItems.value = arr[0] .sort((a, b) => String(a[props.itemText]).localeCompare(String(b[props.itemText]), undefined, { numeric: true, sensitivity: 'base', }) ) .concat(arr[1]) as AnyObject[]; } }; const select = async (e: Event, val: AnyValue) => { const el = e.currentTarget as HTMLElement; // Set focus back to the input search on select if ( props.multiple && props.searchable && document.activeElement !== inputSearch.value?.$el.querySelector('input') ) { inputSearch.value?.$el.querySelector('input').focus(); } // Convert the value to the correct format (in case `valueIsObject` is enabled) and emit if (props.multiple) { if (!isSelected(val)) { emit('update:modelValue', toArrOfObjIfNeeded([...internalValue.value, val])); } else { emit('update:modelValue', toArrOfObjIfNeeded(internalValue.value.filter((item) => item !== val))); } } else { emit('update:modelValue', props.valueIsObject ? getItemByValue(val) : val); } await nextTick(); navigationSvc?.setFocusedItem(el.parentElement as HTMLElement); emit('select', val); }; const toArrOfObjIfNeeded = (arr: AnyValue[]) => { return props.valueIsObject ? arr.map((val) => getItemByValue(val)) : arr; }; const getItemByValue = (value: AnyValue) => { return internalItems.value.find((item) => item[props.itemValue] === value); }; const isSelected = (val: AnyValue) => { return internalValue.value.includes(val); }; const isDisabled = (val: AnyValue) => { const disabledProp = props.disabledBy; if (val && typeof val === 'object' && disabledProp in val) { return val[disabledProp]; } return false; }; const setupNavigationSvc = () => { if (navigationSvc) { navigationSvc.init(); } else { navigationSvc = setupListKeyboardNavigation({ itemContainer: virtualizerRef.value as HTMLElement, itemSelector: '[p-select-list-option]', itemSelectSelector: `[p-select-list-option-item]`, itemFocusClass: 'bg-p-blue-10', }); } }; const destroyNavigationSvc = () => { navigationSvc?.destroy(); navigationSvc = null; }; const onFocus = async () => { setupNavigationSvc(); }; const onMousemove = () => { navigationSvc?.clearFocusedState(); }; const scrollScrollerToTop = async () => { rowVirtualizer.value.scrollToOffset(0); await nextFrame(); }; const scrollToActiveItem = async (options?: { wait: number }) => { if (options?.wait) { await nextLoop(options.wait); } // Scroll and set focus to the selected item on open so that keyboard navigation works correctly const activeIndex = getActiveItemIndex(); if (virtualizerRef.value && rowVirtualizer.value && activeIndex > -1) { // Scroll item to the center of the scroller div rowVirtualizer.value.scrollToIndex(activeIndex, { align: 'center', }); await nextLoop(); await nextFrame(); // After the item has become visible we can apply the active and focus classes const activeEl = virtualizerRef.value?.querySelector(`.${LIST_ITEM_ACTIVE_CLASS}`); navigationSvc?.setFocusedItem(activeEl?.parentNode as HTMLElement); } }; const getActiveItemIndex = () => { return internalItems.value.indexOf(selectedItems.value[0]); }; const selectAll = () => { if (!props.multiple) return; const selectedItems = internalValue.value; const deselectedDisabledItemsValues = deselectedItems.value .filter((item) => isDisabled(item)) .map((item) => item[props.itemValue]); const filteredItems = computedItems.value.map((item) => item[props.itemValue]); const uniqueItems = uniqBy([...selectedItems, ...filteredItems], (item) => item); // We cannot select disabled items so we remove them from the list const toEmit = difference(uniqueItems, deselectedDisabledItemsValues); emit('update:modelValue', toArrOfObjIfNeeded(toEmit)); }; const clearAll = () => { search.value = ''; // We cannot clear disabled items that are selected if (props.multiple) { const disabledItemsValues = internalItems.value .filter((item) => isDisabled(item)) .map((item) => item[props.itemValue]); const selectedItemsValues = internalValue.value; const selectedDisabledItems = intersection(disabledItemsValues, selectedItemsValues); emit('update:modelValue', toArrOfObjIfNeeded(selectedDisabledItems)); } else { if (!isDisabled(selectedItems.value[0])) { emit('update:modelValue', null); } } }; // Watch // Creates the internalItems array watch( () => props.items, (nV) => { internalItems.value = createInternalItems(nV); // Remove values from the internalValue (modelValue) that are not in the items list if (props.multiple && props.items.length && internalValue.value.length) { const internalValueFiltered = internalValue.value.filter((item) => { return internalItems.value.some((i) => i[props.itemValue] === item); }); if (internalValueFiltered.length !== internalValue.value.length) { console.warn(`[p-select-list] Some values in the modelValue are not in the items list.`); emit('update:modelValue', toArrOfObjIfNeeded(internalValueFiltered)); } } }, { immediate: true, } ); return { LIST_ITEM_SIZES, LIST_ITEM_CLASS, LIST_ITEM_ACTIVE_CLASS, LIST_ITEM_DISABLED_CLASS, selectedItems, computedItems, computedItemSize, computedInsideSelected, internalItems, internalValue, search, rowVirtualizer, getValue, getText, isSelected, isDisabled, setupNavigationSvc, destroyNavigationSvc, select, onFocus, onMousemove, scrollToActiveItem, putSelectedItemsOnTop, selectAll, clearAll, }; };