feat(tri): mémoriser les préférences de tri

This commit is contained in:
2026-01-14 23:10:27 +01:00
parent b5af7f13b6
commit ddce3ff3ae
6 changed files with 154 additions and 13 deletions

View File

@@ -0,0 +1,53 @@
import { ref, watch } from 'vue'
import { useCookie } from '#imports'
type SortCookie = {
field?: string
direction?: string
}
const readSortCookie = (value: unknown): SortCookie | null => {
if (!value) {
return null
}
if (typeof value === 'object') {
return value as SortCookie
}
if (typeof value === 'string') {
try {
return JSON.parse(value) as SortCookie
} catch {
return null
}
}
return null
}
export const usePersistedSort = <
TField extends string,
TDirection extends string,
>(
key: string,
defaults: { field: TField; direction: TDirection },
) => {
const cookie = useCookie<string | null>(`sort:${key}`, {
sameSite: 'lax',
})
const stored = readSortCookie(cookie.value)
const sortField = ref<TField>((stored?.field as TField) || defaults.field)
const sortDirection = ref<TDirection>(
(stored?.direction as TDirection) || defaults.direction,
)
watch([sortField, sortDirection], () => {
cookie.value = JSON.stringify({
field: sortField.value,
direction: sortDirection.value,
})
})
return {
sortField,
sortDirection,
}
}