@marktiderman/genesis-core 2.14.0 → 2.15.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.
Files changed (92) hide show
  1. package/dist/aggregate-y-qqJioF.d.ts +34 -0
  2. package/dist/{chunk-7PUFVNPB.js → chunk-2IGAUXYH.js} +5 -3
  3. package/dist/chunk-2IGAUXYH.js.map +1 -0
  4. package/dist/{chunk-KA3BUJ4H.js → chunk-42NVJJTT.js} +3 -3
  5. package/dist/{chunk-KA3BUJ4H.js.map → chunk-42NVJJTT.js.map} +1 -1
  6. package/dist/{chunk-JN47G4UE.js → chunk-7EFTWOMA.js} +56 -2
  7. package/dist/chunk-7EFTWOMA.js.map +1 -0
  8. package/dist/{chunk-S2VYJWB4.js → chunk-E3K2A3PK.js} +3 -3
  9. package/dist/{chunk-S2VYJWB4.js.map → chunk-E3K2A3PK.js.map} +1 -1
  10. package/dist/{chunk-SDAJSJNN.js → chunk-IYGVJFCV.js} +3 -3
  11. package/dist/{chunk-SDAJSJNN.js.map → chunk-IYGVJFCV.js.map} +1 -1
  12. package/dist/chunk-J54XXKQD.js +104 -0
  13. package/dist/chunk-J54XXKQD.js.map +1 -0
  14. package/dist/{chunk-OYDJGPDY.js → chunk-JFHRSG6G.js} +5 -5
  15. package/dist/{chunk-OYDJGPDY.js.map → chunk-JFHRSG6G.js.map} +1 -1
  16. package/dist/{chunk-UHOMTFBD.js → chunk-JTRRAVR4.js} +55 -3
  17. package/dist/chunk-JTRRAVR4.js.map +1 -0
  18. package/dist/{chunk-KV2HW4G4.js → chunk-LB6FMQQM.js} +11 -3
  19. package/dist/chunk-LB6FMQQM.js.map +1 -0
  20. package/dist/{chunk-G6GQPXQS.js → chunk-M5IX7C6U.js} +5 -5
  21. package/dist/{chunk-G6GQPXQS.js.map → chunk-M5IX7C6U.js.map} +1 -1
  22. package/dist/{chunk-AHFIS42U.js → chunk-NZP7YQHS.js} +5 -5
  23. package/dist/{chunk-AHFIS42U.js.map → chunk-NZP7YQHS.js.map} +1 -1
  24. package/dist/{chunk-DFABPMEQ.js → chunk-POUI7GAI.js} +5 -5
  25. package/dist/{chunk-DFABPMEQ.js.map → chunk-POUI7GAI.js.map} +1 -1
  26. package/dist/{chunk-NE2D74BP.js → chunk-QGWQ6LK3.js} +5 -5
  27. package/dist/{chunk-NE2D74BP.js.map → chunk-QGWQ6LK3.js.map} +1 -1
  28. package/dist/{chunk-2K4747KX.js → chunk-R3YXYVWF.js} +7 -2
  29. package/dist/chunk-R3YXYVWF.js.map +1 -0
  30. package/dist/{chunk-RFHUOXZC.js → chunk-SOO54YYY.js} +4 -4
  31. package/dist/{chunk-RFHUOXZC.js.map → chunk-SOO54YYY.js.map} +1 -1
  32. package/dist/{chunk-P3FHXRS2.js → chunk-TKK7D2ZT.js} +6 -6
  33. package/dist/{chunk-P3FHXRS2.js.map → chunk-TKK7D2ZT.js.map} +1 -1
  34. package/dist/{chunk-WDPM5TBO.js → chunk-UDSTWXXZ.js} +3 -3
  35. package/dist/{chunk-WDPM5TBO.js.map → chunk-UDSTWXXZ.js.map} +1 -1
  36. package/dist/chunk-XPBS5YE4.js +24 -0
  37. package/dist/chunk-XPBS5YE4.js.map +1 -0
  38. package/dist/csv.d.ts +1 -1
  39. package/dist/form-types.d.ts +1 -1
  40. package/dist/hooks/index.d.ts +4 -2
  41. package/dist/hooks/index.js +16 -14
  42. package/dist/hooks/mutation-mode.d.ts +1 -1
  43. package/dist/hooks/mutation-mode.js +5 -4
  44. package/dist/hooks/related-keys.d.ts +1 -1
  45. package/dist/hooks/use-aggregate.d.ts +25 -0
  46. package/dist/hooks/use-aggregate.js +10 -0
  47. package/dist/hooks/use-aggregate.js.map +1 -0
  48. package/dist/hooks/use-capabilities.d.ts +1 -1
  49. package/dist/hooks/use-capabilities.js +4 -2
  50. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  51. package/dist/hooks/use-infinite-resource.js +6 -4
  52. package/dist/hooks/use-link-options.d.ts +1 -1
  53. package/dist/hooks/use-link-options.js +8 -6
  54. package/dist/hooks/use-live.d.ts +1 -1
  55. package/dist/hooks/use-live.js +4 -2
  56. package/dist/hooks/use-one.d.ts +1 -1
  57. package/dist/hooks/use-one.js +6 -4
  58. package/dist/hooks/use-persisted-ui-state.js +4 -2
  59. package/dist/hooks/use-relation-label.d.ts +1 -1
  60. package/dist/hooks/use-relation-label.js +4 -2
  61. package/dist/hooks/use-resource-form.d.ts +1 -1
  62. package/dist/hooks/use-resource-form.js +8 -7
  63. package/dist/hooks/use-resource.d.ts +1 -1
  64. package/dist/hooks/use-resource.js +7 -6
  65. package/dist/hooks/use-write.d.ts +1 -1
  66. package/dist/index.d.ts +110 -6
  67. package/dist/index.js +125 -17
  68. package/dist/index.js.map +1 -1
  69. package/dist/navigation.d.ts +77 -1
  70. package/dist/navigation.js +32 -2
  71. package/dist/navigation.js.map +1 -1
  72. package/dist/provider/index.d.ts +12 -4
  73. package/dist/provider/index.js +3 -2
  74. package/dist/resource-view/index.d.ts +456 -166
  75. package/dist/resource-view/index.js +251 -5
  76. package/dist/resource-view/index.js.map +1 -1
  77. package/dist/schema/index.d.ts +3 -3
  78. package/dist/schema/index.js +1 -2
  79. package/dist/testing/index.d.ts +2 -2
  80. package/dist/{types-CtJxwoyv.d.ts → types-D4Bi_Iq8.d.ts} +76 -3
  81. package/dist/workspaces-BKhloJPK.d.ts +255 -0
  82. package/dist/workspaces.d.ts +2 -160
  83. package/dist/workspaces.js +1 -1
  84. package/dist/{write-outcome-Goy1v39G.d.ts → write-outcome-CHPT7Slm.d.ts} +1 -1
  85. package/package.json +1 -1
  86. package/dist/chunk-2K4747KX.js.map +0 -1
  87. package/dist/chunk-7PUFVNPB.js.map +0 -1
  88. package/dist/chunk-JN47G4UE.js.map +0 -1
  89. package/dist/chunk-KV2HW4G4.js.map +0 -1
  90. package/dist/chunk-UHOMTFBD.js.map +0 -1
  91. package/dist/chunk-YDMKMNDS.js +0 -8
  92. package/dist/chunk-YDMKM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,CAAC,CAAA,CAAG,CAAC,CAAA,EAAG,KAAA,CAAM,CAAC,EAAG,CAAC,CAAC,CAAA,GAAI,CAAC,GAAI,KAAA,CAAM,CAAC,CAAA,IAAK,EAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA;AAClG,EAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,EAAE,CAAA,CAAE,WAAA,EAAY;AACtC;AASO,SAAS,gBAAA,CAAsC,YAA0B,KAAA,EAAoB;AAClG,EAAA,MAAM,KAAA,GAAQ,KAAK,KAAK,CAAA,CAAE,MAAM,KAAK,CAAA,CAAE,OAAO,OAAO,CAAA;AACrD,EAAA,IAAI,MAAM,MAAA,KAAW,CAAA,EAAG,OAAO,CAAC,GAAG,UAAU,CAAA;AAC7C,EAAA,OAAO,UAAA,CAAW,MAAA,CAAO,CAAC,CAAA,KAAM;AAC9B,IAAA,MAAM,IAAA,GAAO,KAAK,CAAA,EAAG,CAAA,CAAE,KAAK,CAAA,CAAA,EAAI,CAAA,CAAE,WAAA,IAAe,EAAE,CAAA,CAAE,CAAA;AACrD,IAAA,OAAO,MAAM,KAAA,CAAM,CAAC,SAAS,IAAA,CAAK,QAAA,CAAS,IAAI,CAAC,CAAA;AAAA,EAClD,CAAC,CAAA;AACH;AAEA,SAAS,KAAK,IAAA,EAAsB;AAClC,EAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA,CAAE,QAAQ,SAAA,EAAW,EAAE,EAAE,WAAA,EAAY;AAClE;AAQO,SAAS,iBAAA,CACd,UAAA,EACA,KAAA,GAAkC,oBAAA,EAC7B;AACL,EAAA,OAAO,eAAA,CAAgB,YAAY,KAAK,CAAA,CAAE,QAAQ,CAAC,CAAA,KAAM,EAAE,UAAU,CAAA;AACvE","file":"chunk-JTRRAVR4.js","sourcesContent":["/**\n * Appearance preferences, as data (ADR 0024): the values and the order that decides which one\n * applies. No React, so a server, a phone or `workspaces.ts` can use it; the provider is\n * `appearance.tsx`.\n *\n * app lock > person > organization default > theme default > Genesis default\n */\n\n/** Light, dark, or follow the device: the person's appearance. */\nexport type Appearance = \"light\" | \"dark\" | \"system\";\n\n/** How tightly rows and controls sit. */\nexport type Density = \"compact\" | \"comfortable\" | \"spacious\";\n\n/** The appearances, in a picker's order. */\nexport const APPEARANCES: readonly Appearance[] = Object.freeze([\"system\", \"light\", \"dark\"]);\n/** The densities, tightest first. */\nexport const DENSITIES: readonly Density[] = Object.freeze([\"compact\", \"comfortable\", \"spacious\"]);\n\n/** An appearance and a density, either of which may be unset. */\nexport interface AppearancePreferenceValues {\n appearance?: Appearance | undefined;\n density?: Density | undefined;\n}\n\n/** Genesis's own defaults, the last step of the order. */\nexport const GENESIS_APPEARANCE_DEFAULTS: Readonly<Required<AppearancePreferenceValues>> = Object.freeze({\n appearance: \"system\",\n density: \"comfortable\",\n});\n\n/** Where a resolved value came from. */\nexport type AppearancePreferenceSource = \"app\" | \"person\" | \"organization\" | \"theme\" | \"genesis\";\n\n/** Each layer of the order; any may be missing. */\nexport interface AppearancePreferenceLayers {\n /** The app's lock: a value set here can't be changed by anyone below it. */\n lock?: AppearancePreferenceValues | undefined;\n /** The person's own choice. */\n person?: AppearancePreferenceValues | undefined;\n /** The organization's default for its people (`WorkspaceTheme.defaults`). */\n organization?: AppearancePreferenceValues | undefined;\n /** The app theme's default (its layout's density, say). */\n theme?: AppearancePreferenceValues | undefined;\n}\n\n/** The values that apply, and where each came from. */\nexport interface ResolvedAppearancePreferences {\n appearance: Appearance;\n density: Density;\n source: { appearance: AppearancePreferenceSource; density: AppearancePreferenceSource };\n}\n\n/** Whether a value is an appearance. */\nexport const isAppearance = (v: unknown): v is Appearance => v === \"light\" || v === \"dark\" || v === \"system\";\n/** Whether a value is a density. */\nexport const isDensity = (v: unknown): v is Density => v === \"compact\" || v === \"comfortable\" || v === \"spacious\";\n\n/** Only the known values: a stored or typed-in value that isn't one is left out. */\nexport function toAppearancePreferenceValues(input: unknown): AppearancePreferenceValues {\n if (!input || typeof input !== \"object\") return {};\n const { appearance, density } = input as Record<string, unknown>;\n return { ...(isAppearance(appearance) ? { appearance } : {}), ...(isDensity(density) ? { density } : {}) };\n}\n\n/**\n * The appearance and density that apply: app lock, then the person, then the organization's\n * default, then the theme's, then Genesis's. Values that aren't known appearances or densities\n * are skipped, so a bad stored value falls through to the next layer.\n *\n * @stability Beta\n */\nexport function resolveAppearancePreferences(layers: AppearancePreferenceLayers): ResolvedAppearancePreferences {\n const order: [AppearancePreferenceSource, AppearancePreferenceValues | undefined][] = [\n [\"app\", layers.lock],\n [\"person\", layers.person],\n [\"organization\", layers.organization],\n [\"theme\", layers.theme],\n [\"genesis\", GENESIS_APPEARANCE_DEFAULTS],\n ];\n const pick = <K extends keyof AppearancePreferenceValues>(key: K, valid: (v: unknown) => boolean) => {\n for (const [source, values] of order) {\n const value = values?.[key];\n if (valid(value)) return { value: value as NonNullable<AppearancePreferenceValues[K]>, source };\n }\n return { value: GENESIS_APPEARANCE_DEFAULTS[key] as NonNullable<AppearancePreferenceValues[K]>, source: \"genesis\" as const };\n };\n const appearance = pick(\"appearance\", isAppearance);\n const density = pick(\"density\", isDensity);\n return {\n appearance: appearance.value as Appearance,\n density: density.value as Density,\n source: { appearance: appearance.source, density: density.source },\n };\n}\n\n","/**\n * Workspaces (docs/adr/0004-workspaces.md): where the viewer is working, chosen first and kept in\n * the URL. A workspace is one tenant (an organization), the roll-up across them, or the viewer's\n * own personal space. Everything inside it is scoped to it: its `scope` is the `ResourceScope`\n * every view reads, and its path prefixes every URL inside it.\n *\n * Router-free and DOM-free, like `navigation`: web and native shells share it.\n */\n\nimport type { ResourceScope } from \"./hooks/viewer-scope\";\nimport type { GenesisViewerRoles } from \"./viewer\";\nimport { toAppearancePreferenceValues, type AppearancePreferenceValues } from \"./appearance-values\";\n\n/**\n * The kinds of workspace. Genesis ships three; an app adds its own by module augmentation, and\n * the switcher groups and orders them like the built-in ones:\n *\n * ```ts\n * declare module \"@marktiderman/genesis-core/workspaces\" {\n * interface GenesisWorkspaceKinds {\n * location: true;\n * }\n * }\n * ```\n *\n * @stability Beta\n */\nexport interface GenesisWorkspaceKinds {\n /** One tenant: an organization the viewer is a member or staff of. */\n tenant: true;\n /** The roll-up across every tenant the viewer works in. */\n rollup: true;\n /** The viewer's own things, belonging to no tenant. */\n personal: true;\n}\n\n/** @stability Beta */\nexport type WorkspaceKind = keyof GenesisWorkspaceKinds;\n\n/**\n * One place the viewer can work in.\n *\n * @stability Beta\n */\nexport interface Workspace {\n /** Unique among the viewer's workspaces. For a tenant, usually its URL segment. */\n id: string;\n kind: WorkspaceKind;\n /** Its name: the organization's name, \"All organizations\", \"Personal\". */\n label: string;\n /** A second line in the switcher: the viewer's role there, a location. */\n description?: string;\n /**\n * Where it starts, and the prefix of every URL inside it: `/o/acme`, `/all`, `/me`. Matched at\n * segment boundaries, so `/o/acme` never matches `/o/acme-west`.\n */\n path: string;\n /** What views read inside it: `{ orgId }`, `{ orgId: [...] }`, `{ personId }`. */\n scope: ResourceScope;\n /** The viewer's roles here, for view guards (see `GenesisViewerRoles`). */\n roles?: GenesisViewerRoles;\n /** The workspace's IANA time zone, for columns read on the scope's clock. */\n timeZone?: string | null;\n /** Its picture: a logo URL, else initials made from `label`. */\n image?: string;\n /**\n * A count or short status beside it in the switcher: unread messages, tasks waiting. `0`, an\n * empty string, `null` and undefined show nothing.\n */\n badge?: string | number | null;\n /** Its brand, for the switcher's picture and anything the app themes inside it. */\n theme?: WorkspaceTheme;\n /** Anything else the app needs; Genesis never reads it. */\n meta?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * A workspace's brand. `accent` takes the same values as a public page's brand accent (`#rgb`,\n * `#rrggbb`, `rgb()`, `hsl()` or a bare token triplet like `\"160 84% 39%\"`); genesis-ui turns it\n * into the design system's `--primary` (`workspaceThemeStyle`), darkened when it is too light to\n * carry text.\n *\n * @stability Beta\n */\nexport interface WorkspaceTheme {\n accent?: string;\n /**\n * The app brand this organization wears, by id (`defineAppBrand`'s name, what\n * `data-app-brand` names): its colours and typefaces across the app while the workspace is\n * active. `resolveWorkspaceBrand` picks it, checked against the brands the app ships.\n */\n brand?: string;\n /**\n * The organization's defaults for its people's appearance and density. A person's own choice\n * wins over them, and the app's lock over that (`resolveAppearancePreferences`).\n */\n defaults?: AppearancePreferenceValues;\n}\n\n/**\n * The app brand that applies in a workspace: its `theme.brand` when the app ships a brand by\n * that id (`available`, ids or anything with an `id`), else `fallback`. Without `available`,\n * any brand id is taken as given.\n *\n * ```ts\n * const brand = resolveWorkspaceBrand(active, { available: STARTER_BRANDS, fallback: \"acme\" });\n * document.documentElement.dataset.appBrand = brand;\n * ```\n *\n * @stability Beta\n */\nexport function resolveWorkspaceBrand(\n workspace: Pick<Workspace, \"theme\"> | null | undefined,\n options: { available?: readonly (string | { readonly id: string })[]; fallback?: string } = {},\n): string | undefined {\n const wanted = workspace?.theme?.brand;\n if (wanted) {\n const ids = options.available?.map((b) => (typeof b === \"string\" ? b : b.id));\n if (!ids || ids.includes(wanted)) return wanted;\n if (process.env.NODE_ENV !== \"production\") {\n // genesis-allow-console: a development hint about the app's own data, not a caught error.\n console.warn(`[genesis-core] resolveWorkspaceBrand: the workspace asks for brand \"${wanted}\", which the app doesn't ship.`);\n }\n }\n return options.fallback;\n}\n\n/**\n * The organization's appearance and density defaults, for `AppearancePreferencesProvider`'s\n * `organization`: only known values, empty without a workspace.\n *\n * @stability Beta\n */\nexport function resolveWorkspaceAppearance(workspace: Pick<Workspace, \"theme\"> | null | undefined): AppearancePreferenceValues {\n return toAppearancePreferenceValues(workspace?.theme?.defaults);\n}\n\n/** The kinds in their default order: personal, roll-up, then each tenant. */\nexport const WORKSPACE_KIND_ORDER: readonly WorkspaceKind[] = [\"personal\", \"rollup\", \"tenant\"];\n\nfunction trimPath(path: string): string {\n const bare = path.split(/[?#]/)[0] ?? \"\";\n // Trailing slashes off, keeping \"/\" itself. A loop, not /\\/+$/, which is slow on many slashes.\n let end = bare.length;\n while (end > 1 && bare[end - 1] === \"/\") end--;\n return bare.slice(0, end);\n}\n\nfunction within(pathname: string, prefix: string): boolean {\n const p = trimPath(pathname);\n const w = trimPath(prefix);\n if (w === \"/\") return true;\n return p === w || p.startsWith(`${w}/`);\n}\n\n/**\n * The workspace a URL is in: the one whose `path` is the longest prefix of `pathname`, or\n * undefined when the URL is in none (a sign-in page, the app's front door).\n *\n * @stability Beta\n */\nexport function workspaceAt<W extends Workspace>(workspaces: readonly W[], pathname: string): W | undefined {\n let best: W | undefined;\n for (const w of workspaces) {\n if (within(pathname, w.path) && (!best || trimPath(w.path).length > trimPath(best.path).length)) best = w;\n }\n return best;\n}\n\n/**\n * The path inside a workspace: `/o/acme/clients/42` in `/o/acme` is `/clients/42`; the workspace's\n * own landing page is `/`.\n *\n * @stability Beta\n */\nexport function pathInWorkspace(workspace: Pick<Workspace, \"path\">, pathname: string): string {\n const w = trimPath(workspace.path);\n const p = trimPath(pathname);\n if (!within(p, w)) return \"/\";\n const rest = w === \"/\" ? p : p.slice(w.length);\n return rest || \"/\";\n}\n\n/** @stability Beta */\nexport interface WorkspaceHrefOptions {\n /**\n * Whether to keep the viewer's place when switching: given the path inside the current\n * workspace (`/clients`) and the two workspaces, return the path to open in the target, or\n * false for its landing page. By default the place is kept between workspaces of the same kind,\n * up to the first segment (a list, not one record that belongs to the old workspace):\n * `/o/acme/clients/42` switches to `/o/globex/clients`.\n */\n keep?: (rest: string, from: Workspace, to: Workspace) => string | false;\n}\n\n/** The default `keep`: the same kind keeps the section (the first segment), never a record. */\nexport function keepSection(rest: string, from: Workspace, to: Workspace): string | false {\n if (from.kind !== to.kind) return false;\n const section = rest.split(\"/\").filter(Boolean)[0];\n return section ? `/${section}` : false;\n}\n\n/**\n * Where switching to `to` goes from `pathname`. The URL moves with the viewer: it lands in the same\n * section of the new workspace when that makes sense (see `keep`), else on its landing page.\n *\n * @stability Beta\n */\nexport function workspaceHref(\n workspaces: readonly Workspace[],\n to: Workspace,\n pathname: string | undefined,\n options: WorkspaceHrefOptions = {},\n): string {\n const from = pathname === undefined ? undefined : workspaceAt(workspaces, pathname);\n if (!from || from.id === to.id || pathname === undefined) return to.path;\n const kept = (options.keep ?? keepSection)(pathInWorkspace(from, pathname), from, to);\n if (!kept || kept === \"/\") return to.path;\n const base = trimPath(to.path);\n return `${base === \"/\" ? \"\" : base}${kept.startsWith(\"/\") ? kept : `/${kept}`}`;\n}\n\n/** @stability Beta */\nexport interface WorkspaceGroup<W extends Workspace = Workspace> {\n kind: WorkspaceKind;\n workspaces: W[];\n}\n\n/**\n * The workspaces grouped by kind, in `order` (default {@link WORKSPACE_KIND_ORDER}, then any kind\n * an app added), each group in the order given. Empty groups are left out.\n *\n * @stability Beta\n */\nexport function groupWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): WorkspaceGroup<W>[] {\n const kinds = [...order];\n for (const w of workspaces) if (!kinds.includes(w.kind)) kinds.push(w.kind);\n return kinds\n .map((kind) => ({ kind, workspaces: workspaces.filter((w) => w.kind === kind) }))\n .filter((g) => g.workspaces.length > 0);\n}\n\n/**\n * The workspace to open when the URL names none (the app's front door): the remembered one if the\n * viewer still has it, else the first tenant, else the first workspace.\n *\n * @stability Beta\n */\nexport function defaultWorkspace<W extends Workspace>(workspaces: readonly W[], rememberedId?: string | null): W | undefined {\n return (\n (rememberedId ? workspaces.find((w) => w.id === rememberedId) : undefined) ??\n workspaces.find((w) => w.kind === \"tenant\") ??\n workspaces[0]\n );\n}\n\n/**\n * Initials for a workspace with no image: the first letters of its first two words.\n *\n * @stability Beta\n */\nexport function workspaceInitials(label: string): string {\n const words = label.trim().split(/\\s+/).filter(Boolean);\n const letters = words.length > 1 ? [words[0]![0], words[1]![0]] : [...(words[0] ?? \"\")].slice(0, 2);\n return letters.join(\"\").toUpperCase();\n}\n\n/**\n * The workspaces whose label or second line contains every word of `query`, ignoring case and\n * accents, in the order given. An empty query keeps them all. For the switcher's search box, on\n * the web and on the phone.\n *\n * @stability Beta\n */\nexport function filterWorkspaces<W extends Workspace>(workspaces: readonly W[], query: string): W[] {\n const words = fold(query).split(/\\s+/).filter(Boolean);\n if (words.length === 0) return [...workspaces];\n return workspaces.filter((w) => {\n const text = fold(`${w.label} ${w.description ?? \"\"}`);\n return words.every((word) => text.includes(word));\n });\n}\n\nfunction fold(text: string): string {\n return text.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase();\n}\n\n/**\n * The workspaces in the order the switcher lists them (grouped by kind, in `order`): the order its\n * keyboard jump numbers them, 1 to 9.\n *\n * @stability Beta\n */\nexport function orderedWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): W[] {\n return groupWorkspaces(workspaces, order).flatMap((g) => g.workspaces);\n}\n"]}
