@marktiderman/genesis-core 2.12.0 → 2.14.0
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.
- package/dist/{chunk-PSFKIG27.js → chunk-2K4747KX.js} +7 -4
- package/dist/chunk-2K4747KX.js.map +1 -0
- package/dist/{chunk-ZYJUEJ4Z.js → chunk-4PTQYT5J.js} +11 -5
- package/dist/chunk-4PTQYT5J.js.map +1 -0
- package/dist/{chunk-HBAPYA5K.js → chunk-5ASUMG6K.js} +3 -3
- package/dist/{chunk-HBAPYA5K.js.map → chunk-5ASUMG6K.js.map} +1 -1
- package/dist/{chunk-C62CMLWG.js → chunk-AHFIS42U.js} +6 -6
- package/dist/{chunk-C62CMLWG.js.map → chunk-AHFIS42U.js.map} +1 -1
- package/dist/{chunk-VJGU6E4U.js → chunk-DFABPMEQ.js} +13 -9
- package/dist/chunk-DFABPMEQ.js.map +1 -0
- package/dist/{chunk-POMTRNAL.js → chunk-G6GQPXQS.js} +4 -4
- package/dist/{chunk-POMTRNAL.js.map → chunk-G6GQPXQS.js.map} +1 -1
- package/dist/{chunk-ZHC3MDCS.js → chunk-JN47G4UE.js} +25 -16
- package/dist/chunk-JN47G4UE.js.map +1 -0
- package/dist/{chunk-2VJQVAJD.js → chunk-KA3BUJ4H.js} +3 -3
- package/dist/{chunk-2VJQVAJD.js.map → chunk-KA3BUJ4H.js.map} +1 -1
- package/dist/{chunk-2WS4LGYU.js → chunk-LKRJB632.js} +3 -3
- package/dist/{chunk-2WS4LGYU.js.map → chunk-LKRJB632.js.map} +1 -1
- package/dist/{chunk-LOJGHR5O.js → chunk-NE2D74BP.js} +4 -4
- package/dist/{chunk-LOJGHR5O.js.map → chunk-NE2D74BP.js.map} +1 -1
- package/dist/{chunk-VFT6QKZW.js → chunk-NOPS5EIH.js} +3 -3
- package/dist/{chunk-VFT6QKZW.js.map → chunk-NOPS5EIH.js.map} +1 -1
- package/dist/{chunk-52T2EYXH.js → chunk-NQFIAULD.js} +3 -3
- package/dist/{chunk-52T2EYXH.js.map → chunk-NQFIAULD.js.map} +1 -1
- package/dist/{chunk-3B5O36DU.js → chunk-OYDJGPDY.js} +7 -7
- package/dist/{chunk-3B5O36DU.js.map → chunk-OYDJGPDY.js.map} +1 -1
- package/dist/{chunk-OC4OGB2K.js → chunk-P3FHXRS2.js} +9 -6
- package/dist/chunk-P3FHXRS2.js.map +1 -0
- package/dist/{chunk-YNXLPOAB.js → chunk-RFHUOXZC.js} +4 -4
- package/dist/{chunk-YNXLPOAB.js.map → chunk-RFHUOXZC.js.map} +1 -1
- package/dist/{chunk-XVRIWP7B.js → chunk-S2VYJWB4.js} +3 -3
- package/dist/{chunk-XVRIWP7B.js.map → chunk-S2VYJWB4.js.map} +1 -1
- package/dist/{chunk-HYYTAJBG.js → chunk-SDAJSJNN.js} +3 -3
- package/dist/chunk-SDAJSJNN.js.map +1 -0
- package/dist/{chunk-42QPCDQF.js → chunk-WDPM5TBO.js} +3 -3
- package/dist/{chunk-42QPCDQF.js.map → chunk-WDPM5TBO.js.map} +1 -1
- package/dist/{chunk-LG6TUBVM.js → chunk-WLDSIQJ2.js} +4 -3
- package/dist/chunk-WLDSIQJ2.js.map +1 -0
- package/dist/{chunk-YQBWXG2G.js → chunk-YZV3Z6ZA.js} +3 -3
- package/dist/{chunk-YQBWXG2G.js.map → chunk-YZV3Z6ZA.js.map} +1 -1
- package/dist/conversation/index.d.ts +13 -2
- package/dist/conversation/index.js +7 -2
- package/dist/conversation/index.js.map +1 -1
- package/dist/csv.d.ts +1 -1
- package/dist/errors.js +2 -2
- package/dist/form-types.d.ts +1 -1
- package/dist/gallery/index.d.ts +5 -0
- package/dist/gallery/index.js.map +1 -1
- package/dist/hooks/draft-controller.js +2 -2
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +19 -19
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/mutation-mode.js +6 -6
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +3 -3
- package/dist/hooks/use-draft.js +3 -3
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +4 -4
- package/dist/hooks/use-link-options.d.ts +2 -1
- package/dist/hooks/use-link-options.js +6 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +3 -3
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +4 -4
- package/dist/hooks/use-persisted-ui-state.js +3 -3
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +3 -3
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +10 -10
- package/dist/hooks/use-resource.d.ts +1 -1
- package/dist/hooks/use-resource.js +8 -8
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/hooks/use-write.js +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +20 -20
- package/dist/navigation.d.ts +18 -1
- package/dist/navigation.js +7 -1
- package/dist/navigation.js.map +1 -1
- package/dist/provider/index.d.ts +4 -4
- package/dist/provider/index.js +5 -5
- package/dist/resource-view/index.d.ts +9 -2
- package/dist/resource-view/index.js +13 -4
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +3 -3
- package/dist/schema/index.js +2 -2
- package/dist/storage/index.js +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +1 -1
- package/dist/{types-BzLv8yOm.d.ts → types-CtJxwoyv.d.ts} +6 -0
- package/dist/{write-outcome-DC5hORz-.d.ts → write-outcome-Goy1v39G.d.ts} +4 -2
- package/package.json +1 -1
- package/dist/chunk-HYYTAJBG.js.map +0 -1
- package/dist/chunk-LG6TUBVM.js.map +0 -1
- package/dist/chunk-OC4OGB2K.js.map +0 -1
- package/dist/chunk-PSFKIG27.js.map +0 -1
- package/dist/chunk-VJGU6E4U.js.map +0 -1
- package/dist/chunk-ZHC3MDCS.js.map +0 -1
- package/dist/chunk-ZYJUEJ4Z.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createLocalStorageAdapter } from './chunk-
|
|
1
|
+
import { createLocalStorageAdapter } from './chunk-4PTQYT5J.js';
|
|
2
2
|
import { createContext, useContext, useMemo, useRef, useState, useEffect } from 'react';
|
|
3
3
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
4
4
|
import { jsx } from 'react/jsx-runtime';
|
|
@@ -81,7 +81,10 @@ function createMockProvider(datasets, options = {}) {
|
|
|
81
81
|
const sorts = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
|
|
82
82
|
if (sorts.length > 0) {
|
|
83
83
|
rows.sort((a, b) => {
|
|
84
|
-
for (const { field, order } of sorts) {
|
|
84
|
+
for (const { field, order, nulls } of sorts) {
|
|
85
|
+
if (nulls && a[field] == null !== (b[field] == null)) {
|
|
86
|
+
return a[field] == null === (nulls === "first") ? -1 : 1;
|
|
87
|
+
}
|
|
85
88
|
const cmp = compareValues(a[field], b[field]);
|
|
86
89
|
if (cmp !== 0) return order === "desc" ? -cmp : cmp;
|
|
87
90
|
}
|
|
@@ -251,5 +254,5 @@ function useRestoredReads(queryClient, persist, scope) {
|
|
|
251
254
|
var PersistedViewerContext = createContext(void 0);
|
|
252
255
|
|
|
253
256
|
export { DataProviderRoot, GenesisProvider, PersistedViewerContext, createMockProvider, useDataProvider, useStorage };
|
|
254
|
-
//# sourceMappingURL=chunk-
|
|
255
|
-
//# sourceMappingURL=chunk-
|
|
257
|
+
//# sourceMappingURL=chunk-2K4747KX.js.map
|
|
258
|
+
//# sourceMappingURL=chunk-2K4747KX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/mock-provider.ts","../src/provider/context.tsx"],"names":[],"mappings":";;;;;;AAiBO,SAAS,kBAAA,CACd,QAAA,EACA,OAAA,GAA+B,EAA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,SAAA,CAAU,KAAA,EAAO,EAAE,OAAA,EAAS,IAAA,KAAS,QAAW,CAAA;AACzE,IAAA,MAAM,OAAO,MAAM;AACjB,MAAA,IAAI,CAAC,KAAA,CAAM,MAAA,CAAO,OAAA,WAAkB,IAAI,CAAA;AAAA,IAC1C,CAAA;AACA,IAAA,MAAM,IAAA,GAAO,UAAA,CAAW,IAAA,EAAM,eAAe,CAAA;AAC7C,IAAA,KAAK,QAAA,CAAS,QACX,IAAA,CAAK,MAAO,MAAM,MAAA,CAAO,OAAA,GAAU,SAAY,WAAA,CAAY,OAAA,CAAQ,OAAO,KAAA,CAAM,MAAM,CAAE,CAAA,CACxF,KAAA,CAAM,MAAM,MAAS,CAAA,CACrB,QAAQ,MAAM;AACb,MAAA,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAC,CAAA;AACH,IAAA,OAAO,MAAM;AACX,MAAA,KAAA,CAAM,KAAA,EAAM;AACZ,MAAA,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAA,EAAa,KAAK,CAAC,CAAA;AACvB,EAAA,OAAO,KAAA;AACT;AAMO,IAAM,sBAAA,GAAyB,cAAkC,MAAS","file":"chunk-2K4747KX.js","sourcesContent":["import type {\n DataProvider,\n ListParams,\n FilterParam,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Mock DataProvider — operates on in-memory arrays, deep-cloned on creation\n// ---------------------------------------------------------------------------\n\nexport interface MockProviderOptions {\n /** Simulated latency in ms (default 0). */\n delay?: number;\n}\n\ntype Row = Record<string, unknown>;\n\nexport function createMockProvider(\n datasets: Record<string, Row[]>,\n options: MockProviderOptions = {},\n): DataProvider {\n const { delay = 0 } = options;\n\n // Deep clone so mutations don't affect the original data.\n const store: Record<string, Row[]> = JSON.parse(JSON.stringify(datasets));\n\n // Instance-scoped ID counter (NOT module-level).\n let nextId = 1;\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function getTable(resource: string): Row[] {\n if (!store[resource]) {\n store[resource] = [];\n }\n return store[resource];\n }\n\n async function withDelay<T>(value: T): Promise<T> {\n if (delay > 0) {\n await new Promise((r) => setTimeout(r, delay));\n }\n return value;\n }\n\n function matchesFilter(row: Row, filter: FilterParam): boolean {\n const val = row[filter.field];\n\n switch (filter.operator) {\n case \"eq\":\n return val === filter.value;\n case \"neq\":\n return val !== filter.value;\n case \"gt\":\n return (val as number) > (filter.value as number);\n case \"lt\":\n return (val as number) < (filter.value as number);\n case \"gte\":\n return (val as number) >= (filter.value as number);\n case \"lte\":\n return (val as number) <= (filter.value as number);\n case \"contains\":\n return typeof val === \"string\" &&\n val.toLowerCase().includes(String(filter.value).toLowerCase());\n case \"in\":\n return filter.value.includes(val as string | number | boolean);\n case \"is_null\":\n return val === null || val === undefined;\n case \"is_not_null\":\n return val !== null && val !== undefined;\n case \"between\": {\n const [lo, hi] = filter.value;\n return (val as number) >= (lo as number) && (val as number) <= (hi as number);\n }\n }\n }\n\n function matchesSearch(\n row: Row,\n search: { query: string; fields: string[] },\n ): boolean {\n const q = search.query.toLowerCase();\n return search.fields.some((field) => {\n const val = row[field];\n return typeof val === \"string\" && val.toLowerCase().includes(q);\n });\n }\n\n function compareValues(a: unknown, b: unknown): number {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a.localeCompare(b, undefined, { numeric: true });\n }\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n // Fallback: coerce to string.\n return String(a ?? \"\").localeCompare(String(b ?? \"\"), undefined, {\n numeric: true,\n });\n }\n\n function applyListParams(table: Row[], params: ListParams): { data: Row[]; total: number } {\n let rows = [...table];\n\n // Filters (AND).\n if (params.filters) {\n for (const f of params.filters) {\n rows = rows.filter((r) => matchesFilter(r, f));\n }\n }\n\n // Search (OR across fields, AND with filters).\n if (params.search && params.search.query) {\n rows = rows.filter((r) => matchesSearch(r, params.search!));\n }\n\n const total = rows.length;\n\n // Sort.\n // By each sort field in turn (`sorts`, else `sort`).\n const sorts = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (sorts.length > 0) {\n rows.sort((a, b) => {\n for (const { field, order, nulls } of sorts) {\n if (nulls && (a[field] == null) !== (b[field] == null)) {\n return (a[field] == null) === (nulls === \"first\") ? -1 : 1;\n }\n const cmp = compareValues(a[field], b[field]);\n if (cmp !== 0) return order === \"desc\" ? -cmp : cmp;\n }\n return 0;\n });\n }\n\n // Pagination (offset-based).\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const start = (page - 1) * perPage;\n rows = rows.slice(start, start + perPage);\n }\n\n return { data: rows, total };\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n const provider: DataProvider = {\n async getList(_resource, params) {\n const table = getTable(_resource);\n const result = applyListParams(table, params);\n return withDelay(result) as never;\n },\n\n async getOne(_resource, params) {\n const table = getTable(_resource);\n const row = table.find((r) => String(r.id) === String(params.id));\n if (!row) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async getMany(_resource, params) {\n const table = getTable(_resource);\n const idSet = new Set(params.ids.map(String));\n const rows = table.filter((r) => idSet.has(String(r.id)));\n return withDelay({ data: JSON.parse(JSON.stringify(rows)) }) as never;\n },\n\n async create(_resource, params) {\n const table = getTable(_resource);\n const id = String(nextId++);\n const row = { id, ...params.data } as Row;\n table.push(row);\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async update(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table[idx] = { ...table[idx], ...params.data };\n return withDelay({ data: JSON.parse(JSON.stringify(table[idx])) }) as never;\n },\n\n async deleteOne(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table.splice(idx, 1);\n return withDelay({ data: { id: params.id } });\n },\n };\n\n return provider;\n}\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport type { DataProvider } from \"./types\";\nimport { createMockProvider, type MockProviderOptions } from \"./mock-provider\";\nimport type { StorageAdapter } from \"../storage/types\";\nimport { createLocalStorageAdapter } from \"../storage/adapters\";\nimport type { QueryPersistence } from \"../offline/types\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nconst DataProviderContext = createContext<DataProvider | null>(null);\nconst StorageContext = createContext<StorageAdapter>(createLocalStorageAdapter());\n\n// ---------------------------------------------------------------------------\n// DataProviderRoot — thin context wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Puts a `DataProvider` in context, and nothing else. Mount it inside your\n * app's own `QueryClientProvider` and the Genesis hooks share that cache:\n * the same query keys (`[resource, \"list\", params]`,\n * `[resource, \"detail\", id, select]`), so invalidating `[resource]` from app\n * code refreshes Genesis lists too, and vice versa.\n */\nexport interface DataProviderRootProps {\n provider: DataProvider;\n children: ReactNode;\n}\n\nexport function DataProviderRoot({ provider, children }: DataProviderRootProps) {\n return (\n <DataProviderContext.Provider value={provider}>\n {children}\n </DataProviderContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useDataProvider(): DataProvider {\n const ctx = useContext(DataProviderContext);\n if (!ctx) {\n throw new Error(\n \"useDataProvider must be used inside <DataProviderRoot> or <GenesisProvider>. \" +\n \"Wrap your app (or the relevant subtree) in one of these providers.\",\n );\n }\n return ctx;\n}\n\nexport function useStorage(): StorageAdapter {\n return useContext(StorageContext);\n}\n\n// ---------------------------------------------------------------------------\n// GenesisProvider — convenience wrapper\n// ---------------------------------------------------------------------------\n\ntype Row = Record<string, unknown>;\n\nexport type GenesisProviderProps =\n | {\n children: ReactNode;\n /** Pass a ready-made DataProvider. Mutually exclusive with `mock`. */\n provider: DataProvider;\n mock?: never;\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /**\n * Keep reads on the device and restore them on the next start, so lists and records open at\n * once: `persistOffline({ cache: indexedDbLocalCache(), resources, buster })` from\n * `@marktiderman/genesis-core/offline`. Needs `persistScope`. Give it from the first render:\n * the provider keeps the first one it's given.\n */\n persist?: (client: QueryClient) => QueryPersistence;\n /**\n * Whose cache this is: `cacheScope(user.id, workspaceKey)` once someone is signed in,\n * `null` once nobody is, and `undefined` while that isn't known yet (the session loading).\n * A device is one person's: restoring someone deletes everyone else's kept reads, and\n * `null` deletes them all, so a session that ended outside the app (it expired, or was\n * signed out elsewhere) leaves nothing on the device. Undefined does nothing. A change of\n * scope restores the new one's reads. Clear the QueryClient yourself when the person\n * changes, as a sign-out already does; a `ViewerScope` inside keeps the restored reads for\n * this person. Restoring is client-only: in a server-rendered app, give it after hydration\n * (undefined on the server and the first client render), and the screens restore in the\n * background. Change it only once the provider's session has: a scope must never name a\n * person before the data provider's requests are made as them.\n */\n persistScope?: string | null;\n /**\n * The TanStack Query client to use. Without it, GenesisProvider creates\n * its OWN client — a second cache beside any the app already has, so app\n * queries and Genesis queries would not see each other's invalidations.\n * An app with a `QueryClientProvider` should pass its client here, or\n * use `DataProviderRoot` inside that provider instead.\n */\n queryClient?: QueryClient;\n }\n | {\n children: ReactNode;\n provider?: never;\n /** Pass mock datasets. Mutually exclusive with `provider`. */\n mock: {\n datasets: Record<string, Row[]>;\n options?: MockProviderOptions;\n };\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /** See the `provider` variant. */\n queryClient?: QueryClient;\n /** See the `provider` variant. */\n persist?: (client: QueryClient) => QueryPersistence;\n /** See the `provider` variant. */\n persistScope?: string | null;\n };\n\nconst defaultStorage = createLocalStorageAdapter();\n\n/**\n * Convenience root: a `QueryClientProvider`, storage, and a data provider\n * (yours, or a mock built from datasets). It creates its own `QueryClient`\n * unless you pass `queryClient`; an app that already has one should pass it,\n * or mount `DataProviderRoot` inside its existing `QueryClientProvider`.\n */\nexport function GenesisProvider({\n children,\n provider,\n mock,\n storage,\n queryClient: queryClientProp,\n persist,\n persistScope,\n}: GenesisProviderProps) {\n if (provider && mock) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[GenesisProvider] Both `provider` and `mock` were passed. `provider` takes precedence. This is likely a mistake.\");\n }\n }\n\n // Build provider from mock datasets when no explicit provider is given.\n const resolvedProvider = useMemo(() => {\n if (provider) return provider;\n if (mock) return createMockProvider(mock.datasets, mock.options);\n throw new Error(\n \"<GenesisProvider> requires either a `provider` or `mock` prop.\",\n );\n }, [provider, mock]);\n\n // The caller's QueryClient, or an internal one with sensible defaults.\n const queryClient = useMemo(\n () =>\n queryClientProp ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 5 * 60 * 1000, // 5 minutes\n },\n },\n }),\n [queryClientProp],\n );\n\n const resolvedStorage = storage ?? defaultStorage;\n const restored = useRestoredReads(queryClient, persist, persistScope);\n\n return (\n <QueryClientProvider client={queryClient}>\n <StorageContext.Provider value={resolvedStorage}>\n <DataProviderRoot provider={resolvedProvider}>\n <PersistedViewerContext.Provider value={persist && typeof persistScope === \"string\" ? userOf(persistScope) : undefined}>\n {restored ? children : null}\n </PersistedViewerContext.Provider>\n </DataProviderRoot>\n </StorageContext.Provider>\n </QueryClientProvider>\n );\n}\n\n/** How long the first render waits for the device's reads before it goes on without them. */\nconst RESTORE_WAIT_MS = 400;\n\n/** The person a scope belongs to (`u:<user>|<workspace>`, or a bare user id). */\nconst userOf = (scope: string) => (scope.startsWith(\"u:\") ? scope.slice(2, scope.indexOf(\"|\") < 0 ? undefined : scope.indexOf(\"|\")) : scope);\n\n/**\n * Restores `scope`'s kept reads before the screens first render (so they open from the device),\n * waiting at most RESTORE_WAIT_MS, then saves new reads. Only the first render waits, and never on\n * the server; a later scope change restores in the background. When the person changes or signs\n * out, their reads are deleted from the device before anything of the next scope is restored.\n */\nfunction useRestoredReads(\n queryClient: QueryClient,\n persist: ((client: QueryClient) => QueryPersistence) | undefined,\n scope: string | null | undefined,\n): boolean {\n // The first `persist` given is kept (one given only later is ignored), so a screen that writes\n // it inline doesn't restart the restore on every render.\n const persistRef = useRef(persist);\n const persistence = useMemo(() => (persistRef.current ? persistRef.current(queryClient) : null), [queryClient]);\n const [ready, setReady] = useState(!persistence || !scope || typeof window === \"undefined\");\n // Whose reads this provider last restored or saved, and the clear of them still running.\n const person = useRef<string | null>(null);\n const clearing = useRef<Promise<void>>(Promise.resolve());\n // The scope the last run of the effect saw (\"not known yet\" at mount). A scope that arrives from\n // there is saved only from reads fetched once it's known: whatever the client already holds or\n // is reading may be another session's (the session was loading, or the client outlived this\n // provider and someone else's session), so it's fetched again (`refresh`), never adopted.\n const previous = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n const from = previous.current;\n previous.current = scope;\n if (!persistence || scope === undefined) {\n // Not known yet who's signed in: nothing is restored, saved or deleted.\n setReady(true);\n return;\n }\n if (scope === null) {\n // Nobody signed in: nothing of anyone's stays on the device.\n person.current = null;\n clearing.current = persistence.restore(\"\").catch(() => undefined);\n setReady(true);\n return;\n }\n const next = userOf(scope);\n if (person.current !== null && person.current !== next) {\n clearing.current = persistence.clear().catch(() => undefined);\n }\n person.current = next;\n const abort = new AbortController();\n // Saving starts with the scope. A read made before it is saved only when the scope before was\n // \"not known yet\" (the same session, loading); from another person or workspace, never.\n const stop = persistence.subscribe(scope, { refresh: from === undefined });\n const open = () => {\n if (!abort.signal.aborted) setReady(true);\n };\n const wait = setTimeout(open, RESTORE_WAIT_MS);\n void clearing.current\n .then(() => (abort.signal.aborted ? undefined : persistence.restore(scope, abort.signal)))\n .catch(() => undefined)\n .finally(() => {\n clearTimeout(wait);\n open();\n });\n return () => {\n abort.abort();\n clearTimeout(wait);\n stop();\n };\n }, [persistence, scope]);\n return ready;\n}\n\n/**\n * The person whose kept reads `GenesisProvider` restored (`persistScope`'s user), so a\n * `ViewerScope` inside keeps them for that viewer instead of emptying the cache.\n */\nexport const PersistedViewerContext = createContext<string | undefined>(undefined);\n\n"]}
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
// src/storage/adapters.ts
|
|
2
2
|
function createLocalStorageAdapter() {
|
|
3
|
+
const warned = /* @__PURE__ */ new Set();
|
|
4
|
+
const warn = (doing, key, err) => {
|
|
5
|
+
if (warned.has(`${doing}:${key}`)) return;
|
|
6
|
+
warned.add(`${doing}:${key}`);
|
|
7
|
+
console.warn(`[StorageAdapter] Failed to ${doing} "${key}":`, err instanceof Error ? err.message : String(err));
|
|
8
|
+
};
|
|
3
9
|
return {
|
|
4
10
|
getItem(key) {
|
|
5
11
|
if (typeof window === "undefined" || typeof localStorage === "undefined") return null;
|
|
6
12
|
try {
|
|
7
13
|
return localStorage.getItem(key);
|
|
8
14
|
} catch (err) {
|
|
9
|
-
|
|
15
|
+
warn("read", key, err);
|
|
10
16
|
return null;
|
|
11
17
|
}
|
|
12
18
|
},
|
|
@@ -15,7 +21,7 @@ function createLocalStorageAdapter() {
|
|
|
15
21
|
try {
|
|
16
22
|
localStorage.setItem(key, value);
|
|
17
23
|
} catch (err) {
|
|
18
|
-
|
|
24
|
+
warn("write", key, err);
|
|
19
25
|
}
|
|
20
26
|
},
|
|
21
27
|
removeItem(key) {
|
|
@@ -23,7 +29,7 @@ function createLocalStorageAdapter() {
|
|
|
23
29
|
try {
|
|
24
30
|
localStorage.removeItem(key);
|
|
25
31
|
} catch (err) {
|
|
26
|
-
|
|
32
|
+
warn("remove", key, err);
|
|
27
33
|
}
|
|
28
34
|
}
|
|
29
35
|
};
|
|
@@ -55,5 +61,5 @@ function createNoopStorageAdapter() {
|
|
|
55
61
|
}
|
|
56
62
|
|
|
57
63
|
export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter };
|
|
58
|
-
//# sourceMappingURL=chunk-
|
|
59
|
-
//# sourceMappingURL=chunk-
|
|
64
|
+
//# sourceMappingURL=chunk-4PTQYT5J.js.map
|
|
65
|
+
//# sourceMappingURL=chunk-4PTQYT5J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/adapters.ts"],"names":[],"mappings":";AAGO,SAAS,yBAAA,GAA4C;AAG1D,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAC/B,EAAA,MAAM,IAAA,GAAO,CAAC,KAAA,EAAe,GAAA,EAAa,GAAA,KAAiB;AACzD,IAAA,IAAI,OAAO,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,GAAG,EAAE,CAAA,EAAG;AACnC,IAAA,MAAA,CAAO,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AAC5B,IAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,2BAAA,EAA8B,KAAK,CAAA,EAAA,EAAK,GAAG,CAAA,EAAA,CAAA,EAAM,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,EAChH,CAAA;AACA,EAAA,OAAO;AAAA,IACL,QAAQ,GAAA,EAAK;AACX,MAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,YAAA,KAAiB,aAAa,OAAO,IAAA;AACjF,MAAA,IAAI;AACF,QAAA,OAAO,YAAA,CAAa,QAAQ,GAAG,CAAA;AAAA,MACjC,SAAS,GAAA,EAAK;AACZ,QAAA,IAAA,CAAK,MAAA,EAAQ,KAAK,GAAG,CAAA;AACrB,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA,IACA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orageAdapter } from \"./types\";\n\n/** localStorage adapter with SSR safety. */\nexport function createLocalStorageAdapter(): StorageAdapter {\n // Once per key and operation: a browser that blocks storage fails every read, and a hook reads\n // on every render.\n const warned = new Set<string>();\n const warn = (doing: string, key: string, err: unknown) => {\n if (warned.has(`${doing}:${key}`)) return;\n warned.add(`${doing}:${key}`);\n console.warn(`[StorageAdapter] Failed to ${doing} \"${key}\":`, err instanceof Error ? err.message : String(err));\n };\n return {\n getItem(key) {\n if (typeof window === \"undefined\" || typeof localStorage === \"undefined\") return null;\n try {\n return localStorage.getItem(key);\n } catch (err) {\n warn(\"read\", key, err);\n return null;\n }\n },\n setItem(key, value) {\n if (typeof window === \"undefined\" || typeof localStorage === \"undefined\") return;\n try {\n localStorage.setItem(key, value);\n } catch (err) {\n warn(\"write\", key, err);\n }\n },\n removeItem(key) {\n if (typeof window === \"undefined\" || typeof localStorage === \"undefined\") return;\n try {\n localStorage.removeItem(key);\n } catch (err) {\n warn(\"remove\", key, err);\n }\n },\n };\n}\n\n/** In-memory adapter for testing and SSR. */\nexport function createMemoryStorageAdapter(): StorageAdapter {\n const store = new Map<string, string>();\n return {\n getItem(key) {\n return store.get(key) ?? null;\n },\n setItem(key, value) {\n store.set(key, value);\n },\n removeItem(key) {\n store.delete(key);\n },\n };\n}\n\n/** No-op adapter — all operations silently do nothing. */\nexport function createNoopStorageAdapter(): StorageAdapter {\n return {\n getItem() {\n return null;\n },\n setItem() {},\n removeItem() {},\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isDataWriteError } from './chunk-
|
|
1
|
+
import { isDataWriteError } from './chunk-WLDSIQJ2.js';
|
|
2
2
|
|
|
3
3
|
// src/hooks/draft-controller.ts
|
|
4
4
|
var DEFAULT_DRAFT_DELAY_MS = 800;
|
|
@@ -253,5 +253,5 @@ var DraftController = class {
|
|
|
253
253
|
};
|
|
254
254
|
|
|
255
255
|
export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson };
|
|
256
|
-
//# sourceMappingURL=chunk-
|
|
257
|
-
//# sourceMappingURL=chunk-
|
|
256
|
+
//# sourceMappingURL=chunk-5ASUMG6K.js.map
|
|
257
|
+
//# sourceMappingURL=chunk-5ASUMG6K.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/draft-controller.ts"],"names":[],"mappings":";;;AAgGO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,eAAA,GAAkB;AAGxB,SAAS,WAAW,KAAA,EAAwB;AACjD,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IAAU,KAAA;AAAA,IAAO,CAAC,IAAA,EAAM,CAAA,KAClC,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAC1C,MAAA,CAAO,WAAA;AAAA,MACL,OAAO,OAAA,CAAQ,CAA4B,EAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,MAAO,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,GAAI,CAAA,GAAI,IAAI,CAAE;AAAA,KAC9F,GACA;AAAA,GACN;AACF;AAGA,SAAS,WAAW,CAAA,EAAqB;AACvC,EAAA,IAAI,CAAA,KAAM,MAAA,IAAa,CAAA,KAAM,IAAA,EAAM,OAAO,KAAA;AAC1C,EAAA,IAAI,OAAO,CAAA,KAAM,QAAA,EAAU,OAAO,CAAA,CAAE,MAAK,KAAM,EAAA;AAC/C,EAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,KAAK,UAAU,CAAA;AAC9C,EAAA,IAAI,OAAO,MAAM,QAAA,EAAU,OAAO,OAAO,MAAA,CAAO,CAA4B,CAAA,CAAE,IAAA,CAAK,UAAU,CAAA;AAC7F,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,iBAAiB,KAAA,EAAyB;AACxD,EAAA,IA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AO,KAAK,KAAK,CAAA;AAClD,UAAA,IAAI,UAAA,KAAe,IAAA,CAAK,UAAA,EAAY,MAAM,IAAI,IAAA,EAAK;AACnD,UAAA,IAAI,WAAW,OAAA,EAAS;AACtB,YAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AACb,YAAA,IAAA,CAAK,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA;AACvC,YAAA,IAAA,CAAK,KAAA,CAAM,EAAE,GAAA,EAAK,OAAA,CAAQ,OAAO,MAAA,EAAQ,SAAA,EAAW,KAAA,EAAO,IAAA,EAAM,CAAA;AACjE,YAAA,IAAA,CAAK,OAAA,GAAU,QAAQ,KAAK,CAAA;AAC5B,YAAA,MAAM,IAAI,IAAA,EAAK;AAAA,UACjB;AACA,UAAA,OAAO,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAK,QAAQ,IAAA,EAAK;AAAA,QAC1C;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,KAAA,YAAiB,QAAQ,OAAA,IAAW,OAAA,IAAW,CAAC,WAAA,CAAY,KAAK,GAAG,MAAM,KAAA;AAC9E,QAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY,UAAA,CAAW,OAAA,EAAA,CAAU,IAAA,CAAK,YAAA,IAAgB,GAAA,IAAO,CAAA,IAAK,OAAO,CAAC,CAAA;AAE7F,QAAA,IAAI,CAAC,KAAK,MAAA,EAAO,IAAK,eAAe,IAAA,CAAK,UAAA,EAAY,MAAM,IAAI,IAAA,EAAK;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AACF","file":"chunk-HBAPYA5K.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Autosave a draft (README \"Autosave a draft\")\n//\n// A draft is one row someone edits over time: an answer to a questionnaire, a\n// note, a journal entry. It is saved as they type, a moment after they stop,\n// and the first save adds the row. The app supplies the writes, so this works\n// with any backend; nothing here talks to a database.\n//\n// DraftController holds the rules and is plain TypeScript; `useDraft` is its\n// React wrapper.\n// ---------------------------------------------------------------------------\n\nimport { isDataWriteError } from \"../schema/write-outcome\";\n\n/** A draft's value: a flat map of fields (a table or a list is one field). */\nexport type DraftValue = Record<string, unknown>;\n\nexport type DraftStatus = \"idle\" | \"saving\" | \"saved\" | \"error\" | \"stopped\";\n\nexport interface DraftSeed<V extends DraftValue, R> {\n /** The row as the server has it, or null before the first save. */\n row: R | null;\n /** The value to start from: the row's, or a blank one. */\n value: V;\n}\n\n/** What `adopt` found: the row it merged into, or a row already finished elsewhere. */\nexport type DraftAdoption<R> = { row: R } | { final: R };\n\nexport interface DraftOptions<V extends DraftValue, R> {\n seed: DraftSeed<V, R>;\n /**\n * Changes when the server's copy changes in a way that wins over edits here\n * (it was sent from another tab, a reviewer returned it). The draft then\n * starts again from the new `seed`; see `onRevision`.\n */\n revision?: string | undefined;\n /** The first write: add the row. `keepalive` is set for the save made as the page closes. */\n create: (value: V, hints: { keepalive: boolean }) => Promise<R>;\n /** Later writes. `keepalive` is set for the save made as the page closes. */\n update: (row: R, value: V, hints: { keepalive: boolean }) => Promise<R>;\n /** The value a saved row holds. */\n toValue: (row: R) => V;\n /** A row's identity, to tell the same row from another. Default: its `id`. */\n idOf?: ((row: R) => unknown) | undefined;\n /**\n * The first write found a row already there (another tab started it): merge\n * into it, or report that it is already finished. `dirty` names the fields\n * changed here since the draft started; only those should be written over\n * the existing row's. Without `adopt`, the duplicate is an error.\n */\n adopt?: ((value: V, dirty: ReadonlySet<string>) => Promise<DraftAdoption<R>>) | undefined;\n /** Whether a failed `create` means \"a row is already there\". Default: a `duplicate` write outcome. */\n isDuplicate?: ((error: unknown) => boolean) | undefined;\n /** Never add a row for this value. Default: no field has anything in it. */\n isEmpty?: ((value: V) => boolean) | undefined;\n /** Default: the same JSON, whatever the order of object keys. */\n equal?: ((a: V, b: V) => boolean) | undefined;\n /** How long after the last change to save. Default 800 ms. */\n delayMs?: number | undefined;\n /** False: nothing is written (someone else's draft, or one already sent). Default true. */\n enabled?: boolean | undefined;\n /** After each save, with the row as saved: write it into the app's cache here. */\n onSaved?: ((row: R) => void) | undefined;\n /** `adopt` found the row finished elsewhere: nothing more is saved. */\n onFinal?: ((row: R) => void) | undefined;\n /**\n * `revision` changed with edits not yet saved: return the value to keep (a\n * merge), or null to drop the edits for the server's. Default: drop them.\n */\n onRevision?: ((pending: V, next: DraftSeed<V, R>) => V | null) | undefined;\n /** Whether a failed write is worth trying again. Default: network failures only, never refusals. */\n isRetryable?: ((error: unknown) => boolean) | undefined;\n /** Tries after the first, on a retryable failure. Default 3. */\n retries?: number | undefined;\n /** The first retry's wait; each later one doubles it. Default 500 ms. */\n retryDelayMs?: number | undefined;\n /** The words shown for a failed save. Default: the write error's own plain message. */\n messageOf?: ((error: unknown) => string) | undefined;\n}\n\nexport interface DraftState<V extends DraftValue, R> {\n value: V;\n row: R | null;\n status: DraftStatus;\n /** Why the last save failed, in plain words; null once one succeeds. */\n error: string | null;\n /** True after a new revision replaced edits that weren't saved, so the page can say so. */\n discarded: boolean;\n /**\n * Changes when the value is replaced from outside the editor (merged with\n * another tab's row, or a new revision): remount the editor on it.\n */\n key: number;\n}\n\nexport const DEFAULT_DRAFT_DELAY_MS = 800;\nexport const DRAFT_NOT_SAVED = \"Your changes weren't saved.\";\n\n/** JSON with object keys sorted, so values compare equal whatever order a store keeps keys in. */\nexport function stableJson(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(\n Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n )\n : v,\n );\n}\n\n/** Something in it: not undefined, null, blank text, or a list or object of nothing. */\nfunction hasContent(v: unknown): boolean {\n if (v === undefined || v === null) return false;\n if (typeof v === \"string\") return v.trim() !== \"\";\n if (Array.isArray(v)) return v.some(hasContent);\n if (typeof v === \"object\") return Object.values(v as Record<string, unknown>).some(hasContent);\n return true;\n}\n\n/** The default `isRetryable`: a request that never reached the store. A refusal never is. */\nexport function isNetworkFailure(error: unknown): boolean {\n if (isDataWriteError(error)) return error.outcome === \"error\" && error.code === undefined;\n return error instanceof TypeError;\n}\n\nfunction defaultId(row: unknown): unknown {\n return row && typeof row === \"object\" && \"id\" in row ? (row as { id: unknown }).id : row;\n}\n\nfunction isDuplicateOutcome(error: unknown): boolean {\n return isDataWriteError(error) && error.outcome === \"duplicate\";\n}\n\nfunction plainMessage(error: unknown): string {\n return isDataWriteError(error) && error.message ? error.message : DRAFT_NOT_SAVED;\n}\n\n/** Thrown inside a save to end it quietly: the draft stopped while it ran. */\nclass Halt {}\n\n/**\n * The rules of a draft, without React: one write at a time, add then change,\n * no write when nothing changed or for an empty value, merge into a row\n * another tab started, start again on a new revision, retry network failures,\n * and a final write (`commit`) that ends it.\n */\nexport class DraftController<V extends DraftValue, R> {\n private state: DraftState<V, R>;\n /** The value as last saved (or as loaded): what \"unchanged\" compares with. */\n private saved: V;\n /** Fields changed here since the draft started (or since the last revision). */\n private dirty = new Set<string>();\n private chain: Promise<unknown> = Promise.resolve();\n private timer: ReturnType<typeof setTimeout> | undefined;\n private revision: string | undefined;\n private ended = false;\n /** Bumped by each new revision: a save that started before it lands on nothing. */\n private generation = 0;\n /** The value of the write in flight, so a seed that is only that write coming back is known. */\n private inflight: V | null = null;\n private listeners = new Set<() => void>();\n\n constructor(private readonly options: () => DraftOptions<V, R>) {\n const { seed, revision, toValue } = options();\n this.revision = revision;\n this.saved = seed.row ? toValue(seed.row) : seed.value;\n this.state = { value: seed.value, row: seed.row, status: \"idle\", error: null, discarded: false, key: 0 };\n }\n\n readonly subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n readonly getState = () => this.state;\n\n /** Edits this draft would still save. */\n readonly pending = () => this.active() && !this.same(this.state.value, this.saved);\n\n /** The editor's new value: its changed fields are noted, and it's saved a moment after the last change. */\n readonly set = (value: V) => {\n const before = this.state.value;\n for (const key of new Set([...Object.keys(before), ...Object.keys(value)])) {\n if (stableJson(before[key]) !== stableJson(value[key])) this.dirty.add(key);\n }\n this.patch({ value, discarded: false });\n if (this.active()) this.schedule();\n };\n\n /** Save now, after any write already running. Resolves once written or failed; never rejects. */\n readonly flush = (hints: { keepalive?: boolean } = {}): Promise<void> => {\n this.clearTimer();\n // Never rejects, so one throwing option (isEmpty, equal) can't wedge the chain.\n const run = this.chain\n .then(() => this.save(hints.keepalive ?? false))\n .catch((error: unknown) => {\n this.patch({ status: \"error\", error: (this.options().messageOf ?? plainMessage)(error) });\n });\n this.chain = run;\n return run;\n };\n\n /**\n * The final write (a submit), after any write in flight, given the row so far\n * (null before the first save) and the value. On success nothing more is\n * saved and the draft is `stopped`; on failure it is thrown to the caller and\n * autosave carries on.\n */\n readonly commit = (write: (row: R | null, value: V) => Promise<R>): Promise<R> => {\n this.clearTimer();\n const run = this.chain.then(async () => {\n const row = await write(this.state.row, this.state.value);\n this.ended = true;\n this.saved = this.options().toValue(row);\n this.patch({ row, status: \"stopped\", error: null });\n this.options().onSaved?.(row);\n return row;\n });\n // A failed commit leaves the draft as it was: autosave carries on.\n this.chain = run.catch(() => {\n if (this.pending()) this.schedule();\n });\n return run;\n };\n\n /**\n * The server's seed again. Ignored unless `revision` changed. Then, in order:\n * - the seed is this draft's own save coming back (the same row, holding what\n * was last saved or is being saved): take its row and keep every edit;\n * - it is another row, with edits pending here: those are saved to the row\n * they belong to first, then the draft moves to the new one;\n * - otherwise the server's copy wins: the draft starts again from it, keeping\n * only what `onRevision` returns.\n */\n readonly reseed = (seed: DraftSeed<V, R>, revision: string | undefined) => {\n if (revision === this.revision) return;\n this.revision = revision;\n const opts = this.options();\n const idOf = opts.idOf ?? defaultId;\n const current = this.state.row;\n const echo =\n seed.row !== null &&\n (current === null || idOf(seed.row) === idOf(current)) &&\n (this.same(opts.toValue(seed.row), this.saved) ||\n (this.inflight !== null && this.same(opts.toValue(seed.row), this.inflight)));\n if (echo && (current !== null || this.inflight !== null)) {\n this.patch({ row: seed.row });\n return;\n }\n this.generation++;\n this.clearTimer();\n const pending = !this.same(this.state.value, this.saved);\n if (pending && current !== null && seed.row !== null && idOf(seed.row) !== idOf(current) && this.active()) {\n // Another row: what was typed belongs to the old one, so save it there first.\n const value = this.state.value;\n this.chain = this.chain\n .then(() => opts.update(current, value, { keepalive: false }))\n .then((row) => opts.onSaved?.(row))\n .catch(() => undefined);\n this.startFrom(seed, seed.value, false);\n return;\n }\n const kept = pending ? (opts.onRevision?.(this.state.value, seed) ?? null) : null;\n this.startFrom(seed, kept ?? seed.value, pending && kept === null);\n if (kept !== null && this.pending()) this.schedule();\n };\n\n /** Call when `enabled` may have changed: off stops saving; back on saves what's pending. */\n readonly sync = () => {\n if (!this.enabled()) {\n this.clearTimer();\n if (this.state.status !== \"stopped\") this.patch({ status: \"stopped\" });\n } else if (this.state.status === \"stopped\" && !this.ended) {\n this.patch({ status: \"idle\" });\n if (this.pending()) this.schedule();\n }\n };\n\n private startFrom(seed: DraftSeed<V, R>, value: V, discarded: boolean) {\n this.saved = seed.row ? this.options().toValue(seed.row) : seed.value;\n this.dirty.clear();\n this.ended = false;\n this.inflight = null;\n this.patch({\n row: seed.row,\n value,\n status: this.enabled() ? \"idle\" : \"stopped\",\n error: null,\n discarded,\n key: this.state.key + 1,\n });\n }\n\n private enabled() {\n return this.options().enabled ?? true;\n }\n\n private active() {\n return this.enabled() && !this.ended;\n }\n\n private same(a: V, b: V) {\n const equal = this.options().equal;\n return equal ? equal(a, b) : stableJson(a) === stableJson(b);\n }\n\n private schedule() {\n this.clearTimer();\n this.timer = setTimeout(() => {\n this.timer = undefined;\n void this.flush();\n }, this.options().delayMs ?? DEFAULT_DRAFT_DELAY_MS);\n }\n\n private clearTimer() {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n private patch(change: Partial<DraftState<V, R>>) {\n this.state = { ...this.state, ...change };\n for (const listener of this.listeners) listener();\n }\n\n private async save(keepalive: boolean): Promise<void> {\n if (!this.active()) return;\n const opts = this.options();\n const value = this.state.value;\n if (this.same(value, this.saved)) return;\n const isEmpty = opts.isEmpty ?? ((v: V) => !Object.values(v).some(hasContent));\n if (!this.state.row && isEmpty(value)) return;\n this.patch({ status: \"saving\" });\n const generation = this.generation;\n this.inflight = value;\n try {\n const { row, merged } = await this.write(value, keepalive, this.state.row, generation);\n this.inflight = null;\n // A new revision arrived while this ran: the server's copy won, so this result is stale.\n if (generation !== this.generation) return;\n const stored = opts.toValue(row);\n // What was sent, not what came back: a store that tidies values (trims text, fills\n // defaults) would otherwise look unsaved forever and be written again and again.\n this.saved = merged ? stored : value;\n if (merged) {\n // Another tab's row: show its fields, keeping only those changed here.\n const next = { ...stored } as DraftValue;\n for (const key of this.dirty) next[key] = this.state.value[key];\n this.patch({ row, value: next as V, status: \"saved\", error: null, key: this.state.key + 1 });\n } else {\n this.patch({ row, status: \"saved\", error: null });\n }\n opts.onSaved?.(row);\n // Typed while this save ran, or merged: save again.\n if (this.pending()) this.schedule();\n } catch (error) {\n if (generation === this.generation) this.inflight = null;\n if (error instanceof Halt || generation !== this.generation) return;\n this.patch({ status: \"error\", error: (opts.messageOf ?? plainMessage)(error) });\n }\n }\n\n /**\n * One save: change the row, or add it (merging on a duplicate), retrying network failures.\n * The row is the one the save started with, never one a later revision brought in.\n */\n private async write(\n value: V,\n keepalive: boolean,\n start: R | null,\n generation: number,\n ): Promise<{ row: R; merged: boolean }> {\n const opts = this.options();\n const retries = opts.retries ?? 3;\n const isRetryable = opts.isRetryable ?? isNetworkFailure;\n for (let attempt = 0; ; attempt++) {\n try {\n if (start) return { row: await opts.update(start, value, { keepalive }), merged: false };\n try {\n return { row: await opts.create(value, { keepalive }), merged: false };\n } catch (error) {\n if (!opts.adopt || !(opts.isDuplicate ?? isDuplicateOutcome)(error)) throw error;\n const adopted = await opts.adopt(value, this.dirty);\n if (generation !== this.generation) throw new Halt();\n if (\"final\" in adopted) {\n this.ended = true;\n this.saved = opts.toValue(adopted.final);\n this.patch({ row: adopted.final, status: \"stopped\", error: null });\n opts.onFinal?.(adopted.final);\n throw new Halt();\n }\n return { row: adopted.row, merged: true };\n }\n } catch (error) {\n if (error instanceof Halt || attempt >= retries || !isRetryable(error)) throw error;\n await new Promise((resolve) => setTimeout(resolve, (opts.retryDelayMs ?? 500) * 2 ** attempt));\n // A new revision while waiting: these edits no longer belong to the row it brought.\n if (!this.active() || generation !== this.generation) throw new Halt();\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/draft-controller.ts"],"names":[],"mappings":";;;AAgGO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,eAAA,GAAkB;AAGxB,SAAS,WAAW,KAAA,EAAwB;AACjD,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IAAU,KAAA;AAAA,IAAO,CAAC,IAAA,EAAM,CAAA,KAClC,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAC1C,MAAA,CAAO,WAAA;AAAA,MACL,OAAO,OAAA,CAAQ,CAA4B,EAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,MAAO,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,GAAI,CAAA,GAAI,IAAI,CAAE;AAAA,KAC9F,GACA;AAAA,GACN;AACF;AAGA,SAAS,WAAW,CAAA,EAAqB;AACvC,EAAA,IAAI,CAAA,KAAM,MAAA,IAAa,CAAA,KAAM,IAAA,EAAM,OAAO,KAAA;AAC1C,EAAA,IAAI,OAAO,CAAA,KAAM,QAAA,EAAU,OAAO,CAAA,CAAE,MAAK,KAAM,EAAA;AAC/C,EAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,KAAK,UAAU,CAAA;AAC9C,EAAA,IAAI,OAAO,MAAM,QAAA,EAAU,OAAO,OAAO,MAAA,CAAO,CAA4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A,IAAe,kBAAA,EAAoB,KAAK,CAAA,EAAG,MAAM,KAAA;AAC3E,UAAA,MAAM,UAAU,MAAM,IAAA,CAAK,KAAA,CAAM,KAAA,EAAO,KAAK,KAAK,CAAA;AAClD,UAAA,IAAI,UAAA,KAAe,IAAA,CAAK,UAAA,EAAY,MAAM,IAAI,IAAA,EAAK;AACnD,UAAA,IAAI,WAAW,OAAA,EAAS;AACtB,YAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AACb,YAAA,IAAA,CAAK,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA;AACvC,YAAA,IAAA,CAAK,KAAA,CAAM,EAAE,GAAA,EAAK,OAAA,CAAQ,OAAO,MAAA,EAAQ,SAAA,EAAW,KAAA,EAAO,IAAA,EAAM,CAAA;AACjE,YAAA,IAAA,CAAK,OAAA,GAAU,QAAQ,KAAK,CAAA;AAC5B,YAAA,MAAM,IAAI,IAAA,EAAK;AAAA,UACjB;AACA,UAAA,OAAO,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAK,QAAQ,IAAA,EAAK;AAAA,QAC1C;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,KAAA,YAAiB,QAAQ,OAAA,IAAW,OAAA,IAAW,CAAC,WAAA,CAAY,KAAK,GAAG,MAAM,KAAA;AAC9E,QAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY,UAAA,CAAW,OAAA,EAAA,CAAU,IAAA,CAAK,YAAA,IAAgB,GAAA,IAAO,CAAA,IAAK,OAAO,CAAC,CAAA;AAE7F,QAAA,IAAI,CAAC,KAAK,MAAA,EAAO,IAAK,eAAe,IAAA,CAAK,UAAA,EAAY,MAAM,IAAI,IAAA,EAAK;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AACF","file":"chunk-5ASUMG6K.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Autosave a draft (README \"Autosave a draft\")\n//\n// A draft is one row someone edits over time: an answer to a questionnaire, a\n// note, a journal entry. It is saved as they type, a moment after they stop,\n// and the first save adds the row. The app supplies the writes, so this works\n// with any backend; nothing here talks to a database.\n//\n// DraftController holds the rules and is plain TypeScript; `useDraft` is its\n// React wrapper.\n// ---------------------------------------------------------------------------\n\nimport { isDataWriteError } from \"../schema/write-outcome\";\n\n/** A draft's value: a flat map of fields (a table or a list is one field). */\nexport type DraftValue = Record<string, unknown>;\n\nexport type DraftStatus = \"idle\" | \"saving\" | \"saved\" | \"error\" | \"stopped\";\n\nexport interface DraftSeed<V extends DraftValue, R> {\n /** The row as the server has it, or null before the first save. */\n row: R | null;\n /** The value to start from: the row's, or a blank one. */\n value: V;\n}\n\n/** What `adopt` found: the row it merged into, or a row already finished elsewhere. */\nexport type DraftAdoption<R> = { row: R } | { final: R };\n\nexport interface DraftOptions<V extends DraftValue, R> {\n seed: DraftSeed<V, R>;\n /**\n * Changes when the server's copy changes in a way that wins over edits here\n * (it was sent from another tab, a reviewer returned it). The draft then\n * starts again from the new `seed`; see `onRevision`.\n */\n revision?: string | undefined;\n /** The first write: add the row. `keepalive` is set for the save made as the page closes. */\n create: (value: V, hints: { keepalive: boolean }) => Promise<R>;\n /** Later writes. `keepalive` is set for the save made as the page closes. */\n update: (row: R, value: V, hints: { keepalive: boolean }) => Promise<R>;\n /** The value a saved row holds. */\n toValue: (row: R) => V;\n /** A row's identity, to tell the same row from another. Default: its `id`. */\n idOf?: ((row: R) => unknown) | undefined;\n /**\n * The first write found a row already there (another tab started it): merge\n * into it, or report that it is already finished. `dirty` names the fields\n * changed here since the draft started; only those should be written over\n * the existing row's. Without `adopt`, the duplicate is an error.\n */\n adopt?: ((value: V, dirty: ReadonlySet<string>) => Promise<DraftAdoption<R>>) | undefined;\n /** Whether a failed `create` means \"a row is already there\". Default: a `duplicate` write outcome. */\n isDuplicate?: ((error: unknown) => boolean) | undefined;\n /** Never add a row for this value. Default: no field has anything in it. */\n isEmpty?: ((value: V) => boolean) | undefined;\n /** Default: the same JSON, whatever the order of object keys. */\n equal?: ((a: V, b: V) => boolean) | undefined;\n /** How long after the last change to save. Default 800 ms. */\n delayMs?: number | undefined;\n /** False: nothing is written (someone else's draft, or one already sent). Default true. */\n enabled?: boolean | undefined;\n /** After each save, with the row as saved: write it into the app's cache here. */\n onSaved?: ((row: R) => void) | undefined;\n /** `adopt` found the row finished elsewhere: nothing more is saved. */\n onFinal?: ((row: R) => void) | undefined;\n /**\n * `revision` changed with edits not yet saved: return the value to keep (a\n * merge), or null to drop the edits for the server's. Default: drop them.\n */\n onRevision?: ((pending: V, next: DraftSeed<V, R>) => V | null) | undefined;\n /** Whether a failed write is worth trying again. Default: network failures only, never refusals. */\n isRetryable?: ((error: unknown) => boolean) | undefined;\n /** Tries after the first, on a retryable failure. Default 3. */\n retries?: number | undefined;\n /** The first retry's wait; each later one doubles it. Default 500 ms. */\n retryDelayMs?: number | undefined;\n /** The words shown for a failed save. Default: the write error's own plain message. */\n messageOf?: ((error: unknown) => string) | undefined;\n}\n\nexport interface DraftState<V extends DraftValue, R> {\n value: V;\n row: R | null;\n status: DraftStatus;\n /** Why the last save failed, in plain words; null once one succeeds. */\n error: string | null;\n /** True after a new revision replaced edits that weren't saved, so the page can say so. */\n discarded: boolean;\n /**\n * Changes when the value is replaced from outside the editor (merged with\n * another tab's row, or a new revision): remount the editor on it.\n */\n key: number;\n}\n\nexport const DEFAULT_DRAFT_DELAY_MS = 800;\nexport const DRAFT_NOT_SAVED = \"Your changes weren't saved.\";\n\n/** JSON with object keys sorted, so values compare equal whatever order a store keeps keys in. */\nexport function stableJson(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(\n Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n )\n : v,\n );\n}\n\n/** Something in it: not undefined, null, blank text, or a list or object of nothing. */\nfunction hasContent(v: unknown): boolean {\n if (v === undefined || v === null) return false;\n if (typeof v === \"string\") return v.trim() !== \"\";\n if (Array.isArray(v)) return v.some(hasContent);\n if (typeof v === \"object\") return Object.values(v as Record<string, unknown>).some(hasContent);\n return true;\n}\n\n/** The default `isRetryable`: a request that never reached the store. A refusal never is. */\nexport function isNetworkFailure(error: unknown): boolean {\n if (isDataWriteError(error)) return error.outcome === \"error\" && error.code === undefined;\n return error instanceof TypeError;\n}\n\nfunction defaultId(row: unknown): unknown {\n return row && typeof row === \"object\" && \"id\" in row ? (row as { id: unknown }).id : row;\n}\n\nfunction isDuplicateOutcome(error: unknown): boolean {\n return isDataWriteError(error) && error.outcome === \"duplicate\";\n}\n\nfunction plainMessage(error: unknown): string {\n return isDataWriteError(error) && error.message ? error.message : DRAFT_NOT_SAVED;\n}\n\n/** Thrown inside a save to end it quietly: the draft stopped while it ran. */\nclass Halt {}\n\n/**\n * The rules of a draft, without React: one write at a time, add then change,\n * no write when nothing changed or for an empty value, merge into a row\n * another tab started, start again on a new revision, retry network failures,\n * and a final write (`commit`) that ends it.\n */\nexport class DraftController<V extends DraftValue, R> {\n private state: DraftState<V, R>;\n /** The value as last saved (or as loaded): what \"unchanged\" compares with. */\n private saved: V;\n /** Fields changed here since the draft started (or since the last revision). */\n private dirty = new Set<string>();\n private chain: Promise<unknown> = Promise.resolve();\n private timer: ReturnType<typeof setTimeout> | undefined;\n private revision: string | undefined;\n private ended = false;\n /** Bumped by each new revision: a save that started before it lands on nothing. */\n private generation = 0;\n /** The value of the write in flight, so a seed that is only that write coming back is known. */\n private inflight: V | null = null;\n private listeners = new Set<() => void>();\n\n constructor(private readonly options: () => DraftOptions<V, R>) {\n const { seed, revision, toValue } = options();\n this.revision = revision;\n this.saved = seed.row ? toValue(seed.row) : seed.value;\n this.state = { value: seed.value, row: seed.row, status: \"idle\", error: null, discarded: false, key: 0 };\n }\n\n readonly subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n readonly getState = () => this.state;\n\n /** Edits this draft would still save. */\n readonly pending = () => this.active() && !this.same(this.state.value, this.saved);\n\n /** The editor's new value: its changed fields are noted, and it's saved a moment after the last change. */\n readonly set = (value: V) => {\n const before = this.state.value;\n for (const key of new Set([...Object.keys(before), ...Object.keys(value)])) {\n if (stableJson(before[key]) !== stableJson(value[key])) this.dirty.add(key);\n }\n this.patch({ value, discarded: false });\n if (this.active()) this.schedule();\n };\n\n /** Save now, after any write already running. Resolves once written or failed; never rejects. */\n readonly flush = (hints: { keepalive?: boolean } = {}): Promise<void> => {\n this.clearTimer();\n // Never rejects, so one throwing option (isEmpty, equal) can't wedge the chain.\n const run = this.chain\n .then(() => this.save(hints.keepalive ?? false))\n .catch((error: unknown) => {\n this.patch({ status: \"error\", error: (this.options().messageOf ?? plainMessage)(error) });\n });\n this.chain = run;\n return run;\n };\n\n /**\n * The final write (a submit), after any write in flight, given the row so far\n * (null before the first save) and the value. On success nothing more is\n * saved and the draft is `stopped`; on failure it is thrown to the caller and\n * autosave carries on.\n */\n readonly commit = (write: (row: R | null, value: V) => Promise<R>): Promise<R> => {\n this.clearTimer();\n const run = this.chain.then(async () => {\n const row = await write(this.state.row, this.state.value);\n this.ended = true;\n this.saved = this.options().toValue(row);\n this.patch({ row, status: \"stopped\", error: null });\n this.options().onSaved?.(row);\n return row;\n });\n // A failed commit leaves the draft as it was: autosave carries on.\n this.chain = run.catch(() => {\n if (this.pending()) this.schedule();\n });\n return run;\n };\n\n /**\n * The server's seed again. Ignored unless `revision` changed. Then, in order:\n * - the seed is this draft's own save coming back (the same row, holding what\n * was last saved or is being saved): take its row and keep every edit;\n * - it is another row, with edits pending here: those are saved to the row\n * they belong to first, then the draft moves to the new one;\n * - otherwise the server's copy wins: the draft starts again from it, keeping\n * only what `onRevision` returns.\n */\n readonly reseed = (seed: DraftSeed<V, R>, revision: string | undefined) => {\n if (revision === this.revision) return;\n this.revision = revision;\n const opts = this.options();\n const idOf = opts.idOf ?? defaultId;\n const current = this.state.row;\n const echo =\n seed.row !== null &&\n (current === null || idOf(seed.row) === idOf(current)) &&\n (this.same(opts.toValue(seed.row), this.saved) ||\n (this.inflight !== null && this.same(opts.toValue(seed.row), this.inflight)));\n if (echo && (current !== null || this.inflight !== null)) {\n this.patch({ row: seed.row });\n return;\n }\n this.generation++;\n this.clearTimer();\n const pending = !this.same(this.state.value, this.saved);\n if (pending && current !== null && seed.row !== null && idOf(seed.row) !== idOf(current) && this.active()) {\n // Another row: what was typed belongs to the old one, so save it there first.\n const value = this.state.value;\n this.chain = this.chain\n .then(() => opts.update(current, value, { keepalive: false }))\n .then((row) => opts.onSaved?.(row))\n .catch(() => undefined);\n this.startFrom(seed, seed.value, false);\n return;\n }\n const kept = pending ? (opts.onRevision?.(this.state.value, seed) ?? null) : null;\n this.startFrom(seed, kept ?? seed.value, pending && kept === null);\n if (kept !== null && this.pending()) this.schedule();\n };\n\n /** Call when `enabled` may have changed: off stops saving; back on saves what's pending. */\n readonly sync = () => {\n if (!this.enabled()) {\n this.clearTimer();\n if (this.state.status !== \"stopped\") this.patch({ status: \"stopped\" });\n } else if (this.state.status === \"stopped\" && !this.ended) {\n this.patch({ status: \"idle\" });\n if (this.pending()) this.schedule();\n }\n };\n\n private startFrom(seed: DraftSeed<V, R>, value: V, discarded: boolean) {\n this.saved = seed.row ? this.options().toValue(seed.row) : seed.value;\n this.dirty.clear();\n this.ended = false;\n this.inflight = null;\n this.patch({\n row: seed.row,\n value,\n status: this.enabled() ? \"idle\" : \"stopped\",\n error: null,\n discarded,\n key: this.state.key + 1,\n });\n }\n\n private enabled() {\n return this.options().enabled ?? true;\n }\n\n private active() {\n return this.enabled() && !this.ended;\n }\n\n private same(a: V, b: V) {\n const equal = this.options().equal;\n return equal ? equal(a, b) : stableJson(a) === stableJson(b);\n }\n\n private schedule() {\n this.clearTimer();\n this.timer = setTimeout(() => {\n this.timer = undefined;\n void this.flush();\n }, this.options().delayMs ?? DEFAULT_DRAFT_DELAY_MS);\n }\n\n private clearTimer() {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n private patch(change: Partial<DraftState<V, R>>) {\n this.state = { ...this.state, ...change };\n for (const listener of this.listeners) listener();\n }\n\n private async save(keepalive: boolean): Promise<void> {\n if (!this.active()) return;\n const opts = this.options();\n const value = this.state.value;\n if (this.same(value, this.saved)) return;\n const isEmpty = opts.isEmpty ?? ((v: V) => !Object.values(v).some(hasContent));\n if (!this.state.row && isEmpty(value)) return;\n this.patch({ status: \"saving\" });\n const generation = this.generation;\n this.inflight = value;\n try {\n const { row, merged } = await this.write(value, keepalive, this.state.row, generation);\n this.inflight = null;\n // A new revision arrived while this ran: the server's copy won, so this result is stale.\n if (generation !== this.generation) return;\n const stored = opts.toValue(row);\n // What was sent, not what came back: a store that tidies values (trims text, fills\n // defaults) would otherwise look unsaved forever and be written again and again.\n this.saved = merged ? stored : value;\n if (merged) {\n // Another tab's row: show its fields, keeping only those changed here.\n const next = { ...stored } as DraftValue;\n for (const key of this.dirty) next[key] = this.state.value[key];\n this.patch({ row, value: next as V, status: \"saved\", error: null, key: this.state.key + 1 });\n } else {\n this.patch({ row, status: \"saved\", error: null });\n }\n opts.onSaved?.(row);\n // Typed while this save ran, or merged: save again.\n if (this.pending()) this.schedule();\n } catch (error) {\n if (generation === this.generation) this.inflight = null;\n if (error instanceof Halt || generation !== this.generation) return;\n this.patch({ status: \"error\", error: (opts.messageOf ?? plainMessage)(error) });\n }\n }\n\n /**\n * One save: change the row, or add it (merging on a duplicate), retrying network failures.\n * The row is the one the save started with, never one a later revision brought in.\n */\n private async write(\n value: V,\n keepalive: boolean,\n start: R | null,\n generation: number,\n ): Promise<{ row: R; merged: boolean }> {\n const opts = this.options();\n const retries = opts.retries ?? 3;\n const isRetryable = opts.isRetryable ?? isNetworkFailure;\n for (let attempt = 0; ; attempt++) {\n try {\n if (start) return { row: await opts.update(start, value, { keepalive }), merged: false };\n try {\n return { row: await opts.create(value, { keepalive }), merged: false };\n } catch (error) {\n if (!opts.adopt || !(opts.isDuplicate ?? isDuplicateOutcome)(error)) throw error;\n const adopted = await opts.adopt(value, this.dirty);\n if (generation !== this.generation) throw new Halt();\n if (\"final\" in adopted) {\n this.ended = true;\n this.saved = opts.toValue(adopted.final);\n this.patch({ row: adopted.final, status: \"stopped\", error: null });\n opts.onFinal?.(adopted.final);\n throw new Halt();\n }\n return { row: adopted.row, merged: true };\n }\n } catch (error) {\n if (error instanceof Halt || attempt >= retries || !isRetryable(error)) throw error;\n await new Promise((resolve) => setTimeout(resolve, (opts.retryDelayMs ?? 500) * 2 ** attempt));\n // A new revision while waiting: these edits no longer belong to the row it brought.\n if (!this.active() || generation !== this.generation) throw new Halt();\n }\n }\n }\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { NO_VIEWER } from './chunk-OZYF55E3.js';
|
|
2
2
|
import { workspaceAt, workspaceHref } from './chunk-UHOMTFBD.js';
|
|
3
|
-
import { stableJson } from './chunk-
|
|
4
|
-
import { flushPendingWrites, dropPendingWrites } from './chunk-
|
|
5
|
-
import { PersistedViewerContext } from './chunk-
|
|
3
|
+
import { stableJson } from './chunk-5ASUMG6K.js';
|
|
4
|
+
import { flushPendingWrites, dropPendingWrites } from './chunk-RFHUOXZC.js';
|
|
5
|
+
import { PersistedViewerContext } from './chunk-2K4747KX.js';
|
|
6
6
|
import { isTimeZone, personTimeZone, dayIn } from './chunk-WXENWPWP.js';
|
|
7
|
-
import { reportError } from './chunk-
|
|
7
|
+
import { reportError } from './chunk-NOPS5EIH.js';
|
|
8
8
|
import { useQueryClient } from '@tanstack/react-query';
|
|
9
9
|
import { createContext, useContext, useMemo, useRef, useEffect, useState, Fragment as Fragment$1 } from 'react';
|
|
10
10
|
import { jsx, Fragment } from 'react/jsx-runtime';
|
|
@@ -166,5 +166,5 @@ function WorkspaceScope({ workspaces, pathname, scope, keep, children, ...viewer
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace };
|
|
169
|
-
//# sourceMappingURL=chunk-
|
|
170
|
-
//# sourceMappingURL=chunk-
|
|
169
|
+
//# sourceMappingURL=chunk-AHFIS42U.js.map
|
|
170
|
+
//# sourceMappingURL=chunk-AHFIS42U.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","createContext","useContext","useMemo","useEffect","jsx"],"mappings":";;;;;;;;;;;AAWA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,MAAM,CAAC,UAAA,CAAW,CAAC,CAAA,EAAG,CAAC,CAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,IAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAE,EAAE,GAAA,CAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;AACnJ,IAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,EAAU;AAC9B,MAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,CAAC,CAAA;AACrC,MAAA,IAAI,KAAA,KAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAChD,QAAA,IAAI,QAAQ,GAAA,CAAI,QAAA,KAAa,cAAc,MAAM,IAAI,UAAU,4EAA4E,CAAA;AAC3I,QAAA,QAAA,GAAW,IAAA;AACX,QAAA,OAAO,IAAA;AAAA,MACT;AACA,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CAAY,UAAA,EAAY,QAAQ,CAAA;AAChD,EAAA,MAAM,KAAA,GAAQC,OAAAA;AAAA,IACZ,OAAO;AAAA,MACL,OAAA;AAAA,MACA,UAAA;AAAA,MACA,OAAA,EAAS,CAAC,EAAA,KAAO,aAAA,CAAc,UAAA,EAAY,EAAA,EAAI,QAAA,EAAU,IAAA,GAAO,EAAE,IAAA,EAAK,GAAI,EAAE;AAAA,KAC/E,CAAA;AAAA,IACA,CAAC,OAAA,EAAS,UAAA,EAAY,QAAA,EAAU,IAAI;AAAA,GACtC;AACA,EAAA,MAAM,SAAS,WAAA,CAAY,MAAA;AAC3B,EAAAC,UAAU,MAAM;AACd,IAAA,IAAI,MAAA,IAAU,OAAA,EAAS,QAAA,CAAS,MAAA,EAAQ,QAAQ,EAAE,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACEC,GAAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,OAC9B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-C62CMLWG.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, isTimeZone, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\nimport { PersistedViewerContext } from \"../provider/context\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the person, space or set of people Genesis knows by name, plus\n * whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).\n * Screens turn it into server filters and create defaults (a view's `scope: [\"league_id\"]` reads\n * `league_id`, then `leagueId`); it never decides access (row-level security does).\n */\nexport interface ResourceScope {\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n /** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * The zone of whatever the viewer is scoped to (a location, a league), for columns with\n * `timeZone: \"scope\"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.\n */\n scopeTimeZone?: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied. Inside a\n * `GenesisProvider` with `persist`, it defaults to its `persistScope`'s user.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /**\n * The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.\n * Columns with `timeZone: \"scope\"` read on it; without it they read on the viewer's clock.\n */\n scopeTimeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it\n * doesn't know is never a quiet fallback: it throws in development, and in production it is\n * reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show\n * times on the wrong clock unnoticed.\n */\nexport function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string {\n if (scopeTimeZone === undefined || scopeTimeZone === null || scopeTimeZone === \"\") return viewerZone;\n if (isTimeZone(scopeTimeZone)) return scopeTimeZone;\n const error = new RangeError(`[genesis-core] scopeTimeZone \"${scopeTimeZone}\" isn't a time zone this runtime knows (an IANA name such as \"Europe/Berlin\")`);\n if (process.env.NODE_ENV !== \"production\") throw error;\n // Once per zone: a bad zone in a long-lived screen must not flood the error reporter.\n if (!reportedScopeZones.has(scopeTimeZone)) {\n reportedScopeZones.add(scopeTimeZone);\n reportError(error, \"core:viewer-scope\");\n }\n return viewerZone;\n}\n\n/** The unknown scope zones already reported, so each is reported once per page load. */\nconst reportedScopeZones = new Set<string>();\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const restoredFor = useContext(PersistedViewerContext);\n const persistedViewer = persistedViewerProp !== undefined ? persistedViewerProp : restoredFor;\n const zone = personTimeZone({ timeZone });\n // Memoised, and scopeClock reports a zone once, so a bad zone isn't reported on every render.\n const scopeZone = useMemo(() => scopeClock(scopeTimeZone, zone), [scopeTimeZone, zone]);\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, scopeTimeZone: scopeZone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, scopeZone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted({ viewer, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed-out\"}#${mounted.epoch}`}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n","import { createContext, useContext, useEffect, useMemo } from \"react\";\nimport { ViewerScope, type ViewerScopeProps } from \"./viewer-scope\";\nimport { workspaceAt, workspaceHref, type Workspace, type WorkspaceHrefOptions } from \"../workspaces\";\n\n/**\n * The workspace the viewer is in, and where each of their others is from here.\n *\n * @stability Beta\n */\nexport interface WorkspaceContext<W extends Workspace = Workspace> {\n /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */\n current: W | undefined;\n workspaces: readonly W[];\n /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */\n hrefFor: (to: W) => string;\n}\n\nconst WorkspaceContextValue = createContext<WorkspaceContext | null>(null);\n\n/**\n * The nearest `WorkspaceScope`'s workspaces, or null outside one.\n *\n * @stability Beta\n */\nexport function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null {\n return useContext(WorkspaceContextValue) as WorkspaceContext<W> | null;\n}\n\nconst STORAGE_PREFIX = \"genesis:workspace:\";\n\n/**\n * The workspace this viewer was last in on this device, for the app's front door\n * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.\n *\n * @stability Beta\n */\nexport function rememberedWorkspaceId(viewer: string | null | undefined): string | null {\n if (!viewer || typeof window === \"undefined\") return null;\n try {\n return window.localStorage.getItem(STORAGE_PREFIX + viewer);\n } catch {\n return null;\n }\n}\n\nfunction remember(viewer: string, id: string) {\n try {\n window.localStorage.setItem(STORAGE_PREFIX + viewer, id);\n } catch {\n // private mode or full: the front door falls back to the first tenant.\n }\n}\n\n/** @stability Beta */\nexport interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, \"scope\" | \"roles\" | \"scopeTimeZone\"> {\n /** Every workspace this viewer has. */\n workspaces: readonly W[];\n /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */\n pathname: string;\n /** Scope keys every workspace adds to its own (rarely needed). */\n scope?: ViewerScopeProps[\"scope\"];\n /** How switching keeps the viewer's place (see `workspaceHref`). */\n keep?: WorkspaceHrefOptions[\"keep\"];\n}\n\n/**\n * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current\n * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and\n * `timeZone`), so every view with `scope: [\"org_id\"]` follows the switcher with no screen code. It\n * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.\n *\n * ```tsx\n * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>\n * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>\n * </WorkspaceScope>\n * ```\n *\n * @stability Beta\n */\nexport function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>) {\n const current = workspaceAt(workspaces, pathname);\n const value = useMemo<WorkspaceContext<W>>(\n () => ({\n current,\n workspaces,\n hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {}),\n }),\n [current, workspaces, pathname, keep],\n );\n const viewer = viewerProps.viewer;\n useEffect(() => {\n if (viewer && current) remember(viewer, current.id);\n }, [viewer, current]);\n return (\n <WorkspaceContextValue.Provider value={value as unknown as WorkspaceContext}>\n <ViewerScope\n {...viewerProps}\n scope={{ ...scope, ...current?.scope }}\n {...(current?.roles !== undefined ? { roles: current.roles } : {})}\n {...(current?.timeZone !== undefined ? { scopeTimeZone: current.timeZone } : {})}\n >\n {children}\n </ViewerScope>\n </WorkspaceContextValue.Provider>\n );\n}\n\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","createContext","useContext","useMemo","useEffect","jsx"],"mappings":";;;;;;;;;;;AAWA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IA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,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACEC,GAAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,OAC9B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-AHFIS42U.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, isTimeZone, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\nimport { PersistedViewerContext } from \"../provider/context\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the person, space or set of people Genesis knows by name, plus\n * whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).\n * Screens turn it into server filters and create defaults (a view's `scope: [\"league_id\"]` reads\n * `league_id`, then `leagueId`); it never decides access (row-level security does).\n */\nexport interface ResourceScope {\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n /** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * The zone of whatever the viewer is scoped to (a location, a league), for columns with\n * `timeZone: \"scope\"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.\n */\n scopeTimeZone?: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied. Inside a\n * `GenesisProvider` with `persist`, it defaults to its `persistScope`'s user.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /**\n * The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.\n * Columns with `timeZone: \"scope\"` read on it; without it they read on the viewer's clock.\n */\n scopeTimeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it\n * doesn't know is never a quiet fallback: it throws in development, and in production it is\n * reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show\n * times on the wrong clock unnoticed.\n */\nexport function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string {\n if (scopeTimeZone === undefined || scopeTimeZone === null || scopeTimeZone === \"\") return viewerZone;\n if (isTimeZone(scopeTimeZone)) return scopeTimeZone;\n const error = new RangeError(`[genesis-core] scopeTimeZone \"${scopeTimeZone}\" isn't a time zone this runtime knows (an IANA name such as \"Europe/Berlin\")`);\n if (process.env.NODE_ENV !== \"production\") throw error;\n // Once per zone: a bad zone in a long-lived screen must not flood the error reporter.\n if (!reportedScopeZones.has(scopeTimeZone)) {\n reportedScopeZones.add(scopeTimeZone);\n reportError(error, \"core:viewer-scope\");\n }\n return viewerZone;\n}\n\n/** The unknown scope zones already reported, so each is reported once per page load. */\nconst reportedScopeZones = new Set<string>();\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const restoredFor = useContext(PersistedViewerContext);\n const persistedViewer = persistedViewerProp !== undefined ? persistedViewerProp : restoredFor;\n const zone = personTimeZone({ timeZone });\n // Memoised, and scopeClock reports a zone once, so a bad zone isn't reported on every render.\n const scopeZone = useMemo(() => scopeClock(scopeTimeZone, zone), [scopeTimeZone, zone]);\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, scopeTimeZone: scopeZone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, scopeZone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted({ viewer, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed-out\"}#${mounted.epoch}`}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n","import { createContext, useContext, useEffect, useMemo } from \"react\";\nimport { ViewerScope, type ViewerScopeProps } from \"./viewer-scope\";\nimport { workspaceAt, workspaceHref, type Workspace, type WorkspaceHrefOptions } from \"../workspaces\";\n\n/**\n * The workspace the viewer is in, and where each of their others is from here.\n *\n * @stability Beta\n */\nexport interface WorkspaceContext<W extends Workspace = Workspace> {\n /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */\n current: W | undefined;\n workspaces: readonly W[];\n /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */\n hrefFor: (to: W) => string;\n}\n\nconst WorkspaceContextValue = createContext<WorkspaceContext | null>(null);\n\n/**\n * The nearest `WorkspaceScope`'s workspaces, or null outside one.\n *\n * @stability Beta\n */\nexport function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null {\n return useContext(WorkspaceContextValue) as WorkspaceContext<W> | null;\n}\n\nconst STORAGE_PREFIX = \"genesis:workspace:\";\n\n/**\n * The workspace this viewer was last in on this device, for the app's front door\n * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.\n *\n * @stability Beta\n */\nexport function rememberedWorkspaceId(viewer: string | null | undefined): string | null {\n if (!viewer || typeof window === \"undefined\") return null;\n try {\n return window.localStorage.getItem(STORAGE_PREFIX + viewer);\n } catch {\n return null;\n }\n}\n\nfunction remember(viewer: string, id: string) {\n try {\n window.localStorage.setItem(STORAGE_PREFIX + viewer, id);\n } catch {\n // private mode or full: the front door falls back to the first tenant.\n }\n}\n\n/** @stability Beta */\nexport interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, \"scope\" | \"roles\" | \"scopeTimeZone\"> {\n /** Every workspace this viewer has. */\n workspaces: readonly W[];\n /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */\n pathname: string;\n /** Scope keys every workspace adds to its own (rarely needed). */\n scope?: ViewerScopeProps[\"scope\"];\n /** How switching keeps the viewer's place (see `workspaceHref`). */\n keep?: WorkspaceHrefOptions[\"keep\"];\n}\n\n/**\n * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current\n * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and\n * `timeZone`), so every view with `scope: [\"org_id\"]` follows the switcher with no screen code. It\n * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.\n *\n * ```tsx\n * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>\n * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>\n * </WorkspaceScope>\n * ```\n *\n * @stability Beta\n */\nexport function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>) {\n const current = workspaceAt(workspaces, pathname);\n const value = useMemo<WorkspaceContext<W>>(\n () => ({\n current,\n workspaces,\n hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {}),\n }),\n [current, workspaces, pathname, keep],\n );\n const viewer = viewerProps.viewer;\n useEffect(() => {\n if (viewer && current) remember(viewer, current.id);\n }, [viewer, current]);\n return (\n <WorkspaceContextValue.Provider value={value as unknown as WorkspaceContext}>\n <ViewerScope\n {...viewerProps}\n scope={{ ...scope, ...current?.scope }}\n {...(current?.roles !== undefined ? { roles: current.roles } : {})}\n {...(current?.timeZone !== undefined ? { scopeTimeZone: current.timeZone } : {})}\n >\n {children}\n </ViewerScope>\n </WorkspaceContextValue.Provider>\n );\n}\n\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { relationNamingField } from './chunk-
|
|
2
|
-
import { useInfiniteResource } from './chunk-
|
|
3
|
-
import { useDataProvider } from './chunk-
|
|
1
|
+
import { relationNamingField } from './chunk-WDPM5TBO.js';
|
|
2
|
+
import { useInfiniteResource } from './chunk-G6GQPXQS.js';
|
|
3
|
+
import { useDataProvider } from './chunk-2K4747KX.js';
|
|
4
4
|
import { useMemo, useState, useEffect } from 'react';
|
|
5
5
|
import { useQuery } from '@tanstack/react-query';
|
|
6
6
|
|
|
@@ -34,10 +34,14 @@ function useLinkOptions(target, options = {}) {
|
|
|
34
34
|
const ordered = target.orderBy && IDENTIFIER.test(target.orderBy.field) ? target.orderBy : void 0;
|
|
35
35
|
const orderField = ordered?.field;
|
|
36
36
|
const orderDirection = ordered?.direction === "desc" ? "desc" : "asc";
|
|
37
|
-
const
|
|
37
|
+
const orderNulls = ordered?.nulls === "first" || ordered?.nulls === "last" ? ordered.nulls : void 0;
|
|
38
|
+
const sortsFor = (by, order = "asc", nulls) => {
|
|
39
|
+
const first = { field: by, order, ...nulls ? { nulls } : {} };
|
|
40
|
+
return by === field || !IDENTIFIER.test(field) ? [first] : [first, { field, order: "asc" }];
|
|
41
|
+
};
|
|
38
42
|
const sortBy = orderField ?? naming;
|
|
39
|
-
const sortKey = sortBy ? `${sortBy}:${orderField ? orderDirection : "asc"}` : void 0;
|
|
40
|
-
const sorts = sortBy ? sortsFor(sortBy, orderField ? orderDirection : "asc") : void 0;
|
|
43
|
+
const sortKey = sortBy ? `${sortBy}:${orderField ? orderDirection : "asc"}:${orderField && orderNulls || ""}` : void 0;
|
|
44
|
+
const sorts = sortBy ? sortsFor(sortBy, orderField ? orderDirection : "asc", orderField ? orderNulls : void 0) : void 0;
|
|
41
45
|
const [sortedBy, setSortedBy] = useState(sortKey);
|
|
42
46
|
const list = useInfiniteResource(target.resource, {
|
|
43
47
|
...filters ? { defaultFilters: filters } : {},
|
|
@@ -51,7 +55,7 @@ function useLinkOptions(target, options = {}) {
|
|
|
51
55
|
const { setSorts, setSearch } = list;
|
|
52
56
|
useEffect(() => {
|
|
53
57
|
if (!sortBy) return;
|
|
54
|
-
setSorts(sortsFor(sortBy, orderField ? orderDirection : "asc"));
|
|
58
|
+
setSorts(sortsFor(sortBy, orderField ? orderDirection : "asc", orderField ? orderNulls : void 0));
|
|
55
59
|
setSortedBy(sortKey);
|
|
56
60
|
}, [sortKey, field, setSorts]);
|
|
57
61
|
useEffect(() => {
|
|
@@ -84,5 +88,5 @@ function useLinkOptions(target, options = {}) {
|
|
|
84
88
|
}
|
|
85
89
|
|
|
86
90
|
export { useLinkOptions };
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
88
|
-
//# sourceMappingURL=chunk-
|
|
91
|
+
//# sourceMappingURL=chunk-DFABPMEQ.js.map
|
|
92
|
+
//# sourceMappingURL=chunk-DFABPMEQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-link-options.ts"],"names":[],"mappings":";;;;;;AAaA,IAAM,UAAA,GAAa,0BAAA;AACnB,IAAM,MAAA,GAAS,6CAAA;AAyDf,SAAS,MAAM,KAAA,EAA+B;AAC5C,EAAA,IAAI,OAAO,UAAU,QAAA,IAAY,MAAA,CAAO,SAA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CAAK,WAAA;AAAA,IACd,UAAU,IAAA,CAAK,aAAA;AAAA,IACf,eAAe,IAAA,CAAK;AAAA,GACtB;AACF","file":"chunk-DFABPMEQ.js","sourcesContent":["// The rows a link's picker offers (docs/RESOURCE-VIEW.md, \"Links in forms\"): the linked resource\n// listed through the data provider, so row-level security decides what the viewer can pick, with\n// the picker's filters (the linked view's scope and default filter), searched and paged on the\n// server, a page at a time. Web's RelationField and native's link picker both draw it.\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, FilterParam, SortParam } from \"../provider/types\";\nimport { useInfiniteResource } from \"./use-infinite-resource\";\nimport { relationNamingField } from \"./use-relation-label\";\n\n// Field names only go into `select` and `sort`, so nothing else rides along in the request.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst NAMING = /^(name|title|label|full_name|display_name)$/;\n\nexport interface LinkTarget {\n /** The linked resource. */\n resource: string;\n /** The linked field the link stores. Default `id`. */\n field?: string | undefined;\n /** The linked field that names a row. Default: the provider's `describe`, else a name-like field. */\n labelField?: string | undefined;\n /** The linked fields a search matches. Default: the naming field. */\n searchFields?: readonly string[] | undefined;\n /**\n * The order rows are listed in (a `position`), then the key. Default: by the naming field, then\n * the key. A view's link passes its `orderBy` (`link.orderBy`, or the linked view's for `\"view\"`).\n */\n orderBy?: { readonly field: string; readonly direction?: \"asc\" | \"desc\" | undefined; readonly nulls?: \"first\" | \"last\" | undefined } | undefined;\n}\n\nexport interface UseLinkOptionsOptions {\n /** Filters every request carries: the linked view's scope and default filter, the link's own. */\n filters?: FilterParam[] | undefined;\n /** What the person typed. Sent to the server (`search`), never matched against loaded rows. */\n search?: string | undefined;\n /** Rows per page. Default 25. */\n perPage?: number | undefined;\n /** Default true. A picker passes false until it opens, so a closed form asks for nothing. */\n enabled?: boolean | undefined;\n /**\n * The words for a row whose naming field is empty: a picker passes its catalogue's\n * (`common.untitled`). Default \"Untitled\". Never the row's raw key.\n */\n untitled?: string | undefined;\n}\n\n/** One row a picker offers: the key it stores and the words it shows. */\nexport interface LinkOption {\n /** The linked row's key, as the row holds it (text or a number). */\n value: string | number;\n label: string;\n}\n\nexport interface UseLinkOptionsReturn {\n options: LinkOption[];\n /** The naming field used, once known. */\n labelField: string | undefined;\n /** Whether a search can be sent: false when nothing names the rows. */\n searchable: boolean;\n /** The first page is loading. */\n isLoading: boolean;\n isError: boolean;\n /** More rows than are loaded match. */\n hasMore: boolean;\n /** Loads the next page. Does nothing while one loads or none is left. */\n loadMore: () => void;\n isLoadingMore: boolean;\n}\n\nfunction words(value: unknown): string | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n if (typeof value !== \"string\") return null;\n return value.trim() || null;\n}\n\n/**\n * The rows a link can point at, for a picker: listed through the data provider with `filters`,\n * searched on the server with `search` across `searchFields` (else the naming field), sorted by\n * `orderBy` (else the naming field) then the key, `perPage` at a time (`loadMore` for the next). A large table is\n * never loaded whole. Each option is the row's key and its words; a row with no words shows\n * `untitled`, never its key.\n */\nexport function useLinkOptions(target: LinkTarget, options: UseLinkOptionsOptions = {}): UseLinkOptionsReturn {\n const { filters, search = \"\", perPage = 25, enabled = true, untitled = \"Untitled\" } = options;\n const provider = useDataProvider();\n const field = target.field ?? \"id\";\n\n // The naming field: the target's, else `describe`'s (shared with a link's words).\n const named = useQuery({\n queryKey: [target.resource, \"naming-field\"],\n enabled: enabled && !target.labelField,\n staleTime: Infinity,\n retry: false,\n queryFn: async () => (await relationNamingField(provider, target.resource)) ?? null,\n });\n const labelField = target.labelField ?? named.data ?? undefined;\n const settled = Boolean(target.labelField) || named.isFetched;\n const naming = labelField && IDENTIFIER.test(labelField) ? labelField : undefined;\n const searchFields = useMemo(\n () => (target.searchFields?.length ? [...target.searchFields] : naming ? [naming] : []).filter((f) => IDENTIFIER.test(f)),\n // By value: a caller's inline list is one list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(target.searchFields ?? null), naming],\n );\n\n // The naming field the list is sorted by: known at once when the target names it, else set\n // below once `describe` answers, before the first request goes.\n // Then by the key: rows that share a name keep one order across pages, so offset paging never\n // skips or repeats one (a provider without `multiSort` sorts by the name only).\n // A caller's own order (a `position`) wins over the name: known at once, so it never waits on\n // `describe` to sort.\n const ordered = target.orderBy && IDENTIFIER.test(target.orderBy.field) ? target.orderBy : undefined;\n const orderField = ordered?.field;\n const orderDirection = ordered?.direction === \"desc\" ? \"desc\" : \"asc\";\n const orderNulls = ordered?.nulls === \"first\" || ordered?.nulls === \"last\" ? ordered.nulls : undefined;\n const sortsFor = (by: string, order: \"asc\" | \"desc\" = \"asc\", nulls?: \"first\" | \"last\"): SortParam[] => {\n const first: SortParam = { field: by, order, ...(nulls ? { nulls } : {}) };\n return by === field || !IDENTIFIER.test(field) ? [first] : [first, { field, order: \"asc\" }];\n };\n const sortBy = orderField ?? naming;\n const sortKey = sortBy ? `${sortBy}:${orderField ? orderDirection : \"asc\"}:${(orderField && orderNulls) || \"\"}` : undefined;\n const sorts = sortBy ? sortsFor(sortBy, orderField ? orderDirection : \"asc\", orderField ? orderNulls : undefined) : undefined;\n const [sortedBy, setSortedBy] = useState<string | undefined>(sortKey);\n const list = useInfiniteResource<BaseRecord>(target.resource, {\n ...(filters ? { defaultFilters: filters } : {}),\n perPage,\n ...(naming && IDENTIFIER.test(field) ? { select: `${field},${naming}` } : {}),\n ...(sorts ? { defaultSorts: sorts } : {}),\n searchFields,\n // Not before the naming field is known, so the first request is already sorted and narrowed.\n enabled: enabled && settled && (!sortKey || sortedBy === sortKey),\n });\n\n // The sort and the search follow the order (the caller's, else the naming field) and what the\n // person typed.\n const { setSorts, setSearch } = list;\n useEffect(() => {\n if (!sortBy) return;\n setSorts(sortsFor(sortBy, orderField ? orderDirection : \"asc\", orderField ? orderNulls : undefined));\n setSortedBy(sortKey);\n // sortsFor reads only `field`; sortKey follows sortBy, the direction and where empty values go.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sortKey, field, setSorts]);\n useEffect(() => {\n setSearch(searchFields.length ? search.trim() : \"\");\n }, [search, searchFields.length, setSearch]);\n\n const rows = list.rows;\n const linkOptions = useMemo(() => {\n const seen = new Set<string>();\n const out: LinkOption[] = [];\n for (const row of rows as Record<string, unknown>[]) {\n const key = row[field];\n if (typeof key !== \"string\" && !(typeof key === \"number\" && Number.isFinite(key))) continue;\n if (seen.has(String(key))) continue;\n seen.add(String(key));\n const name = naming ? row[naming] : row[Object.keys(row).find((k) => NAMING.test(k)) ?? \"\"];\n // A row with no words shows `untitled`, never its raw key.\n out.push({ value: key, label: words(name) ?? untitled });\n }\n return out;\n }, [rows, field, naming, untitled]);\n\n return {\n options: linkOptions,\n labelField: naming,\n searchable: searchFields.length > 0,\n isLoading: enabled && (!settled || list.query.isPending),\n isError: list.query.isError,\n hasMore: list.hasNextPage,\n loadMore: list.fetchNextPage,\n isLoadingMore: list.isFetchingNextPage,\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { useLiveInvalidation } from './chunk-
|
|
1
|
+
import { useLiveInvalidation } from './chunk-S2VYJWB4.js';
|
|
2
2
|
import { resourceKeys } from './chunk-7PUFVNPB.js';
|
|
3
|
-
import { useDataProvider } from './chunk-
|
|
3
|
+
import { useDataProvider } from './chunk-2K4747KX.js';
|
|
4
4
|
import { useState, useCallback, useMemo, useRef } from 'react';
|
|
5
5
|
import { useInfiniteQuery, keepPreviousData } from '@tanstack/react-query';
|
|
6
6
|
|
|
@@ -145,5 +145,5 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
export { useInfiniteResource };
|
|
148
|
-
//# sourceMappingURL=chunk-
|
|
149
|
-
//# sourceMappingURL=chunk-
|
|
148
|
+
//# sourceMappingURL=chunk-G6GQPXQS.js.map
|
|
149
|
+
//# sourceMappingURL=chunk-G6GQPXQS.js.map
|