@marktiderman/genesis-core 2.1.0 → 2.2.1

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.
@@ -0,0 +1,58 @@
1
+ // src/workspaces.ts
2
+ var WORKSPACE_KIND_ORDER = ["personal", "rollup", "tenant"];
3
+ function trimPath(path) {
4
+ const bare = path.split(/[?#]/)[0] ?? "";
5
+ let end = bare.length;
6
+ while (end > 1 && bare[end - 1] === "/") end--;
7
+ return bare.slice(0, end);
8
+ }
9
+ function within(pathname, prefix) {
10
+ const p = trimPath(pathname);
11
+ const w = trimPath(prefix);
12
+ if (w === "/") return true;
13
+ return p === w || p.startsWith(`${w}/`);
14
+ }
15
+ function workspaceAt(workspaces, pathname) {
16
+ let best;
17
+ for (const w of workspaces) {
18
+ if (within(pathname, w.path) && (!best || trimPath(w.path).length > trimPath(best.path).length)) best = w;
19
+ }
20
+ return best;
21
+ }
22
+ function pathInWorkspace(workspace, pathname) {
23
+ const w = trimPath(workspace.path);
24
+ const p = trimPath(pathname);
25
+ if (!within(p, w)) return "/";
26
+ const rest = w === "/" ? p : p.slice(w.length);
27
+ return rest || "/";
28
+ }
29
+ function keepSection(rest, from, to) {
30
+ if (from.kind !== to.kind) return false;
31
+ const section = rest.split("/").filter(Boolean)[0];
32
+ return section ? `/${section}` : false;
33
+ }
34
+ function workspaceHref(workspaces, to, pathname, options = {}) {
35
+ const from = pathname === void 0 ? void 0 : workspaceAt(workspaces, pathname);
36
+ if (!from || from.id === to.id || pathname === void 0) return to.path;
37
+ const kept = (options.keep ?? keepSection)(pathInWorkspace(from, pathname), from, to);
38
+ if (!kept || kept === "/") return to.path;
39
+ const base = trimPath(to.path);
40
+ return `${base === "/" ? "" : base}${kept.startsWith("/") ? kept : `/${kept}`}`;
41
+ }
42
+ function groupWorkspaces(workspaces, order = WORKSPACE_KIND_ORDER) {
43
+ const kinds = [...order];
44
+ for (const w of workspaces) if (!kinds.includes(w.kind)) kinds.push(w.kind);
45
+ return kinds.map((kind) => ({ kind, workspaces: workspaces.filter((w) => w.kind === kind) })).filter((g) => g.workspaces.length > 0);
46
+ }
47
+ function defaultWorkspace(workspaces, rememberedId) {
48
+ return (rememberedId ? workspaces.find((w) => w.id === rememberedId) : void 0) ?? workspaces.find((w) => w.kind === "tenant") ?? workspaces[0];
49
+ }
50
+ function workspaceInitials(label) {
51
+ const words = label.trim().split(/\s+/).filter(Boolean);
52
+ const letters = words.length > 1 ? [words[0][0], words[1][0]] : [...words[0] ?? ""].slice(0, 2);
53
+ return letters.join("").toUpperCase();
54
+ }
55
+
56
+ export { WORKSPACE_KIND_ORDER, defaultWorkspace, groupWorkspaces, keepSection, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials };
57
+ //# sourceMappingURL=chunk-5JRXF7F7.js.map
58
+ //# sourceMappingURL=chunk-5JRXF7F7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/workspaces.ts"],"names":[],"mappings":";AAqEO,IAAM,oBAAA,GAAiD,CAAC,UAAA,EAAY,QAAA,EAAU,QAAQ;AAE7F,SAAS,SAAS,IAAA,EAAsB;AACtC,EAAA,MAAM,OAAO,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AAEtC,EAAA,IAAI,MAAM,IAAA,CAAK,MAAA;AACf,EAAA,OAAO,MAAM,CAAA,IAAK,IAAA,CAAK,GAAA,GAAM,CAAC,MAAM,GAAA,EAAK,GAAA,EAAA;AACzC,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA;AAC1B;AAEA,SAAS,MAAA,CAAO,UAAkB,MAAA,EAAyB;AACzD,EAAA,MAAM,CAAA,GAAI,SAAS,QAAQ,CAAA;AAC3B,EAAA,MAAM,CAAA,GAAI,SAAS,MAAM,CAAA;AACzB,EAAA,IAAI,CAAA,KAAM,KAAK,OAAO,IAAA;AACtB,EAAA,OAAO,MAAM,CAAA,IAAK,CA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AA6C;AAC3H,EAAA,OAAA,CACG,eAAe,UAAA,CAAW,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,OAAO,YAAY,CAAA,GAAI,WAChE,UAAA,CAAW,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,QAAQ,CAAA,IAC1C,WAAW,CAAC,CAAA;AAEhB;AAOO,SAAS,kBAAkB,KAAA,EAAuB;AACvD,EAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,EAAK,CAAE,MAAM,KAAK,CAAA,CAAE,OAAO,OAAO,CAAA;AACtD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,CAAC,MAAM,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","file":"chunk-5JRXF7F7.js","sourcesContent":["/**\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\";\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 /** Anything else the app needs; Genesis never reads it. */\n meta?: Readonly<Record<string, unknown>>;\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"]}
@@ -1,6 +1,7 @@
1
1
  import { NO_VIEWER } from './chunk-OZYF55E3.js';
2
- import { flushPendingWrites, dropPendingWrites } from './chunk-OSFG3GFY.js';
2
+ import { workspaceAt, workspaceHref } from './chunk-5JRXF7F7.js';
3
3
  import { stableJson } from './chunk-HBAPYA5K.js';
4
+ import { flushPendingWrites, dropPendingWrites } from './chunk-OSFG3GFY.js';
4
5
  import { isTimeZone, personTimeZone, dayIn } from './chunk-3B4IFDMK.js';
5
6
  import { reportError } from './chunk-ZIMQUFXD.js';
6
7
  import { useQueryClient } from '@tanstack/react-query';
@@ -116,7 +117,51 @@ function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, scopeTim
116
117
  }
117
118
  return /* @__PURE__ */ jsx(ViewerContextValue.Provider, { value, children: /* @__PURE__ */ jsx(Fragment$1, { children }, `${viewer ?? "signed-out"}#${mounted.epoch}`) });
118
119
  }
