@arbidocs/react 0.5.158 → 0.5.159
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/calls/livekit/index.cjs +50 -50
- package/dist/{chunk-IX4HOS5Z.cjs → chunk-5ECKSF6H.cjs} +13 -4
- package/dist/chunk-5ECKSF6H.cjs.map +1 -0
- package/dist/{chunk-6RRKO4ZK.cjs → chunk-6HJZCIND.cjs} +10 -10
- package/dist/{chunk-6RRKO4ZK.cjs.map → chunk-6HJZCIND.cjs.map} +1 -1
- package/dist/{chunk-QWKTQYGM.cjs → chunk-V7GGKT6W.cjs} +13 -10
- package/dist/chunk-V7GGKT6W.cjs.map +1 -0
- package/dist/conversation-list.js +4 -1
- package/dist/conversation-list.js.map +2 -2
- package/dist/index.cjs +526 -519
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-KbsNPTEN.d.ts → index.d-COC3NkxH.d.ts} +6 -0
- package/dist/index.d.ts +2 -2
- package/dist/notifications/notify-store.js +11 -2
- package/dist/notifications/notify-store.js.map +2 -2
- package/dist/shell/index.cjs +50 -50
- package/dist/shell/index.d.ts +1 -1
- package/dist/workspaces/switch.js +41 -34
- package/dist/workspaces/switch.js.map +2 -2
- package/package.json +3 -3
- package/dist/chunk-IX4HOS5Z.cjs.map +0 -1
- package/dist/chunk-QWKTQYGM.cjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/workspaces/switch.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Switching the workspace the app is in: the one coordinator for \"the user is now in workspace X\".\n *\n * The server keeps the active workspace in the session, so every workspace-scoped GET reads the\n * workspace currently open for the session. A naive switch (set the id, `/open` in the background)\n * races every observer that refetches when the id changes: those requests reach a server still in\n * the previous workspace and seed the cache with its data. `switchWorkspace` keeps the order:\n *\n * 1. leave the workspace: its session state (`leaveWorkspace`) and its cached queries go, so\n * nothing shows or refetches the old workspace's data;\n * 2. the selection is cleared, so queries gated on it stop during the round trip;\n * 3. `arbi.selectWorkspace(target)`: the server session is now in the target;\n * 4. the conversations and tags `/open` returned seed their lists, then the selection is\n * committed (`workspaceId`, `workspaceStatus: 'open'`).\n *\n * Concurrent switches (A, then B, then C in quick succession): only the last one commits, and the\n * SDK runs the opens one at a time with the latest request winning, so the server session ends in\n * the last one too. `settled` waits out the switches in flight.\n *\n * A sign-out (`arbi.onSigningOut`, before the server revokes the token) overtakes every switch and\n * open in flight and cancels the queries in flight: the SDK has already stopped new requests and\n * aborts the ones in flight, so none comes back 401 or is reported as a failure.\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport { onlineManager, useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiWorkspaceSupersededError,\n type Arbi,\n type WorkspaceOpenResponse,\n} from '@arbidocs/sdk/browser'\nimport { isAbortError } from '@arbidocs/client'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useWorkspaces } from '../hooks'\nimport { useArbiSessionState, useArbiSessionStore, type ArbiSessionStore } from '../session'\nimport { notify } from '../notifications/notify-store'\nimport { getEntityLabel } from '../entities/registry'\n\n/**\n * What depends on the session's open workspace: dropped on a switch, so nothing of the workspace\n * left shows in the next, and a return reads it afresh.\n */\nconst WORKSPACE_SCOPED_PACKAGE_KEYS = [\n arbiQueryKeys.allDocuments(),\n arbiQueryKeys.allSimilarDocuments(),\n arbiQueryKeys.allWorkspaceUsers(),\n arbiQueryKeys.documentSignatures(),\n arbiQueryKeys.signatureRequests(),\n arbiQueryKeys.databases(),\n]\n\n/** Cancel (so nothing in flight lands afterwards) and drop every workspace-scoped query. */\nfunction drainWorkspaceQueries(queryClient: QueryClient): void {\n for (const queryKey of WORKSPACE_SCOPED_PACKAGE_KEYS) {\n void queryClient.cancelQueries({ queryKey })\n queryClient.removeQueries({ queryKey })\n }\n}\n\n/** The conversations and tags `/open` returned seed their lists (patched in place from then on). */\nfunction seedOpenedWorkspace(\n queryClient: QueryClient,\n workspaceId: string,\n opened: WorkspaceOpenResponse\n): void {\n if (opened.conversations)\n queryClient.setQueryData(arbiQueryKeys.conversations(workspaceId), opened.conversations)\n if (opened.tags) queryClient.setQueryData(arbiQueryKeys.tags(workspaceId), opened.tags)\n}\n\n/** The server refused to open an archived workspace (423 `workspace_archived`). */\nexport function isWorkspaceArchivedError(error: unknown): boolean {\n const body = (error as { apiError?: unknown } | null | undefined)?.apiError ?? error\n const detail = (body as { detail?: unknown } | null | undefined)?.detail\n return (\n !!detail &&\n typeof detail === 'object' &&\n (detail as { code?: unknown }).code === 'workspace_archived'\n )\n}\n\n/** What to tell someone who tried to open an archived workspace. */\nexport const archivedWorkspaceMessage = (name: string) =>\n `\"${name}\" is archived. Its owner can unarchive it from the workspace list.`\n\ninterface ListedWorkspace {\n external_id: string\n name: string\n archive?: unknown\n}\n\nconst listedWorkspace = (queryClient: QueryClient, workspaceId: string) =>\n queryClient\n .getQueryData<ListedWorkspace[]>(arbiQueryKeys.workspaces())\n ?.find((w) => w.external_id === workspaceId)\n\n// One sequence for every hook instance, so a newer switch anywhere wins.\nlet switchEpoch = 0\n// The switches not yet settled (opened, refused or overtaken).\nconst switching = new Set<Promise<boolean>>()\n\n/** Exported for tests. */\nexport const resetSwitchEpochForTests = () => {\n switchEpoch = 0\n switching.clear()\n}\n\n/** How long a switch waits for the signed-in session to reach its `Arbi` (see `signedIn`). */\nconst SIGNED_IN_WAIT_MS = 10_000\nconst SIGNED_IN_POLL_MS = 50\n\n/**\n * Wait until the `Arbi` in scope holds the login. Right after a sign-in (or a reload) the session\n * is signed in before the host's `Arbi` has its keys (a host reads them from the device and then\n * renews its `Arbi`): an open asked for in that window would fail with \"Not logged in\". Resolves\n * at once when it holds them, or when the session is not signed in at all (nothing to wait for).\n */\nasync function signedIn(arbi: () => Arbi, timeoutMs = SIGNED_IN_WAIT_MS): Promise<void> {\n const deadline = Date.now() + timeoutMs\n while (\n !arbi().isLoggedIn &&\n arbi().session?.getState().signedIn === true &&\n Date.now() < deadline\n ) {\n await new Promise((resolve) => setTimeout(resolve, SIGNED_IN_POLL_MS))\n }\n}\n\n/** Resolves once no workspace switch is in flight (including any started while waiting). */\nasync function switchesSettled(): Promise<void> {\n while (switching.size > 0) await Promise.allSettled([...switching])\n}\n\nexport interface SwitchWorkspaceTarget {\n id: string\n /** For the notices; default: the name in the workspace list. */\n name?: string\n}\n\nexport interface UseSwitchWorkspaceResult {\n /**\n * Make `target` the workspace the app is in. True once it is open (at once when it already\n * is); false when it could not be (archived, offline, refused: the user was told), or when a\n * newer switch overtook it.\n */\n switchWorkspace: (target: SwitchWorkspaceTarget) => Promise<boolean>\n /** Leave the workspace for none (after deleting or leaving it), with the same clean-up. */\n clearWorkspace: () => void\n /**\n * Open the selected workspace on the server session as it is, without leaving anything or a\n * notice: after a sign-in or a reload (a new server session), or to re-assert it before a write.\n * False when there is none, it could not be opened, or a switch overtook it.\n */\n openSelectedWorkspace: () => Promise<boolean>\n /**\n * Resolves once no switch is in flight: the selection is then committed (or back to where it\n * was), so reading it says which workspace the session is in.\n */\n settled: () => Promise<void>\n}\n\n/** What a workspace switch runs on. */\nexport interface WorkspaceSwitchContext {\n /** The `Arbi` on the signed-in session, as of the switch. */\n arbi: () => Arbi\n session: ArbiSessionStore\n queryClient: QueryClient\n}\n\n/**\n * The workspace switch over a host's session, for code that runs outside `<ArbiHost>` (a host's\n * own environment, built before its host). Inside, use `useSwitchWorkspace`.\n */\nexport function createWorkspaceSwitch({\n arbi,\n session,\n queryClient,\n}: WorkspaceSwitchContext): UseSwitchWorkspaceResult {\n const switchWorkspace = (target: SwitchWorkspaceTarget): Promise<boolean> => {\n const run = runSwitch(target)\n switching.add(run)\n void run.finally(() => switching.delete(run))\n return run\n }\n\n const runSwitch = async (target: SwitchWorkspaceTarget): Promise<boolean> => {\n const { workspaceId: previousId, workspaceStatus } = session.getState()\n const isSame = previousId === target.id\n if (isSame && workspaceStatus === 'open') return true\n\n const listed = listedWorkspace(queryClient, target.id)\n const name = target.name || listed?.name || ''\n const noun = getEntityLabel('WORKSPACE')\n // An archived workspace cannot be opened: say so before leaving the current one.\n if (listed?.archive) {\n notify.info(archivedWorkspaceMessage(name))\n return false\n }\n // Offline, the user stays in the workspace they are in: another one's lists cannot load.\n if (!isSame && !onlineManager.isOnline()) {\n notify.info(\n `You're offline \u2014 you can only use the ${noun} you're already in. Reconnect to switch.`\n )\n return false\n }\n\n const epoch = ++switchEpoch\n notify.info(`Opening \"${name}\" ${noun}\u2026`, { workspaceId: target.id, duration: 2000 })\n // Signed in, but the keys not on this `Arbi` yet: the open waits for them, not fails.\n await signedIn(arbi)\n if (epoch !== switchEpoch) return false\n // Not yet open (a reload): nothing to leave, it only needs `/open`.\n if (!isSame) {\n session.leaveWorkspace()\n drainWorkspaceQueries(queryClient)\n session.setWorkspaceId(null)\n }\n session.setWorkspaceStatus('opening')\n\n performance.mark('arbi:workspace-open:start')\n let opened: WorkspaceOpenResponse\n try {\n opened = await arbi().selectWorkspace(target.id)\n } catch (error) {\n // A sign-out stopped it: the session is going, nothing to restore or report.\n if (isAbortError(error)) return false\n const superseded = error instanceof ArbiWorkspaceSupersededError\n if (!superseded) console.error('[switchWorkspace] /open failed:', error)\n // Overtaken before its turn by a newer switch: that one commits. By an open from elsewhere\n // (no newer switch): back to the previous selection, closed, as for a failure.\n if (superseded && epoch === switchEpoch) {\n if (previousId) session.setWorkspaceId(previousId)\n session.setWorkspaceStatus('closed')\n } else if (epoch === switchEpoch) {\n // Back to the previous selection, closed: `useOpenSelectedWorkspace` opens it again.\n if (previousId) session.setWorkspaceId(previousId)\n session.setWorkspaceStatus('closed')\n if (isWorkspaceArchivedError(error)) {\n // Archived since the list was read: refresh it so it shows as archived.\n notify.info(archivedWorkspaceMessage(name))\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() })\n } else {\n notify.error(`Failed to open \"${name}\" ${noun}`)\n }\n }\n return false\n }\n // A newer switch started meanwhile: it commits, not this one.\n if (epoch !== switchEpoch) return false\n\n seedOpenedWorkspace(queryClient, target.id, opened)\n performance.mark('arbi:workspace-open:response')\n session.setWorkspaceId(target.id)\n session.setWorkspaceStatus('open')\n return true\n }\n\n const clearWorkspace = () => {\n ++switchEpoch\n session.leaveWorkspace()\n drainWorkspaceQueries(queryClient)\n session.setWorkspaceId(null)\n }\n\n const openSelectedWorkspace = async (): Promise<boolean> => {\n const workspaceId = session.getState().workspaceId\n if (!workspaceId) return false\n const epoch = switchEpoch\n await signedIn(arbi)\n if (epoch !== switchEpoch || session.getState().workspaceId !== workspaceId) return false\n performance.mark('arbi:workspace-open:start')\n let opened: WorkspaceOpenResponse\n try {\n opened = await arbi().selectWorkspace(workspaceId)\n } catch (error) {\n // Overtaken by a newer open, or stopped by a sign-out: nothing to report.\n if (!(error instanceof ArbiWorkspaceSupersededError) && !isAbortError(error)) {\n console.error('[openSelectedWorkspace] /open failed:', error)\n }\n return false\n }\n // A switch started meanwhile: it commits its own workspace.\n if (epoch !== switchEpoch || session.getState().workspaceId !== workspaceId) return false\n seedOpenedWorkspace(queryClient, workspaceId, opened)\n performance.mark('arbi:workspace-open:response')\n session.setWorkspaceStatus('open')\n return true\n }\n\n return { switchWorkspace, clearWorkspace, openSelectedWorkspace, settled: switchesSettled }\n}\n\n/** The workspace switch of the `<ArbiHost>` in scope (its `Arbi`, its session state). */\nexport function useSwitchWorkspace(): UseSwitchWorkspaceResult {\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n const session = useArbiSessionStore()\n const queryClient = useQueryClient()\n // Signing out: the switches and opens in flight are overtaken, the queries in flight cancelled.\n useEffect(\n () =>\n arbi.onSigningOut?.(() => {\n ++switchEpoch\n void queryClient.cancelQueries()\n }),\n [arbi, queryClient]\n )\n return useMemo(\n () => createWorkspaceSwitch({ arbi: () => arbiRef.current, session, queryClient }),\n [session, queryClient]\n )\n}\n\n/**\n * Keep the selected workspace open on the server session: open it once signed in (after a\n * sign-in or a reload, when the selection was kept but the server session is new), and drop it\n * when the workspace list says it was archived since (by its owner, perhaps on another device),\n * or that it is gone (deleted, or the person left or was removed): the app is then on the\n * workspace list. Mounted once, by the signed-in app.\n */\nexport function useOpenSelectedWorkspace(): void {\n const arbi = useArbi()\n const { clearWorkspace, openSelectedWorkspace } = useSwitchWorkspace()\n const workspaceId = useArbiSessionState((s) => s.workspaceId)\n const status = useArbiSessionState((s) => s.workspaceStatus)\n const session = useArbiSessionStore()\n const queryClient = useQueryClient()\n const { data: workspaces, isLoading: listing, isFetching } = useWorkspaces()\n const listed = workspaces as ListedWorkspace[] | undefined\n const archived = listed?.find((w) => w.external_id === workspaceId && w.archive)\n // The open workspace is gone (deleted, or the person left or was removed) once a list read after\n // it was opened no longer has it: one read before (access granted since) may not have it yet.\n // (Counted, not timed: a read can land in the same millisecond.)\n const reads = queryClient.getQueryState(arbiQueryKeys.workspaces())?.dataUpdateCount ?? 0\n const opened = useRef<{ id: string | null; reads: number }>({ id: null, reads: 0 })\n const openId = status === 'open' ? workspaceId : null\n if (opened.current.id !== openId) opened.current = { id: openId, reads }\n const gone =\n !!openId &&\n !!listed &&\n !isFetching &&\n reads > opened.current.reads &&\n !listed.some((w) => w.external_id === openId)\n\n useEffect(() => {\n if (!archived) return\n notify.info(archivedWorkspaceMessage(archived.name))\n clearWorkspace()\n }, [archived, clearWorkspace])\n\n useEffect(() => {\n if (gone) clearWorkspace()\n }, [gone, clearWorkspace])\n\n // One open at a time; a failed one is tried again when the session or selection changes.\n const opening = useRef(false)\n const signedIn = arbi.isLoggedIn\n useEffect(() => {\n // After the workspace list: it says whether the workspace was archived, and it holds the key\n // the open needs (no list of the open's own).\n if (\n !workspaceId ||\n archived ||\n gone ||\n listing ||\n status !== 'closed' ||\n !signedIn ||\n opening.current\n )\n return\n opening.current = true\n void openSelectedWorkspace()\n .then(async (ok) => {\n if (ok) return\n // Refused: deleted, or left, since (the kept selection of a reload)? The list read now\n // says. (Not the list a reload restores: it may predate a workspace created since.)\n const fresh = await queryClient\n .fetchQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n staleTime: 0,\n })\n .catch(() => null)\n if (\n fresh &&\n session.getState().workspaceId === workspaceId &&\n !(fresh as ListedWorkspace[]).some((w) => w.external_id === workspaceId)\n )\n clearWorkspace()\n })\n .finally(() => {\n opening.current = false\n })\n }, [\n arbi,\n session,\n clearWorkspace,\n openSelectedWorkspace,\n queryClient,\n workspaceId,\n archived,\n gone,\n listing,\n status,\n signedIn,\n ])\n}\n"],
|
|
5
|
-
"mappings": "AAwBA,SAAS,WAAW,SAAS,cAAc;AAC3C,SAAS,eAAe,sBAAwC;AAChE;AAAA,EACE;AAAA,OAGK;AACP,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,eAAe,qBAAqB;AAC7C,SAAS,qBAAqB,2BAAkD;AAChF,SAAS,cAAc;AACvB,SAAS,sBAAsB;AAM/B,MAAM,gCAAgC;AAAA,EACpC,cAAc,aAAa;AAAA,EAC3B,cAAc,oBAAoB;AAAA,EAClC,cAAc,kBAAkB;AAAA,EAChC,cAAc,mBAAmB;AAAA,EACjC,cAAc,kBAAkB;AAAA,EAChC,cAAc,UAAU;AAC1B;AAGA,SAAS,sBAAsB,aAAgC;AAC7D,aAAW,YAAY,+BAA+B;AACpD,SAAK,YAAY,cAAc,EAAE,SAAS,CAAC;AAC3C,gBAAY,cAAc,EAAE,SAAS,CAAC;AAAA,EACxC;AACF;AAGA,SAAS,oBACP,aACA,aACA,QACM;AACN,MAAI,OAAO;AACT,gBAAY,aAAa,cAAc,cAAc,WAAW,GAAG,OAAO,aAAa;AACzF,MAAI,OAAO,KAAM,aAAY,aAAa,cAAc,KAAK,WAAW,GAAG,OAAO,IAAI;AACxF;AAGO,SAAS,yBAAyB,OAAyB;AAChE,QAAM,OAAQ,OAAqD,YAAY;AAC/E,QAAM,SAAU,MAAkD;AAClE,SACE,CAAC,CAAC,UACF,OAAO,WAAW,YACj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,QAAQ,SAAS;AACnB,aAAO,KAAK,yBAAyB,IAAI,CAAC;AAC1C,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,UAAU,CAAC,cAAc,SAAS,GAAG;AACxC,aAAO;AAAA,QACL,8CAAyC,IAAI;AAAA,MAC/C;AACA,aAAO;AAAA,IACT;AAEA,UAAM,QAAQ,EAAE;AAChB,
|
|
4
|
+
"sourcesContent": ["/**\n * Switching the workspace the app is in: the one coordinator for \"the user is now in workspace X\".\n *\n * The server keeps the active workspace in the session, so every workspace-scoped GET reads the\n * workspace currently open for the session. A naive switch (set the id, `/open` in the background)\n * races every observer that refetches when the id changes: those requests reach a server still in\n * the previous workspace and seed the cache with its data. `switchWorkspace` keeps the order:\n *\n * 1. leave the workspace: its session state (`leaveWorkspace`) and its cached queries go, so\n * nothing shows or refetches the old workspace's data;\n * 2. the selection is cleared, so queries gated on it stop during the round trip;\n * 3. `arbi.selectWorkspace(target)`: the server session is now in the target;\n * 4. the conversations and tags `/open` returned seed their lists, then the selection is\n * committed (`workspaceId`, `workspaceStatus: 'open'`).\n *\n * Concurrent switches (A, then B, then C in quick succession): only the last one commits, and the\n * SDK runs the opens one at a time with the latest request winning, so the server session ends in\n * the last one too. `settled` waits out the switches in flight.\n *\n * A sign-out (`arbi.onSigningOut`, before the server revokes the token) overtakes every switch and\n * open in flight and cancels the queries in flight: the SDK has already stopped new requests and\n * aborts the ones in flight, so none comes back 401 or is reported as a failure.\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport { onlineManager, useQueryClient, type QueryClient } from '@tanstack/react-query'\nimport {\n ArbiWorkspaceSupersededError,\n type Arbi,\n type WorkspaceOpenResponse,\n} from '@arbidocs/sdk/browser'\nimport { isAbortError } from '@arbidocs/client'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useWorkspaces } from '../hooks'\nimport { useArbiSessionState, useArbiSessionStore, type ArbiSessionStore } from '../session'\nimport { notify } from '../notifications/notify-store'\nimport { getEntityLabel } from '../entities/registry'\n\n/**\n * What depends on the session's open workspace: dropped on a switch, so nothing of the workspace\n * left shows in the next, and a return reads it afresh.\n */\nconst WORKSPACE_SCOPED_PACKAGE_KEYS = [\n arbiQueryKeys.allDocuments(),\n arbiQueryKeys.allSimilarDocuments(),\n arbiQueryKeys.allWorkspaceUsers(),\n arbiQueryKeys.documentSignatures(),\n arbiQueryKeys.signatureRequests(),\n arbiQueryKeys.databases(),\n]\n\n/** Cancel (so nothing in flight lands afterwards) and drop every workspace-scoped query. */\nfunction drainWorkspaceQueries(queryClient: QueryClient): void {\n for (const queryKey of WORKSPACE_SCOPED_PACKAGE_KEYS) {\n void queryClient.cancelQueries({ queryKey })\n queryClient.removeQueries({ queryKey })\n }\n}\n\n/** The conversations and tags `/open` returned seed their lists (patched in place from then on). */\nfunction seedOpenedWorkspace(\n queryClient: QueryClient,\n workspaceId: string,\n opened: WorkspaceOpenResponse\n): void {\n if (opened.conversations)\n queryClient.setQueryData(arbiQueryKeys.conversations(workspaceId), opened.conversations)\n if (opened.tags) queryClient.setQueryData(arbiQueryKeys.tags(workspaceId), opened.tags)\n}\n\n/** The server refused to open an archived workspace (423 `workspace_archived`). */\nexport function isWorkspaceArchivedError(error: unknown): boolean {\n const body = (error as { apiError?: unknown } | null | undefined)?.apiError ?? error\n const detail = (body as { detail?: unknown } | null | undefined)?.detail\n return (\n !!detail &&\n typeof detail === 'object' &&\n (detail as { code?: unknown }).code === 'workspace_archived'\n )\n}\n\n/** What to tell someone who tried to open an archived workspace. */\nexport const archivedWorkspaceMessage = (name: string) =>\n `\"${name}\" is archived. Its owner can unarchive it from the workspace list.`\n\ninterface ListedWorkspace {\n external_id: string\n name: string\n archive?: unknown\n}\n\nconst listedWorkspace = (queryClient: QueryClient, workspaceId: string) =>\n queryClient\n .getQueryData<ListedWorkspace[]>(arbiQueryKeys.workspaces())\n ?.find((w) => w.external_id === workspaceId)\n\n// One sequence for every hook instance, so a newer switch anywhere wins.\nlet switchEpoch = 0\n// The switches not yet settled (opened, refused or overtaken).\nconst switching = new Set<Promise<boolean>>()\n\n/** Exported for tests. */\nexport const resetSwitchEpochForTests = () => {\n switchEpoch = 0\n switching.clear()\n}\n\n/** How long a switch waits for the signed-in session to reach its `Arbi` (see `signedIn`). */\nconst SIGNED_IN_WAIT_MS = 10_000\nconst SIGNED_IN_POLL_MS = 50\n\n/**\n * Wait until the `Arbi` in scope holds the login. Right after a sign-in (or a reload) the session\n * is signed in before the host's `Arbi` has its keys (a host reads them from the device and then\n * renews its `Arbi`): an open asked for in that window would fail with \"Not logged in\". Resolves\n * at once when it holds them, or when the session is not signed in at all (nothing to wait for).\n */\nasync function signedIn(arbi: () => Arbi, timeoutMs = SIGNED_IN_WAIT_MS): Promise<void> {\n const deadline = Date.now() + timeoutMs\n while (\n !arbi().isLoggedIn &&\n arbi().session?.getState().signedIn === true &&\n Date.now() < deadline\n ) {\n await new Promise((resolve) => setTimeout(resolve, SIGNED_IN_POLL_MS))\n }\n}\n\n/** Resolves once no workspace switch is in flight (including any started while waiting). */\nasync function switchesSettled(): Promise<void> {\n while (switching.size > 0) await Promise.allSettled([...switching])\n}\n\nexport interface SwitchWorkspaceTarget {\n id: string\n /** For the notices; default: the name in the workspace list. */\n name?: string\n}\n\nexport interface UseSwitchWorkspaceResult {\n /**\n * Make `target` the workspace the app is in. True once it is open (at once when it already\n * is); false when it could not be (archived, offline, refused: the user was told), or when a\n * newer switch overtook it.\n */\n switchWorkspace: (target: SwitchWorkspaceTarget) => Promise<boolean>\n /** Leave the workspace for none (after deleting or leaving it), with the same clean-up. */\n clearWorkspace: () => void\n /**\n * Open the selected workspace on the server session as it is, without leaving anything or a\n * notice: after a sign-in or a reload (a new server session), or to re-assert it before a write.\n * False when there is none, it could not be opened, or a switch overtook it.\n */\n openSelectedWorkspace: () => Promise<boolean>\n /**\n * Resolves once no switch is in flight: the selection is then committed (or back to where it\n * was), so reading it says which workspace the session is in.\n */\n settled: () => Promise<void>\n}\n\n/** What a workspace switch runs on. */\nexport interface WorkspaceSwitchContext {\n /** The `Arbi` on the signed-in session, as of the switch. */\n arbi: () => Arbi\n session: ArbiSessionStore\n queryClient: QueryClient\n}\n\n/**\n * The workspace switch over a host's session, for code that runs outside `<ArbiHost>` (a host's\n * own environment, built before its host). Inside, use `useSwitchWorkspace`.\n */\nexport function createWorkspaceSwitch({\n arbi,\n session,\n queryClient,\n}: WorkspaceSwitchContext): UseSwitchWorkspaceResult {\n const switchWorkspace = (target: SwitchWorkspaceTarget): Promise<boolean> => {\n const run = runSwitch(target)\n switching.add(run)\n void run.finally(() => switching.delete(run))\n return run\n }\n\n const runSwitch = async (target: SwitchWorkspaceTarget): Promise<boolean> => {\n const { workspaceId: previousId, workspaceStatus } = session.getState()\n const isSame = previousId === target.id\n if (isSame && workspaceStatus === 'open') return true\n\n const listed = listedWorkspace(queryClient, target.id)\n const name = target.name || listed?.name || ''\n const noun = getEntityLabel('WORKSPACE')\n // An archived workspace cannot be opened: say so before leaving the current one.\n if (listed?.archive) {\n notify.info(archivedWorkspaceMessage(name))\n return false\n }\n // Offline, the user stays in the workspace they are in: another one's lists cannot load.\n if (!isSame && !onlineManager.isOnline()) {\n notify.info(\n `You're offline \u2014 you can only use the ${noun} you're already in. Reconnect to switch.`\n )\n return false\n }\n\n const epoch = ++switchEpoch\n const opening = notify.info(`Opening \"${name}\" ${noun}\u2026`, {\n workspaceId: target.id,\n duration: 2000,\n })\n try {\n // Signed in, but the keys not on this `Arbi` yet: the open waits for them, not fails.\n await signedIn(arbi)\n if (epoch !== switchEpoch) return false\n // Not yet open (a reload): nothing to leave, it only needs `/open`.\n if (!isSame) {\n session.leaveWorkspace()\n drainWorkspaceQueries(queryClient)\n session.setWorkspaceId(null)\n }\n session.setWorkspaceStatus('opening')\n\n performance.mark('arbi:workspace-open:start')\n let opened: WorkspaceOpenResponse\n try {\n opened = await arbi().selectWorkspace(target.id)\n } catch (error) {\n // A sign-out stopped it: the session is going, nothing to restore or report.\n if (isAbortError(error)) return false\n const superseded = error instanceof ArbiWorkspaceSupersededError\n if (!superseded) console.error('[switchWorkspace] /open failed:', error)\n // Overtaken before its turn by a newer switch: that one commits. By an open from elsewhere\n // (no newer switch): back to the previous selection, closed, as for a failure.\n if (superseded && epoch === switchEpoch) {\n if (previousId) session.setWorkspaceId(previousId)\n session.setWorkspaceStatus('closed')\n } else if (epoch === switchEpoch) {\n // Back to the previous selection, closed: `useOpenSelectedWorkspace` opens it again.\n if (previousId) session.setWorkspaceId(previousId)\n session.setWorkspaceStatus('closed')\n if (isWorkspaceArchivedError(error)) {\n // Archived since the list was read: refresh it so it shows as archived.\n notify.info(archivedWorkspaceMessage(name))\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() })\n } else {\n notify.error(`Failed to open \"${name}\" ${noun}`)\n }\n }\n return false\n }\n // A newer switch started meanwhile: it commits, not this one.\n if (epoch !== switchEpoch) return false\n\n seedOpenedWorkspace(queryClient, target.id, opened)\n performance.mark('arbi:workspace-open:response')\n session.setWorkspaceId(target.id)\n session.setWorkspaceStatus('open')\n return true\n } finally {\n // The open is over (open, failed or overtaken): its progress toast goes with it.\n notify.dismiss(opening)\n }\n }\n\n const clearWorkspace = () => {\n ++switchEpoch\n session.leaveWorkspace()\n drainWorkspaceQueries(queryClient)\n session.setWorkspaceId(null)\n }\n\n const openSelectedWorkspace = async (): Promise<boolean> => {\n const workspaceId = session.getState().workspaceId\n if (!workspaceId) return false\n const epoch = switchEpoch\n await signedIn(arbi)\n if (epoch !== switchEpoch || session.getState().workspaceId !== workspaceId) return false\n performance.mark('arbi:workspace-open:start')\n let opened: WorkspaceOpenResponse\n try {\n opened = await arbi().selectWorkspace(workspaceId)\n } catch (error) {\n // Overtaken by a newer open, or stopped by a sign-out: nothing to report.\n if (!(error instanceof ArbiWorkspaceSupersededError) && !isAbortError(error)) {\n console.error('[openSelectedWorkspace] /open failed:', error)\n }\n return false\n }\n // A switch started meanwhile: it commits its own workspace.\n if (epoch !== switchEpoch || session.getState().workspaceId !== workspaceId) return false\n seedOpenedWorkspace(queryClient, workspaceId, opened)\n performance.mark('arbi:workspace-open:response')\n session.setWorkspaceStatus('open')\n return true\n }\n\n return { switchWorkspace, clearWorkspace, openSelectedWorkspace, settled: switchesSettled }\n}\n\n/** The workspace switch of the `<ArbiHost>` in scope (its `Arbi`, its session state). */\nexport function useSwitchWorkspace(): UseSwitchWorkspaceResult {\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n const session = useArbiSessionStore()\n const queryClient = useQueryClient()\n // Signing out: the switches and opens in flight are overtaken, the queries in flight cancelled.\n useEffect(\n () =>\n arbi.onSigningOut?.(() => {\n ++switchEpoch\n void queryClient.cancelQueries()\n }),\n [arbi, queryClient]\n )\n return useMemo(\n () => createWorkspaceSwitch({ arbi: () => arbiRef.current, session, queryClient }),\n [session, queryClient]\n )\n}\n\n/**\n * Keep the selected workspace open on the server session: open it once signed in (after a\n * sign-in or a reload, when the selection was kept but the server session is new), and drop it\n * when the workspace list says it was archived since (by its owner, perhaps on another device),\n * or that it is gone (deleted, or the person left or was removed): the app is then on the\n * workspace list. Mounted once, by the signed-in app.\n */\nexport function useOpenSelectedWorkspace(): void {\n const arbi = useArbi()\n const { clearWorkspace, openSelectedWorkspace } = useSwitchWorkspace()\n const workspaceId = useArbiSessionState((s) => s.workspaceId)\n const status = useArbiSessionState((s) => s.workspaceStatus)\n const session = useArbiSessionStore()\n const queryClient = useQueryClient()\n const { data: workspaces, isLoading: listing, isFetching } = useWorkspaces()\n const listed = workspaces as ListedWorkspace[] | undefined\n const archived = listed?.find((w) => w.external_id === workspaceId && w.archive)\n // The open workspace is gone (deleted, or the person left or was removed) once a list read after\n // it was opened no longer has it: one read before (access granted since) may not have it yet.\n // (Counted, not timed: a read can land in the same millisecond.)\n const reads = queryClient.getQueryState(arbiQueryKeys.workspaces())?.dataUpdateCount ?? 0\n const opened = useRef<{ id: string | null; reads: number }>({ id: null, reads: 0 })\n const openId = status === 'open' ? workspaceId : null\n if (opened.current.id !== openId) opened.current = { id: openId, reads }\n const gone =\n !!openId &&\n !!listed &&\n !isFetching &&\n reads > opened.current.reads &&\n !listed.some((w) => w.external_id === openId)\n\n useEffect(() => {\n if (!archived) return\n notify.info(archivedWorkspaceMessage(archived.name))\n clearWorkspace()\n }, [archived, clearWorkspace])\n\n useEffect(() => {\n if (gone) clearWorkspace()\n }, [gone, clearWorkspace])\n\n // One open at a time; a failed one is tried again when the session or selection changes.\n const opening = useRef(false)\n const signedIn = arbi.isLoggedIn\n useEffect(() => {\n // After the workspace list: it says whether the workspace was archived, and it holds the key\n // the open needs (no list of the open's own).\n if (\n !workspaceId ||\n archived ||\n gone ||\n listing ||\n status !== 'closed' ||\n !signedIn ||\n opening.current\n )\n return\n opening.current = true\n void openSelectedWorkspace()\n .then(async (ok) => {\n if (ok) return\n // Refused: deleted, or left, since (the kept selection of a reload)? The list read now\n // says. (Not the list a reload restores: it may predate a workspace created since.)\n const fresh = await queryClient\n .fetchQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n staleTime: 0,\n })\n .catch(() => null)\n if (\n fresh &&\n session.getState().workspaceId === workspaceId &&\n !(fresh as ListedWorkspace[]).some((w) => w.external_id === workspaceId)\n )\n clearWorkspace()\n })\n .finally(() => {\n opening.current = false\n })\n }, [\n arbi,\n session,\n clearWorkspace,\n openSelectedWorkspace,\n queryClient,\n workspaceId,\n archived,\n gone,\n listing,\n status,\n signedIn,\n ])\n}\n"],
|
|
5
|
+
"mappings": "AAwBA,SAAS,WAAW,SAAS,cAAc;AAC3C,SAAS,eAAe,sBAAwC;AAChE;AAAA,EACE;AAAA,OAGK;AACP,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,eAAe,qBAAqB;AAC7C,SAAS,qBAAqB,2BAAkD;AAChF,SAAS,cAAc;AACvB,SAAS,sBAAsB;AAM/B,MAAM,gCAAgC;AAAA,EACpC,cAAc,aAAa;AAAA,EAC3B,cAAc,oBA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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACAA;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": ["signedIn"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arbidocs/react",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.159",
|
|
4
4
|
"description": "React hooks and provider for the ARBI SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -117,8 +117,8 @@
|
|
|
117
117
|
"build-storybook": "storybook build"
|
|
118
118
|
},
|
|
119
119
|
"dependencies": {
|
|
120
|
-
"@arbidocs/client": "0.5.
|
|
121
|
-
"@arbidocs/sdk": "0.5.
|
|
120
|
+
"@arbidocs/client": "0.5.159",
|
|
121
|
+
"@arbidocs/sdk": "0.5.159",
|
|
122
122
|
"@didit-protocol/sdk-web": "0.4.0",
|
|
123
123
|
"@livekit/components-react": "2.9.24",
|
|
124
124
|
"@radix-ui/react-avatar": "^1.2.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notifications/notify-store.ts","../src/chat/chat-artifacts.ts"],"names":["create","renderToStaticMarkup","toast","saved","useSyncExternalStore"],"mappings":";;;;;;;;AAsFO,IAAM,yBAAA,GAA4B;AAuBzC,IAAI,GAAA,GAAM,CAAA;AACV,IAAM,GAAA,GAAM,MAAM,CAAA,CAAA,EAAI,IAAA,CAAK,GAAA,EAAI,CAAE,QAAA,CAAS,EAAE,CAAC,CAAA,EAAA,CAAI,GAAA,EAAA,EAAO,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAGpE,SAAS,WAAW,KAAA,EAA6C;AAC/D,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,OAAO,KAAA,CAAM,OAAO,CAAC,CAAA,KAAM,EAAE,MAAA,IAAU,EAAE,WAAW,yBAAyB,CAAA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AA,GAA2B;AACzC,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACxB,EAAA,SAAA,GAAY,EAAC;AACb,EAAA,KAAA,GAAQ,EAAC;AACT,EAAA,IAAA,EAAK;AACP;AAGO,SAAS,gBAAA,GAA2D;AACzE,EAAA,OAAO,SAAA;AACT;AAGO,SAAS,gBAAgB,UAAA,EAAuC;AACrE,EAAA,OAAO,UAAA,GAAa,SAAA,CAAU,UAAU,CAAA,GAAI,MAAA;AAC9C;AAGO,SAAS,gBAAgB,UAAA,EAAuC;AACrE,EAAA,OAAOC,0BAAA;AAAA,IACL,SAAA;AAAA,IACA,MAAM,gBAAgB,UAAU,CAAA;AAAA,IAChC,MAAM;AAAA,GACR;AACF;AAGO,SAAS,uBAAuB,SAAA,EAAsC;AAC3E,EAAA,OAAOA,0BAAA;AAAA,IACL,SAAA;AAAA,IACA,MACE,SAAA,GACI,MAAA,CAAO,MAAA,CAAO,SAAS,CAAA,CAAE,IAAA,CAAK,CAAC,QAAA,KAAa,QAAA,CAAS,YAAA,KAAiB,SAAS,CAAA,GAC/E,MAAA;AAAA,IACN,MAAM;AAAA,GACR;AACF","file":"chunk-IX4HOS5Z.cjs","sourcesContent":["/**\n * The one notification history: every `notify.*` call pops a transient toast (rendered by\n * <Toaster/>, on sonner) and, unless `{ record: false }`, records an entry. The same entries feed\n * the topbar bell (<NotificationBell/>), its unread badge and a host's notification page; backend\n * bridges reconcile their own slices into it with {@link syncSource}.\n *\n * notify.success('Saved') // toast + entry\n * notify.error('Upload failed', { record: false }) // toast only\n * notify.info('Opening workspace…', { ambient: true }) // a log line: never badges\n *\n * sonner owns the transient toast lifecycle (stacking, timing, dismissal); this store owns the\n * history, the mute switch and what a host configures once (workspace glyph and link, see\n * {@link configureNotify}; persistence, see {@link persistNotifyHistory}). Brand-neutral: no seed\n * data, no app imports. For full sonner power the raw `toast` is re-exported.\n */\nimport { type ReactNode } from 'react'\nimport { renderToStaticMarkup } from 'react-dom/server'\n// This module IS the sanctioned toast engine home — the app-level rule that\n// steers callers to notify() doesn't apply here.\n// eslint-disable-next-line no-restricted-imports\nimport { toast } from 'sonner'\nimport { create } from 'zustand'\n\nexport { toast }\n\nexport type NotifyVariant = 'success' | 'error' | 'info' | 'warning'\n\nexport interface AppNotification {\n id: string\n title: string\n description?: string\n variant: NotifyVariant\n /** Epoch ms the entry was recorded. */\n ts: number\n read: boolean\n /** Optional in-app link the entry deep-links to (passed to the bell's onNavigate). */\n href?: string\n /** Optional click action — wins over `href` when both are present. Session\n * history only: never persisted, so a closure is safe here. */\n onSelect?: () => void\n /** The label of the action `onSelect` runs (\"Reply\", \"View\"). */\n actionLabel?: string\n /** Workspace the entry belongs to. */\n workspaceId?: string\n /** Markup of a rich (non-string) toast message, for a log that shows it as it was toasted. */\n html?: string\n /** Routine session activity (\"Opening workspace…\", \"Saved\") — kept for the\n * log but not something that demands attention: excluded from the unread\n * badge and from the bell's list. */\n ambient?: boolean\n /** Where the entry comes from. Session entries (`notify.*`) have none; a\n * backend bridge stamps its own (e.g. 'server') so {@link syncSource} can\n * replace exactly its slice on every refetch without touching the rest. */\n source?: string\n}\n\nexport interface NotifyOptions {\n /** Shown under the title in the toast; a string description is also recorded. */\n description?: ReactNode\n /** Record an entry in the history (default true). False pops the toast only — for an event\n * whose entry arrives another way (a server-persisted notification synced by a bridge). */\n record?: boolean\n /** Pop the transient toast (default true unless muted). False records the entry only. */\n toast?: boolean\n /** Recorded title for a rich (non-string) toast title. Default: the string title, else the\n * rich title's text. */\n recordTitle?: string\n /** Recorded markup for a rich toast title (default: the title rendered to static markup). */\n html?: string\n href?: string\n /** Workspace the notification belongs to: its glyph shows in the toast and its link is the\n * entry's default `href` (both as configured with {@link configureNotify}). */\n workspaceId?: string\n duration?: number\n /** A toast action button (sonner). Clicking the entry runs it too. */\n action?: { label: ReactNode; onClick: () => void }\n /** Override the toast glyph (sonner). */\n icon?: ReactNode\n /** Extra class on the toast (sonner). */\n className?: string\n /** Record as routine session activity (see {@link AppNotification.ambient}): born read. */\n ambient?: boolean\n}\n\n/** Session entries kept (oldest dropped first) — a safety net against pathological growth; a\n * large upload can log many entries, so it is generous. Source slices are bounded by their source. */\nexport const MAX_SESSION_NOTIFICATIONS = 5000\n\ninterface NotifyState {\n notifications: AppNotification[]\n /** Toasts are muted: entries are still recorded — the history is what the user comes back to. */\n muted: boolean\n setMuted: (muted: boolean) => void\n markRead: (id: string) => void\n markAllRead: () => void\n removeNotification: (id: string) => void\n removeNotifications: (ids: readonly string[]) => void\n clearNotifications: () => void\n /** Replace the history (e.g. seed a demo/initial set). */\n seed: (items: AppNotification[]) => void\n /** Record an entry (used by `notify.*`; sonner renders the toast). */\n record: (note: AppNotification) => void\n /** Reconcile one source's slice with fresh truth (e.g. a backend list on\n * every refetch): entries stamped with `source` are replaced wholesale —\n * including their read state, which the source owns — while entries from\n * other sources (session activity) stay untouched. Newest first. */\n syncSource: (source: string, items: AppNotification[]) => void\n}\n\nlet seq = 0\nconst uid = () => `n${Date.now().toString(36)}${(seq++).toString(36)}`\n\n/** Keep at most {@link MAX_SESSION_NOTIFICATIONS} session entries (newest first). */\nfunction capSession(items: AppNotification[]): AppNotification[] {\n let session = 0\n return items.filter((n) => n.source || ++session <= MAX_SESSION_NOTIFICATIONS)\n}\n\nexport const useNotify = create<NotifyState>((set) => ({\n notifications: [],\n muted: false,\n setMuted: (muted) => set({ muted }),\n markRead: (id) =>\n set((s) => ({\n notifications: s.notifications.map((n) => (n.id === id ? { ...n, read: true } : n)),\n })),\n markAllRead: () =>\n set((s) => ({ notifications: s.notifications.map((n) => ({ ...n, read: true })) })),\n removeNotification: (id) =>\n set((s) => ({ notifications: s.notifications.filter((n) => n.id !== id) })),\n removeNotifications: (ids) => {\n const drop = new Set(ids)\n set((s) => ({ notifications: s.notifications.filter((n) => !drop.has(n.id)) }))\n },\n clearNotifications: () => set({ notifications: [] }),\n seed: (items) => set({ notifications: items }),\n record: (note) => set((s) => ({ notifications: capSession([note, ...s.notifications]) })),\n syncSource: (source, items) =>\n set((s) => ({\n notifications: [\n ...items.map((n) => ({ ...n, source })),\n ...s.notifications.filter((n) => n.source !== source),\n ].sort((a, b) => b.ts - a.ts),\n })),\n}))\n\n/** What a host configures once for every `notify.*` call. */\nexport interface NotifyConfig {\n /** The toast glyph of a notification that names a workspace. */\n workspaceIcon?: (workspaceId: string) => ReactNode\n /** The default link of an entry that names a workspace. */\n workspaceHref?: (workspaceId: string) => string | undefined\n /** The default of {@link NotifyOptions.ambient} for calls that do not say: a host whose own\n * toasts are mostly confirmations (\"Saved\") records them as log lines, and passes\n * `ambient: false` for what should claim attention. Default false. */\n ambient?: boolean\n}\n\nlet config: NotifyConfig = {}\n\n/** Set the host's workspace glyph and link (merged into what is configured). */\nexport function configureNotify(next: NotifyConfig): void {\n config = { ...config, ...next }\n}\n\nfunction richMarkup(title: ReactNode): string | undefined {\n try {\n return renderToStaticMarkup(title)\n } catch {\n return undefined\n }\n}\n\nconst textOf = (html: string | undefined) =>\n (html ?? '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n\n/** Ergonomic helper — `notify.success('Saved')` — toast (sonner) + optional entry. */\nfunction make(variant: NotifyVariant) {\n return (title: ReactNode, opts: NotifyOptions = {}): string => {\n const { workspaceId } = opts\n const ambient = opts.ambient ?? config.ambient ?? false\n if (opts.toast !== false && !useNotify.getState().muted) {\n toast[variant](title, {\n description: opts.description,\n duration: opts.duration,\n action: opts.action,\n icon: opts.icon ?? (workspaceId ? config.workspaceIcon?.(workspaceId) : undefined),\n className: opts.className,\n })\n }\n const id = uid()\n if (opts.record !== false) {\n const html =\n opts.html ?? (typeof title === 'string' || title == null ? undefined : richMarkup(title))\n useNotify.getState().record({\n id,\n // A rich toast still needs a READABLE title — \"Passage copied: gamma-services p.1\",\n // not \"Notification\" — so it comes from the rendered markup, tags stripped.\n title:\n opts.recordTitle ?? (typeof title === 'string' ? title : textOf(html) || 'Notification'),\n description: typeof opts.description === 'string' ? opts.description : undefined,\n variant,\n ts: Date.now(),\n // Ambient activity is a log line, not a claim on attention: it never wears an unread dot.\n read: ambient,\n // Clicking the entry goes where the notification points: its action (when it has one),\n // an explicit link, or the workspace it happened in.\n href: opts.href ?? (workspaceId ? config.workspaceHref?.(workspaceId) : undefined),\n onSelect: opts.action?.onClick,\n actionLabel: opts.action ? String(opts.action.label) : undefined,\n workspaceId,\n html,\n ambient,\n })\n }\n return id\n }\n}\nexport const notify = {\n success: make('success'),\n error: make('error'),\n info: make('info'),\n warning: make('warning'),\n}\n\n/** Replace the history — inject a seed/initial set. */\nexport function seedNotifications(items: AppNotification[]): void {\n useNotify.getState().seed(items)\n}\n\ninterface SavedHistory {\n muted?: boolean\n notifications?: AppNotification[]\n}\n\n/**\n * Keep the session history and the mute switch across reloads in `storage` under `key`: restores\n * them now and saves every change. Source slices are not saved (their source re-syncs them), and\n * neither are actions — a closure does not survive a reload. Returns the unsubscribe.\n */\nexport function persistNotifyHistory(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedHistory | null\n if (saved) {\n const known = new Set(useNotify.getState().notifications.map((n) => n.id))\n useNotify.setState((s) => ({\n muted: saved.muted ?? s.muted,\n notifications: capSession(\n [\n ...s.notifications,\n ...(saved.notifications ?? []).filter((n) => !n.source && !known.has(n.id)),\n ].sort((a, b) => b.ts - a.ts)\n ),\n }))\n }\n } catch {\n // Unreadable or blocked storage: start empty.\n }\n let saved: AppNotification[] = []\n let savedMuted: boolean | undefined\n return useNotify.subscribe((s) => {\n const session = s.notifications.filter((n) => !n.source)\n // A backend re-sync or a read change elsewhere leaves the session slice as it was.\n if (\n s.muted === savedMuted &&\n session.length === saved.length &&\n session.every((n, i) => n === saved[i])\n )\n return\n saved = session\n savedMuted = s.muted\n // JSON drops the undefined fields: an action's closure cannot be saved, nor its label alone.\n const notifications = session.map((n) => ({\n ...n,\n onSelect: undefined,\n actionLabel: undefined,\n }))\n try {\n storage.setItem(key, JSON.stringify({ muted: s.muted, notifications }))\n } catch {\n // Full or blocked storage: the in-memory history still works.\n }\n })\n}\n\n/** Unread count selector for the topbar bell — ambient session activity never\n * demands attention, so it never counts. */\nexport const selectUnread = (s: NotifyState): number =>\n s.notifications.filter((n) => !n.read && !n.ambient).length\n\n/** Default glyph colour per variant (raw palette, override via `toneClassNames`). */\nexport const DEFAULT_NOTIFY_TONE: Record<NotifyVariant, string> = {\n success: 'text-green-600',\n error: 'text-destructive',\n warning: 'text-amber-500',\n info: 'text-blue-500',\n}\n","import { useSyncExternalStore } from 'react'\nimport type { ArtifactEvent } from '@arbidocs/sdk/browser'\n\n/**\n * The documents the assistant is writing (or wrote) in this tab's chats, as their artifact events\n * stream in: the chat engine records every one (`recordChatArtifact`), before the host's\n * `chat.onArtifact` shows it. One store for every surface that shows a draft as it is written: the\n * answer's artifact card, the document viewer, and a drafting chat's document pane.\n *\n * A module-level store, like the open-document registry: a chat and a viewer agree wherever they\n * sit in the tree. It holds what streamed in this tab only; a saved draft is read from the\n * documents list. Cleared on sign-out (`clearChatArtifacts`).\n */\n\n/** An artifact as it streams: what the events said so far. */\nexport interface ChatArtifact {\n /** The document it is written into (`doc-…`). */\n docExtId: string\n title: string\n /** The content so far (Markdown, or the html/react source of a live artifact). */\n content: string\n /**\n * `markdown` / `text` are document drafts (stored by the server as Word documents); `html` /\n * `react` are live artifacts; `image` is a generated image; `presentation` a slide deck (.pptx).\n */\n mode: ArtifactEvent['mode']\n isComplete: boolean\n version?: number | null\n /** The answer that writes it. */\n messageExtId?: string\n /** The conversation it is written in (`new` until the server named it). */\n conversationId: string\n createdAt: string\n}\n\nlet artifacts: Record<string, ChatArtifact> = {}\n/** Document ids, most recently started last. */\nlet order: string[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((listener) => listener())\n}\n\n/** Record an artifact event of a chat turn in `conversationId`. */\nexport function recordChatArtifact(event: ArtifactEvent, conversationId: string): void {\n const previous = artifacts[event.doc_ext_id]\n const artifact: ChatArtifact = {\n docExtId: event.doc_ext_id,\n title: event.title,\n content: event.content,\n mode: event.mode,\n isComplete: event.is_complete,\n version: event.version,\n createdAt: new Date().toISOString(),\n messageExtId: event.message_ext_id ?? undefined,\n conversationId,\n }\n artifacts = { ...artifacts, [artifact.docExtId]: artifact }\n if (!previous) order = [...order, artifact.docExtId]\n emit()\n}\n\n/** Forget every streamed artifact (sign-out). */\nexport function clearChatArtifacts(): void {\n if (order.length === 0) return\n artifacts = {}\n order = []\n emit()\n}\n\n/** Every artifact streamed in this tab, by document id. */\nexport function getChatArtifacts(): Readonly<Record<string, ChatArtifact>> {\n return artifacts\n}\n\n/** The artifact streaming (or streamed) into this document, if one did in this tab. */\nexport function getChatArtifact(documentId: string | null | undefined) {\n return documentId ? artifacts[documentId] : undefined\n}\n\n/** The artifact streaming into this document, if one is. Re-renders as it streams. */\nexport function useChatArtifact(documentId: string | null | undefined) {\n return useSyncExternalStore(\n subscribe,\n () => getChatArtifact(documentId),\n () => undefined\n )\n}\n\n/** The artifact this answer writes (or wrote), if it did in this tab. */\nexport function useMessageChatArtifact(messageId: string | null | undefined) {\n return useSyncExternalStore(\n subscribe,\n () =>\n messageId\n ? Object.values(artifacts).find((artifact) => artifact.messageExtId === messageId)\n : undefined,\n () => undefined\n )\n}\n"]}
|