@@ -36,6 +36,14 @@ function decodeRecordKey(contract, id) {
36
36
  return out;
37
37
  }
38
38
 
39
- export { decodeRecordKey, encodeRecordKey, keyFields };
40
- //# sourceMappingURL=chunk-KV2HW4G4.js.map
41
- //# sourceMappingURL=chunk-KV2HW4G4.js.map
39
+ // src/schema/types.ts
40
+ function defineResource() {
41
+ return (contract) => contract;
42
+ }
43
+ function fieldControl(field) {
44
+ return field?.control ?? field?.widget;
45
+ }
46
+
47
+ export { decodeRecordKey, defineResource, encodeRecordKey, fieldControl, keyFields };
48
+ //# sourceMappingURL=chunk-LB6FMQQM.js.map
49
+ //# sourceMappingURL=chunk-LB6FMQQM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema/keys.ts","../src/schema/types.ts"],"names":[],"mappings":";AAYO,SAAS,UAAU,QAAA,EAA4D;AACpF,EAAA,OAAO,OAAO,SAAS,GAAA,KAAQ,QAAA,GAAW,CAAC,QAAA,CAAS,GAAG,IAAI,QAAA,CAAS,GAAA;AACtE;AAEA,SAAS,QAAA,CAAS,KAAc,KAAA,EAAgC;AAC9D,EAAA,MAAM,KAAA,GAAQ,IAAI,KAAK,CAA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,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,IACE,CAAC,MAAM,OAAA,CAAQ,MAAM,KACrB,MAAA,CAAO,MAAA,KAAW,OAAO,MAAA,IACzB,CAAC,OAAO,KAAA,CAAM,CAAC,MAAM,OAAO,CAAA,KAAM,YAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EACnE;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,MAAM,MAAuC,EAAC;AAC9C,EAAA,MAAA,CAAO,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AAC3B,IAAA,GAAA,CAAI,KAAK,CAAA,GAAI,MAAA,CAAO,CAAC,CAAA;AAAA,EACvB,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT;;;ACwFO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC;AAwOO,SAAS,aAAa,KAAA,EAA6H;AACxJ,EAAA,OAAQ,KAAA,EAAO,WAAW,KAAA,EAAO,MAAA;AACnC","file":"chunk-LB6FMQQM.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Record identity for single and composite keys (DATA-STUDIO.md decision 13)\n//\n// `DataProvider` methods take one `Identifier`. A composite key travels\n// through that same slot as a canonical string, so every existing provider\n// signature stays as it is and a junction table still has one id per row.\n// ---------------------------------------------------------------------------\n\nimport type { Identifier } from \"../provider/types\";\nimport type { DataRow, ResourceContract } from \"./types\";\n\n/** The key of a contract as a list, whichever form `key` was declared in. */\nexport function keyFields(contract: Pick<ResourceContract, \"key\">): readonly string[] {\n return typeof contract.key === \"string\" ? [contract.key] : contract.key;\n}\n\nfunction keyValue(row: DataRow, field: string): string | number {\n const value = row[field];\n if (typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\" || typeof value === \"boolean\") return String(value);\n throw new Error(\n `Record key field \"${field}\" is ${value === null ? \"null\" : typeof value}; ` +\n \"a key value must be a string or a number.\",\n );\n}\n\n/**\n * One `Identifier` for a row.\n *\n * A single-field key returns the raw value, so `id`-keyed resources look\n * exactly as they always have. A composite key returns a JSON array of the\n * values in key order, e.g. `'[\"c-1\",\"u-7\"]'`.\n */\nexport function encodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n row: DataRow,\n): Identifier {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return keyValue(row, fields[0]!);\n return JSON.stringify(fields.map((field) => keyValue(row, field)));\n}\n\n/**\n * The inverse of {@link encodeRecordKey}: field name → value.\n *\n * Throws on an id that does not fit the key, rather than guessing, because a\n * guessed key addresses the wrong row.\n */\nexport function decodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n id: Identifier,\n): Record<string, string | number> {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return { [fields[0]!]: id };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(String(id));\n } catch {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== fields.length ||\n !parsed.every((v) => typeof v === \"string\" || typeof v === \"number\")\n ) {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n const out: Record<string, string | number> = {};\n fields.forEach((field, i) => {\n out[field] = parsed[i] as string | number;\n });\n return out;\n}\n","// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType } from \"../form-types\";\n\n/**\n * Which form control fits a field (`text`, `textarea`, `date`, `tel`…): a hint a form reads.\n * The field's `control` (decision F, ADR 0021).\n *\n * @stability Beta\n */\nexport type ControlHint = FieldType;\n\n/**\n * @deprecated Renamed `ControlHint`: \"widget\" now means a dashboard tile (docs/GLOSSARY.md).\n * Kept as an alias; removed in the next major.\n */\nexport type WidgetHint = ControlHint;\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /**\n * Which form control fits this field (`textarea`, `date`, `tel`…). A hint: a UI may still\n * choose another. Read it with `fieldControl(field)`, which also reads the old `widget`.\n */\n readonly control?: ControlHint;\n /**\n * @deprecated Renamed `control` (\"widget\" now means a dashboard tile). Still read wherever\n * `control` is (`fieldControl`); `control` wins when both are set. Removed in the next major.\n */\n readonly widget?: ControlHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /**\n * The version field the resource's writes are checked against, asked per\n * resource (`capabilities(resource)`). Present only with `versionedWrites`.\n * The Genesis write hooks send `String(row[version.field])` from the row\n * they last read as `expectedVersion`, so an edit made on a stale copy is\n * refused as a `conflict` instead of overwriting someone else's.\n */\n readonly version?: VersionField;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n\n/**\n * A field's form-control hint: its `control`, else the deprecated `widget`. Every reader goes\n * through this, so a contract written with either name works.\n *\n * @stability Beta\n */\nexport function fieldControl(field: { readonly control?: string | undefined; readonly widget?: string | undefined } | undefined): ControlHint | undefined {\n return (field?.control ?? field?.widget) as ControlHint | undefined;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { useLiveInvalidation } from './chunk-S2VYJWB4.js';
2
- import { resourceKeys } from './chunk-7PUFVNPB.js';
3
- import { useDataProvider } from './chunk-2K4747KX.js';
1
+ import { useLiveInvalidation } from './chunk-E3K2A3PK.js';
2
+ import { resourceKeys } from './chunk-2IGAUXYH.js';
3
+ import { useDataProvider } from './chunk-R3YXYVWF.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-G6GQPXQS.js.map
149
- //# sourceMappingURL=chunk-G6GQPXQS.js.map
148
+ //# sourceMappingURL=chunk-M5IX7C6U.js.map
149
+ //# sourceMappingURL=chunk-M5IX7C6U.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-infinite-resource.ts"],"names":["keepPreviousData","first","keepPrevious"],"mappings":";;;;;;AA+FA,SAAS,UAAU,OAAA,EAA4C;AAC7D,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IAAA,CACT,OAAA,IAAW,EAAC,EAAG,GAAA;AAAA,MAAI,CAAC,MACnB,MAAA,CAAO,WAAA,CAAY,OAAO,OAAA,CAAQ,CAAC,EAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAM,EAAE,aAAA,CAAc,CAAC,CAAC,CAAC;AAAA;AAC7E,GACF;AACF;AAEO,SAAS,mBAAA,CACd,QAAA,EACA,OAAA,GAAsC,EAAC,EACT;AAC9B,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,YAAA;AAAA,IACA,cAAA;AAAA,IACA,OAAA,GAAU,EAAA;AAAA,IACV,aAAA,GAAgB,EAAA;AA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M,QAAQ,SAAA,CAAU,OAAA,EAAS,GAAA,KAAQ,SAAA,GAAY,UAAU,OAAA,GAAU,IAAA;AACzE,EAAA,MAAM,QAAQ,KAAA,EAAO,KAAA;AAErB,EAAA,MAAM;AAAA,IACJ,aAAA,EAAe,SAAA;AAAA,IACf,WAAA;AAAA,IACA,kBAAA;AAAA,IACA,iBAAA,EAAmB,aAAA;AAAA,IACnB,eAAA;AAAA,IACA;AAAA,GACF,GAAI,KAAA;AACJ,EAAA,MAAM,aAAA,GAAgB,YAAY,MAAM;AACtC,IAAA,IAAI,CAAC,eAAe,kBAAA,EAAoB;AACxC,IAAA,KAAK,SAAA,EAAU;AAAA,EACjB,CAAA,EAAG,CAAC,SAAA,EAAW,WAAA,EAAa,kBAAkB,CAAC,CAAA;AAC/C,EAAA,MAAM,iBAAA,GAAoB,YAAY,MAAM;AAC1C,IAAA,IAAI,CAAC,mBAAmB,sBAAA,EAAwB;AAChD,IAAA,KAAK,aAAA,EAAc;AAAA,EACrB,CAAA,EAAG,CAAC,aAAA,EAAe,eAAA,EAAiB,sBAAsB,CAAC,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA,EAAiB,CAAC,CAAC,KAAA,EAAO,QAAA;AAAA,IAC1B,aAAA;AAAA,IACA,WAAA,EAAa,CAAC,CAAC,WAAA;AAAA,IACf,iBAAA;AAAA,IACA,eAAA,EAAiB,CAAC,CAAC,eAAA;AAAA,IACnB,kBAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-G6GQPXQS.js","sourcesContent":["import { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n keepPreviousData as keepPrevious,\n useInfiniteQuery,\n type InfiniteData,\n type UseInfiniteQueryResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n FilterParam,\n ListParams,\n ListResult,\n SortParam,\n} from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// useInfiniteResource — a list that grows with \"Load more\", by cursor.\n//\n// Asks for the first page with `cursor: null`. A provider that serves cursor\n// paging answers with `nextCursor` and is paged by keyset from then on; one\n// that doesn't answers without it and is paged by `page` (offset) until\n// `total` rows are loaded. Pages live under `[resource, \"infinite\", params]`,\n// so writes on the resource (which invalidate `[resource]`) refetch them,\n// and pending optimistic and undoable writes are patched into every page.\n// ---------------------------------------------------------------------------\n\nexport interface UseInfiniteResourceOptions {\n defaultSort?: SortParam;\n /**\n * Sort by several fields, first one first, e.g. a grouped list: the group, then the order\n * within it. Wins over `defaultSort`. On a provider without `multiSort` only the first applies.\n */\n defaultSorts?: SortParam[];\n /** Re-synced when its value changes, like `useResource`'s. */\n defaultFilters?: FilterParam[];\n /** Rows per page. Default 25. */\n perPage?: number;\n /** The search to start with. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax. Must include the sort and key columns. */\n select?: string;\n /** Fields to search across when `setSearch` is called. */\n searchFields?: string[];\n /** Disable fetching. */\n enabled?: boolean;\n /** Refetch the loaded pages when the provider reports a change. See `UseResourceOptions.live`. */\n live?: boolean | LiveOptions;\n /**\n * Keep at most this many pages loaded (TanStack Query's `maxPages`): scrolling far drops pages\n * from the front, and scrolling back loads them again, so a long feed and a live refetch stay\n * cheap. Needs a provider that pages by cursor both ways (`prevCursor`); offset paging ignores it.\n */\n maxPages?: number;\n /**\n * Keep the current rows on screen while a new search, sort or filter loads, instead of a\n * loading state for each change. Default false.\n */\n keepPreviousData?: boolean;\n}\n\n/** Where one page starts: its offset page, and its cursor (`null` for the first). */\nexport interface InfinitePageParam {\n page: number;\n cursor: string | null;\n}\n\nexport interface UseInfiniteResourceReturn<T> {\n /** The TanStack infinite query. */\n query: UseInfiniteQueryResult<InfiniteData<ListResult<T>, InfinitePageParam>>;\n /** Every loaded row, in order. */\n rows: T[];\n /** Rows matching the filters and search, from the first page's count. */\n total: number | undefined;\n /** True when `total` is the database's estimate, so a screen says \"about\". */\n totalIsEstimate: boolean;\n /** Loads the next page. Does nothing while one is loading or none is left. */\n fetchNextPage: () => void;\n hasNextPage: boolean;\n /** Load the page before the first loaded one (after `maxPages` dropped it). No-op when there is none. */\n fetchPreviousPage: () => void;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n /** The params every page is asked with (without its page and cursor). */\n params: Omit<ListParams, \"pagination\"> & { perPage: number };\n /** Sort by one field (or none). Replaces every sort. */\n setSort: (sort: SortParam | undefined) => void;\n /** Sort by several fields, first one first. */\n setSorts: (sorts: SortParam[]) => void;\n setFilters: (filters: FilterParam[]) => void;\n setSearch: (query: string) => void;\n}\n\nfunction filterKey(filters: FilterParam[] | undefined): string {\n return JSON.stringify(\n (filters ?? []).map((f) =>\n Object.fromEntries(Object.entries(f).sort(([a], [b]) => a.localeCompare(b))),\n ),\n );\n}\n\nexport function useInfiniteResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseInfiniteResourceOptions = {},\n): UseInfiniteResourceReturn<T> {\n const {\n defaultSort,\n defaultSorts,\n defaultFilters,\n perPage = 25,\n defaultSearch = \"\",\n select,\n searchFields,\n enabled = true,\n live,\n keepPreviousData = false,\n } = options;\n const provider = useDataProvider();\n\n const [sorts, setSortsRaw] = useState<SortParam[]>(() =>\n defaultSorts && defaultSorts.length > 0 ? defaultSorts : defaultSort ? [defaultSort] : [],\n );\n const setSort = useCallback((next: SortParam | undefined) => setSortsRaw(next ? [next] : []), []);\n const setSorts = useCallback((next: SortParam[]) => setSortsRaw(next), []);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [search, setSearch] = useState(defaultSearch);\n\n // Follow `defaultFilters` by value, during render (see useResource).\n const defaultKey = filterKey(defaultFilters);\n const [syncedKey, setSyncedKey] = useState(defaultKey);\n if (defaultKey !== syncedKey) {\n setSyncedKey(defaultKey);\n setFiltersRaw(defaultFilters ?? []);\n }\n\n const setFilters = useCallback((next: FilterParam[]) => setFiltersRaw(next), []);\n\n const params = useMemo(() => {\n const p: Omit<ListParams, \"pagination\"> & { perPage: number } = {\n perPage,\n // The first sort is `sort` too, for a provider that sorts by one field only.\n sort: sorts[0],\n ...(sorts.length > 1 ? { sorts } : {}),\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (search && searchFields && searchFields.length > 0) {\n p.search = { query: search, fields: searchFields };\n }\n return p;\n }, [perPage, sorts, filters, select, search, searchFields]);\n\n // Whether the provider pages by cursor (it sends `nextCursor`), learnt from the first page.\n const cursorMode = useRef(false);\n const query = useInfiniteQuery<\n ListResult<T>,\n Error,\n InfiniteData<ListResult<T>, InfinitePageParam>,\n readonly unknown[],\n InfinitePageParam\n >({\n queryKey: resourceKeys(resource).infinite(params),\n initialPageParam: { page: 1, cursor: null },\n queryFn: ({ pageParam }) => {\n const { perPage: size, ...rest } = params;\n return provider.getList<T>(resource, {\n ...rest,\n pagination: { page: pageParam.page, perPage: size, cursor: pageParam.cursor },\n });\n },\n getNextPageParam: (last, pages, lastParam) => {\n if (last.nextCursor !== undefined) {\n // Cursor mode: the provider says whether there is more.\n return last.nextCursor ? { page: lastParam.page + 1, cursor: last.nextCursor } : undefined;\n }\n // Offset mode: more while the last page was full and, when the total is\n // an exact count, fewer than `total` rows are loaded. An uncounted\n // (`count: \"none\"`, total -1) or estimated total (RLS makes the planner\n // guess low) never stops the list early: only a short page does.\n const loaded = pages.reduce((n, p) => n + p.data.length, 0);\n const first = pages[0];\n const exact = !!first && first.total >= 0 && !first.totalIsEstimate;\n if (last.data.length < params.perPage || (exact && loaded >= first.total)) return undefined;\n return { page: lastParam.page + 1, cursor: null };\n },\n getPreviousPageParam: (first, _pages, firstParam) =>\n // Cursor mode only: offset pages aren't dropped from the front.\n first.prevCursor ? { page: firstParam.page - 1, cursor: first.prevCursor } : undefined,\n // Only once the provider is known to page by cursor: TanStack drops pages whenever maxPages is\n // set, and offset pages can't be loaded back, so they would be lost.\n ...(options.maxPages !== undefined && options.maxPages > 0 && cursorMode.current ? { maxPages: options.maxPages } : {}),\n enabled,\n ...(keepPreviousData ? { placeholderData: keepPrevious } : {}),\n });\n\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // A row can move between pages while the user scrolls (its sort value\n // changed, or rows before it were added): show it once, where it first appears.\n const rows = useMemo(() => {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const page of query.data?.pages ?? []) {\n for (const row of page.data) {\n const id = row?.id;\n if (id != null) {\n const key = String(id);\n if (seen.has(key)) continue;\n seen.add(key);\n }\n out.push(row);\n }\n }\n return out;\n }, [query.data]);\n const first = query.data?.pages[0];\n if (first && first.nextCursor !== undefined) cursorMode.current = true;\n // The count comes with the list's first page only. Once maxPages drops that page (or a refetch\n // starts from a back cursor) the loaded first page has no count, so keep the last one seen for\n // these params.\n const paramsKey = JSON.stringify(params);\n const lastCount = useRef<{ key: string; total: number; estimate: boolean } | null>(null);\n // Not from placeholder pages (keepPreviousData): they're the old params' rows and count.\n if (first && first.total >= 0 && !query.isPlaceholderData) {\n lastCount.current = { key: paramsKey, total: first.total, estimate: !!first.totalIsEstimate };\n }\n const count = lastCount.current?.key === paramsKey ? lastCount.current : null;\n const total = count?.total;\n\n const {\n fetchNextPage: fetchNext,\n hasNextPage,\n isFetchingNextPage,\n fetchPreviousPage: fetchPrevious,\n hasPreviousPage,\n isFetchingPreviousPage,\n } = query;\n const fetchNextPage = useCallback(() => {\n if (!hasNextPage || isFetchingNextPage) return;\n void fetchNext();\n }, [fetchNext, hasNextPage, isFetchingNextPage]);\n const fetchPreviousPage = useCallback(() => {\n if (!hasPreviousPage || isFetchingPreviousPage) return;\n void fetchPrevious();\n }, [fetchPrevious, hasPreviousPage, isFetchingPreviousPage]);\n\n return {\n query,\n rows,\n total,\n totalIsEstimate: !!count?.estimate,\n fetchNextPage,\n hasNextPage: !!hasNextPage,\n fetchPreviousPage,\n hasPreviousPage: !!hasPreviousPage,\n isFetchingNextPage,\n params,\n setSort,\n setSorts,\n setFilters,\n setSearch,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-infinite-resource.ts"],"names":["keepPreviousData","first","keepPrevious"],"mappings":";;;;;;AA+FA,SAAS,UAAU,OAAA,EAA4C;AAC7D,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IAAA,CACT,OAAA,IAAW,EAAC,EAAG,GAAA;AAAA,MAAI,CAAC,MACnB,MAAA,CAAO,WAAA,CAAY,OAAO,OAAA,CAAQ,CAAC,EAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAM,EAAE,aAAA,CAAc,CAAC,CAAC,CAAC;AAAA;AAC7E,GACF;AACF;AAEO,SAAS,mBAAA,CACd,QAAA,EACA,OAAA,GAAsC,EAAC,EACT;AAC9B,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,YAAA;AAAA,IACA,cAAA;AAAA,IACA,OAAA,GAAU,EAAA;AAAA,IACV,aAAA,GAAgB,EAAA;AAAA,IAChB,MAAA;AAAA,IACA,YAAA;AAAA,IACA,OAAA,GAAU,IAAA;AAAA,IACV,IAAA;AAAA,sBACAA,kBAAA,GAAmB;AAAA,GACrB,GAAI,OAAA;AACJ,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,CAAC,KAAA,EAAO,WAAW,CAAA,GAAI,QAAA;AAAA,IAAsB,MACjD,YAAA,IAAgB,YAAA,CAAa,MAAA,GAAS,CAAA,GAAI,eAAe,WAAA,GAAc,CAAC,WAAW,CAAA,GAAI;AAAC,GAC1F;AACA,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,CAAC,IAAA,KAAgC,WAAA,CAAY,IAAA,GAAO,CAAC,IAAI,CAAA,GAAI,EAAE,CAAA,EAAG,EAAE,CAAA;AAChG,EAA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AM,iBAAA,GAAoB,YAAY,MAAM;AAC1C,IAAA,IAAI,CAAC,mBAAmB,sBAAA,EAAwB;AAChD,IAAA,KAAK,aAAA,EAAc;AAAA,EACrB,CAAA,EAAG,CAAC,aAAA,EAAe,eAAA,EAAiB,sBAAsB,CAAC,CAAA;AAE3D,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA,EAAiB,CAAC,CAAC,KAAA,EAAO,QAAA;AAAA,IAC1B,aAAA;AAAA,IACA,WAAA,EAAa,CAAC,CAAC,WAAA;AAAA,IACf,iBAAA;AAAA,IACA,eAAA,EAAiB,CAAC,CAAC,eAAA;AAAA,IACnB,kBAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-M5IX7C6U.js","sourcesContent":["import { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n keepPreviousData as keepPrevious,\n useInfiniteQuery,\n type InfiniteData,\n type UseInfiniteQueryResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n FilterParam,\n ListParams,\n ListResult,\n SortParam,\n} from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// useInfiniteResource — a list that grows with \"Load more\", by cursor.\n//\n// Asks for the first page with `cursor: null`. A provider that serves cursor\n// paging answers with `nextCursor` and is paged by keyset from then on; one\n// that doesn't answers without it and is paged by `page` (offset) until\n// `total` rows are loaded. Pages live under `[resource, \"infinite\", params]`,\n// so writes on the resource (which invalidate `[resource]`) refetch them,\n// and pending optimistic and undoable writes are patched into every page.\n// ---------------------------------------------------------------------------\n\nexport interface UseInfiniteResourceOptions {\n defaultSort?: SortParam;\n /**\n * Sort by several fields, first one first, e.g. a grouped list: the group, then the order\n * within it. Wins over `defaultSort`. On a provider without `multiSort` only the first applies.\n */\n defaultSorts?: SortParam[];\n /** Re-synced when its value changes, like `useResource`'s. */\n defaultFilters?: FilterParam[];\n /** Rows per page. Default 25. */\n perPage?: number;\n /** The search to start with. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax. Must include the sort and key columns. */\n select?: string;\n /** Fields to search across when `setSearch` is called. */\n searchFields?: string[];\n /** Disable fetching. */\n enabled?: boolean;\n /** Refetch the loaded pages when the provider reports a change. See `UseResourceOptions.live`. */\n live?: boolean | LiveOptions;\n /**\n * Keep at most this many pages loaded (TanStack Query's `maxPages`): scrolling far drops pages\n * from the front, and scrolling back loads them again, so a long feed and a live refetch stay\n * cheap. Needs a provider that pages by cursor both ways (`prevCursor`); offset paging ignores it.\n */\n maxPages?: number;\n /**\n * Keep the current rows on screen while a new search, sort or filter loads, instead of a\n * loading state for each change. Default false.\n */\n keepPreviousData?: boolean;\n}\n\n/** Where one page starts: its offset page, and its cursor (`null` for the first). */\nexport interface InfinitePageParam {\n page: number;\n cursor: string | null;\n}\n\nexport interface UseInfiniteResourceReturn<T> {\n /** The TanStack infinite query. */\n query: UseInfiniteQueryResult<InfiniteData<ListResult<T>, InfinitePageParam>>;\n /** Every loaded row, in order. */\n rows: T[];\n /** Rows matching the filters and search, from the first page's count. */\n total: number | undefined;\n /** True when `total` is the database's estimate, so a screen says \"about\". */\n totalIsEstimate: boolean;\n /** Loads the next page. Does nothing while one is loading or none is left. */\n fetchNextPage: () => void;\n hasNextPage: boolean;\n /** Load the page before the first loaded one (after `maxPages` dropped it). No-op when there is none. */\n fetchPreviousPage: () => void;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n /** The params every page is asked with (without its page and cursor). */\n params: Omit<ListParams, \"pagination\"> & { perPage: number };\n /** Sort by one field (or none). Replaces every sort. */\n setSort: (sort: SortParam | undefined) => void;\n /** Sort by several fields, first one first. */\n setSorts: (sorts: SortParam[]) => void;\n setFilters: (filters: FilterParam[]) => void;\n setSearch: (query: string) => void;\n}\n\nfunction filterKey(filters: FilterParam[] | undefined): string {\n return JSON.stringify(\n (filters ?? []).map((f) =>\n Object.fromEntries(Object.entries(f).sort(([a], [b]) => a.localeCompare(b))),\n ),\n );\n}\n\nexport function useInfiniteResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseInfiniteResourceOptions = {},\n): UseInfiniteResourceReturn<T> {\n const {\n defaultSort,\n defaultSorts,\n defaultFilters,\n perPage = 25,\n defaultSearch = \"\",\n select,\n searchFields,\n enabled = true,\n live,\n keepPreviousData = false,\n } = options;\n const provider = useDataProvider();\n\n const [sorts, setSortsRaw] = useState<SortParam[]>(() =>\n defaultSorts && defaultSorts.length > 0 ? defaultSorts : defaultSort ? [defaultSort] : [],\n );\n const setSort = useCallback((next: SortParam | undefined) => setSortsRaw(next ? [next] : []), []);\n const setSorts = useCallback((next: SortParam[]) => setSortsRaw(next), []);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [search, setSearch] = useState(defaultSearch);\n\n // Follow `defaultFilters` by value, during render (see useResource).\n const defaultKey = filterKey(defaultFilters);\n const [syncedKey, setSyncedKey] = useState(defaultKey);\n if (defaultKey !== syncedKey) {\n setSyncedKey(defaultKey);\n setFiltersRaw(defaultFilters ?? []);\n }\n\n const setFilters = useCallback((next: FilterParam[]) => setFiltersRaw(next), []);\n\n const params = useMemo(() => {\n const p: Omit<ListParams, \"pagination\"> & { perPage: number } = {\n perPage,\n // The first sort is `sort` too, for a provider that sorts by one field only.\n sort: sorts[0],\n ...(sorts.length > 1 ? { sorts } : {}),\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (search && searchFields && searchFields.length > 0) {\n p.search = { query: search, fields: searchFields };\n }\n return p;\n }, [perPage, sorts, filters, select, search, searchFields]);\n\n // Whether the provider pages by cursor (it sends `nextCursor`), learnt from the first page.\n const cursorMode = useRef(false);\n const query = useInfiniteQuery<\n ListResult<T>,\n Error,\n InfiniteData<ListResult<T>, InfinitePageParam>,\n readonly unknown[],\n InfinitePageParam\n >({\n queryKey: resourceKeys(resource).infinite(params),\n initialPageParam: { page: 1, cursor: null },\n queryFn: ({ pageParam }) => {\n const { perPage: size, ...rest } = params;\n return provider.getList<T>(resource, {\n ...rest,\n pagination: { page: pageParam.page, perPage: size, cursor: pageParam.cursor },\n });\n },\n getNextPageParam: (last, pages, lastParam) => {\n if (last.nextCursor !== undefined) {\n // Cursor mode: the provider says whether there is more.\n return last.nextCursor ? { page: lastParam.page + 1, cursor: last.nextCursor } : undefined;\n }\n // Offset mode: more while the last page was full and, when the total is\n // an exact count, fewer than `total` rows are loaded. An uncounted\n // (`count: \"none\"`, total -1) or estimated total (RLS makes the planner\n // guess low) never stops the list early: only a short page does.\n const loaded = pages.reduce((n, p) => n + p.data.length, 0);\n const first = pages[0];\n const exact = !!first && first.total >= 0 && !first.totalIsEstimate;\n if (last.data.length < params.perPage || (exact && loaded >= first.total)) return undefined;\n return { page: lastParam.page + 1, cursor: null };\n },\n getPreviousPageParam: (first, _pages, firstParam) =>\n // Cursor mode only: offset pages aren't dropped from the front.\n first.prevCursor ? { page: firstParam.page - 1, cursor: first.prevCursor } : undefined,\n // Only once the provider is known to page by cursor: TanStack drops pages whenever maxPages is\n // set, and offset pages can't be loaded back, so they would be lost.\n ...(options.maxPages !== undefined && options.maxPages > 0 && cursorMode.current ? { maxPages: options.maxPages } : {}),\n enabled,\n ...(keepPreviousData ? { placeholderData: keepPrevious } : {}),\n });\n\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // A row can move between pages while the user scrolls (its sort value\n // changed, or rows before it were added): show it once, where it first appears.\n const rows = useMemo(() => {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const page of query.data?.pages ?? []) {\n for (const row of page.data) {\n const id = row?.id;\n if (id != null) {\n const key = String(id);\n if (seen.has(key)) continue;\n seen.add(key);\n }\n out.push(row);\n }\n }\n return out;\n }, [query.data]);\n const first = query.data?.pages[0];\n if (first && first.nextCursor !== undefined) cursorMode.current = true;\n // The count comes with the list's first page only. Once maxPages drops that page (or a refetch\n // starts from a back cursor) the loaded first page has no count, so keep the last one seen for\n // these params.\n const paramsKey = JSON.stringify(params);\n const lastCount = useRef<{ key: string; total: number; estimate: boolean } | null>(null);\n // Not from placeholder pages (keepPreviousData): they're the old params' rows and count.\n if (first && first.total >= 0 && !query.isPlaceholderData) {\n lastCount.current = { key: paramsKey, total: first.total, estimate: !!first.totalIsEstimate };\n }\n const count = lastCount.current?.key === paramsKey ? lastCount.current : null;\n const total = count?.total;\n\n const {\n fetchNextPage: fetchNext,\n hasNextPage,\n isFetchingNextPage,\n fetchPreviousPage: fetchPrevious,\n hasPreviousPage,\n isFetchingPreviousPage,\n } = query;\n const fetchNextPage = useCallback(() => {\n if (!hasNextPage || isFetchingNextPage) return;\n void fetchNext();\n }, [fetchNext, hasNextPage, isFetchingNextPage]);\n const fetchPreviousPage = useCallback(() => {\n if (!hasPreviousPage || isFetchingPreviousPage) return;\n void fetchPrevious();\n }, [fetchPrevious, hasPreviousPage, isFetchingPreviousPage]);\n\n return {\n query,\n rows,\n total,\n totalIsEstimate: !!count?.estimate,\n fetchNextPage,\n hasNextPage: !!hasNextPage,\n fetchPreviousPage,\n hasPreviousPage: !!hasPreviousPage,\n isFetchingNextPage,\n params,\n setSort,\n setSorts,\n setFilters,\n setSearch,\n };\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { NO_VIEWER } from './chunk-OZYF55E3.js';
2
- import { workspaceAt, workspaceHref } from './chunk-UHOMTFBD.js';
2
+ import { workspaceAt, workspaceHref } from './chunk-JTRRAVR4.js';
3
3
  import { stableJson } from './chunk-5ASUMG6K.js';
