import { MaybeRefOrGetter, computed, ref, toValue } from "vue"; export type SortDirection = "asc" | "desc"; export type UseSortOptions = { defaultSortKey?: string; defaultSortDirection?: SortDirection; ignoredColums?: MaybeRefOrGetter; }; export const useSort = (array: MaybeRefOrGetter, options?: UseSortOptions) => { const sortKey = ref(options?.defaultSortKey ?? null); const sortDirection = ref(options?.defaultSortDirection ?? null); const sortBy = (key: string, direction: SortDirection) => { sortKey.value = key; sortDirection.value = direction; }; const showColumn = (sortKey: string) => !toValue(options?.ignoredColums)?.includes(sortKey); const headerProps = computed(() => ({ onSort: sortBy, showColumn, currentSortKey: sortKey.value, sortDirection: sortDirection.value })); const sortedArray = computed(() => toValue(array).sort((a, b) => { if (sortKey.value === null || sortDirection.value === null) { return 0; } const aValue = (a as any)[sortKey.value]; const bValue = (b as any)[sortKey.value]; if (aValue === bValue) { return 0; } if (sortDirection.value === "asc") { return aValue > bValue ? 1 : -1; } else { return aValue > bValue ? -1 : 1; } })); return { sortedArray, headerProps, showColumn }; }