use-list-columns.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use client'
  2. import { useCallback, useState } from 'react'
  3. import { useRouter } from 'next/navigation'
  4. import {
  5. LIST_COLUMNS_COOKIE,
  6. LIST_COLUMNS_COOKIE_MAX_AGE,
  7. parseListColumnsCookie,
  8. } from '@/lib/list-columns'
  9. import type { ListKey } from '@/lib/list-sort-preference'
  10. /**
  11. * The optional columns a table is showing, and turning one on or off.
  12. *
  13. * The server renders the page from the same cookie (`resolveListColumns`), so
  14. * the list starts with the right columns; this keeps the table in step while
  15. * the menu is being used and writes the choice back. `router.refresh()` after
  16. * a change so a column that needs a wider query gets one on the next load.
  17. */
  18. export function useListColumns(list: ListKey, initial: string[]) {
  19. const router = useRouter()
  20. const [columns, setColumns] = useState<string[]>(initial)
  21. const toggle = useCallback(
  22. (column: string, on: boolean) => {
  23. setColumns((current) => {
  24. const next = on
  25. ? current.includes(column)
  26. ? current
  27. : [...current, column]
  28. : current.filter((c) => c !== column)
  29. write(list, next)
  30. return next
  31. })
  32. router.refresh()
  33. },
  34. [list, router]
  35. )
  36. return { columns, shows: (column: string) => columns.includes(column), toggle }
  37. }
  38. function write(list: ListKey, columns: string[]) {
  39. const next = { ...read(), [list]: columns }
  40. document.cookie = `${LIST_COLUMNS_COOKIE}=${encodeURIComponent(
  41. JSON.stringify(next)
  42. )}; path=/; max-age=${LIST_COLUMNS_COOKIE_MAX_AGE}; SameSite=Lax`
  43. }
  44. function read(): Partial<Record<ListKey, string[]>> {
  45. const match = document.cookie.split('; ').find((c) => c.startsWith(`${LIST_COLUMNS_COOKIE}=`))
  46. if (!match) return {}
  47. return parseListColumnsCookie(match.slice(LIST_COLUMNS_COOKIE.length + 1))
  48. }