@burdenoff/microfe-calendar 2026.1120.1 → 2026.1123.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/CalendarRoutes.d.ts +3 -0
  2. package/dist/CalendarRoutes.js +37 -32
  3. package/dist/CalendarRoutes.js.map +1 -1
  4. package/dist/generated/global-operations.d.ts +74 -0
  5. package/dist/generated/global-operations.js +20 -0
  6. package/dist/generated/global-operations.js.map +1 -0
  7. package/dist/generated/global-types.d.ts +9902 -578
  8. package/dist/generated/wspace-operations.d.ts +298 -0
  9. package/dist/generated/wspace-operations.js +126 -1
  10. package/dist/generated/wspace-operations.js.map +1 -1
  11. package/dist/generated/wspace-types.d.ts +204825 -48049
  12. package/dist/providers/CalendarProvider.d.ts +2 -0
  13. package/dist/providers/CalendarProvider.js +12 -10
  14. package/dist/providers/CalendarProvider.js.map +1 -1
  15. package/dist/translations/en.d.ts +5 -0
  16. package/dist/types/index.d.ts +6 -0
  17. package/dist/v2/CalendarPageV2.d.ts +1 -0
  18. package/dist/v2/CalendarPageV2.js +19 -0
  19. package/dist/v2/CalendarPageV2.js.map +1 -0
  20. package/dist/v2/CalendarRoutesV2.d.ts +1 -0
  21. package/dist/v2/CalendarRoutesV2.js +117 -0
  22. package/dist/v2/CalendarRoutesV2.js.map +1 -0
  23. package/dist/v2/data/invalidation.d.ts +4 -0
  24. package/dist/v2/data/normalize.d.ts +26 -0
  25. package/dist/v2/data/normalize.js +87 -0
  26. package/dist/v2/data/normalize.js.map +1 -0
  27. package/dist/v2/data/useCalendarsV2.d.ts +16 -0
  28. package/dist/v2/data/useCalendarsV2.js +25 -0
  29. package/dist/v2/data/useCalendarsV2.js.map +1 -0
  30. package/dist/v2/data/useEventsInRangeV2.d.ts +18 -0
  31. package/dist/v2/data/useFreeBusy.d.ts +22 -0
  32. package/dist/v2/data/useKeyedLoad.d.ts +17 -0
  33. package/dist/v2/prefs/CalendarPrefsProvider.d.ts +25 -0
  34. package/dist/v2/prefs/CalendarPrefsProvider.js +52 -0
  35. package/dist/v2/prefs/CalendarPrefsProvider.js.map +1 -0
  36. package/dist/v2/prefs/calendarPrefs.d.ts +73 -0
  37. package/dist/v2/prefs/calendarPrefs.js +71 -0
  38. package/dist/v2/prefs/calendarPrefs.js.map +1 -0
  39. package/dist/v2/prefs/prefsApi.d.ts +16 -0
  40. package/dist/v2/prefs/prefsApi.js +46 -0
  41. package/dist/v2/prefs/prefsApi.js.map +1 -0
  42. package/dist/v2/prefs/prefsSession.d.ts +55 -0
  43. package/dist/v2/prefs/prefsSession.js +94 -0
  44. package/dist/v2/prefs/prefsSession.js.map +1 -0
  45. package/dist/v2/prefs/prefsStorage.d.ts +17 -0
  46. package/dist/v2/prefs/prefsStorage.js +56 -0
  47. package/dist/v2/prefs/prefsStorage.js.map +1 -0
  48. package/dist/v2/routes.d.ts +43 -0
  49. package/dist/v2/routes.js +60 -0
  50. package/dist/v2/routes.js.map +1 -0
  51. package/dist/v2/state/calendarV2Store.d.ts +54 -0
  52. package/dist/v2/state/calendarV2Store.js +78 -0
  53. package/dist/v2/state/calendarV2Store.js.map +1 -0
  54. package/dist/v2/state/useCalendarV2Navigation.d.ts +25 -0
  55. package/dist/v2/state/useCalendarV2Navigation.js +52 -0
  56. package/dist/v2/state/useCalendarV2Navigation.js.map +1 -0
  57. package/dist/v2/state/useCalendarV2PrefsBridge.d.ts +1 -0
  58. package/dist/v2/state/useCalendarV2PrefsBridge.js +28 -0
  59. package/dist/v2/state/useCalendarV2PrefsBridge.js.map +1 -0
  60. package/dist/v2/time/calendarTime.d.ts +115 -0
  61. package/dist/v2/time/calendarTime.js +59 -0
  62. package/dist/v2/time/calendarTime.js.map +1 -0
  63. package/dist/v2/types.d.ts +202 -0
  64. package/package.json +12 -5