4
- import { flushPendingWrites, dropPendingWrites } from './chunk-RFHUOXZC.js';
5
- import { PersistedViewerContext } from './chunk-2K4747KX.js';
4
+ import { flushPendingWrites, dropPendingWrites } from './chunk-SOO54YYY.js';
5
+ import { PersistedViewerContext } from './chunk-R3YXYVWF.js';
6
6
  import { isTimeZone, personTimeZone, dayIn } from './chunk-WXENWPWP.js';
7
7
  import { reportError } from './chunk-NOPS5EIH.js';
8
8
  import { useQueryClient } from '@tanstack/react-query';
@@ -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-AHFIS42U.js.map
170
- //# sourceMappingURL=chunk-AHFIS42U.js.map
169
+ //# sourceMappingURL=chunk-NZP7YQHS.js.map
170
+ //# sourceMappingURL=chunk-NZP7YQHS.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,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,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
+ {"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","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AAY,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-NZP7YQHS.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-WDPM5TBO.js';
2
- import { useInfiniteResource } from './chunk-G6GQPXQS.js';
3
- import { useDataProvider } from './chunk-2K4747KX.js';
1
+ import { relationNamingField } from './chunk-UDSTWXXZ.js';
2
+ import { useInfiniteResource } from './chunk-M5IX7C6U.js';
3
+ import { useDataProvider } from './chunk-R3YXYVWF.js';
4
4
  import { useMemo, useState, useEffect } from 'react';
5
5
  import { useQuery } from '@tanstack/react-query';
6
6
 
@@ -88,5 +88,5 @@ function useLinkOptions(target, options = {}) {
88
88
  }
89
89
 
90
90
  export { useLinkOptions };
91
- //# sourceMappingURL=chunk-DFABPMEQ.js.map
92
- //# sourceMappingURL=chunk-DFABPMEQ.js.map
91
+ //# sourceMappingURL=chunk-POUI7GAI.js.map
92
+ //# sourceMappingURL=chunk-POUI7GAI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-link-options.ts"],"names":[],"mapp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CAAA;AAAA,IAClC,SAAA,EAAW,OAAA,KAAY,CAAC,OAAA,IAAW,KAAK,KAAA,CAAM,SAAA,CAAA;AAAA,IAC9C,OAAA,EAAS,KAAK,KAAA,CAAM,OAAA;AAAA,IACpB,SAAS,IAAA,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
+ {"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,SAAS,KAAK,CAAA,EAAG,OAAO,MAAA,CAAO,KAAK,CAAA;AAC5E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,IAAA;AACtC,EAAA,OAAO,KAAA,CAAM,MAAK,IAAK,IAAA;AACzB;AASO,SAAS,cAAA,CAAe,MAAA,EAAoB,OAAA,GAAiC,EAAC,EAAyB;AAC5G,EAA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K,CAAA;AACrB,MAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,EAAE,OAAO,QAAQ,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,CAAA,EAAI;AACnF,MAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,GAAG,CAAC,CAAA,EAAG;AAC3B,MAAA,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,GAAG,CAAC,CAAA;AACpB,MAAA,MAAM,OAAO,MAAA,GAAS,GAAA,CAAI,MAAM,CAAA,GAAI,GAAA,CAAI,OAAO,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,KAAM,MAAA,CAAO,KAAK,CAAC,CAAC,KAAK,EAAE,CAAA;AAE1F,MAAA,GAAA,CAAI,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,EAAK,OAAO,KAAA,CAAM,IAAI,CAAA,IAAK,QAAA,EAAU,CAAA;AAAA,IACzD;AACA,IAAA,OAAO,GAAA;AAAA,EACT,GAAG,CAAC,IAAA,EAAM,KAAA,EAAO,MAAA,EAAQ,QAAQ,CAAC,CAAA;AAElC,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,WAAA;AAAA,IACT,UAAA,EAAY,MAAA;AAAA,IACZ,UAAA,EAAY,aAAa,MAAA,GAAS,CAAA;AAAA,IAClC,SAAA,EAAW,OAAA,KAAY,CAAC,OAAA,IAAW,KAAK,KAAA,CAAM,SAAA,CAAA;AAAA,IAC9C,OAAA,EAAS,KAAK,KAAA,CAAM,OAAA;AAAA,IACpB,SAAS,IAAA,CAAK,WAAA;AAAA,IACd,UAAU,IAAA,CAAK,aAAA;AAAA,IACf,eAAe,IAAA,CAAK;AAAA,GACtB;AACF","file":"chunk-POUI7GAI.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-S2VYJWB4.js';
2
- import { resourceKeys } from './chunk-7PUFVNPB.js';
3
- import { useDataProvider } from './chunk-2K4747KX.js';
1
+ import { useLiveInvalidation } from './chunk-E3K2A3PK.js';
2
+ import { resourceKeys } from './chunk-2IGAUXYH.js';
3
+ import { useDataProvider } from './chunk-R3YXYVWF.js';
4
4
  import { useQuery } from '@tanstack/react-query';
5
5
 
6
6
  function useOne(resource, id, options = {}) {
@@ -35,5 +35,5 @@ function useOne(resource, id, options = {}) {
35
35
  }
36
36
 
37
37
  export { useOne };
38
- //# sourceMappingURL=chunk-NE2D74BP.js.map
39
- //# sourceMappingURL=chunk-NE2D74BP.js.map
38
+ //# sourceMappingURL=chunk-QGWQ6LK3.js.map
39
+ //# sourceMappingURL=chunk-QGWQ6LK3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-NE2D74BP.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-QGWQ6LK3.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { toAggregateValues } from './chunk-J54XXKQD.js';
1
2
  import { createLocalStorageAdapter } from './chunk-4PTQYT5J.js';
2
3
  import { createContext, useContext, useMemo, useRef, useState, useEffect } from 'react';
3
4
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -104,6 +105,10 @@ function createMockProvider(datasets, options = {}) {
104
105
  const result = applyListParams(table, params);
105
106
  return withDelay(result);
106
107
  },
108
+ async aggregate(_resource, params) {
109
+ const { data } = applyListParams(getTable(_resource), { filters: params.filters, search: params.search });
110
+ return withDelay({ values: toAggregateValues(data, params.metrics) });
111
+ },
107
112
  async getOne(_resource, params) {
108
113
  const table = getTable(_resource);
109
114
  const row = table.find((r) => String(r.id) === String(params.id));
@@ -254,5 +259,5 @@ function useRestoredReads(queryClient, persist, scope) {
254
259
  var PersistedViewerContext = createContext(void 0);
255
260
 
256
261
  export { DataProviderRoot, GenesisProvider, PersistedViewerContext, createMockProvider, useDataProvider, useStorage };
257
- //# sourceMappingURL=chunk-2K4747KX.js.map
258
- //# sourceMappingURL=chunk-2K4747KX.js.map
262
+ //# sourceMappingURL=chunk-R3YXYVWF.js.map
263
+ //# sourceMappingURL=chunk-R3YXYVWF.js.map