use-remembered-sort.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use client'
  2. import { useEffect } from 'react'
  3. import { useSearchParams } from 'next/navigation'
  4. import {
  5. LIST_SORT_COOKIE,
  6. LIST_SORT_COOKIE_MAX_AGE,
  7. parseListSortCookie,
  8. type ListKey,
  9. } from '@/lib/list-sort-preference'
  10. /**
  11. * Records the sort a list is currently showing, so returning to it later comes
  12. * back in the same order. See `resolveListSort` for the read side.
  13. *
  14. * It watches the URL rather than wrapping each table's sort handler: every list
  15. * already routes a column click through `?sortBy=`, so this needs no changes to
  16. * the existing handlers and cannot fall out of step with them.
  17. */
  18. export function useRememberedSort(list: ListKey) {
  19. const searchParams = useSearchParams()
  20. const sortBy = searchParams.get('sortBy')
  21. const sortOrder = searchParams.get('sortOrder') === 'asc' ? 'asc' : 'desc'
  22. useEffect(() => {
  23. // No column in the URL means the page is on its default or on what was
  24. // already remembered; either way there is nothing new to store.
  25. if (!sortBy) return
  26. const next = { ...readCookie(), [list]: `${sortBy}:${sortOrder}` }
  27. document.cookie = `${LIST_SORT_COOKIE}=${encodeURIComponent(
  28. JSON.stringify(next)
  29. )}; path=/; max-age=${LIST_SORT_COOKIE_MAX_AGE}; SameSite=Lax`
  30. }, [list, sortBy, sortOrder])
  31. }
  32. function readCookie(): Record<string, string> {
  33. const match = document.cookie.split('; ').find((c) => c.startsWith(`${LIST_SORT_COOKIE}=`))
  34. if (!match) return {}
  35. try {
  36. return parseListSortCookie(decodeURIComponent(match.slice(LIST_SORT_COOKIE.length + 1)))
  37. } catch {
  38. return {}
  39. }
  40. }