feat(tri): mémoriser les préférences de tri
This commit is contained in:
53
app/composables/usePersistedSort.ts
Normal file
53
app/composables/usePersistedSort.ts
Normal 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,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user