120
+ var WorkspaceContextValue = createContext(null);
121
+ function useWorkspace() {
122
+ return useContext(WorkspaceContextValue);
123
+ }
124
+ var STORAGE_PREFIX = "genesis:workspace:";
125
+ function rememberedWorkspaceId(viewer) {
126
+ if (!viewer || typeof window === "undefined") return null;
127
+ try {
128
+ return window.localStorage.getItem(STORAGE_PREFIX + viewer);
129
+ } catch {
130
+ return null;
131
+ }
132
+ }
133
+ function remember(viewer, id) {
134
+ try {
135
+ window.localStorage.setItem(STORAGE_PREFIX + viewer, id);
136
+ } catch {
137
+ }
138
+ }
139
+ function WorkspaceScope({ workspaces, pathname, scope, keep, children, ...viewerProps }) {
140
+ const current = workspaceAt(workspaces, pathname);
141
+ const value = useMemo(
142
+ () => ({
143
+ current,
144
+ workspaces,
145
+ hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {})
146
+ }),
147
+ [current, workspaces, pathname, keep]
148
+ );
149
+ const viewer = viewerProps.viewer;
150
+ useEffect(() => {
151
+ if (viewer && current) remember(viewer, current.id);
152
+ }, [viewer, current]);
153
+ return /* @__PURE__ */ jsx(WorkspaceContextValue.Provider, { value, children: /* @__PURE__ */ jsx(
154
+ ViewerScope,
155
+ {
156
+ ...viewerProps,
157
+ scope: { ...scope, ...current?.scope },
158
+ ...current?.roles !== void 0 ? { roles: current.roles } : {},
159
+ ...current?.timeZone !== void 0 ? { scopeTimeZone: current.timeZone } : {},
160
+ children
161
+ }
162
+ ) });
163
+ }
119
164
 
