Просмотр исходного кода

Remember which item types are shown on the calendar (#624)

* Remember which item types are shown on the calendar

* Offer the calendar filters in the view menu and trust the browser cookie
Bernt Christian Egeland 1 день назад
Родитель
Сommit
4e8c9fd112

+ 171 - 0
src/__tests__/features/calendar/calendar-type-filters-memory.test.tsx

@@ -0,0 +1,171 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { CalendarSidebar, typeFiltersFrom } from '@/features/calendar/Components/CalendarSidebar'
+import { CalendarToolbar } from '@/features/calendar/Components/CalendarToolbar'
+import { useCalendarPreferences } from '@/features/calendar/Components/useCalendarPreferences'
+import {
+  CALENDAR_PREFERENCES_COOKIE,
+  type CalendarPreferences,
+  LEGACY_STORAGE_KEY,
+  parseCalendarPreferences,
+} from '@/features/calendar/Lib/calendar-preferences'
+import type { CalendarEventType } from '@/features/calendar/Actions/calendarActions'
+
+const counts: Record<CalendarEventType, number> = {
+  service: 3,
+  appointment: 1,
+  reminder: 2,
+  quote: 4,
+  message: 0,
+  external: 0,
+  closure: 0,
+  absence: 0,
+}
+
+/** The cookie as the calendar page reads it on the server. */
+function cookieValue(): string | undefined {
+  const raw = document.cookie
+    .split('; ')
+    .find((c) => c.startsWith(`${CALENDAR_PREFERENCES_COOKIE}=`))
+    ?.slice(CALENDAR_PREFERENCES_COOKIE.length + 1)
+  return raw ? decodeURIComponent(raw) : undefined
+}
+
+function setCookie(value: string) {
+  document.cookie = `${CALENDAR_PREFERENCES_COOKIE}=${encodeURIComponent(value)}; path=/`
+}
+
+/** The sidebar wired to the stored preferences the way the calendar wires it. */
+function Calendar({ initial }: { initial: CalendarPreferences | null }) {
+  const { preferences, setTypeShown } = useCalendarPreferences(initial)
+  return (
+    <CalendarSidebar
+      selectedDate={new Date(2026, 10, 17)}
+      month={new Date(2026, 10, 1)}
+      busyDates={[]}
+      filters={typeFiltersFrom(preferences.hiddenTypes)}
+      counts={counts}
+      total={10}
+      onSelectDate={() => undefined}
+      onMonthChange={() => undefined}
+      onFilterChange={setTypeShown}
+    />
+  )
+}
+
+/** Opens the calendar the way the page does: preferences from the cookie. */
+function openCalendar() {
+  return render(<Calendar initial={parseCalendarPreferences(cookieValue())} />)
+}
+
+function checkbox(name: string) {
+  return screen.getByRole('checkbox', { name })
+}
+
+const ALL = ['Work orders', 'Appointments', 'Reminders', 'Quotes']
+
+describe('calendar type filters', () => {
+  beforeEach(() => {
+    window.localStorage.clear()
+    document.cookie = `${CALENDAR_PREFERENCES_COOKIE}=; path=/; max-age=0`
+  })
+
+  it('keeps an unticked kind unticked after leaving the calendar and coming back', () => {
+    const first = openCalendar()
+    expect(checkbox('Quotes')).toHaveAttribute('data-state', 'checked')
+
+    fireEvent.click(checkbox('Quotes'))
+    expect(checkbox('Quotes')).toHaveAttribute('data-state', 'unchecked')
+    first.unmount()
+
+    // Unticked on the very first render: nothing ticked flashes before it.
+    openCalendar()
+    expect(checkbox('Quotes')).toHaveAttribute('data-state', 'unchecked')
+    expect(checkbox('Work orders')).toHaveAttribute('data-state', 'checked')
+
+    // Ticking it again is remembered too.
+    fireEvent.click(checkbox('Quotes'))
+    expect(checkbox('Quotes')).toHaveAttribute('data-state', 'checked')
+    expect(parseCalendarPreferences(cookieValue())?.hiddenTypes).toEqual([])
+  })
+
+  it('ignores kinds it does not know and shows everything it does', () => {
+    setCookie(JSON.stringify({ hiddenTypes: ['reminder', 'retired-kind', 42, null] }))
+    openCalendar()
+    expect(checkbox('Reminders')).toHaveAttribute('data-state', 'unchecked')
+    for (const name of ['Work orders', 'Appointments', 'Quotes']) {
+      expect(checkbox(name)).toHaveAttribute('data-state', 'checked')
+    }
+  })
+
+  it.each([
+    ['not JSON', '{oops'],
+    ['not a list', JSON.stringify({ hiddenTypes: 'quote' })],
+    ['not an object', JSON.stringify('quote')],
+  ])('shows every kind when the stored value is %s', async (_label, raw) => {
+    setCookie(raw)
+    window.localStorage.setItem(LEGACY_STORAGE_KEY, raw)
+    openCalendar()
+    // Let the mount effect run before asserting nothing changed.
+    await new Promise((resolve) => setTimeout(resolve, 0))
+    for (const name of ALL) {
+      expect(checkbox(name)).toHaveAttribute('data-state', 'checked')
+    }
+  })
+
+  it('carries over kinds hidden before the preferences moved to a cookie', async () => {
+    window.localStorage.setItem(LEGACY_STORAGE_KEY, JSON.stringify({ hiddenTypes: ['quote'] }))
+    openCalendar()
+    await waitFor(() => expect(checkbox('Quotes')).toHaveAttribute('data-state', 'unchecked'))
+    expect(parseCalendarPreferences(cookieValue())?.hiddenTypes).toEqual(['quote'])
+  })
+
+  it('trusts the browser cookie over an older copy the page was restored from', async () => {
+    setCookie(JSON.stringify({ hiddenTypes: ['quote'] }))
+    // What a Back navigation can hand over: preferences from before Quotes was hidden.
+    render(<Calendar initial={parseCalendarPreferences(JSON.stringify({ hiddenTypes: [] }))} />)
+    await waitFor(() => expect(checkbox('Quotes')).toHaveAttribute('data-state', 'unchecked'))
+    expect(parseCalendarPreferences(cookieValue())?.hiddenTypes).toEqual(['quote'])
+  })
+
+  it('lets the view menu show a hidden kind again where the sidebar is not drawn', async () => {
+    setCookie(JSON.stringify({ hiddenTypes: ['quote', 'absence'] }))
+    function Toolbar() {
+      const { preferences, update, setTypeShown } = useCalendarPreferences(
+        parseCalendarPreferences(cookieValue())
+      )
+      return (
+        <CalendarToolbar
+          title="November 2026"
+          view="month"
+          loading={false}
+          sidebarOpen={false}
+          preferences={preferences}
+          onViewChange={() => undefined}
+          onPrev={() => undefined}
+          onNext={() => undefined}
+          onToday={() => undefined}
+          onToggleSidebar={() => undefined}
+          onPreferenceChange={update}
+          onCreate={() => undefined}
+          filters={typeFiltersFrom(preferences.hiddenTypes)}
+          counts={counts}
+          onFilterChange={setTypeShown}
+        />
+      )
+    }
+    render(<Toolbar />)
+    const trigger = screen.getByRole('button', { name: /Month/ })
+    fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false })
+    const quotes = await screen.findByRole('menuitemcheckbox', { name: /Quotes/ })
+    expect(quotes).toHaveAttribute('data-state', 'unchecked')
+    // Leave has nothing this month but is hidden, so it is listed to be undone.
+    expect(screen.getByRole('menuitemcheckbox', { name: /Leave/ })).toBeInTheDocument()
+    expect(screen.queryByRole('menuitemcheckbox', { name: /Closed days/ })).toBeNull()
+
+    fireEvent.click(quotes)
+    await waitFor(() =>
+      expect(parseCalendarPreferences(cookieValue())?.hiddenTypes).toEqual(['absence'])
+    )
+  })
+})