@@ -0,0 +1,52 @@
1
+ import { useCalendar as e } from "../../providers/CalendarProvider.js";
2
+ import { resolveTimeZone as t } from "../time/calendarTime.js";
3
+ import { createCalendarPrefsApi as n } from "./prefsApi.js";
4
+ import { createPrefsSession as r } from "./prefsSession.js";
5
+ import { readInitialPrefs as i, saveDeviceCopy as a } from "./prefsStorage.js";
6
+ import { createContext as o, use as s, useEffect as c, useMemo as l, useState as u, useSyncExternalStore as d } from "react";
7
+ import { jsx as f } from "react/jsx-runtime";
8
+ // src/v2/prefs/CalendarPrefsProvider.tsx
9
+ var p = 1500, m = o(null);
10
+ function h({ children: t, api: o }) {
11
+ let { authToken: s } = e(), p = l(() => o ?? n(s), [o, s]), [h] = u(() => r({
12
+ api: p,
13
+ initial: i(),
14
+ saveDeviceCopy: a
15
+ })), g = d(h.subscribe, h.getSnapshot, h.getSnapshot);
16
+ c(() => h.setApi(p), [h, p]), c(() => {
17
+ h.start();
18
+ let e = () => h.retry(), t = () => h.flush(!0);
19
+ return window.addEventListener("online", e), window.addEventListener("pagehide", t), () => {
20
+ window.removeEventListener("online", e), window.removeEventListener("pagehide", t), h.stop();
21
+ };
22
+ }, [h]);
23
+ let _ = l(() => ({
24
+ ...g,
25
+ update: h.update,
26
+ clearLegacyVisibleCalendarIds: h.clearLegacyVisibleCalendarIds
27
+ }), [g, h]);
28
+ return /* @__PURE__ */ f(m, {
29
+ value: _,
30
+ children: t
31
+ });
32
+ }
33
+ function g() {
34
+ let e = s(m);
35
+ if (!e) throw Error("useCalendarPrefs must be used within CalendarPrefsProvider");
36
+ return e;
37
+ }
38
+ function _() {
39
+ let { prefs: e } = g();
40
+ return l(() => t(e.timeZone), [e.timeZone]);
41
+ }
42
+ function v(e = p) {
43
+ let { status: t } = g(), [n, r] = u(!1);
44
+ return c(() => {
45
+ if (t !== "loading") return;
46
+ let n = setTimeout(() => r(!0), e);
47
+ return () => clearTimeout(n);
48
+ }, [t, e]), t !== "loading" || n;
49
+ }
50
+ export { h as CalendarPrefsProvider, g as useCalendarPrefs, _ as useCalendarTimeZone, v as usePrefsSettled };
51
+
52
+ //# sourceMappingURL=CalendarPrefsProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CalendarPrefsProvider.js","names":["PREFS_WAIT_MS","CalendarPrefsContext","createContext","CalendarPrefsProvider","useCalendar","accountApi","useMemo","api","createCalendarPrefsApi","authToken","session","useState","createPrefsSession","readInitialPrefs","snapshot","useSyncExternalStore","useEffect","onOnline","onPageHide","value","useCalendarPrefs","context","use","useCalendarTimeZone","resolveTimeZone","prefs","usePrefsSettled","waitedOut","setWaitedOut","status","timer","maxWaitMs"],"sources":["../../../src/v2/prefs/CalendarPrefsProvider.tsx"],"sourcesContent":["/**\n * The person's calendar settings for the redesigned calendar (BOFF-15698 B3), on their\n * account, for every part under `CalendarRoutesV2` (`useCalendarPrefs`).\n *\n * Before the account answers, or when it can't be reached, the calendar shows this device's\n * copy of the account's settings, else what today's calendar kept on this device, else the\n * defaults (`prefsStorage.ts`). Reading, writing and retrying are `prefsSession.ts`'s.\n *\n * One provider serves one person: `CalendarRoutesV2` keys it by the signed-in user, so another\n * person signing in gets a new session and never sees or writes the previous person's settings.\n */\nimport {\n createContext,\n use,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { useCalendar } from '../../providers/CalendarProvider';\nimport { resolveTimeZone } from '../time/calendarTime';\nimport type { CalendarPrefs } from './calendarPrefs';\nimport { createCalendarPrefsApi, type CalendarPrefsApi } from './prefsApi';\nimport { createPrefsSession, type PrefsSnapshot } from './prefsSession';\nimport { readInitialPrefs, saveDeviceCopy } from './prefsStorage';\n\n/** How long an address waits for the account's settings before using what this device has. */\nconst PREFS_WAIT_MS = 1500;\n\nexport interface CalendarPrefsContextValue extends PrefsSnapshot {\n /** Changes settings at once; they are written to the account shortly after. */\n update: (patch: Partial<CalendarPrefs>) => void;\n /** Call once today's ticked calendars have been turned into hidden ones. */\n clearLegacyVisibleCalendarIds: () => void;\n}\n\nconst CalendarPrefsContext = createContext<CalendarPrefsContextValue | null>(null);\n\nexport interface CalendarPrefsProviderProps {\n children: ReactNode;\n /** The account calls; the global gateway's by default (tests pass their own). */\n api?: CalendarPrefsApi;\n}\n\nexport function CalendarPrefsProvider({ children, api }: CalendarPrefsProviderProps) {\n const { authToken } = useCalendar();\n const accountApi = useMemo(() => api ?? createCalendarPrefsApi(authToken), [api, authToken]);\n const [session] = useState(() =>\n createPrefsSession({ api: accountApi, initial: readInitialPrefs(), saveDeviceCopy })\n );\n const snapshot = useSyncExternalStore(\n session.subscribe,\n session.getSnapshot,\n session.getSnapshot\n );\n\n useEffect(() => session.setApi(accountApi), [session, accountApi]);\n\n useEffect(() => {\n session.start();\n const onOnline = () => session.retry();\n const onPageHide = () => session.flush(true);\n window.addEventListener('online', onOnline);\n window.addEventListener('pagehide', onPageHide);\n return () => {\n window.removeEventListener('online', onOnline);\n window.removeEventListener('pagehide', onPageHide);\n session.stop();\n };\n }, [session]);\n\n const value = useMemo<CalendarPrefsContextValue>(\n () => ({\n ...snapshot,\n update: session.update,\n clearLegacyVisibleCalendarIds: session.clearLegacyVisibleCalendarIds,\n }),\n [snapshot, session]\n );\n\n return <CalendarPrefsContext value={value}>{children}</CalendarPrefsContext>;\n}\n\n/** The person's calendar settings. Only inside the redesigned calendar (`CalendarRoutesV2`). */\nexport function useCalendarPrefs(): CalendarPrefsContextValue {\n const context = use(CalendarPrefsContext);\n if (!context) throw new Error('useCalendarPrefs must be used within CalendarPrefsProvider');\n return context;\n}\n\n/** The time zone the calendar shows: the person's choice, else this device's. */\nexport function useCalendarTimeZone(): string {\n const { prefs } = useCalendarPrefs();\n return useMemo(() => resolveTimeZone(prefs.timeZone), [prefs.timeZone]);\n}\n\n/**\n * True once the account's settings have been read (or couldn't be), or after `maxWaitMs`: for\n * one-time decisions, such as where an address redirects, that a stale device copy must not make.\n */\nexport function usePrefsSettled(maxWaitMs: number = PREFS_WAIT_MS): boolean {\n const { status } = useCalendarPrefs();\n const [waitedOut, setWaitedOut] = useState(false);\n useEffect(() => {\n if (status !== 'loading') return undefined;\n const timer = setTimeout(() => setWaitedOut(true), maxWait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AG,CAACA,EAAM,QAAQ,CAAC;AACxE;AAMA,SAAgBC,EAAgB,IAAoB1B,GAAwB;CAC1E,IAAM,EAAE,cAAWoB,EAAiB,GAC9B,CAACO,GAAWC,KAAgBjB,EAAS,EAAK;CAMhD,OALAK,QAAgB;EACd,IAAIa,MAAW,WAAW;EAC1B,IAAMC,IAAQ,iBAAiBF,EAAa,EAAI,GAAGG,CAAS;EAC5D,aAAa,aAAaD,CAAK;CACjC,GAAG,CAACD,GAAQE,CAAS,CAAC,GACfF,MAAW,aAAaF;AACjC"}
@@ -0,0 +1,73 @@
1
+ import { HourCycle, WeekStart } from '@burdenoff/fe-libs/ui';
2
+ import { CalendarV2View } from '../types';
3
+ /** The key the settings live under in the account's preferences. */
4
+ export declare const CALENDAR_PREFS_KEY = "calendar";
5
+ /** The most hidden calendars kept (the calendars query lists at most 200). */
6
+ export declare const MAX_HIDDEN_CALENDARS = 200;
7
+ /** Event lengths a person can default to, in minutes. */
8
+ export declare const MIN_DEFAULT_DURATION = 5;
9
+ export declare const MAX_DEFAULT_DURATION: number;
10
+ /** The earliest a default reminder can fire: four weeks before. */
11
+ export declare const MAX_DEFAULT_REMINDER: number;
12
+ export interface CalendarPrefs {
13
+ /** The IANA zone the calendar shows; null follows this device. */
14
+ timeZone: string | null;
15
+ /** `h23` 24-hour clock (the default), `h12` 12-hour. */
16
+ hourCycle: HourCycle;
17
+ /** 1 Monday (the default), 0 Sunday, 6 Saturday. */
18
+ weekStart: WeekStart;
19
+ showWeekends: boolean;
20
+ /** The view the calendar opens on. */
21
+ defaultView: CalendarV2View;
22
+ /** Minutes a new event lasts. */
23
+ defaultDuration: number;
24
+ /** Minutes before an event its reminder fires; null for none. */
25
+ defaultReminder: number | null;
26
+ /** Fade events that have ended. */
27
+ dimPast: boolean;
28
+ /** Show events the person declined. */
29
+ showDeclined: boolean;
30
+ /** Calendars unticked in the rail. */
31
+ hiddenCalendarIds: string[];
32
+ /** The Workflow runs layer (decision 1: off until turned on). */
33
+ runsLayer: boolean;
34
+ }
35
+ export declare const DEFAULT_CALENDAR_PREFS: Readonly<CalendarPrefs>;
36
+ /**
37
+ * The valid settings in a stored value (anything else, or a value that isn't an object, gives
38
+ * nothing). A time zone is kept as today's IANA name.
39
+ */
40
+ export declare function parseCalendarPrefs(value: unknown): Partial<CalendarPrefs>;
41
+ /** Complete settings: `prefs` over the defaults. */
42
+ export declare function withDefaults(prefs: Partial<CalendarPrefs>): CalendarPrefs;
43
+ /** The settings as stored: every key, checked, so a write never drops one. */
44
+ export declare function toStoredPrefs(prefs: CalendarPrefs): CalendarPrefs;
45
+ /** Whether two complete settings say the same. */
46
+ export declare function samePrefs(a: CalendarPrefs, b: CalendarPrefs): boolean;
47
+ /**
48
+ * Today's calendar keeps a few settings on the device (`burdenoff-calendar-storage`, the
49
+ * zustand store of the pages every other product shows). What the redesign takes from it the
50
+ * first time the account has no calendar settings.
51
+ */
52
+ export interface LegacyCalendarState {
53
+ prefs: Partial<CalendarPrefs>;
54
+ /**
55
+ * The calendars ticked there (empty: all of them). The redesign keeps the unticked ones
56
+ * instead, so these become hidden ids once the calendar list is known.
57
+ */
58
+ visibleCalendarIds: string[];
59
+ }
60
+ /**
61
+ * Reads today's stored calendar state (`{ state: { currentView, selectedTimeZone,
62
+ * visibleCalendars } }`). The last view used becomes the opening view (Year → Month,
63
+ * Timeline → Week, Agenda → List). The zone is kept only when it isn't this device's: today's
64
+ * store saves the device's zone even when nobody picked one, and keeping that would stop the
65
+ * calendar following the device. Null when there is nothing to take.
66
+ */
67
+ export declare function readLegacyCalendarState(stored: unknown, deviceTimeZone: string): LegacyCalendarState | null;
68
+ /**
69
+ * The calendars to hide so that only `visibleIds` show, from all the person's calendars.
70
+ * Nothing is hidden when `visibleIds` is empty (today's store reads that as "all") or names
71
+ * none of the calendars (they were all removed since).
72
+ */
73
+ export declare function hiddenFromVisible(visibleIds: readonly string[], allCalendarIds: readonly string[]): string[];
@@ -0,0 +1,71 @@
1
+ import { isCalendarV2View as e, viewForName as t } from "../routes.js";
2
+ import { isWeekStart as n } from "../time/calendarTime.js";
3
+ import { canonicalTimeZone as r } from "@burdenoff/fe-libs/ui";
4
+ // src/v2/prefs/calendarPrefs.ts
5
+ var i = "calendar", a = 1440, o = 40320, s = Object.freeze({
6
+ timeZone: null,
7
+ hourCycle: "h23",
8
+ weekStart: 1,
9
+ showWeekends: !0,
10
+ defaultView: "week",
11
+ defaultDuration: 60,
12
+ defaultReminder: 10,
13
+ dimPast: !0,
14
+ showDeclined: !1,
15
+ hiddenCalendarIds: [],
16
+ runsLayer: !1
17
+ });
18
+ function c(e) {
19
+ return typeof e == "object" && !!e && !Array.isArray(e);
20
+ }
21
+ function l(e, t, n) {
22
+ return typeof e == "number" && Number.isInteger(e) && e >= t && e <= n;
23
+ }
24
+ function u(e) {
25
+ if (!Array.isArray(e)) return;
26
+ let t = e.filter((e) => typeof e == "string" && e.trim() !== "");
27
+ return [...new Set(t)].sort().slice(0, 200);
28
+ }
29
+ function d(t) {
30
+ if (!c(t)) return {};
31
+ let i = {};
32
+ if (t.timeZone === null) i.timeZone = null;
33
+ else if (typeof t.timeZone == "string") {
34
+ let e = r(t.timeZone);
35
+ e && (i.timeZone = e);
36
+ }
37
+ (t.hourCycle === "h23" || t.hourCycle === "h12") && (i.hourCycle = t.hourCycle), n(t.weekStart) && (i.weekStart = t.weekStart), typeof t.showWeekends == "boolean" && (i.showWeekends = t.showWeekends), e(t.defaultView) && (i.defaultView = t.defaultView), l(t.defaultDuration, 5, 1440) && (i.defaultDuration = t.defaultDuration), t.defaultReminder === null ? i.defaultReminder = null : l(t.defaultReminder, 0, 40320) && (i.defaultReminder = t.defaultReminder), typeof t.dimPast == "boolean" && (i.dimPast = t.dimPast), typeof t.showDeclined == "boolean" && (i.showDeclined = t.showDeclined);
38
+ let a = u(t.hiddenCalendarIds);
39
+ return a && (i.hiddenCalendarIds = a), typeof t.runsLayer == "boolean" && (i.runsLayer = t.runsLayer), i;
40
+ }
41
+ function f(e) {
42
+ return {
43
+ ...s,
44
+ ...e,
45
+ hiddenCalendarIds: [...e.hiddenCalendarIds ?? s.hiddenCalendarIds]
46
+ };
47
+ }
48
+ function p(e) {
49
+ return f(d(e));
50
+ }
51
+ function m(e, n) {
52
+ let i = c(e) && c(e.state) ? e.state : null;
53
+ if (!i) return null;
54
+ let a = {}, o = t(typeof i.currentView == "string" ? i.currentView : null);
55
+ if (o && (a.defaultView = o), typeof i.selectedTimeZone == "string") {
56
+ let e = r(i.selectedTimeZone);
57
+ e && e !== r(n) && (a.timeZone = e);
58
+ }
59
+ let s = u(i.visibleCalendars) ?? [];
60
+ return Object.keys(a).length === 0 && s.length === 0 ? null : {
61
+ prefs: a,
62
+ visibleCalendarIds: s
63
+ };
64
+ }
65
+ function h(e, t) {
66
+ let n = new Set(e);
67
+ return t.some((e) => n.has(e)) ? u(t.filter((e) => !n.has(e))) ?? [] : [];
68
+ }
69
+ export { i as CALENDAR_PREFS_KEY, s as DEFAULT_CALENDAR_PREFS, a as MAX_DEFAULT_DURATION, o as MAX_DEFAULT_REMINDER, h as hiddenFromVisible, d as parseCalendarPrefs, m as readLegacyCalendarState, p as toStoredPrefs, f as withDefaults };
70
+
71
+ //# sourceMappingURL=calendarPrefs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendarPrefs.js","names":["CALENDAR_PREFS_KEY","MAX_DEFAULT_DURATION","MAX_DEFAULT_REMINDER","DEFAULT_CALENDAR_PREFS","isRecord","value","isWholeNumberWithin","min","max","parseCalendarIds","ids","id","parseCalendarPrefs","prefs","zone","canonicalTimeZone","isWeekStart","isCalendarV2View","hidden","withDefaults","toStoredPrefs","readLegacyCalendarState","state","stored","opening","viewForName","deviceTimeZone","visibleCalendarIds","hiddenFromVisible","visible","visibleIds","allCalendarIds"],"sources":["../../../src/v2/prefs/calendarPrefs.ts"],"sourcesContent":["/**\n * The person's calendar settings (BOFF-15698 B3, operator decision 6): kept on their account\n * under the `calendar` key of global-auth-svc's preferences, so they follow the person across\n * devices and workspaces.\n *\n * `updateMyPreferences` merges the keys it is given into the stored ones one level deep, so\n * the whole `calendar` object is always written (`toStoredPrefs`); a partial write would drop\n * the keys it leaves out. Everything read back is checked (`parseCalendarPrefs`): a value that\n * isn't valid falls back to its default instead of breaking the calendar.\n */\nimport { canonicalTimeZone, type HourCycle, type WeekStart } from '@burdenoff/fe-libs/ui';\nimport { isCalendarV2View, viewForName } from '../routes';\nimport { isWeekStart } from '../time/calendarTime';\nimport type { CalendarV2View } from '../types';\n\n/** The key the settings live under in the account's preferences. */\nexport const CALENDAR_PREFS_KEY = 'calendar';\n\n/** The most hidden calendars kept (the calendars query lists at most 200). */\nexport const MAX_HIDDEN_CALENDARS = 200;\n/** Event lengths a person can default to, in minutes. */\nexport const MIN_DEFAULT_DURATION = 5;\nexport const MAX_DEFAULT_DURATION = 24 * 60;\n/** The earliest a default reminder can fire: four weeks before. */\nexport const MAX_DEFAULT_REMINDER = 4 * 7 * 24 * 60;\n\nexport interface CalendarPrefs {\n /** The IANA zone the calendar shows; null follows this device. */\n timeZone: string | null;\n /** `h23` 24-hour clock (the default), `h12` 12-hour. */\n hourCycle: HourCycle;\n /** 1 Monday (the default), 0 Sunday, 6 Saturday. */\n weekStart: WeekStart;\n showWeekends: boolean;\n /** The view the calendar opens on. */\n defaultView: CalendarV2View;\n /** Minutes a new event lasts. */\n defaultDuration: number;\n /** Minutes before an event its reminder fires; null for none. */\n defaultReminder: number | null;\n /** Fade events that have ended. */\n dimPast: boolean;\n /** Show events the person declined. */\n showDeclined: boolean;\n /** Calendars unticked in the rail. */\n hiddenCalendarIds: string[];\n /** The Workflow runs layer (decision 1: off until turned on). */\n runsLayer: boolean;\n}\n\nexport const DEFAULT_CALENDAR_PREFS: Readonly<CalendarPrefs> = Object.freeze({\n timeZone: null,\n hourCycle: 'h23',\n weekStart: 1,\n showWeekends: true,\n defaultView: 'week',\n defaultDuration: 60,\n defaultReminder: 10,\n dimPast: true,\n showDeclined: false,\n hiddenCalendarIds: [],\n runsLayer: false,\n});\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isWholeNumberWithin(value: unknown, min: number, max: number): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;\n}\n\n/** The hidden calendar ids from a stored value: strings, no blanks or repeats, sorted. */\nfunction parseCalendarIds(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const ids = value.filter((id): id is string => typeof id === 'string' && id.trim() !== '');\n return [...new Set(ids)].sort().slice(0, MAX_HIDDEN_CALENDARS);\n}\n\n/**\n * The valid settings in a stored value (anything else, or a value that isn't an object, gives\n * nothing). A time zone is kept as today's IANA name.\n */\nexport function parseCalendarPrefs(value: unknown): Partial<CalendarPrefs> {\n if (!isRecord(value)) return {};\n const prefs: Partial<CalendarPrefs> = {};\n if (value.timeZone === null) prefs.timeZone = null;\n else if (typeof value.timeZone === 'string') {\n const zone = canonicalTimeZone(value.timeZone);\n if (zone) prefs.timeZone = zone;\n }\n if (value.hourCycle === 'h23' || value.hourCycle === 'h12') prefs.hourCycle = value.hourCycle;\n if (isWeekStart(value.weekStart)) prefs.weekStart = value.weekStart;\n if (typeof value.showWeekends === 'boolean') prefs.showWeekends = value.showWeekends;\n if (isCalendarV2View(value.defaultView)) prefs.defaultView = value.defaultView;\n if (isWholeNumberWithin(value.defaultDuration, MIN_DEFAULT_DURATION, MAX_DEFAULT_DURATION)) {\n prefs.defaultDuration = value.defaultDuration;\n }\n if (value.defaultReminder === null) prefs.defaultReminder = null;\n else if (isWholeNumberWithin(value.defaultReminder, 0, MAX_DEFAULT_REMINDER)) {\n prefs.defaultReminder = value.defaultReminder;\n }\n if (typeof value.dimPast === 'boolean') prefs.dimPast = value.dimPast;\n if (typeof value.showDeclined === 'boolean') prefs.showDeclined = value.showDeclined;\n const hidden = parseCalendarIds(value.hiddenCalendarIds);\n if (hidden) prefs.hiddenCalendarIds = hidden;\n if (typeof value.runsLayer === 'boolean') prefs.runsLayer = value.runsLayer;\n return prefs;\n}\n\n/** Complete settings: `prefs` over the defaults. */\nexport function withDefaults(prefs: Partial<CalendarPrefs>): CalendarPrefs {\n return {\n ...DEFAULT_CALENDAR_PREFS,\n ...prefs,\n hiddenCalendarIds: [...(prefs.hiddenCalendarIds ?? DEFAULT_CALENDAR_PREFS.hiddenCalendarIds)],\n };\n}\n\n/** The settings as stored: every key, checked, so a write never drops one. */\nexport function toStoredPrefs(prefs: CalendarPrefs): CalendarPrefs {\n return withDefaults(parseCalendarPrefs(prefs));\n}\n\n/** Whether two complete settings say the same. */\nexport function samePrefs(a: CalendarPrefs, b: CalendarPrefs): boolean {\n return JSON.stringify(toStoredPrefs(a)) === JSON.stringify(toStoredPrefs(b));\n}\n\n/**\n * Today's calendar keeps a few settings on the device (`burdenoff-calendar-storage`, the\n * zustand store of the pages every other product shows). What the redesign takes from it the\n * first time the account has no calendar settings.\n */\nexport interface LegacyCalendarState {\n prefs: Partial<CalendarPrefs>;\n /**\n * The calendars ticked there (empty: all of them). The redesign keeps the unticked ones\n * instead, so these become hidden ids once the calendar list is known.\n */\n visibleCalendarIds: string[];\n}\n\n/**\n * Reads today's stored calendar state (`{ state: { currentView, selectedTimeZone,\n * visibleCalendars } }`). The last view used becomes the opening view (Year → Month,\n * Timeline → Week, Agenda → List). The zone is kept only when it isn't this device's: today's\n * store saves the device's zone even when nobody picked one, and keeping that would stop the\n * calendar following the device. Null when there is nothing to take.\n */\nexport function readLegacyCalendarState(\n stored: unknown,\n deviceTimeZone: string\n): LegacyCalendarState | null {\n const state = isRecord(stored) && isRecord(stored.state) ? stored.state : null;\n if (!state) return null;\n const prefs: Partial<CalendarPrefs> = {};\n const opening = viewForName(typeof state.currentView === 'string' ? state.currentView : null);\n if (opening) prefs.defaultView = opening;\n if (typeof state.selectedTimeZone === 'string') {\n const zone = canonicalTimeZone(state.selectedTimeZone);\n if (zone && zone !== canonicalTimeZone(deviceTimeZone)) prefs.timeZone = zone;\n }\n const visibleCalendarIds = parseCalendarIds(state.visibleCalendars) ?? [];\n if (Object.keys(prefs).length === 0 && visibleCalendarIds.length === 0) return null;\n return { prefs, visibleCalendarIds };\n}\n\n/**\n * The calendars to hide so that only `visibleIds` show, from all the person's calendars.\n * Nothing is hidden when `visibleIds` is empty (today's store reads that as \"all\") or names\n * none of the calendars (they were all removed since).\n */\nexport function hiddenFromVisible(\n visibleIds: readonly string[],\n allCalendarIds: readonly string[]\n): string[] {\n const visible = new Set(visibleIds);\n if (!allCalendarIds.some((id) => visible.has(id))) return [];\n return parseCalendarIds(allCalendarIds.filter((id) => !visible.has(id))) ?? [];\n}\n"],"mappings":";;;;AAgBA,IAAaA,IAAqB,YAMrBC,IAAuB,MAEvBC,IAAuB,OA0BvBC,IAAkD,OAAO,OAAO;CAC3E,UAAU;CACV,WAAW;CACX,WAAW;CACX,cAAc;CACd,aAAa;CACb,iBAAiB;CACjB,iBAAiB;CACjB,SAAS;CACT,cAAc;CACd,mBAAmB,CAAC;CACpB,WAAW;AACb,CAAC;AAED,SAASC,EAAS,GAAkD;CAClE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAASC,EAAoB,GAAgB,GAAa,GAA8B;CACtF,OAAO,OAAOD,KAAU,YAAY,OAAO,UAAUA,CAAK,KAAKA,KAASE,KAAOF,KAASG;AAC1F;AAGA,SAASC,EAAiB,GAAsC;CAC9D,IAAI,CAAC,MAAM,QAAQJ,CAAK,GAAG;CAC3B,IAAMK,IAAML,EAAM,QAAQ,MAAqB,OAAOM,KAAO,YAAYA,EAAG,KAAK,MAAM,EAAE;CACzF,OAAO,CAAC,GAAG,IAAI,IAAID,CAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,GAAA,GAAuB;AAC/D;AAMA,SAAgBE,EAAmB,GAAwC;CACzE,IAAI,CAACR,EAASC,CAAK,GAAG,OAAO,CAAC;CAC9B,IAAMQ,IAAgC,C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AAUC,EAAY,OAAOH,EAAM,eAAgB,WAAWA,EAAM,cAAc,IAAI;CAE5F,IADIE,MAAS,EAAM,cAAcA,IAC7B,OAAOF,EAAM,oBAAqB,UAAU;EAC9C,IAAMR,IAAOC,EAAkBO,EAAM,gBAAgB;EACrD,AAAIR,KAAQA,MAASC,EAAkBW,CAAc,MAAG,EAAM,WAAWZ;CAC3E;CACA,IAAMa,IAAqBlB,EAAiBa,EAAM,gBAAgB,KAAK,CAAC;CAExE,OADI,OAAO,KAAKT,CAAK,CAAC,CAAC,WAAW,KAAKc,EAAmB,WAAW,IAAU,OACxE;EAAE;EAAO;CAAmB;AACrC;AAOA,SAAgBC,EACd,GACA,GACU;CACV,IAAMC,IAAU,IAAI,IAAIC,CAAU;CAElC,OADKC,EAAe,MAAM,MAAOF,EAAQ,IAAIlB,CAAE,CAAC,IACzCF,EAAiBsB,EAAe,QAAQ,MAAO,CAACF,EAAQ,IAAIlB,CAAE,CAAC,CAAC,KAAK,CAAC,IADnB,CAAC;AAE7D"}
@@ -0,0 +1,16 @@
1
+ import { CalendarPrefs } from './calendarPrefs';
2
+ export interface CalendarPrefsApi {
3
+ /** The stored `calendar` value; undefined when the account has none yet. Throws when unreadable. */
4
+ load: () => Promise<unknown>;
5
+ /** Writes the whole `calendar` object. Throws when it wasn't saved. */
6
+ save: (prefs: CalendarPrefs, options?: {
7
+ keepalive?: boolean;
8
+ }) => Promise<void>;
9
+ /**
10
+ * Writes carry this person's own token, so a write made while leaving (even as another
11
+ * person signs in) still reaches the right account. Without it, leaving writes nothing and
12
+ * the change waits in the device copy.
13
+ */
14
+ canWriteOnExit?: boolean;
15
+ }
16
+ export declare function createCalendarPrefsApi(authToken?: string): CalendarPrefsApi;
@@ -0,0 +1,46 @@
1
+ import { CalendarV2MyPreferencesDocument as e, CalendarV2SavePreferencesDocument as t } from "../../generated/global-operations.js";
2
+ import { CALENDAR_PREFS_KEY as n } from "./calendarPrefs.js";
3
+ import { print as r } from "graphql";
4
+ import { graphqlFetch as i } from "@burdenoff/fe-libs/shared/graphql";
5
+ // src/v2/prefs/prefsApi.ts
6
+ function a(e, t) {
7
+ let n = e.errors?.[0]?.message;
8
+ return n ? Error(n) : e.data ? null : Error(t);
9
+ }
10
+ function o(e) {
11
+ return typeof e == "object" && !!e && !Array.isArray(e);
12
+ }
13
+ function s(s) {
14
+ return {
15
+ canWriteOnExit: !!s,
16
+ async load() {
17
+ let t = await i({
18
+ gateway: "global",
19
+ authToken: s,
20
+ query: r(e),
21
+ operationName: "CalendarV2MyPreferences",
22
+ responseCache: "reload",
23
+ suppressGlobalErrorEvent: !0
24
+ }), c = a(t, "Your calendar settings could not be read");
25
+ if (c) throw c;
26
+ let l = t.data?.myPreferences?.preferences;
27
+ return o(l) ? l[n] : void 0;
28
+ },
29
+ async save(e, o = {}) {
30
+ let c = a(await i({
31
+ gateway: "global",
32
+ authToken: s,
33
+ query: r(t),
34
+ operationName: "CalendarV2SavePreferences",
35
+ variables: { input: { [n]: e } },
36
+ keepalive: o.keepalive,
37
+ authTokenMode: o.keepalive && s ? "pinned" : void 0,
38
+ suppressGlobalErrorEvent: !0
39
+ }), "Your calendar settings were not saved");
40
+ if (c) throw c;
41
+ }
42
+ };
43
+ }
44
+ export { s as createCalendarPrefsApi };
45
+
46
+ //# sourceMappingURL=prefsApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefsApi.js","names":["failure","message","response","fallback","isRecord","value","createCalendarPrefsApi","authToken","graphqlFetch","print","CalendarV2MyPreferencesDocument","error","preferences","CALENDAR_PREFS_KEY","CalendarV2SavePreferencesDocument","prefs","options"],"sources":["../../../src/v2/prefs/prefsApi.ts"],"sourcesContent":["/**\n * Reading and writing the person's calendar settings on their account (BOFF-15698 B3):\n * global-auth-svc's `myPreferences` / `updateMyPreferences` on the global gateway, called the\n * way the Workspaces dashboard calls its preferences (`graphqlFetch`, gateway `global`).\n */\nimport { print } from 'graphql';\nimport { graphqlFetch, type GraphQLResponse } from '@burdenoff/fe-libs/shared/graphql';\nimport {\n CalendarV2MyPreferencesDocument,\n CalendarV2SavePreferencesDocument,\n type CalendarV2MyPreferencesQuery,\n type CalendarV2SavePreferencesMutation,\n} from '../../generated/global-operations';\nimport { CALENDAR_PREFS_KEY, type CalendarPrefs } from './calendarPrefs';\n\nexport interface CalendarPrefsApi {\n /** The stored `calendar` value; undefined when the account has none yet. Throws when unreadable. */\n load: () => Promise<unknown>;\n /** Writes the whole `calendar` object. Throws when it wasn't saved. */\n save: (prefs: CalendarPrefs, options?: { keepalive?: boolean }) => Promise<void>;\n /**\n * Writes carry this person's own token, so a write made while leaving (even as another\n * person signs in) still reaches the right account. Without it, leaving writes nothing and\n * the change waits in the device copy.\n */\n canWriteOnExit?: boolean;\n}\n\nfunction failure(response: GraphQLResponse<unknown>, fallback: string): Error | null {\n const message = response.errors?.[0]?.message;\n if (message) return new Error(message);\n return response.data ? null : new Error(fallback);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function createCalendarPrefsApi(authToken?: string): CalendarPrefsApi {\n return {\n canWriteOnExit: Boolean(authToken),\n\n async load() {\n const response = await graphqlFetch<CalendarV2MyPreferencesQuery>({\n gateway: 'global',\n authToken,\n query: print(CalendarV2MyPreferencesDocument),\n operationName: 'CalendarV2MyPreferences',\n responseCache: 'reload',\n // The calendar shows this device's copy when the account can't be read.\n suppressGlobalErrorEvent: true,\n });\n const error = failure(response, 'Your calendar settings could not be read');\n if (error) throw error;\n const preferences = response.data?.myPreferences?.preferences;\n return isRecord(preferences) ? preferences[CALENDAR_PREFS_KEY] : undefined;\n },\n\n async save(prefs, options = {}) {\n const response = await graphqlFetch<CalendarV2SavePreferencesMutation>({\n gateway: 'global',\n authToken,\n query: print(CalendarV2SavePreferencesDocument),\n operationName: 'CalendarV2SavePreferences',\n variables: { input: { [CALENDAR_PREFS_KEY]: prefs } },\n keepalive: options.keepalive,\n // Leaving the page: the bearer this calendar was given, never another profile's.\n authTokenMode: options.keepalive && authToken ? 'pinned' : undefined,\n // The settings dialog says when a change wasn't saved; the calendar keeps it and retries.\n suppressGlobalErrorEvent: true,\n });\n const error = failure(response, 'Your calendar settings were not saved');\n if (error) throw error;\n },\n };\n}\n"],"mappings":";;;;;AA4BA,SAASA,EAAQ,GAAoC,GAAgC;CACnF,IAAMC,IAAUC,EAAS,SAAS,EAAE,EAAE;CAEtC,OADID,IAAoB,MAAMA,CAAO,IAC9BC,EAAS,OAAO,OAAW,MAAMC,CAAQ;AAClD;AAEA,SAASC,EAAS,GAAkD;CAClE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAAgBC,EAAuB,GAAsC;CAC3E,OAAO;EACL,gBAAgB,EAAQC;EAExB,MAAM,OAAO;GACX,IAAML,IAAW,MAAMM,EAA2C;IAChE,SAAS;IACT;IACA,OAAOC,EAAMC,CAA+B;IAC5C,eAAe;IACf,eAAe;IAEf,0BAA0B;GAC5B,CAAC,GACKC,IAAQX,EAAQE,GAAU,0CAA0C;GAC1E,IAAIS,GAAO,MAAMA;GACjB,IAAMC,IAAcV,EAAS,MAAM,eAAe;GAClD,OAAOE,EAASQ,CAAW,IAAIA,EAAYC,KAAsB,KAAA;EACnE;EAEA,MAAM,KAAK,GAAO,IAAU,CAAC,GAAG;GAa9B,IAAMF,IAAQX,EAAQ,MAZCQ,EAAgD;IACrE,SAAS;IACT;IACA,OAAOC,EAAMK,CAAiC;IAC9C,eAAe;IACf,WAAW,EAAE,OAAO,GAAGD,IAAqBE,EAAM,EAAE;IACpD,WAAWC,EAAQ;IAEnB,eAAeA,EAAQ,aAAaT,IAAY,WAAW,KAAA;IAE3D,0BAA0B;GAC5B,CAAC,GAC+B,uCAAuC;GACvE,IAAII,GAAO,MAAMA;EACnB;CACF;AACF"}
@@ -0,0 +1,55 @@
1
+ import { CalendarPrefs } from './calendarPrefs';
2
+ import { CalendarPrefsApi } from './prefsApi';
3
+ /** How long after the last change the settings are written. */
4
+ export declare const SAVE_DELAY_MS = 500;
5
+ export interface PrefsSnapshot {
6
+ prefs: CalendarPrefs;
7
+ /** `loading` until the account is read; `offline` when it couldn't be (retried). */
8
+ status: 'loading' | 'ready' | 'offline';
9
+ /** Where `prefs` came from. */
10
+ source: 'account' | 'device' | 'defaults';
11
+ /** `error`: a change wasn't saved; it is kept and saved again with the next one. */
12
+ saveState: 'idle' | 'saving' | 'error';
13
+ /** Changes when settings arrive from the account, not when changed here. */
14
+ revision: number;
15
+ /** Today's calendar's ticked calendars, on the first visit of an account with no settings. */
16
+ legacyVisibleCalendarIds: readonly string[] | null;
17
+ }
18
+ /** What shows before the account answers. */
19
+ export interface InitialPrefs {
20
+ prefs: CalendarPrefs;
21
+ source: 'device' | 'defaults';
22
+ /** Changes this device made that the account never confirmed. */
23
+ pending: Partial<CalendarPrefs>;
24
+ /** Today's calendar's ticked calendars, when the settings came from it. */
25
+ legacyVisibleCalendarIds: readonly string[] | null;
26
+ }
27
+ export interface PrefsSessionOptions {
28
+ api: CalendarPrefsApi;
29
+ initial: InitialPrefs;
30
+ /** Keeps this device's copy of the settings, with the changes not yet confirmed. */
31
+ saveDeviceCopy: (prefs: CalendarPrefs, pending: Partial<CalendarPrefs>) => void;
32
+ saveDelayMs?: number;
33
+ }
34
+ export interface PrefsSession {
35
+ getSnapshot: () => PrefsSnapshot;
36
+ subscribe: (listener: () => void) => () => void;
37
+ /** Starts (or restarts) the visit: reads the account unless it was read. */
38
+ start: () => void;
39
+ /**
40
+ * Leaving: writes what is waiting at once when the API carries this person's own token
41
+ * (`canWriteOnExit`), then stops; anything unwritten stays in the device copy.
42
+ */
43
+ stop: () => void;
44
+ /** Reads the account (again, after a failure); a no-op once read or while reading. */
45
+ load: () => void;
46
+ update: (patch: Partial<CalendarPrefs>) => void;
47
+ /** Writes waiting changes now; `keepalive` when the page is going away (sent at once). */
48
+ flush: (keepalive?: boolean) => void;
49
+ /** Back online: read the account if it wasn't, else write what is waiting. */
50
+ retry: () => void;
51
+ clearLegacyVisibleCalendarIds: () => void;
52
+ /** The same person's new token. */
53
+ setApi: (api: CalendarPrefsApi) => void;
54
+ }
55
+ export declare function createPrefsSession(options: PrefsSessionOptions): PrefsSession;
@@ -0,0 +1,94 @@
1
+ import { DEFAULT_CALENDAR_PREFS as e, parseCalendarPrefs as t, toStoredPrefs as n, withDefaults as r } from "./calendarPrefs.js";
2
+ function i(e, t) {
3
+ return JSON.stringify(e) === JSON.stringify(t);
4
+ }
5
+ function a(t) {
6
+ return Object.hasOwn(e, t);
7
+ }
8
+ function o(e) {
9
+ let o = e.saveDelayMs ?? 500, s = e.api, c = {
10
+ prefs: e.initial.prefs,
11
+ status: "loading",
12
+ source: e.initial.source,
13
+ saveState: "idle",
14
+ revision: 0,
15
+ legacyVisibleCalendarIds: null
16
+ }, l = /* @__PURE__ */ new Set(), u = t(e.initial.pending), d = 0, f = -1, p = !1, m = !1, h = 0, g = !1, _ = !1, v = !1, y = null, b = (e) => {
17
+ c = {
18
+ ...c,
19
+ ...e
20
+ };
21
+ for (let e of l) e();
22
+ }, x = () => Object.keys(u).length > 0, S = () => e.saveDeviceCopy(c.prefs, u), C = () => {
23
+ y &&= (clearTimeout(y), null);
24
+ }, w = (e) => {
25
+ let t = d;
26
+ h += 1, b({ saveState: "saving" }), s.save(n(c.prefs), { keepalive: e }).then(() => {
27
+ --h, t < f ? _ = !0 : f = t, v ? _ && h === 0 && s.canWriteOnExit && (_ = !1, w(!0)) : (f === d && !_ && (u = {}, S()), h > 0 || (b({ saveState: "idle" }), _ ? (_ = !1, u = { ...c.prefs }, S(), T()) : (g || d !== f) && (g = !1, T())));
28
+ }, () => {
29
+ --h, v || h > 0 || (g = !1, b({ saveState: "error" }));
30
+ });
31
+ }, T = (e = !1) => {
32
+ C(), !v && p && x() && (h > 0 && !e ? g = !0 : w(e));
33
+ }, E = (e) => {
34
+ C(), v || (y = setTimeout(() => T(), e));
35
+ }, D = () => {
36
+ v || p || m || (m = !0, s.load().then((n) => {
37
+ if (m = !1, v) return;
38
+ p = !0;
39
+ let i = n != null, a = i ? r(t(n)) : c.prefs, o = r({
40
+ ...a,
41
+ ...u
42
+ });
43
+ !i && e.initial.source !== "defaults" && (u = { ...o }), b({
44
+ prefs: o,
45
+ status: "ready",
46
+ source: "account",
47
+ revision: c.revision + 1,
48
+ legacyVisibleCalendarIds: i ? null : e.initial.legacyVisibleCalendarIds
49
+ }), S(), x() && E(0);
50
+ }, () => {
51
+ m = !1, v || b({ status: "offline" });
52
+ }));
53
+ };
54
+ return {
55
+ getSnapshot: () => c,
56
+ subscribe: (e) => (l.add(e), () => {
57
+ l.delete(e);
58
+ }),
59
+ start: () => {
60
+ v = !1, D();
61
+ },
62
+ stop: () => {
63
+ s.canWriteOnExit && T(!0), C(), v = !0;
64
+ },
65
+ load: D,
66
+ update: (e) => {
67
+ if (v) return;
68
+ let n = c.prefs, s = r({
69
+ ...n,
70
+ ...t({
71
+ ...n,
72
+ ...e
73
+ })
74
+ }), l = Object.keys(e).filter(a).filter((e) => !i(s[e], n[e]));
75
+ if (l.length === 0) return;
76
+ let f = { ...u };
77
+ for (let e of l) Object.assign(f, { [e]: s[e] });
78
+ u = f, d += 1, b({ prefs: s }), S(), p ? E(o) : D();
79
+ },
80
+ flush: T,
81
+ retry: () => {
82
+ p ? T() : D();
83
+ },
84
+ clearLegacyVisibleCalendarIds: () => {
85
+ c.legacyVisibleCalendarIds !== null && b({ legacyVisibleCalendarIds: null });
86
+ },
87
+ setApi: (e) => {
88
+ s = e;
89
+ }
90
+ };
91
+ }
92
+ export { o as createPrefsSession };
93
+
94
+ //# sourceMappingURL=prefsSession.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefsSession.js","names":["same","a","b","isPrefsKey","DEFAULT_CALENDAR_PREFS","key","createPrefsSession","delay","options","api","snapshot","listeners","dirty","parseCalendarPrefs","version","confirmed","loaded","loading","inFlight","writeAgain","stale","stopped","timer","emit","patch","listener","hasDirty","keepCopy","clearTimer","send","sent","toStoredPrefs","flush","keepalive","scheduleSave","wait","load","hasStored","stored","base","withDefaults","prefs","current","next","changed","nextDirty"],"sources":["../../../src/v2/prefs/prefsSession.ts"],"sourcesContent":["/**\n * The person's calendar settings for one visit of the redesigned calendar (BOFF-15698 B3):\n * read once from the account, changed at once, written back shortly after the last change.\n * Plain code (no React), so `CalendarPrefsProvider` stays a thin wrapper.\n *\n * - Before the account has been read, `prefs` is this device's copy (or the defaults).\n * - Nothing is written until the account has been read: writing the whole `calendar` object\n * from a fallback would overwrite settings made on another device. Changes made meanwhile are\n * laid over what the account says and written once it has been read.\n * - Changes the account hasn't confirmed stay in the device copy (`pending`) and are laid over\n * the account on the next visit, so a change made as the page closed is never lost.\n * - The first time the account has no calendar settings, what this device had is written to\n * it (never bare defaults, so later default changes still reach the person).\n * - One write at a time, so an older write can't land after a newer one. Only a page that is\n * going away sends its newest settings at once (keepalive); should an older write still land\n * after a newer one, the newest is written again.\n */\nimport {\n DEFAULT_CALENDAR_PREFS,\n parseCalendarPrefs,\n toStoredPrefs,\n withDefaults,\n type CalendarPrefs,\n} from './calendarPrefs';\nimport type { CalendarPrefsApi } from './prefsApi';\n\n/** How long after the last change the settings are written. */\nexport const SAVE_DELAY_MS = 500;\n\nexport interface PrefsSnapshot {\n prefs: CalendarPrefs;\n /** `loading` until the account is read; `offline` when it couldn't be (retried). */\n status: 'loading' | 'ready' | 'offline';\n /** Where `prefs` came from. */\n source: 'account' | 'device' | 'defaults';\n /** `error`: a change wasn't saved; it is kept and saved again with the next one. */\n saveState: 'idle' | 'saving' | 'error';\n /** Changes when settings arrive from the account, not when changed here. */\n revision: number;\n /** Today's calendar's ticked calendars, on the first visit of an account with no settings. */\n legacyVisibleCalendarIds: readonly string[] | null;\n}\n\n/** What shows before the account answers. */\nexport interface InitialPrefs {\n prefs: CalendarPrefs;\n source: 'device' | 'defaults';\n /** Changes this device made that the account never confirmed. */\n pending: Partial<CalendarPrefs>;\n /** Today's calendar's ticked calendars, when the settings came from it. */\n legacyVisibleCalendarIds: readonly string[] | null;\n}\n\nexport interface PrefsSessionOptions {\n api: CalendarPrefsApi;\n initial: InitialPrefs;\n /** Keeps this device's copy of the settings, with the changes not yet confirmed. */\n saveDeviceCopy: (prefs: CalendarPrefs, pending: Partial<CalendarPrefs>) => void;\n saveDelayMs?: number;\n}\n\nexport interface PrefsSession {\n getSnapshot: () => PrefsSnapshot;\n subscribe: (listener: () => void) => () => void;\n /** Starts (or restarts) the visit: reads the account unless it was read. */\n start: () => void;\n /**\n * Leaving: writes what is waiting at once when the API carries this person's own token\n * (`canWriteOnExit`), then stops; anything unwritten stays in the device copy.\n */\n stop: () => void;\n /** Reads the account (again, after a failure); a no-op once read or while reading. */\n load: () => void;\n update: (patch: Partial<CalendarPrefs>) => void;\n /** Writes waiting changes now; `keepalive` when the page is going away (sent at once). */\n flush: (keepalive?: boolean) => void;\n /** Back online: read the account if it wasn't, else write what is waiting. */\n retry: () => void;\n clearLegacyVisibleCalendarIds: () => void;\n /** The same person's new token. */\n setApi: (api: CalendarPrefsApi) => void;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction isPrefsKey(key: string): key is keyof CalendarPrefs {\n return Object.hasOwn(DEFAULT_CALENDAR_PREFS, key);\n}\n\nexport function createPrefsSession(options: PrefsSessionOptions): PrefsSession {\n const delay = options.saveDelayMs ?? SAVE_DELAY_MS;\n let api = options.api;\n let snapshot: PrefsSnapshot = {\n prefs: options.initial.prefs,\n status: 'loading',\n source: options.initial.source,\n saveState: 'idle',\n revision: 0,\n legacyVisibleCalendarIds: null,\n };\n const listeners = new Set<() => void>();\n /** Settings changed here (or on an earlier visit) and not yet confirmed by the account. */\n let dirty: Partial<CalendarPrefs> = parseCalendarPrefs(options.initial.pending);\n /** Counts changes; each write remembers the count it carried. */\n let version = 0;\n /** The newest count the account is known to hold. */\n let confirmed = -1;\n let loaded = false;\n let loading = false;\n let inFlight = 0;\n /** A write was asked for while another was on its way. */\n let writeAgain = false;\n /** An older write landed after a newer one: the account holds stale settings. */\n let stale = false;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const emit = (patch: Partial<PrefsSnapshot>) => {\n snapshot = { ...snapshot, ...patch };\n for (const listener of listeners) listener();\n };\n const hasDirty = () => Object.keys(dirty).length > 0;\n const keepCopy = () => options.saveDeviceCopy(snapshot.prefs, dirty);\n const clearTimer = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n const send = (keepalive: boolean) => {\n const sent = version;\n inFlight += 1;\n emit({ saveState: 'saving' });\n api.save(toStoredPrefs(snapshot.prefs), { keepalive }).then(\n () => {\n inFlight -= 1;\n if (sent < confirmed) stale = true;\n else confirmed = sent;\n if (stopped) {\n // Left (or another person signed in): the device copy may be someone else's now, but a\n // stale landing is still put right, on this person's own token.\n if (stale && inFlight === 0 && api.canWriteOnExit) {\n stale = false;\n send(true);\n }\n return;\n }\n if (confirmed === version && !stale) {\n dirty = {};\n keepCopy();\n }\n if (inFlight > 0) return;\n emit({ saveState: 'idle' });\n if (stale) {\n // Write the newest again, whole.\n stale = false;\n dirty = { ...snapshot.prefs };\n keepCopy();\n flush();\n } else if (writeAgain || version !== confirmed) {\n writeAgain = false;\n flush();\n }\n },\n () => {\n inFlight -= 1;\n if (stopped || inFlight > 0) return;\n writeAgain = false;\n emit({ saveState: 'error' });\n }\n );\n };\n\n const flush = (keepalive = false) => {\n clearTimer();\n if (stopped || !loaded || !hasDirty()) return;\n if (inFlight > 0 && !keepalive) {\n writeAgain = true;\n return;\n }\n send(keepalive);\n };\n\n const scheduleSave = (wait: number) => {\n clearTimer();\n if (!stopped) timer = setTimeout(() => flush(), wait);\n };\n\n const load = () => {\n if (stopped || loaded || loading) return;\n loading = true;\n api.load().then(\n (stored) => {\n loading = false;\n // Stopped meanwhile: the answer may be for someone else now; a restart reads again.\n if (stopped) return;\n loaded = true;\n const hasStored = stored !== undefined && stored !== null;\n const base = hasStored ? withDefaults(parseCalendarPrefs(stored)) : snapshot.prefs;\n const prefs = withDefaults({ ...base, ...dirty });\n if (!hasStored && options.initial.source !== 'defaults') dirty = { ...prefs };\n emit({\n prefs,\n status: 'ready',\n source: 'account',\n revision: snapshot.revision + 1,\n legacyVisibleCalendarIds: hasStored ? null : options.initial.legacyVisibleCalendarIds,\n });\n keepCopy();\n if (hasDirty()) scheduleSave(0);\n },\n () => {\n loading = false;\n if (!stopped) emit({ status: 'offline' });\n }\n );\n };\n\n const update = (patch: Partial<CalendarPrefs>) => {\n if (stopped) return;\n const current = snapshot.prefs;\n // A value that isn't valid is dropped by the parse, so the current one stays.\n const next = withDefaults({ ...current, ...parseCalendarPrefs({ ...current, ...patch }) });\n const changed = Object.keys(patch)\n .filter(isPrefsKey)\n .filter((key) => !same(next[key], current[key]));\n if (changed.length === 0) return;\n const nextDirty: Partial<CalendarPrefs> = { ...dirty };\n for (const key of changed) Object.assign(nextDirty, { [key]: next[key] });\n dirty = nextDirty;\n version += 1;\n emit({ prefs: next });\n keepCopy();\n if (loaded) scheduleSave(delay);\n else load();\n };\n\n return {\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n start: () => {\n stopped = false;\n load();\n },\n stop: () => {\n if (api.canWriteOnExit) flush(true);\n clearTimer();\n stopped = true;\n },\n load,\n update,\n flush,\n retry: () => {\n if (!loaded) load();\n else flush();\n },\n clearLegacyVisibleCalendarIds: () => {\n if (snapshot.legacyVisibleCalendarIds !== null) emit({ legacyVisibleCalendarIds: null });\n },\n setApi: (next) => {\n api = next;\n },\n };\n}\n"],"mappings":";AAmFA,SAASA,EAAK,GAAY,GAAqB;CAC7C,OAAO,KAAK,UAAUC,CAAC,MAAM,KAAK,UAAUC,CAAC;AAC/C;AAEA,SAASC,EAAW,GAAyC;CAC3D,OAAO,OAAO,OAAOC,GAAwBC,CAAG;AAClD;AAEA,SAAgBC,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ACb,IAAMqB,IAAUhC,EAAS,OAEnBiC,IAAOH,EAAa;IAAE,GAAGE;IAAS,GAAG7B,EAAmB;KAAE,GAAG6B;KAAS,GAAGlB;IAAM,CAAC;GAAE,CAAC,GACnFoB,IAAU,OAAO,KAAKpB,CAAK,CAAC,CAC/B,OAAOrB,CAAU,CAAC,CAClB,QAAQ,MAAQ,CAACH,EAAK2C,EAAKtC,IAAMqC,EAAQrC,EAAI,CAAC;GACjD,IAAIuC,EAAQ,WAAW,GAAG;GAC1B,IAAMC,IAAoC,EAAE,GAAGjC,EAAM;GACrD,KAAK,IAAMP,KAAOuC,GAAS,OAAO,OAAOC,GAAW,GAAGxC,IAAMsC,EAAKtC,GAAK,CAAC;GAKxE,AAJA,IAAQwC,GACR,KAAW,GACXtB,EAAK,EAAE,OAAOoB,EAAK,CAAC,GACpBhB,EAAS,GACLX,IAAQkB,EAAa3B,CAAK,IACzB6B,EAAK;EACZ;EAqBE;EACA,aAAa;GACX,AAAKpB,IACAgB,EAAM,IADEI,EAAK;EAEpB;EACA,qCAAqC;GACnC,AAAI1B,EAAS,6BAA6B,QAAMa,EAAK,EAAE,0BAA0B,KAAK,CAAC;EACzF;EACA,SAAS,MAAS;GAChB,IAAMoB;EACR;CACF;AACF"}
@@ -0,0 +1,17 @@
1
+ import { CalendarPrefs } from './calendarPrefs';
2
+ import { InitialPrefs } from './prefsSession';
3
+ /** Where today's calendar keeps its settings on this device (its zustand store). */
4
+ export declare const LEGACY_STORAGE_KEY = "burdenoff-calendar-storage";
5
+ /** This device's copy of the account's calendar settings. */
6
+ export declare const DEVICE_PREFS_KEY = "burdenoff-calendar-v2-prefs";
7
+ /** What the device copy holds. */
8
+ export interface DevicePrefsCopy {
9
+ prefs: CalendarPrefs;
10
+ /** Changes made on this device that the account hasn't confirmed. */
11
+ pending: Partial<CalendarPrefs>;
12
+ }
13
+ /** This device's copy, checked; null when there is none. */
14
+ export declare function readDeviceCopy(): DevicePrefsCopy | null;
15
+ export declare function saveDeviceCopy(prefs: CalendarPrefs, pending: Partial<CalendarPrefs>): void;
16
+ /** This device's copy, else today's calendar's settings, else the defaults. */
17
+ export declare function readInitialPrefs(): InitialPrefs;
@@ -0,0 +1,56 @@
1
+ import { resolveTimeZone as e } from "../time/calendarTime.js";
2
+ import { parseCalendarPrefs as t, readLegacyCalendarState as n, withDefaults as r } from "./calendarPrefs.js";
3
+ import { getProfileScopedKey as i } from "@burdenoff/fe-libs/shared/utils";
4
+ // src/v2/prefs/prefsStorage.ts
5
+ var a = "burdenoff-calendar-storage", o = "burdenoff-calendar-v2-prefs";
6
+ function s(e) {
7
+ return typeof e == "object" && !!e && !Array.isArray(e);
8
+ }
9
+ function c(e) {
10
+ try {
11
+ let t = window.localStorage.getItem(i(e));
12
+ return t === null ? null : JSON.parse(t);
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+ function l() {
18
+ let e = c(o);
19
+ return !s(e) || !s(e.prefs) ? null : {
20
+ prefs: r(t(e.prefs)),
21
+ pending: t(e.pending)
22
+ };
23
+ }
24
+ function u(e, t) {
25
+ let n = {
26
+ prefs: e,
27
+ pending: t
28
+ };
29
+ try {
30
+ window.localStorage.setItem(i(o), JSON.stringify(n));
31
+ } catch {}
32
+ }
33
+ function d() {
34
+ let t = l();
35
+ if (t) return {
36
+ prefs: t.prefs,
37
+ source: "device",
38
+ pending: t.pending,
39
+ legacyVisibleCalendarIds: null
40
+ };
41
+ let i = n(c(a), e(null));
42
+ return i ? {
43
+ prefs: r(i.prefs),
44
+ source: "device",
45
+ pending: {},
46
+ legacyVisibleCalendarIds: i.visibleCalendarIds.length > 0 ? i.visibleCalendarIds : null
47
+ } : {
48
+ prefs: r({}),
49
+ source: "defaults",
50
+ pending: {},
51
+ legacyVisibleCalendarIds: null
52
+ };
53
+ }
54
+ export { o as DEVICE_PREFS_KEY, a as LEGACY_STORAGE_KEY, l as readDeviceCopy, d as readInitialPrefs, u as saveDeviceCopy };
55
+
56
+ //# sourceMappingURL=prefsStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefsStorage.js","names":["LEGACY_STORAGE_KEY","DEVICE_PREFS_KEY","isRecord","value","readStorage","text","getProfileScopedKey","key","readDeviceCopy","stored","withDefaults","parseCalendarPrefs","saveDeviceCopy","copy","readInitialPrefs","device","legacy","readLegacyCalendarState","resolveTimeZone"],"sources":["../../../src/v2/prefs/prefsStorage.ts"],"sourcesContent":["/**\n * The calendar settings kept on this device (BOFF-15698 B3), per signed-in profile:\n *\n * - `burdenoff-calendar-v2-prefs`: this device's copy of the account's settings, with the\n * changes made here that the account hasn't confirmed yet (`pending`). The next visit lays\n * `pending` over what the account says and writes it, so a change made just before the page\n * closed (or before a write failed) is never lost.\n * - `burdenoff-calendar-storage`: today's calendar's own settings (its zustand store), read once\n * for the first visit of an account with no calendar settings.\n */\nimport { getProfileScopedKey } from '@burdenoff/fe-libs/shared/utils';\nimport { resolveTimeZone } from '../time/calendarTime';\nimport {\n parseCalendarPrefs,\n readLegacyCalendarState,\n withDefaults,\n type CalendarPrefs,\n} from './calendarPrefs';\nimport type { InitialPrefs } from './prefsSession';\n\n/** Where today's calendar keeps its settings on this device (its zustand store). */\nexport const LEGACY_STORAGE_KEY = 'burdenoff-calendar-storage';\n/** This device's copy of the account's calendar settings. */\nexport const DEVICE_PREFS_KEY = 'burdenoff-calendar-v2-prefs';\n\n/** What the device copy holds. */\nexport interface DevicePrefsCopy {\n prefs: CalendarPrefs;\n /** Changes made on this device that the account hasn't confirmed. */\n pending: Partial<CalendarPrefs>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A value kept on this device for the signed-in profile; null when absent or unreadable. */\nfunction readStorage(key: string): unknown {\n try {\n const text = window.localStorage.getItem(getProfileScopedKey(key));\n if (text === null) return null;\n const value: unknown = JSON.parse(text);\n return value;\n } catch {\n return null;\n }\n}\n\n/** This device's copy, checked; null when there is none. */\nexport function readDeviceCopy(): DevicePrefsCopy | null {\n const stored = readStorage(DEVICE_PREFS_KEY);\n if (!isRecord(stored) || !isRecord(stored.prefs)) return null;\n return {\n prefs: withDefaults(parseCalendarPrefs(stored.prefs)),\n pending: parseCalendarPrefs(stored.pending),\n };\n}\n\nexport function saveDeviceCopy(prefs: CalendarPrefs, pending: Partial<CalendarPrefs>): void {\n const copy: DevicePrefsCopy = { prefs, pending };\n try {\n window.localStorage.setItem(getProfileScopedKey(DEVICE_PREFS_KEY), JSON.stringify(copy));\n } catch {\n // Storage blocked or full: the account copy still works.\n }\n}\n\n/** This device's copy, else today's calendar's settings, else the defaults. */\nexport function readInitialPrefs(): InitialPrefs {\n const device = readDeviceCopy();\n if (device) {\n return {\n prefs: device.prefs,\n source: 'device',\n pending: device.pending,\n legacyVisibleCalendarIds: null,\n };\n }\n const legacy = readLegacyCalendarState(readStorage(LEGACY_STORAGE_KEY), resolveTimeZone(null));\n if (legacy) {\n return {\n prefs: withDefaults(legacy.prefs),\n source: 'device',\n pending: {},\n legacyVisibleCalendarIds:\n legacy.visibleCalendarIds.length > 0 ? legacy.visibleCalendarIds : null,\n };\n }\n return {\n prefs: withDefaults({}),\n source: 'defaults',\n pending: {},\n legacyVisibleCalendarIds: null,\n };\n}\n"],"mappings":";;;;AAqBA,IAAaA,IAAqB,8BAErBC,IAAmB;AAShC,SAASC,EAAS,GAAkD;CAClE,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAGA,SAASC,EAAY,GAAsB;CACzC,IAAI;EACF,IAAMC,IAAO,OAAO,aAAa,QAAQC,EAAoBC,CAAG,CAAC;EAGjE,OAFIF,MAAS,OAAa,OACH,KAAK,MAAMA,CAC3B;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAGA,SAAgBG,IAAyC;CACvD,IAAMC,IAASL,EAAYH,CAAgB;CAE3C,OADI,CAACC,EAASO,CAAM,KAAK,CAACP,EAASO,EAAO,KAAK,IAAU,OAClD;EACL,OAAOC,EAAaC,EAAmBF,EAAO,KAAK,CAAC;EACpD,SAASE,EAAmBF,EAAO,OAAO;CAC5C;AACF;AAEA,SAAgBG,EAAe,GAAsB,GAAuC;CAC1F,IAAMC,IAAwB;EAAE;EAAO;CAAQ;CAC/C,IAAI;EACF,OAAO,aAAa,QAAQP,EAAoBL,CAAgB,GAAG,KAAK,UAAUY,CAAI,CAAC;CACzF,QAAQ,CAER;AACF;AAGA,SAAgBC,IAAiC;CAC/C,IAAMC,IAASP,EAAe;CAC9B,IAAIO,GACF,OAAO;EACL,OAAOA,EAAO;EACd,QAAQ;EACR,SAASA,EAAO;EAChB,0BAA0B;CAC5B;CAEF,IAAMC,IAASC,EAAwBb,EAAYJ,CAAkB,GAAGkB,EAAgB,IAAI,CAAC;CAU7F,OATIF,IACK;EACL,OAAON,EAAaM,EAAO,KAAK;EAChC,QAAQ;EACR,SAAS,CAAC;EACV,0BACEA,EAAO,mBAAmB,SAAS,IAAIA,EAAO,qBAAqB;CACvE,IAEK;EACL,OAAON,EAAa,CAAC,CAAC;EACtB,QAAQ;EACR,SAAS,CAAC;EACV,0BAA0B;CAC5B;AACF"}
@@ -0,0 +1,43 @@
1
+ import { DateValue } from '@burdenoff/fe-libs/ui';
2
+ import { CalendarV2Dialog, CalendarV2View } from './types';
3
+ export declare const CALENDAR_V2_VIEWS: readonly CalendarV2View[];
4
+ export declare const CALENDAR_V2_DIALOGS: readonly CalendarV2Dialog[];
5
+ /** The view an address shows when it names none. */
6
+ export declare const DEFAULT_VIEW: CalendarV2View;
7
+ /** Today's views the redesign drops, and the view each now opens (§2). */
8
+ export declare const LEGACY_VIEW_REDIRECTS: Readonly<Record<string, CalendarV2View>>;
9
+ /** Today's pages that are dialogs in the redesign (§2), opened over the week view. */
10
+ export declare const LEGACY_PAGE_DIALOGS: Readonly<Record<string, CalendarV2Dialog>>;
11
+ /** The query parameters the redesign reads. */
12
+ export declare const SEARCH_PARAMS: {
13
+ readonly date: "date";
14
+ readonly dialog: "dialog";
15
+ readonly event: "event";
16
+ };
17
+ export declare function isCalendarV2View(value: unknown): value is CalendarV2View;
18
+ export declare function isCalendarV2Dialog(value: unknown): value is CalendarV2Dialog;
19
+ /**
20
+ * The view an address's view name opens: a redesign view as it is, a dropped one where §2
21
+ * sends it, anything else null. Own keys only, so `constructor` or `toString` read as unknown.
22
+ */
23
+ export declare function viewForName(name: string | null | undefined): CalendarV2View | null;
24
+ /** The calendar's base path without a trailing slash: `/calendar`, or '' at the root. */
25
+ export declare function normalizeBasePath(basePath: string | undefined): string;
26
+ /** What an address of the redesign says. */
27
+ export interface CalendarV2Location {
28
+ /** The day the address names, when it names a real one. */
29
+ date: DateValue | null;
30
+ dialog: CalendarV2Dialog | null;
31
+ eventId: string | null;
32
+ }
33
+ /** Reads the redesign's query parameters; anything that isn't a real value reads as absent. */
34
+ export declare function readCalendarV2Search(search: string | URLSearchParams): CalendarV2Location;
35
+ /**
36
+ * A query string: `search` with `changes` applied (a null or undefined value removes the
37
+ * parameter). Other parameters are kept, so a redirect does not drop what a link carried.
38
+ */
39
+ export declare function withSearchParams(search: string | URLSearchParams, changes: Readonly<Record<string, string | null | undefined>>): string;
40
+ /** The path of a view under the calendar's base path: `/calendar/view/week`. */
41
+ export declare function viewPath(basePath: string, view: CalendarV2View): string;
42
+ /** A full address of the redesign: a view, with the query parameters `changes` sets. */
43
+ export declare function calendarV2Href(basePath: string, view: CalendarV2View, changes?: Readonly<Record<string, string | null | undefined>>, keep?: string | URLSearchParams): string;