120
- export { ViewerScope, clearViewerCache, scopeClock, useOptionalViewerScope, useViewer, useViewerScope };
121
- //# sourceMappingURL=chunk-3FFBW4XC.js.map
122
- //# sourceMappingURL=chunk-3FFBW4XC.js.map
165
+ export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace };
166
+ //# sourceMappingURL=chunk-N5BKU7PR.js.map
167
+ //# sourceMappingURL=chunk-N5BKU7PR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","createContext","useContext","useMemo","useEffect","jsx"],"mappings":";;;;;;;;;;AAUA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,MAAM,CAAC,UAAA,CAAW,CAAC,CAAA,EAAG,CAAC,CAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,IAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAE,EAAE,GAAA,CAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;AACnJ,IAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,EAAU;AAC9B,MAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,CAAC,CAAA;AACrC,MAAA,IAAI,KAAA,KAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AAChD,QAAA,IAAI,QAAQ,GAAA,CAAI,QAAA,KAAa,cAAc,MAAM,IAAI,UAAU,4EAA4E,CAAA;AAC3I,QAAA,QAAA,GAAW,IAAA;AACX,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,OAAO,OAAO,WAAA,CA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CAAc,UAAA,EAAY,EAAA,EAAI,QAAA,EAAU,IAAA,GAAO,EAAE,IAAA,EAAK,GAAI,EAAE;AAAA,KAC/E,CAAA;AAAA,IACA,CAAC,OAAA,EAAS,UAAA,EAAY,QAAA,EAAU,IAAI;AAAA,GACtC;AACA,EAAA,MAAM,SAAS,WAAA,CAAY,MAAA;AAC3B,EAAAC,UAAU,MAAM;AACd,IAAA,IAAI,MAAA,IAAU,OAAA,EAAS,QAAA,CAAS,MAAA,EAAQ,QAAQ,EAAE,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACEC,GAAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,OAC9B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-N5BKU7PR.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\";\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.\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, scope, roles, timeZone, scopeTimeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\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"]}
@@ -6,7 +6,10 @@ export { useCapabilities } from './use-capabilities.js';
6
6
  export { UseWriteOptions, UseWriteReturn, WRITE_FAILED, useWrite } from './use-write.js';
7
7
  export { UseDraftReturn, useDraft } from './use-draft.js';
8
8
  export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftAdoption, DraftController, DraftOptions, DraftSeed, DraftState, DraftStatus, DraftValue, isNetworkFailure, stableJson } from './draft-controller.js';
9
- export { G as GenesisViewerRoles, N as NO_VIEWER, R as ResourceScope, V as Viewer, a as ViewerContext, b as ViewerScope, c as ViewerScopeProps, d as clearViewerCache, s as scopeClock, u as useOptionalViewerScope, e as useViewer, f as useViewerScope } from '../viewer-scope-bthEYSOB.js';
9
+ import { c as ViewerScopeProps } from '../viewer-scope-bthEYSOB.js';
10
+ export { G as GenesisViewerRoles, N as NO_VIEWER, R as ResourceScope, V as Viewer, a as ViewerContext, b as ViewerScope, d as clearViewerCache, s as scopeClock, u as useOptionalViewerScope, e as useViewer, f as useViewerScope } from '../viewer-scope-bthEYSOB.js';
11
+ import * as react from 'react';
12
+ import { Workspace, WorkspaceHrefOptions } from '../workspaces.js';
10
13
  export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, LiveOptions } from './use-live.js';
11
14
  export { UseResourceFormOptions, UseResourceFormReturn, blankValues, buildArrayItemDefaults, useResourceForm } from './use-resource-form.js';
12
15
  export { UseWizardReturn, WizardStep, useWizard } from './use-wizard.js';
@@ -16,6 +19,59 @@ import '@tanstack/react-query';
16
19
  import '../types-CXhqXPN1.js';
17
20
  import '../types-o8j7g6O6.js';
18
21
  import '../form-types.js';
19
- import 'react';
20
22
  import '../dates.js';
21
23
  import 'react-hook-form';