+ 11 - 0
src/app/(authenticated)/calendar/page.tsx

@@ -1,3 +1,4 @@
+import { cookies } from 'next/headers'
 import { resolveCurrencyCode } from '@/lib/currencies'
 import { resolveCurrencyCode } from '@/lib/currencies'
 import { getCalendarEvents } from '@/features/calendar/Actions/calendarActions'
 import { getCalendarEvents } from '@/features/calendar/Actions/calendarActions'
 import { getDisplaySettings } from '@/features/settings/Actions/settingsActions'
 import { getDisplaySettings } from '@/features/settings/Actions/settingsActions'
@@ -20,6 +21,10 @@ import {
   type CalendarView,
   type CalendarView,
 } from '@/features/calendar/Lib/calendar-range'
 } from '@/features/calendar/Lib/calendar-range'
 import { pageTitle } from '@/lib/page-title'
 import { pageTitle } from '@/lib/page-title'
+import {
+  CALENDAR_PREFERENCES_COOKIE,
+  parseCalendarPreferences,
+} from '@/features/calendar/Lib/calendar-preferences'
 
 
 export function generateMetadata() {
 export function generateMetadata() {
   return pageTitle('calendar')
   return pageTitle('calendar')
@@ -84,6 +89,11 @@ export default async function CalendarPage({
         }
         }
       : null
       : null
 
 
+  // Read here so the first paint already has the kinds this person hid.
+  const preferences = parseCalendarPreferences(
+    (await cookies()).get(CALENDAR_PREFERENCES_COOKIE)?.value
+  )
+
   const events = eventsResult.success && eventsResult.data ? eventsResult.data : []
   const events = eventsResult.success && eventsResult.data ? eventsResult.data : []
 
 
   return (
   return (
@@ -99,6 +109,7 @@ export default async function CalendarPage({
           currencyCode={currencyCode}
           currencyCode={currencyCode}
           messageChannels={messageChannels}
           messageChannels={messageChannels}
           timeOff={timeOff}
           timeOff={timeOff}
+          initialPreferences={preferences}
         />
         />
       </div>
       </div>
     </>
     </>

+ 17 - 16
src/features/calendar/Components/CalendarClient.tsx

@@ -40,7 +40,7 @@ import {
 } from '../Lib/calendar-range'
 } from '../Lib/calendar-range'
 import { compareEvents, isEventDone } from './calendar-utils'
 import { compareEvents, isEventDone } from './calendar-utils'
 import { CalendarEventList } from './CalendarEventList'
 import { CalendarEventList } from './CalendarEventList'
-import { CalendarSidebar, type TypeFilters } from './CalendarSidebar'
+import { CalendarSidebar, typeFiltersFrom } from './CalendarSidebar'
 import { CalendarToolbar, type CreateKind } from './CalendarToolbar'
 import { CalendarToolbar, type CreateKind } from './CalendarToolbar'
 import type { DayActions } from './DayContextMenu'
 import type { DayActions } from './DayContextMenu'
 import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
 import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
@@ -48,7 +48,7 @@ import { type BookingEdit, EventPeekProvider } from './EventPeek'
 import { MonthView } from './MonthView'
 import { MonthView } from './MonthView'
 import { ScheduleView } from './ScheduleView'
 import { ScheduleView } from './ScheduleView'
 import { TimeGridView } from './TimeGridView'
 import { TimeGridView } from './TimeGridView'
-import { useCalendarPreferences } from './useCalendarPreferences'
+import { type CalendarPreferences, useCalendarPreferences } from './useCalendarPreferences'
 import { YearView } from './YearView'
 import { YearView } from './YearView'
 
 
 interface CalendarClientProps {
 interface CalendarClientProps {
@@ -67,6 +67,8 @@ interface CalendarClientProps {
    * the workshop does not track time off.
    * the workshop does not track time off.
    */
    */
   timeOff?: { technicians: TechnicianOption[] } | null
   timeOff?: { technicians: TechnicianOption[] } | null
+  /** The viewing preferences from the cookie; null when none are stored yet. */
+  initialPreferences?: CalendarPreferences | null
 }
 }
 
 
 const ALL_TYPES: CalendarEventType[] = [
 const ALL_TYPES: CalendarEventType[] = [
@@ -107,6 +109,7 @@ export default function CalendarClient({
   currencyCode,
   currencyCode,
   messageChannels,
   messageChannels,
   timeOff = null,
   timeOff = null,
+  initialPreferences = null,
 }: CalendarClientProps) {
 }: CalendarClientProps) {
   const t = useTranslations('calendar')
   const t = useTranslations('calendar')
   const tWorkOrders = useTranslations('workOrders.list')
   const tWorkOrders = useTranslations('workOrders.list')
@@ -114,7 +117,11 @@ export default function CalendarClient({
   const pathname = usePathname()
   const pathname = usePathname()
   const isMobile = useIsMobile()
   const isMobile = useIsMobile()
   const { weekStartDay } = useDateSettings()
   const { weekStartDay } = useDateSettings()
-  const { preferences, update: updatePreferences } = useCalendarPreferences()
+  const {
+    preferences,
+    update: updatePreferences,
+    setTypeShown,
+  } = useCalendarPreferences(initialPreferences)
 
 
   const [view, setView] = useState<CalendarView>(initialView)
   const [view, setView] = useState<CalendarView>(initialView)
   const [date, setDate] = useState<Date>(
   const [date, setDate] = useState<Date>(
@@ -127,16 +134,9 @@ export default function CalendarClient({
     return start && end ? { start, end } : null
     return start && end ? { start, end } : null
   })
   })
   const [loading, setLoading] = useState(false)
   const [loading, setLoading] = useState(false)
-  const [filters, setFilters] = useState<TypeFilters>({
-    service: true,
-    reminder: true,
-    quote: true,
-    message: true,
-    external: true,
-    closure: true,
-    absence: true,
-    appointment: true,
-  })
+  // Remembered in the browser with the other viewing preferences, so a kind
+  // unticked here stays unticked after a trip to the work board or a reload.
+  const filters = useMemo(() => typeFiltersFrom(preferences.hiddenTypes), [preferences.hiddenTypes])
 
 
   // Dialogs the calendar can open
   // Dialogs the calendar can open
   const [showPicker, setShowPicker] = useState(false)
   const [showPicker, setShowPicker] = useState(false)
@@ -535,6 +535,9 @@ export default function CalendarClient({
           onPreferenceChange={updatePreferences}
           onPreferenceChange={updatePreferences}
           onCreate={handleCreate}
           onCreate={handleCreate}
           canSetTimeOff={timeOff !== null}
           canSetTimeOff={timeOff !== null}
+          filters={filters}
+          counts={counts}
+          onFilterChange={setTypeShown}
         />
         />
         <div className="flex min-h-0 flex-1">
         <div className="flex min-h-0 flex-1">
           {preferences.sidebarOpen && (
           {preferences.sidebarOpen && (
@@ -553,9 +556,7 @@ export default function CalendarClient({
                   setDate(new Date(m.getFullYear(), m.getMonth(), 1))
                   setDate(new Date(m.getFullYear(), m.getMonth(), 1))
                 }
                 }
               }}
               }}
-              onFilterChange={(type, checked) =>
-                setFilters((current) => ({ ...current, [type]: checked }))
-              }
+              onFilterChange={setTypeShown}
             />
             />
           )}
           )}
           <div className="flex min-h-0 min-w-0 flex-1 flex-col">{body}</div>
           <div className="flex min-h-0 min-w-0 flex-1 flex-col">{body}</div>

+ 27 - 4
src/features/calendar/Components/CalendarSidebar.tsx

@@ -20,10 +20,34 @@ const FILTER_ORDER: CalendarEventType[] = [
   'external',
   'external',
 ]
 ]
 
 
-/** Shown only when there is something of the kind in view. */
+/**
+ * The ticks the list shows for what this person has hidden. A kind not in
+ * the stored list is shown, and stored names the calendar does not know
+ * are passed over.
+ */
+export function typeFiltersFrom(hiddenTypes: readonly string[]): TypeFilters {
+  const hidden = new Set(hiddenTypes)
+  return Object.fromEntries(FILTER_ORDER.map((type) => [type, !hidden.has(type)])) as TypeFilters
+}
+
+/** Listed only when there is something of the kind in view, or it is hidden. */
 const ONLY_WHEN_PRESENT: CalendarEventType[] = ['external', 'closure', 'absence']
 const ONLY_WHEN_PRESENT: CalendarEventType[] = ['external', 'closure', 'absence']
 
 
-const FILTER_LABEL: Record<CalendarEventType, string> = {
+/**
+ * The kinds the list offers, in order. A hidden kind is always listed, so a
+ * choice remembered from another visit can be undone.
+ */
+export function listedTypes(
+  counts: Record<CalendarEventType, number>,
+  filters: TypeFilters
+): CalendarEventType[] {
+  return FILTER_ORDER.filter(
+    (type) => !ONLY_WHEN_PRESENT.includes(type) || counts[type] > 0 || !filters[type]
+  )
+}
+
+/** The key under `calendar.filters` that names a kind. */
+export const FILTER_LABEL: Record<CalendarEventType, string> = {
   service: 'services',
   service: 'services',
   reminder: 'reminders',
   reminder: 'reminders',
   quote: 'quotes',
   quote: 'quotes',
@@ -88,8 +112,7 @@ export function CalendarSidebar({
           </span>
           </span>
         </div>
         </div>
         <ul className="space-y-0.5">
         <ul className="space-y-0.5">
-          {FILTER_ORDER.map((type) => {
-            if (ONLY_WHEN_PRESENT.includes(type) && counts[type] === 0) return null
+          {listedTypes(counts, filters).map((type) => {
             const palette = typePalette(type)
             const palette = typePalette(type)
             return (
             return (
               <li key={type}>
               <li key={type}>

+ 36 - 0
src/features/calendar/Components/CalendarToolbar.tsx

@@ -21,7 +21,9 @@ import {
   DropdownMenu,
   DropdownMenu,
   DropdownMenuCheckboxItem,
   DropdownMenuCheckboxItem,
   DropdownMenuContent,
   DropdownMenuContent,
+  DropdownMenuGroup,
   DropdownMenuItem,
   DropdownMenuItem,
+  DropdownMenuLabel,
   DropdownMenuRadioGroup,
   DropdownMenuRadioGroup,
   DropdownMenuRadioItem,
   DropdownMenuRadioItem,
   DropdownMenuSeparator,
   DropdownMenuSeparator,
@@ -31,6 +33,9 @@ import {
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 import type { CalendarView } from '../Lib/calendar-range'
 import type { CalendarView } from '../Lib/calendar-range'
 import type { CalendarPreferences } from './useCalendarPreferences'
 import type { CalendarPreferences } from './useCalendarPreferences'
+import type { CalendarEventType } from '../Actions/calendarActions'
+import { FILTER_LABEL, listedTypes, type TypeFilters } from './CalendarSidebar'
+import { typePalette } from './calendar-utils'
 
 
 export type CreateKind = 'workOrder' | 'appointment' | 'reminder' | 'quote' | 'message' | 'timeOff'
 export type CreateKind = 'workOrder' | 'appointment' | 'reminder' | 'quote' | 'message' | 'timeOff'
 
 
@@ -58,6 +63,10 @@ interface CalendarToolbarProps {
   onCreate: (kind: CreateKind) => void
   onCreate: (kind: CreateKind) => void
   /** Whether this person may set technicians on leave, and the workshop tracks it. */
   /** Whether this person may set technicians on leave, and the workshop tracks it. */
   canSetTimeOff?: boolean
   canSetTimeOff?: boolean
+  /** The kinds shown, for the menu copy of the sidebar list where the sidebar is not drawn. */
+  filters: TypeFilters
+  counts: Record<CalendarEventType, number>
+  onFilterChange: (type: CalendarEventType, checked: boolean) => void
 }
 }
 
 
 /**
 /**
@@ -78,6 +87,9 @@ export function CalendarToolbar({
   onToggleSidebar,
   onToggleSidebar,
   onPreferenceChange,
   onPreferenceChange,
   onCreate,
   onCreate,
+  filters,
+  counts,
+  onFilterChange,
   canSetTimeOff = false,
   canSetTimeOff = false,
 }: CalendarToolbarProps) {
 }: CalendarToolbarProps) {
   const t = useTranslations('calendar')
   const t = useTranslations('calendar')
@@ -169,6 +181,30 @@ export function CalendarToolbar({
             >
             >
               {t('options.showWeekNumbers')}
               {t('options.showWeekNumbers')}
             </DropdownMenuCheckboxItem>
             </DropdownMenuCheckboxItem>
+            {/* The sidebar's list, for widths where the sidebar is not drawn or
+                when it is closed, so a hidden kind can always be shown again. */}
+            <DropdownMenuGroup className={cn(sidebarOpen && 'lg:hidden')}>
+              <DropdownMenuSeparator />
+              <DropdownMenuLabel className="text-xs text-muted-foreground">
+                {t('sidebar.calendars')}
+              </DropdownMenuLabel>
+              {listedTypes(counts, filters).map((type) => (
+                <DropdownMenuCheckboxItem
+                  key={type}
+                  checked={filters[type]}
+                  onCheckedChange={(checked) => onFilterChange(type, !!checked)}
+                  onSelect={(event) => event.preventDefault()}
+                >
+                  <span
+                    className={cn('mr-2 h-2.5 w-2.5 shrink-0 rounded-sm', typePalette(type).dot)}
+                  />
+                  <span className="flex-1">{t(`filters.${FILTER_LABEL[type]}`)}</span>
+                  <span className="ml-2 text-xs tabular-nums text-muted-foreground">
+                    {counts[type]}
+                  </span>
+                </DropdownMenuCheckboxItem>
+              ))}
+            </DropdownMenuGroup>
           </DropdownMenuContent>
           </DropdownMenuContent>
         </DropdownMenu>
         </DropdownMenu>
 
 

+ 59 - 47
src/features/calendar/Components/useCalendarPreferences.ts

@@ -1,59 +1,71 @@
 'use client'
 'use client'
 
 
 import { useCallback, useEffect, useState } from 'react'
 import { useCallback, useEffect, useState } from 'react'
+import {
+  type CalendarPreferences,
+  DEFAULT_CALENDAR_PREFERENCES,
+  LEGACY_STORAGE_KEY,
+  parseCalendarPreferences,
+  readCalendarPreferencesCookie,
+  rememberCalendarPreferences,
+} from '../Lib/calendar-preferences'
+
+export type { CalendarPreferences } from '../Lib/calendar-preferences'
 
 
 /**
 /**
- * How this person likes the calendar drawn. Kept in the browser: these are
- * viewing habits, not workshop data, and a planner on the front desk PC and
- * a phone in the pit may well want different ones.
+ * The calendar's viewing preferences. `initial` is what the page read from
+ * the cookie on the server, so the first paint matches what was chosen;
+ * null when there is no cookie yet.
  */
  */
-export interface CalendarPreferences {
-  showWeekends: boolean
-  showCompleted: boolean
-  showWeekNumbers: boolean
-  sidebarOpen: boolean
-}
-
-const STORAGE_KEY = 'torqvoice.calendar.preferences'
-
-const DEFAULTS: CalendarPreferences = {
-  showWeekends: true,
-  showCompleted: true,
-  showWeekNumbers: false,
-  sidebarOpen: true,
-}
-
-function read(): CalendarPreferences {
-  try {
-    const raw = window.localStorage.getItem(STORAGE_KEY)
-    if (!raw) return DEFAULTS
-    const parsed = JSON.parse(raw) as Partial<CalendarPreferences>
-    return { ...DEFAULTS, ...parsed }
-  } catch {
-    return DEFAULTS
-  }
-}
-
-export function useCalendarPreferences() {
-  // Defaults on the server and the first client paint, so hydration agrees;
-  // the stored values land right after.
-  const [preferences, setPreferences] = useState<CalendarPreferences>(DEFAULTS)
+export function useCalendarPreferences(initial: CalendarPreferences | null = null) {
+  const [preferences, setPreferences] = useState<CalendarPreferences>(
+    initial ?? DEFAULT_CALENDAR_PREFERENCES
+  )
 
 
+  // The cookie in the browser is the latest word: a page restored by Back
+  // or Forward can carry preferences older than the last change. With no
+  // cookie at all, carry over what an earlier build kept in local storage,
+  // once, and from then on the cookie is what counts.
   useEffect(() => {
   useEffect(() => {
-    setPreferences(read())
+    const current = readCalendarPreferencesCookie()
+    if (current) {
+      setPreferences(current)
+      return
+    }
+    let legacy: CalendarPreferences | null = null
+    try {
+      legacy = parseCalendarPreferences(window.localStorage.getItem(LEGACY_STORAGE_KEY))
+    } catch {
+      // Storage blocked: stay on the defaults.
+    }
+    if (legacy) {
+      setPreferences(legacy)
+      rememberCalendarPreferences(legacy)
+    }
   }, [])
   }, [])
 
 
-  const update = useCallback((patch: Partial<CalendarPreferences>) => {
-    setPreferences((current) => {
-      const next = { ...current, ...patch }
-      try {
-        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
-      } catch {
-        // Private mode or a full store: the choice still applies for the session.
-      }
-      return next
-    })
-  }, [])
+  const change = useCallback(
+    (patchFor: (current: CalendarPreferences) => Partial<CalendarPreferences>) => {
+      setPreferences((current) => {
+        const next = { ...current, ...patchFor(current) }
+        rememberCalendarPreferences(next)
+        return next
+      })
+    },
+    []
+  )
+
+  const update = useCallback((patch: Partial<CalendarPreferences>) => change(() => patch), [change])
+
+  /** Ticks or unticks one kind in the sidebar list and remembers it. */
+  const setTypeShown = useCallback(
+    (type: string, shown: boolean) =>
+      change((current) => {
+        const others = current.hiddenTypes.filter((hidden) => hidden !== type)
+        return { hiddenTypes: shown ? others : [...others, type] }
+      }),
+    [change]
+  )
 
 
-  return { preferences, update }
+  return { preferences, update, setTypeShown }
 }
 }

+ 91 - 0
src/features/calendar/Lib/calendar-preferences.ts

@@ -0,0 +1,91 @@
+/**
+ * How this person likes the calendar drawn. Kept in the browser: these are
+ * viewing habits, not workshop data, and a planner on the front desk PC and
+ * a phone in the pit may well want different ones.
+ *
+ * A cookie rather than local storage, so the calendar page reads it on the
+ * server and the first paint already has the right kinds ticked and hidden.
+ */
+export interface CalendarPreferences {
+  showWeekends: boolean
+  showCompleted: boolean
+  showWeekNumbers: boolean
+  sidebarOpen: boolean
+  /**
+   * The kinds unticked in the sidebar list. What is hidden, not what is
+   * shown, so a kind added to the calendar later starts out visible.
+   */
+  hiddenTypes: string[]
+}
+
+export const CALENDAR_PREFERENCES_COOKIE = 'calendarPreferences'
+
+/** Where the preferences lived before the cookie; read once to carry them over. */
+export const LEGACY_STORAGE_KEY = 'torqvoice.calendar.preferences'
+
+/** A year, the same as the other remembered view choices. */
+const MAX_AGE = 60 * 60 * 24 * 365
+
+/** More than the calendar has kinds; a longer list is not one this app wrote. */
+const MAX_HIDDEN = 32
+
+export const DEFAULT_CALENDAR_PREFERENCES: CalendarPreferences = {
+  showWeekends: true,
+  showCompleted: true,
+  showWeekNumbers: false,
+  sidebarOpen: true,
+  hiddenTypes: [],
+}
+
+const BOOLEAN_KEYS = ['showWeekends', 'showCompleted', 'showWeekNumbers', 'sidebarOpen'] as const
+
+/**
+ * Reads stored preferences, taking only values of the right shape. Anything
+ * else, written by an older build or by hand, falls back to the default
+ * instead of breaking the page. Null when nothing usable is stored.
+ */
+export function parseCalendarPreferences(
+  raw: string | null | undefined
+): CalendarPreferences | null {
+  if (!raw) return null
+  let parsed: unknown
+  try {
+    parsed = JSON.parse(raw)
+  } catch {
+    return null
+  }
+  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
+  const stored = parsed as Record<string, unknown>
+  const next: CalendarPreferences = { ...DEFAULT_CALENDAR_PREFERENCES }
+  for (const key of BOOLEAN_KEYS) {
+    if (typeof stored[key] === 'boolean') next[key] = stored[key]
+  }
+  if (Array.isArray(stored.hiddenTypes)) {
+    next.hiddenTypes = stored.hiddenTypes
+      .filter((v): v is string => typeof v === 'string' && v.length <= 32)
+      .slice(0, MAX_HIDDEN)
+  }
+  return next
+}
+
+export function rememberCalendarPreferences(preferences: CalendarPreferences): void {
+  if (typeof document === 'undefined') return
+  document.cookie = `${CALENDAR_PREFERENCES_COOKIE}=${encodeURIComponent(
+    JSON.stringify(preferences)
+  )}; path=/; max-age=${MAX_AGE}; samesite=lax`
+}
+
+/** The cookie as this browser holds it now; null when there is none. */
+export function readCalendarPreferencesCookie(): CalendarPreferences | null {
+  if (typeof document === 'undefined') return null
+  const raw = document.cookie
+    .split('; ')
+    .find((c) => c.startsWith(`${CALENDAR_PREFERENCES_COOKIE}=`))
+    ?.slice(CALENDAR_PREFERENCES_COOKIE.length + 1)
+  if (!raw) return null
+  try {
+    return parseCalendarPreferences(decodeURIComponent(raw))
+  } catch {
+    return null
+  }
+}