list-sort-preference.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Remembered sort order for the list pages.
  3. *
  4. * Sort lives in the URL, so it survives a refresh but not a trip through the
  5. * sidebar: coming back to a list lands on a bare path and the order silently
  6. * reverts to the default. This keeps the last order each list was sorted by,
  7. * so the choice sticks the way people expect it to.
  8. *
  9. * A cookie rather than localStorage because the pages resolve their sort on
  10. * the server. Reading it there means the first paint is already in the right
  11. * order, with no flash of default sorting and no client-side redirect.
  12. */
  13. /** Every list that remembers its sort. Keys are stored, so keep them stable. */
  14. export type ListKey =
  15. | 'customers'
  16. | 'vehicles'
  17. | 'workOrders'
  18. | 'quotes'
  19. | 'inventory'
  20. | 'inspections'
  21. | 'laborPresets'
  22. | 'billing'
  23. export const LIST_SORT_COOKIE = 'listSort'
  24. /** A year: long enough to feel permanent, short enough to age out eventually. */
  25. export const LIST_SORT_COOKIE_MAX_AGE = 60 * 60 * 24 * 365
  26. export type SortOrder = 'asc' | 'desc'
  27. export type ListSort = {
  28. sortBy: string | undefined
  29. sortOrder: SortOrder
  30. }
  31. /**
  32. * Parses the cookie: `{"customers":"name:asc"}`. Anything malformed yields an
  33. * empty map rather than throwing, since a hand-edited or truncated cookie must
  34. * never break a page render.
  35. */
  36. export function parseListSortCookie(raw: string | undefined): Record<string, string> {
  37. if (!raw) return {}
  38. try {
  39. const parsed = JSON.parse(raw)
  40. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
  41. const out: Record<string, string> = {}
  42. for (const [key, value] of Object.entries(parsed)) {
  43. if (typeof value === 'string') out[key] = value
  44. }
  45. return out
  46. } catch {
  47. return {}
  48. }
  49. }
  50. /** Splits a stored `column:direction` pair, rejecting anything else. */
  51. export function parseStoredSort(stored: string | undefined): ListSort | null {
  52. if (!stored) return null
  53. const [sortBy, sortOrder] = stored.split(':')
  54. if (!sortBy) return null
  55. return { sortBy, sortOrder: sortOrder === 'asc' ? 'asc' : 'desc' }
  56. }