24
+
25
+ /**
26
+ * The workspace the viewer is in, and where each of their others is from here.
27
+ *
28
+ * @stability Beta
29
+ */
30
+ interface WorkspaceContext<W extends Workspace = Workspace> {
31
+ /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */
32
+ current: W | undefined;
33
+ workspaces: readonly W[];
34
+ /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */
35
+ hrefFor: (to: W) => string;
36
+ }
37
+ /**
38
+ * The nearest `WorkspaceScope`'s workspaces, or null outside one.
39
+ *
40
+ * @stability Beta
41
+ */
42
+ declare function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null;
43
+ /**
44
+ * The workspace this viewer was last in on this device, for the app's front door
45
+ * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.
46
+ *
47
+ * @stability Beta
48
+ */
49
+ declare function rememberedWorkspaceId(viewer: string | null | undefined): string | null;
50
+ /** @stability Beta */
51
+ interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, "scope" | "roles" | "scopeTimeZone"> {
52
+ /** Every workspace this viewer has. */
53
+ workspaces: readonly W[];
54
+ /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */
55
+ pathname: string;
56
+ /** Scope keys every workspace adds to its own (rarely needed). */
57
+ scope?: ViewerScopeProps["scope"];
58
+ /** How switching keeps the viewer's place (see `workspaceHref`). */
59
+ keep?: WorkspaceHrefOptions["keep"];
60
+ }
61
+ /**
62
+ * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current
63
+ * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and
64
+ * `timeZone`), so every view with `scope: ["org_id"]` follows the switcher with no screen code. It
65
+ * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.
66
+ *
67
+ * ```tsx
68
+ * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>
69
+ * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>
70
+ * </WorkspaceScope>
71
+ * ```
72
+ *
73
+ * @stability Beta
74
+ */
75
+ declare function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>): react.JSX.Element;
76
+
77
+ export { ViewerScopeProps, type WorkspaceContext, WorkspaceScope, type WorkspaceScopeProps, rememberedWorkspaceId, useWorkspace };
@@ -1,6 +1,8 @@
1
- export { ViewerScope, clearViewerCache, scopeClock, useOptionalViewerScope, useViewer, useViewerScope } from '../chunk-3FFBW4XC.js';
1
+ export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from '../chunk-N5BKU7PR.js';
2
+ export { useWizard } from '../chunk-7KOLYF27.js';
2
3
  export { WRITE_FAILED, useWrite } from '../chunk-52T2EYXH.js';
3
4
  export { NO_VIEWER } from '../chunk-OZYF55E3.js';
5
+ export { useDraft } from '../chunk-DF2UWEEB.js';
4
6
  export { useInfiniteResource } from '../chunk-2VVZ2KX3.js';
5
7
  export { loadRelationLabel, useRelationLabel } from '../chunk-XMC4EJUE.js';
6
8
  export { blankValues, buildArrayItemDefaults, useResourceForm } from '../chunk-X6EO3XBB.js';
@@ -8,7 +10,8 @@ export { useOne } from '../chunk-GWQHP3RC.js';
8
10
  export { useResource } from '../chunk-CC37H7O2.js';
9
11
  export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS } from '../chunk-K4ZNAF3G.js';
10
12
  export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from '../chunk-XQO4OH2N.js';
11
- export { useWizard } from '../chunk-7KOLYF27.js';
13
+ import '../chunk-5JRXF7F7.js';
14
+ export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from '../chunk-HBAPYA5K.js';
12
15
  import '../chunk-AUVKRXRC.js';
13
16
  export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from '../chunk-OSFG3GFY.js';
14
17
  import '../chunk-7PUFVNPB.js';
@@ -16,8 +19,6 @@ import '../chunk-7NUL32W7.js';
16
19
  export { useCapabilities } from '../chunk-LGTXQTHA.js';
17
20
  import '../chunk-VDEW4AOS.js';
18
21
  import '../chunk-ZYJUEJ4Z.js';
19
- export { useDraft } from '../chunk-DF2UWEEB.js';
20
- export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from '../chunk-HBAPYA5K.js';
21
22
  import '../chunk-3B4IFDMK.js';
22
23
  import '../chunk-ZIMQUFXD.js';
23
24
  import '../chunk-PA6WJE5E.js';
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export { UseWriteOptions, UseWriteReturn, WRITE_FAILED, useWrite } from './hooks
14
14
  export { UseDraftReturn, useDraft } from './hooks/use-draft.js';
15
15
  export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftAdoption, DraftController, DraftOptions, DraftSeed, DraftState, DraftStatus, DraftValue, isNetworkFailure, stableJson } from './hooks/draft-controller.js';
16
16
  export { G as GenesisViewerRoles, N as NO_VIEWER, R as ResourceScope, V as Viewer, a as ViewerContext, b as ViewerScope, c as ViewerScopeProps, d as clearViewerCache, s as scopeClock, u as useOptionalViewerScope, e as useViewer, f as useViewerScope } from './viewer-scope-bthEYSOB.js';
17
+ export { WorkspaceContext, WorkspaceScope, WorkspaceScopeProps, rememberedWorkspaceId, useWorkspace } from './hooks/index.js';
17
18
  export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, LiveOptions } from './hooks/use-live.js';
18
19
  export { UseResourceFormOptions, UseResourceFormReturn, blankValues, buildArrayItemDefaults, useResourceForm } from './hooks/use-resource-form.js';
19
20
  export { UseWizardReturn, WizardStep, useWizard } from './hooks/use-wizard.js';
