@marktiderman/genesis-core 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-N5BKU7PR.js → chunk-5NEOX2N7.js} +3 -3
- package/dist/{chunk-N5BKU7PR.js.map → chunk-5NEOX2N7.js.map} +1 -1
- package/dist/{chunk-5JRXF7F7.js → chunk-UHOMTFBD.js} +17 -3
- package/dist/chunk-UHOMTFBD.js.map +1 -0
- package/dist/hooks/index.js +2 -2
- package/dist/index.js +2 -2
- package/dist/workspaces.d.ts +34 -1
- package/dist/workspaces.js +1 -1
- package/package.json +8 -8
- package/dist/chunk-5JRXF7F7.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { NO_VIEWER } from './chunk-OZYF55E3.js';
|
|
2
|
-
import { workspaceAt, workspaceHref } from './chunk-
|
|
2
|
+
import { workspaceAt, workspaceHref } from './chunk-UHOMTFBD.js';
|
|
3
3
|
import { stableJson } from './chunk-HBAPYA5K.js';
|
|
4
4
|
import { flushPendingWrites, dropPendingWrites } from './chunk-OSFG3GFY.js';
|
|
5
5
|
import { isTimeZone, personTimeZone, dayIn } from './chunk-3B4IFDMK.js';
|
|
@@ -163,5 +163,5 @@ function WorkspaceScope({ workspaces, pathname, scope, keep, children, ...viewer
|
|
|
163
163
|
}
|
|
164
164
|
|
|
165
165
|
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace };
|
|
166
|
-
//# sourceMappingURL=chunk-
|
|
167
|
-
//# sourceMappingURL=chunk-
|
|
166
|
+
//# sourceMappingURL=chunk-5NEOX2N7.js.map
|
|
167
|
+
//# sourceMappingURL=chunk-5NEOX2N7.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hooks/workspace-scope.tsx"],"names":["Fragment","createContext","useContext","useMem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AAA,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"]}
|
|
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,UAA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GAAQC,OAAAA;AAAA,IACZ,OAAO;AAAA,MACL,OAAA;AAAA,MACA,UAAA;AAAA,MACA,OAAA,EAAS,CAAC,EAAA,KAAO,aAAA,CAAc,UAAA,EAAY,EAAA,EAAI,QAAA,EAAU,IAAA,GAAO,EAAE,IAAA,EAAK,GAAI,EAAE;AAAA,KAC/E,CAAA;AAAA,IACA,CAAC,OAAA,EAAS,UAAA,EAAY,QAAA,EAAU,IAAI;AAAA,GACtC;AACA,EAAA,MAAM,SAAS,WAAA,CAAY,MAAA;AAC3B,EAAAC,UAAU,MAAM;AACd,IAAA,IAAI,MAAA,IAAU,OAAA,EAAS,QAAA,CAAS,MAAA,EAAQ,QAAQ,EAAE,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACEC,GAAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,OAC9B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-5NEOX2N7.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"]}
|
|
@@ -52,7 +52,21 @@ function workspaceInitials(label) {
|
|
|
52
52
|
const letters = words.length > 1 ? [words[0][0], words[1][0]] : [...words[0] ?? ""].slice(0, 2);
|
|
53
53
|
return letters.join("").toUpperCase();
|
|
54
54
|
}
|
|
55
|
+
function filterWorkspaces(workspaces, query) {
|
|
56
|
+
const words = fold(query).split(/\s+/).filter(Boolean);
|
|
57
|
+
if (words.length === 0) return [...workspaces];
|
|
58
|
+
return workspaces.filter((w) => {
|
|
59
|
+
const text = fold(`${w.label} ${w.description ?? ""}`);
|
|
60
|
+
return words.every((word) => text.includes(word));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function fold(text) {
|
|
64
|
+
return text.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
|
65
|
+
}
|
|
66
|
+
function orderedWorkspaces(workspaces, order = WORKSPACE_KIND_ORDER) {
|
|
67
|
+
return groupWorkspaces(workspaces, order).flatMap((g) => g.workspaces);
|
|
68
|
+
}
|
|
55
69
|
|
|
56
|
-
export { WORKSPACE_KIND_ORDER, defaultWorkspace, groupWorkspaces, keepSection, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials };
|
|
57
|
-
//# sourceMappingURL=chunk-
|
|
58
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
export { WORKSPACE_KIND_ORDER, defaultWorkspace, filterWorkspaces, groupWorkspaces, keepSection, orderedWorkspaces, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials };
|
|
71
|
+
//# sourceMappingURL=chunk-UHOMTFBD.js.map
|
|
72
|
+
//# sourceMappingURL=chunk-UHOMTFBD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workspaces.ts"],"names":[],"mappings":";AAwFO,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,CAAA,CAAE,UAAA,CAAW,CAAA,EA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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-UHOMTFBD.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 /**\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\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"]}
|
package/dist/hooks/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from '../chunk-
|
|
1
|
+
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from '../chunk-5NEOX2N7.js';
|
|
2
2
|
export { useWizard } from '../chunk-7KOLYF27.js';
|
|
3
3
|
export { WRITE_FAILED, useWrite } from '../chunk-52T2EYXH.js';
|
|
4
4
|
export { NO_VIEWER } from '../chunk-OZYF55E3.js';
|
|
@@ -10,7 +10,7 @@ export { useOne } from '../chunk-GWQHP3RC.js';
|
|
|
10
10
|
export { useResource } from '../chunk-CC37H7O2.js';
|
|
11
11
|
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS } from '../chunk-K4ZNAF3G.js';
|
|
12
12
|
export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from '../chunk-XQO4OH2N.js';
|
|
13
|
-
import '../chunk-
|
|
13
|
+
import '../chunk-UHOMTFBD.js';
|
|
14
14
|
export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from '../chunk-HBAPYA5K.js';
|
|
15
15
|
import '../chunk-AUVKRXRC.js';
|
|
16
16
|
export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from '../chunk-OSFG3GFY.js';
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ 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, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-
|
|
5
|
+
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-5NEOX2N7.js';
|
|
6
6
|
export { useWizard } from './chunk-7KOLYF27.js';
|
|
7
7
|
export { WRITE_FAILED, useWrite } from './chunk-52T2EYXH.js';
|
|
8
8
|
export { NO_VIEWER } from './chunk-OZYF55E3.js';
|
|
@@ -14,7 +14,7 @@ export { useOne } from './chunk-GWQHP3RC.js';
|
|
|
14
14
|
export { useResource } from './chunk-CC37H7O2.js';
|
|
15
15
|
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS } from './chunk-K4ZNAF3G.js';
|
|
16
16
|
export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from './chunk-XQO4OH2N.js';
|
|
17
|
-
import './chunk-
|
|
17
|
+
import './chunk-UHOMTFBD.js';
|
|
18
18
|
export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from './chunk-HBAPYA5K.js';
|
|
19
19
|
import './chunk-AUVKRXRC.js';
|
|
20
20
|
export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './chunk-OSFG3GFY.js';
|
package/dist/workspaces.d.ts
CHANGED
|
@@ -62,9 +62,27 @@ interface Workspace {
|
|
|
62
62
|
timeZone?: string | null;
|
|
63
63
|
/** Its picture: a logo URL, else initials made from `label`. */
|
|
64
64
|
image?: string;
|
|
65
|
+
/**
|
|
66
|
+
* A count or short status beside it in the switcher: unread messages, tasks waiting. `0`, an
|
|
67
|
+
* empty string, `null` and undefined show nothing.
|
|
68
|
+
*/
|
|
69
|
+
badge?: string | number | null;
|
|
70
|
+
/** Its brand, for the switcher's picture and anything the app themes inside it. */
|
|
71
|
+
theme?: WorkspaceTheme;
|
|
65
72
|
/** Anything else the app needs; Genesis never reads it. */
|
|
66
73
|
meta?: Readonly<Record<string, unknown>>;
|
|
67
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* A workspace's brand. `accent` takes the same values as a public page's brand accent (`#rgb`,
|
|
77
|
+
* `#rrggbb`, `rgb()`, `hsl()` or a bare token triplet like `"160 84% 39%"`); genesis-ui turns it
|
|
78
|
+
* into the design system's `--primary` (`workspaceThemeStyle`), darkened when it is too light to
|
|
79
|
+
* carry text.
|
|
80
|
+
*
|
|
81
|
+
* @stability Beta
|
|
82
|
+
*/
|
|
83
|
+
interface WorkspaceTheme {
|
|
84
|
+
accent?: string;
|
|
85
|
+
}
|
|
68
86
|
/** The kinds in their default order: personal, roll-up, then each tenant. */
|
|
69
87
|
declare const WORKSPACE_KIND_ORDER: readonly WorkspaceKind[];
|
|
70
88
|
/**
|
|
@@ -126,5 +144,20 @@ declare function defaultWorkspace<W extends Workspace>(workspaces: readonly W[],
|
|
|
126
144
|
* @stability Beta
|
|
127
145
|
*/
|
|
128
146
|
declare function workspaceInitials(label: string): string;
|
|
147
|
+
/**
|
|
148
|
+
* The workspaces whose label or second line contains every word of `query`, ignoring case and
|
|
149
|
+
* accents, in the order given. An empty query keeps them all. For the switcher's search box, on
|
|
150
|
+
* the web and on the phone.
|
|
151
|
+
*
|
|
152
|
+
* @stability Beta
|
|
153
|
+
*/
|
|
154
|
+
declare function filterWorkspaces<W extends Workspace>(workspaces: readonly W[], query: string): W[];
|
|
155
|
+
/**
|
|
156
|
+
* The workspaces in the order the switcher lists them (grouped by kind, in `order`): the order its
|
|
157
|
+
* keyboard jump numbers them, 1 to 9.
|
|
158
|
+
*
|
|
159
|
+
* @stability Beta
|
|
160
|
+
*/
|
|
161
|
+
declare function orderedWorkspaces<W extends Workspace>(workspaces: readonly W[], order?: readonly WorkspaceKind[]): W[];
|
|
129
162
|
|
|
130
|
-
export { type GenesisWorkspaceKinds, WORKSPACE_KIND_ORDER, type Workspace, type WorkspaceGroup, type WorkspaceHrefOptions, type WorkspaceKind, defaultWorkspace, groupWorkspaces, keepSection, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials };
|
|
163
|
+
export { type GenesisWorkspaceKinds, WORKSPACE_KIND_ORDER, type Workspace, type WorkspaceGroup, type WorkspaceHrefOptions, type WorkspaceKind, type WorkspaceTheme, defaultWorkspace, filterWorkspaces, groupWorkspaces, keepSection, orderedWorkspaces, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials };
|
package/dist/workspaces.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { WORKSPACE_KIND_ORDER, defaultWorkspace, groupWorkspaces, keepSection, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials } from './chunk-
|
|
1
|
+
export { WORKSPACE_KIND_ORDER, defaultWorkspace, filterWorkspaces, groupWorkspaces, keepSection, orderedWorkspaces, pathInWorkspace, workspaceAt, workspaceHref, workspaceInitials } from './chunk-UHOMTFBD.js';
|
|
2
2
|
//# sourceMappingURL=workspaces.js.map
|
|
3
3
|
//# sourceMappingURL=workspaces.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -102,15 +102,15 @@
|
|
|
102
102
|
"README.md"
|
|
103
103
|
],
|
|
104
104
|
"peerDependencies": {
|
|
105
|
-
"
|
|
105
|
+
"@hookform/resolvers": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0",
|
|
106
106
|
"@tanstack/react-query": "^5.0.0",
|
|
107
|
+
"react": "^19.0.0",
|
|
107
108
|
"react-hook-form": "^7.0.0",
|
|
108
|
-
"zod": "^3.0.0 || ^4.0.0"
|
|
109
|
-
"@hookform/resolvers": "^3.0.0 || ^4.0.0 || ^5.0.0"
|
|
109
|
+
"zod": "^3.0.0 || ^4.0.0"
|
|
110
110
|
},
|
|
111
111
|
"devDependencies": {
|
|
112
|
-
"@hookform/resolvers": "^
|
|
113
|
-
"@tanstack/react-query": "^5.
|
|
112
|
+
"@hookform/resolvers": "^6.0.0",
|
|
113
|
+
"@tanstack/react-query": "^5.104.5",
|
|
114
114
|
"@testing-library/react": "^16.3.2",
|
|
115
115
|
"@types/react": "^19.2.14",
|
|
116
116
|
"@types/react-dom": "^19.2.3",
|
|
@@ -120,8 +120,8 @@
|
|
|
120
120
|
"react-hook-form": "^7.56.4",
|
|
121
121
|
"tsup": "^8.3.0",
|
|
122
122
|
"typescript": "~6.0.3",
|
|
123
|
-
"vitest": "^
|
|
124
|
-
"zod": "^
|
|
123
|
+
"vitest": "^5.0.5",
|
|
124
|
+
"zod": "^4.6.7"
|
|
125
125
|
},
|
|
126
126
|
"genesis": {
|
|
127
127
|
"doctor": {
|
|
@@ -1 +0,0 @@
|
|
|
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;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,EAAA,OAAO,KAAA,CACJ,IAAI,CAAC,IAAA,MAAU,EAAE,IAAA,EAAM,UAAA,EAAY,UAAA,CAAW,MAAA,CAAO,CAAC,CAAA,KAAM,EAAE,IAAA,KAAS,IAAI,CAAA,EAAE,CAAE,CAAA,CAC/E,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,UAAA,CAAW,MAAA,GAAS,CAAC,CAAA;AAC1C;AAQO,SAAS,gBAAA,CAAsC,YAA0B,YAAA,EAA6C;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"]}
|