@@ -28,6 +29,7 @@ export { ClassifiedError, ClassifyErrorOptions, ErrorKind, ErrorMessages, ErrorR
28
29
  export { titleCase } from './utils.js';
29
30
  import 'react';
30
31
  import './dates.js';
32
+ import './workspaces.js';
31
33
  import 'react-hook-form';
32
34
 
33
35
  /** Who and when a key is for. `viewer` is required; null means signed out. */
package/dist/index.js CHANGED
@@ -2,9 +2,11 @@ export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabas
2
2
  export { defineResource } from './chunk-7FVTGKTX.js';
3
3
  export { decodeRecordKey, encodeRecordKey, keyFields } from './chunk-KV2HW4G4.js';
4
4
  import './chunk-XCX2TRBL.js';
5
- export { ViewerScope, clearViewerCache, scopeClock, useOptionalViewerScope, useViewer, useViewerScope } from './chunk-3FFBW4XC.js';
5
+ export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-N5BKU7PR.js';
6
+ export { useWizard } from './chunk-7KOLYF27.js';
6
7
  export { WRITE_FAILED, useWrite } from './chunk-52T2EYXH.js';
7
8
  export { NO_VIEWER } from './chunk-OZYF55E3.js';
9
+ export { useDraft } from './chunk-DF2UWEEB.js';
8
10
  export { useInfiniteResource } from './chunk-2VVZ2KX3.js';
9
11
  export { loadRelationLabel, useRelationLabel } from './chunk-XMC4EJUE.js';
10
12
  export { blankValues, buildArrayItemDefaults, useResourceForm } from './chunk-X6EO3XBB.js';
@@ -12,7 +14,8 @@ export { useOne } from './chunk-GWQHP3RC.js';
12
14
  export { useResource } from './chunk-CC37H7O2.js';
13
15
  export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS } from './chunk-K4ZNAF3G.js';
14
16
  export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from './chunk-XQO4OH2N.js';
15
- export { useWizard } from './chunk-7KOLYF27.js';
17
+ import './chunk-5JRXF7F7.js';
18
+ export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from './chunk-HBAPYA5K.js';
16
19
  import './chunk-AUVKRXRC.js';
17
20
  export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './chunk-OSFG3GFY.js';
18
21
  export { defineQueryKeys, resourceKeys } from './chunk-7PUFVNPB.js';
@@ -20,8 +23,6 @@ import './chunk-7NUL32W7.js';
20
23
  export { useCapabilities } from './chunk-LGTXQTHA.js';
21
24
  export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from './chunk-VDEW4AOS.js';
22
25
  export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './chunk-ZYJUEJ4Z.js';
23
- export { useDraft } from './chunk-DF2UWEEB.js';
24
- export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from './chunk-HBAPYA5K.js';
25
26
  import './chunk-3B4IFDMK.js';
26
27
  export { classifyError, defaultErrorReporter, errorMessages, getErrorReporter, reportError, setErrorReporter } from './chunk-ZIMQUFXD.js';
27
28
  export { fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from './chunk-PA6WJE5E.js';
@@ -1,4 +1,4 @@
1
- import { D as DataRow, e as ResourceContract, F as FieldSchema, i as RowAction, j as RowOf } from '../types-o8j7g6O6.js';
1
+ import { D as DataRow, e as ResourceContract, j as RowOf, i as RowAction, F as FieldSchema } from '../types-o8j7g6O6.js';
2
2
  import { C as ChipTone, R as Readiness } from '../status-BXRokZD9.js';
3
3
  import { V as Viewer, R as ResourceScope } from '../viewer-scope-bthEYSOB.js';
4
4
  export { G as GenesisViewerRoles, N as NO_VIEWER } from '../viewer-scope-bthEYSOB.js';
@@ -376,6 +376,13 @@ type ScopeValue = string | number | boolean | null;
376
376
  * it is left out; row-level security still decides what the viewer reads.
377
377
  */
378
378
  declare function scopeValues(view: Pick<ResourceView<any, any>, "resource" | "definition">, scope: ResourceScope | null | undefined): Readonly<Record<string, ScopeValue>>;
379
+ /**
380
+ * The view's scope keys as a list filter, the way `ResourceView` applies them itself: like
381
+ * {@link scopeValues}, but a list (`{ orgId: ["o1", "o2"] }`, a roll-up across organizations)
382
+ * filters to any of its values, and a key the scope doesn't set is left out instead of throwing.
383
+ * A single value also starts new rows; a list doesn't, so a new row in a roll-up asks which one.
384
+ */
385
+ declare function scopeFilter(view: Pick<ResourceView<any, any>, "definition">, scope: ResourceScope | null | undefined): Readonly<Record<string, ScopeValue | readonly (string | number)[]>>;
379
386
 
380
387
  /**
381
388
  * A screen's `tree` (`<ResourceView tree={{ getParentId }} />`): rows nest under the row
@@ -470,33 +477,33 @@ declare function cascadeSelection(selected: ReadonlySet<string>, id: string, des
470
477
 
471
478
  type AnyView = ResourceView<ResourceContract<any>, any>;
472
479
  /** Equality filters for a child list, sent to the server: `{ brand_id: brand.id }`. `null` is "is empty". */
473
- type WorkspaceFilter = Readonly<Record<string, string | number | boolean | null>>;
480
+ type RecordViewFilter = Readonly<Record<string, string | number | boolean | null>>;
474
481
  interface SectionBase {
475
- /** Unique in the workspace; the screen's route segment or slot key. */
482
+ /** Unique in the record view; the screen's route segment or slot key. */
476
483
  id: string;
477
484
  label: string;
478
485
  }
479
486
  /** A child list: another view, filtered by this record. */
480
- interface WorkspaceListSection<Row extends DataRow = DataRow> extends SectionBase {
487
+ interface RecordViewListSection<Row extends DataRow = DataRow> extends SectionBase {
481
488
  list: {
482
489
  view: AnyView;
483
- filter: (row: Row) => WorkspaceFilter;
490
+ filter: (row: Row) => RecordViewFilter;
484
491
  };
485
492
  settings?: never;
486
493
  }
487
494
  /** A few of this record's own fields, edited in place. Each must be in `view.writable("edit")`. */
488
- interface WorkspaceSettingsSection<Name extends string = string> extends SectionBase {
495
+ interface RecordViewSettingsSection<Name extends string = string> extends SectionBase {
489
496
  settings: readonly Name[];
490
497
  list?: never;
491
498
  }
492
499
  /** A section the screen fills itself, through a slot keyed by `id`. */
493
- interface WorkspaceSlotSection extends SectionBase {
500
+ interface RecordViewSlotSection extends SectionBase {
494
501
  list?: never;
495
502
  settings?: never;
496
503
  }
497
- type WorkspaceSection<Row extends DataRow = DataRow, Name extends string = string> = WorkspaceListSection<Row> | WorkspaceSettingsSection<Name> | WorkspaceSlotSection;
504
+ type RecordViewSection<Row extends DataRow = DataRow, Name extends string = string> = RecordViewListSection<Row> | RecordViewSettingsSection<Name> | RecordViewSlotSection;
498
505
  /** One readiness check: "Has a logo", ok or not, and why not. */
499
- interface WorkspaceReadinessItem {
506
+ interface RecordViewReadinessItem {
500
507
  /** A stable key for the check; default its position and title. */
501
508
  id?: string;
502
509
  title: string;
@@ -505,17 +512,17 @@ interface WorkspaceReadinessItem {
505
512
  /** Genesis chip tones only. Default `success` when ok, `warning` when not. */
506
513
  tone?: ViewTone;
507
514
  }
508
- /** What `defineWorkspace` accepts. */
509
- interface WorkspaceDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> {
515
+ /** What `defineRecordView` accepts. */
516
+ interface RecordViewDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> {
510
517
  /** The view actions the header offers, by name, in order. Default: every view action. */
511
518
  header?: {
512
519
  actions?: readonly string[];
513
520
  };
514
- sections: readonly WorkspaceSection<Row, FieldNameOf<C>>[];
515
- readiness?: (row: Row) => readonly WorkspaceReadinessItem[];
521
+ sections: readonly RecordViewSection<Row, FieldNameOf<C>>[];
522
+ readiness?: (row: Row) => readonly RecordViewReadinessItem[];
516
523
  }
517
524
  /** A section as a renderer draws it. */
518
- type ResolvedWorkspaceSection = {
525
+ type ResolvedRecordViewSection = {
519
526
  readonly id: string;
520
527
  readonly label: string;
521
528
  readonly kind: "list";
@@ -531,7 +538,7 @@ type ResolvedWorkspaceSection = {
531
538
  readonly kind: "slot";
532
539
  };
533
540
  /** A header action with whether this row allows it. */
534
- interface WorkspaceHeaderAction {
541
+ interface RecordViewHeaderAction {
535
542
  readonly name: string;
536
543
  readonly label: string;
537
544
  readonly confirm?: string;
@@ -541,17 +548,17 @@ interface WorkspaceHeaderAction {
541
548
  readonly allowed: Allowed;
542
549
  }
543
550
  /** The header for one row: the view's summary plus the header's actions. */
544
- interface WorkspaceHeader {
551
+ interface RecordViewHeader {
545
552
  readonly title: string;
546
553
  readonly subtitle?: string;
547
554
  readonly chips: readonly {
548
555
  label: string;
549
556
  tone?: ViewTone;
550
557
  }[];
551
- readonly actions: readonly WorkspaceHeaderAction[];
558
+ readonly actions: readonly RecordViewHeaderAction[];
552
559
  }
553
560
  /** What a screen and its provider add to the header: they only narrow the view's guards. */
554
- interface WorkspaceHeaderOptions<Row extends DataRow = DataRow> {
561
+ interface RecordViewHeaderOptions<Row extends DataRow = DataRow> {
555
562
  /** The screen's own rule: `false` hides the action, a sentence refuses it with that reason. */
556
563
  can?: (action: string, row: Row) => Allowed | boolean;
557
564
  /** Whether anything can run actions here (the screen's `onAction`, or the provider's `runAction`). `false` hides them all. */
@@ -570,14 +577,14 @@ interface ResolvedReadinessItem {
570
577
  readonly reason?: string;
571
578
  readonly tone: ViewTone;
572
579
  }
573
- /** What `defineWorkspace` returns: frozen, with pure helpers for the renderers. */
574
- interface ResourceWorkspace<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> {
580
+ /** What `defineRecordView` returns: frozen, with pure helpers for the renderers. */
581
+ interface RecordView<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> {
575
582
  readonly view: ResourceView<C, Row>;
576
- readonly sections: readonly ResolvedWorkspaceSection[];
583
+ readonly sections: readonly ResolvedRecordViewSection[];
577
584
  /** The header's action names, in order. */
578
585
  readonly headerActions: readonly string[];
579
586
  readonly hasReadiness: boolean;
580
- section(id: string): ResolvedWorkspaceSection | undefined;
587
+ section(id: string): ResolvedRecordViewSection | undefined;
581
588
  /** The record's address for the provider: its key fields (`keyFields`), composite keys encoded. */
582
589
  recordId(row: Row): Identifier;
583
590
  /**
@@ -586,7 +593,7 @@ interface ResourceWorkspace<C extends ResourceContract = ResourceContract, Row e
586
593
  * Without a viewer the guard gets no one, so one that needs the viewer locks them.
587
594
  */
588
595
  settingsLocked(row: Row, viewer?: Viewer): string | null;
589
- headerFor(row: Row, options?: WorkspaceHeaderOptions<Row>): WorkspaceHeader;
596
+ headerFor(row: Row, options?: RecordViewHeaderOptions<Row>): RecordViewHeader;
590
597
  /**
591
598
  * Settings fields as the view's form resolves them (`view.form("edit")`), in the order listed:
592
599
  * one section's, or every settings section's without an id.
@@ -598,7 +605,7 @@ interface ResourceWorkspace<C extends ResourceContract = ResourceContract, Row e
598
605
  * A list section's filter for this row. In development, a filter with no key, or a value that
599
606
  * isn't a string, number, boolean or null, throws: it would show every child row.
600
607
  */
601
- listFilter(sectionId: string, row: Row): WorkspaceFilter;
608
+ listFilter(sectionId: string, row: Row): RecordViewFilter;
602
609
  /** The readiness checks for this row, tones resolved; empty without `readiness`. */
603
610
  readinessFor(row: Row): readonly ResolvedReadinessItem[];
604
611
  /**
@@ -608,13 +615,13 @@ interface ResourceWorkspace<C extends ResourceContract = ResourceContract, Row e
608
615
  */
609
616
  readinessSummary(row: Row): Readiness | null;
610
617
  }
611
- /** Whether a value is a workspace (`defineWorkspace`'s result). */
612
- declare function isWorkspace(value: unknown): value is ResourceWorkspace;
618
+ /** Whether a value is a record view (`defineRecordView`'s result). */
619
+ declare function isRecordView(value: unknown): value is RecordView;
613
620
  /**
614
621
  * One record's screen from its view:
615
622
  *
616
623
  * ```ts
617
- * export const brandWorkspace = defineWorkspace(brandsView, {
624
+ * export const brandRecordView = defineRecordView(brandsView, {
618
625
  * header: { actions: ["archive"] },
619
626
  * sections: [
620
627
  * { id: "products", label: "Products", list: { view: productsView, filter: (b) => ({ brand_id: b.id }) } },
@@ -626,8 +633,20 @@ declare function isWorkspace(value: unknown): value is ResourceWorkspace;
626
633
  * ```
627
634
  *
628
635
  * Throws {@link ViewDefinitionError} for a settings field the view can't write, a header action
629
- * the view doesn't define, a repeated section id, or a section that holds another workspace.
636
+ * the view doesn't define, a repeated section id, or a section that holds another record view.
630
637
  */
631
- declare function defineWorkspace<C extends ResourceContract, Row extends DataRow = RowOf<C>>(view: ResourceView<C, Row>, definition: WorkspaceDefinition<C, Row>): ResourceWorkspace<C, Row>;
638
+ declare function defineRecordView<C extends ResourceContract, Row extends DataRow = RowOf<C>>(view: ResourceView<C, Row>, definition: RecordViewDefinition<C, Row>): RecordView<C, Row>;
639
+ /** @deprecated Renamed `defineRecordView`. */
640
+ declare const defineWorkspace: typeof defineRecordView;
641
+ /** @deprecated Renamed `isRecordView`. */
642
+ declare const isWorkspace: typeof isRecordView;
643
+ /** @deprecated Renamed `RecordView`. */
644
+ type ResourceWorkspace<C extends ResourceContract = ResourceContract, Row extends DataRow = RowOf<C>> = RecordView<C, Row>;
645
+ /** @deprecated Renamed `RecordViewDefinition`. */
646
+ type WorkspaceDefinition<C extends ResourceContract, Row extends DataRow = RowOf<C>> = RecordViewDefinition<C, Row>;
647
+ /** @deprecated Renamed `RecordViewSection`. */
648
+ type WorkspaceSection<Row extends DataRow = DataRow, Name extends string = string> = RecordViewSection<Row, Name>;
649
+ /** @deprecated Renamed `RecordViewHeaderAction`. */
650
+ type WorkspaceHeaderAction = RecordViewHeaderAction;
632
651
 
633
- export { type Allowed, type ComputedColumn, type DisplayHint, type FieldNameOf, type ResolvedColumn, type ResolvedFormField, type ResolvedReadinessItem, type ResolvedViewAction, type ResolvedWorkspaceSection, type ResourceTree, type ResourceView, type ResourceWorkspace, type RowImage, RowOf, type RowPicture, type RowSummary, type TimeZoneName, type TreeNode, type TreeOptions, type TreeResult, type ViewAction, type ViewColumn, type ViewCopy, type ViewDefinition, ViewDefinitionError, type ViewField, type ViewFormItem, type ViewGuards, type ViewPreset, type ViewTimeZone, type ViewTone, Viewer, type WorkspaceDefinition, type WorkspaceFilter, type WorkspaceHeader, type WorkspaceHeaderAction, type WorkspaceHeaderOptions, type WorkspaceListSection, type WorkspaceReadinessItem, type WorkspaceSection, type WorkspaceSettingsSection, type WorkspaceSlotSection, cascadeSelection, defineView, defineWorkspace, deriveDisplay, initialExpanded, initialsOf, isWorkspace, plural, rowPicture, scopeValues, setExpanded, singular, treeRows, valueText };
652
+ export { type Allowed, type ComputedColumn, type DisplayHint, type FieldNameOf, type RecordView, type RecordViewDefinition, type RecordViewFilter, type RecordViewHeader, type RecordViewHeaderAction, type RecordViewHeaderOptions, type RecordViewListSection, type RecordViewReadinessItem, type RecordViewSection, type RecordViewSettingsSection, type RecordViewSlotSection, type ResolvedColumn, type ResolvedFormField, type ResolvedReadinessItem, type ResolvedRecordViewSection, type ResolvedViewAction, type ResourceTree, type ResourceView, type ResourceWorkspace, type RowImage, RowOf, type RowPicture, type RowSummary, type TimeZoneName, type TreeNode, type TreeOptions, type TreeResult, type ViewAction, type ViewColumn, type ViewCopy, type ViewDefinition, ViewDefinitionError, type ViewField, type ViewFormItem, type ViewGuards, type ViewPreset, type ViewTimeZone, type ViewTone, Viewer, type WorkspaceDefinition, type WorkspaceHeaderAction, type WorkspaceSection, cascadeSelection, defineRecordView, defineView, defineWorkspace, deriveDisplay, initialExpanded, initialsOf, isRecordView, isWorkspace, plural, rowPicture, scopeFilter, scopeValues, setExpanded, singular, treeRows, valueText };