@anchrd/intel-ui 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/package.json +1 -1
  2. package/src/app/action-slot/action-slot.tsx +23 -0
  3. package/src/app/app-sidebar/app-sidebar.tsx +39 -24
  4. package/src/app/app-tree/app-tree.tsx +431 -60
  5. package/src/app/app.tsx +17 -2
  6. package/src/app/sidebar-resize-handle/sidebar-resize-handle.tsx +2 -1
  7. package/src/app/tree-move/tree-move.tsx +197 -0
  8. package/src/app/user-footer/user-footer.tsx +73 -46
  9. package/src/app/view-toggle/view-toggle.tsx +77 -0
  10. package/src/blocknote-view/blocknote-view.tsx +19 -2
  11. package/src/branding/favicon.default.svg +2 -2
  12. package/src/branding/favicon.svg +2 -2
  13. package/src/components/ui/dropdown-menu.tsx +78 -0
  14. package/src/data/intel-data-provider/intel-data-provider.ts +120 -54
  15. package/src/data/intel-data-provider/intel-data-provider.types.ts +47 -12
  16. package/src/document-link/document-link.tsx +132 -0
  17. package/src/flow-runs/flow-runs.tsx +225 -0
  18. package/src/flows/flows.tsx +670 -271
  19. package/src/flows/node-icon/node-icon.ts +28 -0
  20. package/src/flows/node-palette/node-palette.tsx +174 -0
  21. package/src/flows/node-palette/node-palette.types.ts +15 -0
  22. package/src/graph-pane/graph-pane.tsx +44 -0
  23. package/src/i18n/en.json +141 -24
  24. package/src/knowledge/knowledge.tsx +69 -355
  25. package/src/knowledge-editor/knowledge-editor.tsx +169 -21
  26. package/src/knowledge-graph/knowledge-graph.ts +26 -24
  27. package/src/knowledge-graph/knowledge-graph.tsx +33 -24
  28. package/src/knowledge-table/knowledge-table.tsx +129 -0
  29. package/src/main.tsx +2 -2
  30. package/src/resource-menu/resource-menu.tsx +580 -0
  31. package/src/router/selection-search.ts +27 -3
  32. package/src/save-button/save-button.tsx +103 -0
  33. package/src/styles.css +37 -0
  34. package/src/theme/theme.ts +24 -0
  35. package/src/tools/tools.tsx +3 -3
  36. package/src/app/header-actions/header-actions.tsx +0 -15
@@ -1,28 +1,37 @@
1
1
  import {
2
+ AppendKnowledgeTableRowsInput,
3
+ AppendKnowledgeTableRowsResult,
2
4
  ArchiveKnowledgeNodeInput,
3
5
  CompleteFlowRunStepInput,
4
6
  CreateFlowInput,
5
- CreateKnowledgeLinkInput,
6
7
  CreateKnowledgeNodeInput,
7
- DeleteKnowledgeLinkInput,
8
+ DefineKnowledgeTableInput,
8
9
  Flow,
9
10
  FlowDocument,
10
11
  FlowList,
12
+ FlowPublishPreview,
13
+ FlowRequirements,
14
+ FlowRunHistory,
15
+ FlowRunList,
11
16
  FlowRunStep,
12
17
  KnowledgeDocument,
13
18
  KnowledgeGraph,
14
- KnowledgeLink,
15
19
  KnowledgeLinkList,
16
20
  KnowledgeNode,
17
21
  KnowledgeNodeList,
22
+ KnowledgeTable,
18
23
  KnowledgeVersionList,
24
+ ListFlowRunsInput,
19
25
  ListFlowsInput,
20
26
  ListKnowledgeNodesInput,
27
+ PreviewFlowPublishInput,
21
28
  ProblemDetails,
22
29
  PublishFlowInput,
23
- ResourceGrant,
30
+ RelationGraph,
31
+ RelationGraphInput,
32
+ ResolveKnowledgeLinksInput,
33
+ ResolveKnowledgeLinksResult,
24
34
  ResourceGrantList,
25
- RevokeFlowGrantInput,
26
35
  RevokeGrantResult,
27
36
  RevokeKnowledgeGrantInput,
28
37
  SaveFlowVersionInput,
@@ -31,17 +40,30 @@ import {
31
40
  SearchKnowledgeInput,
32
41
  SearchKnowledgeResult,
33
42
  SessionUser,
34
- ShareFlowInput,
35
43
  ShareKnowledgeInput,
44
+ ShareKnowledgeResult,
36
45
  StartFlowRunInput,
37
46
  ToolCatalog,
38
47
  UpdateFlowInput,
39
48
  UpdateKnowledgeNodeInput,
40
49
  } from "@anchrd/intel-contract";
41
- import { z } from "zod";
50
+ import type { z } from "zod";
42
51
  import type { IntelDataProvider, TreeEntry } from "./intel-data-provider.types.ts";
43
52
 
44
- const DeleteResult = z.strictObject({ deleted: z.boolean() });
53
+ // ⚠️ The refusal's `code`, not only its prose. A view that has to tell four different refusals
54
+ // apart — "you may not write there", "that is not a folder", "that would be a cycle", "someone
55
+ // else changed it" — cannot do so from `detail`, which is a sentence the server is free to
56
+ // reword. The code is the contract (`ProblemDetails.code`); the message stays what it was.
57
+ export class IntelRequestError extends Error {
58
+ constructor(
59
+ public readonly status: number,
60
+ public readonly code: string | null,
61
+ message: string,
62
+ ) {
63
+ super(message);
64
+ this.name = "IntelRequestError";
65
+ }
66
+ }
45
67
 
46
68
  // Attachment uploads and downloads share this budget, so it is generous rather than snappy.
47
69
  const RequestTimeoutMs = 60_000;
@@ -51,6 +73,16 @@ export function loginPath(returnTo?: string): string {
51
73
  return returnTo ? `/auth/login?returnTo=${encodeURIComponent(returnTo)}` : "/auth/login";
52
74
  }
53
75
 
76
+ /**
77
+ * One flow as one row of the tree. Two levels show flows — the contents of a folder, and what an
78
+ * expanded flow calls — and they are two lists of the same rows, so they are built here once. Two
79
+ * copies of this would keep returning something plausible and slowly stop agreeing on what a flow
80
+ * row is (#30).
81
+ */
82
+ export function flowEntry(flow: Flow): TreeEntry {
83
+ return { type: "flow", id: flow.id, title: flow.title, kind: "flow", flow };
84
+ }
85
+
54
86
  export function createIntelDataProvider(
55
87
  deps: { fetch?: typeof fetch; baseUrl?: string; onUnauthorized?(): void } = {},
56
88
  ): IntelDataProvider {
@@ -86,7 +118,9 @@ export function createIntelDataProvider(
86
118
  .json()
87
119
  .catch(() => null),
88
120
  );
89
- throw new Error(
121
+ throw new IntelRequestError(
122
+ result.status,
123
+ parsed.success ? (parsed.data.code ?? null) : null,
90
124
  parsed.success
91
125
  ? (parsed.data.detail ?? parsed.data.title)
92
126
  : `Intel responded with ${result.status}`,
@@ -144,13 +178,7 @@ export function createIntelDataProvider(
144
178
  kind: node.kind,
145
179
  node,
146
180
  })),
147
- ...flows.items.map((flow) => ({
148
- type: "flow" as const,
149
- id: flow.id,
150
- title: flow.title,
151
- kind: "flow" as const,
152
- flow,
153
- })),
181
+ ...flows.items.map(flowEntry),
154
182
  ];
155
183
  // Folders first, then everything else by title: a document and a flow sit side by side, and
156
184
  // the icon is what tells them apart.
@@ -176,21 +204,13 @@ export function createIntelDataProvider(
176
204
  async listKnowledgeLinks(nodeId) {
177
205
  return await request(`/knowledge/${encodeURIComponent(nodeId)}/links`, KnowledgeLinkList);
178
206
  },
179
- async createKnowledgeLink(input) {
180
- const parsed = CreateKnowledgeLinkInput.parse(input);
181
- return await request(
182
- `/knowledge/${encodeURIComponent(parsed.sourceNodeId)}/links`,
183
- KnowledgeLink,
184
- { method: "POST", body: JSON.stringify(parsed) },
185
- );
186
- },
187
- async deleteKnowledgeLink(input) {
188
- const parsed = DeleteKnowledgeLinkInput.parse(input);
189
- return await request(
190
- `/knowledge/${encodeURIComponent(parsed.sourceNodeId)}/links/${encodeURIComponent(parsed.linkId)}/revoke`,
191
- DeleteResult,
192
- { method: "POST", body: JSON.stringify(parsed) },
193
- );
207
+ // ⚠️ POST, not GET. The identifiers of the documents a text links to belong in a body: a
208
+ // query string of them would end up in logs and referrers.
209
+ async resolveKnowledgeLinks(input) {
210
+ return await request("/knowledge/links/resolve", ResolveKnowledgeLinksResult, {
211
+ method: "POST",
212
+ body: JSON.stringify(ResolveKnowledgeLinksInput.parse(input)),
213
+ });
194
214
  },
195
215
  async saveKnowledge(input) {
196
216
  const parsed = SaveKnowledgeVersionInput.parse(input);
@@ -211,6 +231,28 @@ export function createIntelDataProvider(
211
231
  async getKnowledgeAttachment(nodeId) {
212
232
  return await (await response(`/knowledge/${encodeURIComponent(nodeId)}/attachment`)).blob();
213
233
  },
234
+ async getKnowledgeTable(nodeId) {
235
+ return await request(`/knowledge/${encodeURIComponent(nodeId)}/table`, KnowledgeTable);
236
+ },
237
+ async defineKnowledgeTable(input) {
238
+ const parsed = DefineKnowledgeTableInput.parse(input);
239
+ return await request(
240
+ `/knowledge/${encodeURIComponent(parsed.nodeId)}/table`,
241
+ KnowledgeTable,
242
+ {
243
+ method: "POST",
244
+ body: JSON.stringify(parsed),
245
+ },
246
+ );
247
+ },
248
+ async appendKnowledgeTableRows(input) {
249
+ const parsed = AppendKnowledgeTableRowsInput.parse(input);
250
+ return await request(
251
+ `/knowledge/${encodeURIComponent(parsed.nodeId)}/table/rows`,
252
+ AppendKnowledgeTableRowsResult,
253
+ { method: "POST", body: JSON.stringify(parsed) },
254
+ );
255
+ },
214
256
  async listKnowledgeVersions(nodeId) {
215
257
  return await request(
216
258
  `/knowledge/${encodeURIComponent(nodeId)}/versions`,
@@ -248,7 +290,7 @@ export function createIntelDataProvider(
248
290
  const parsed = ShareKnowledgeInput.parse(input);
249
291
  return await request(
250
292
  `/knowledge/${encodeURIComponent(parsed.resourceId)}/grants`,
251
- ResourceGrant,
293
+ ShareKnowledgeResult,
252
294
  { method: "POST", body: JSON.stringify(parsed) },
253
295
  );
254
296
  },
@@ -264,6 +306,30 @@ export function createIntelDataProvider(
264
306
  async getFlow(flowId) {
265
307
  return await request(`/flows/${encodeURIComponent(flowId)}`, FlowDocument);
266
308
  },
309
+ async listFlowCalls(flowId) {
310
+ return await request(`/flows/${encodeURIComponent(flowId)}/calls`, FlowList);
311
+ },
312
+ async getRelationGraph(scope, limit) {
313
+ const parsed = RelationGraphInput.parse({
314
+ scope,
315
+ ...(limit === undefined ? {} : { limit }),
316
+ });
317
+ const params = new URLSearchParams({
318
+ of: parsed.scope.of,
319
+ limit: String(parsed.limit),
320
+ // A folder scope without an ID is the root of the shared tree, and an absent parameter is
321
+ // how that is said — the same distinction `/flows?parentId=` makes.
322
+ ...(parsed.scope.of === "flow"
323
+ ? { flowId: parsed.scope.flowId }
324
+ : parsed.scope.folderId
325
+ ? { folderId: parsed.scope.folderId }
326
+ : {}),
327
+ });
328
+ return await request(`/flows/graph?${params}`, RelationGraph);
329
+ },
330
+ async getFlowRequirements(flowId) {
331
+ return await request(`/flows/${encodeURIComponent(flowId)}/requirements`, FlowRequirements);
332
+ },
267
333
  async createFlow(input) {
268
334
  return await request("/flows", Flow, {
269
335
  method: "POST",
@@ -277,28 +343,6 @@ export function createIntelDataProvider(
277
343
  body: JSON.stringify(parsed),
278
344
  });
279
345
  },
280
- async listFlowGrants(flowId) {
281
- return await request(`/flows/${encodeURIComponent(flowId)}/grants`, ResourceGrantList);
282
- },
283
- async shareFlow(input) {
284
- const parsed = ShareFlowInput.parse(input);
285
- return await request(
286
- `/flows/${encodeURIComponent(parsed.resourceId)}/grants`,
287
- ResourceGrant,
288
- {
289
- method: "POST",
290
- body: JSON.stringify(parsed),
291
- },
292
- );
293
- },
294
- async revokeFlowGrant(input) {
295
- const parsed = RevokeFlowGrantInput.parse(input);
296
- return await request(
297
- `/flows/${encodeURIComponent(parsed.resourceId)}/grants/${encodeURIComponent(parsed.grantId)}/revoke`,
298
- RevokeGrantResult,
299
- { method: "POST", body: JSON.stringify(parsed) },
300
- );
301
- },
302
346
  async saveFlow(input) {
303
347
  const parsed = SaveFlowVersionInput.parse(input);
304
348
  return await request(`/flows/${encodeURIComponent(parsed.flowId)}/versions`, FlowDocument, {
@@ -306,6 +350,13 @@ export function createIntelDataProvider(
306
350
  body: JSON.stringify(parsed),
307
351
  });
308
352
  },
353
+ async previewFlowPublish(input) {
354
+ const parsed = PreviewFlowPublishInput.parse(input);
355
+ return await request(
356
+ `/flows/${encodeURIComponent(parsed.flowId)}/versions/${encodeURIComponent(parsed.versionId)}/publish-preview`,
357
+ FlowPublishPreview,
358
+ );
359
+ },
309
360
  async publishFlow(input) {
310
361
  const parsed = PublishFlowInput.parse(input);
311
362
  return await request(`/flows/${encodeURIComponent(parsed.flowId)}/publish`, Flow, {
@@ -320,9 +371,24 @@ export function createIntelDataProvider(
320
371
  body: JSON.stringify(parsed),
321
372
  });
322
373
  },
374
+ async listFlowRuns(input) {
375
+ const parsed = ListFlowRunsInput.parse(input);
376
+ // Only what was actually asked for travels. `failedOnly` is the parameter's presence rather
377
+ // than a value, which is the same shape the server reads it back with.
378
+ const params = new URLSearchParams({ limit: String(parsed.limit) });
379
+ if (parsed.failedOnly) params.set("failedOnly", "");
380
+ if (parsed.cursor) params.set("cursor", parsed.cursor);
381
+ return await request(
382
+ `/flows/${encodeURIComponent(parsed.flowId)}/runs?${params}`,
383
+ FlowRunList,
384
+ );
385
+ },
323
386
  async getFlowRun(runId) {
324
387
  return await request(`/flow-runs/${encodeURIComponent(runId)}`, FlowRunStep);
325
388
  },
389
+ async getFlowRunSteps(runId) {
390
+ return await request(`/flow-runs/${encodeURIComponent(runId)}/steps`, FlowRunHistory);
391
+ },
326
392
  async completeFlowStep(input) {
327
393
  const parsed = CompleteFlowRunStepInput.parse(input);
328
394
  return await request(`/flow-runs/${encodeURIComponent(parsed.runId)}/complete`, FlowRunStep, {
@@ -1,28 +1,37 @@
1
1
  import type {
2
+ AppendKnowledgeTableRowsInput,
3
+ AppendKnowledgeTableRowsResult,
2
4
  ArchiveKnowledgeNodeInput,
3
5
  CompleteFlowRunStepInput,
4
6
  CreateFlowInput,
5
- CreateKnowledgeLinkInput,
6
7
  CreateKnowledgeNodeInput,
7
- DeleteKnowledgeLinkInput,
8
+ DefineKnowledgeTableInput,
8
9
  Flow,
9
10
  FlowDocument,
10
11
  FlowList,
12
+ FlowPublishPreview,
13
+ FlowRequirements,
14
+ FlowRunHistory,
15
+ FlowRunList,
11
16
  FlowRunStep,
12
17
  KnowledgeDocument,
13
18
  KnowledgeGraph,
14
- KnowledgeLink,
15
19
  KnowledgeLinkList,
16
20
  KnowledgeNode,
17
21
  KnowledgeNodeKind,
18
22
  KnowledgeNodeList,
23
+ KnowledgeTable,
19
24
  KnowledgeVersionList,
25
+ ListFlowRunsInput,
20
26
  ListFlowsInput,
21
27
  ListKnowledgeNodesInput,
28
+ PreviewFlowPublishInput,
22
29
  PublishFlowInput,
23
- ResourceGrant,
30
+ RelationGraph,
31
+ RelationGraphScope,
32
+ ResolveKnowledgeLinksInput,
33
+ ResolveKnowledgeLinksResult,
24
34
  ResourceGrantList,
25
- RevokeFlowGrantInput,
26
35
  RevokeGrantResult,
27
36
  RevokeKnowledgeGrantInput,
28
37
  SaveFlowVersionInput,
@@ -31,8 +40,8 @@ import type {
31
40
  SearchKnowledgeInput,
32
41
  SearchKnowledgeResult,
33
42
  SessionUser,
34
- ShareFlowInput,
35
43
  ShareKnowledgeInput,
44
+ ShareKnowledgeResult,
36
45
  StartFlowRunInput,
37
46
  ToolCatalog,
38
47
  UpdateFlowInput,
@@ -55,30 +64,56 @@ export interface IntelDataProvider {
55
64
  createKnowledge(input: CreateKnowledgeNodeInput): Promise<KnowledgeNode>;
56
65
  getKnowledgeGraph(limit?: number): Promise<KnowledgeGraph>;
57
66
  listKnowledgeLinks(nodeId: string): Promise<KnowledgeLinkList>;
58
- createKnowledgeLink(input: CreateKnowledgeLinkInput): Promise<KnowledgeLink>;
59
- deleteKnowledgeLink(input: DeleteKnowledgeLinkInput): Promise<{ deleted: boolean }>;
67
+ // The titles of the documents a text links to, for the reader. A target they may not see, or one
68
+ // that is gone, is absent from the answer — the two look the same on purpose (#41).
69
+ resolveKnowledgeLinks(input: ResolveKnowledgeLinksInput): Promise<ResolveKnowledgeLinksResult>;
60
70
  saveKnowledge(input: SaveKnowledgeVersionInput): Promise<KnowledgeDocument>;
61
71
  saveKnowledgeAttachment(input: SaveKnowledgeAttachmentInput): Promise<KnowledgeDocument>;
62
72
  getKnowledgeAttachment(nodeId: string): Promise<Blob>;
73
+ // A table as columns and rows. The CSV stays canonical — `getKnowledge` still answers with it,
74
+ // which is what the download uses — and this is the same bytes read by the server's one reader.
75
+ getKnowledgeTable(nodeId: string): Promise<KnowledgeTable>;
76
+ defineKnowledgeTable(input: DefineKnowledgeTableInput): Promise<KnowledgeTable>;
77
+ appendKnowledgeTableRows(
78
+ input: AppendKnowledgeTableRowsInput,
79
+ ): Promise<AppendKnowledgeTableRowsResult>;
63
80
  portalConnectUrl(returnTo?: string): string;
64
81
  listKnowledgeVersions(nodeId: string): Promise<KnowledgeVersionList>;
65
82
  updateKnowledge(input: UpdateKnowledgeNodeInput): Promise<KnowledgeNode>;
66
83
  archiveKnowledge(input: ArchiveKnowledgeNodeInput): Promise<KnowledgeNode>;
67
84
  searchKnowledge(input: SearchKnowledgeInput): Promise<SearchKnowledgeResult>;
68
85
  listKnowledgeGrants(resourceId: string): Promise<ResourceGrantList>;
69
- shareKnowledge(input: ShareKnowledgeInput): Promise<ResourceGrant>;
86
+ // The grant, and what the grant does not cover: the documents the flows in this folder read that
87
+ // the new principal still cannot. A warning, never a refusal (ADR-0004 §4).
88
+ shareKnowledge(input: ShareKnowledgeInput): Promise<ShareKnowledgeResult>;
70
89
  revokeKnowledgeGrant(input: RevokeKnowledgeGrantInput): Promise<RevokeGrantResult>;
71
90
  listFlows(input?: ListFlowsInput): Promise<FlowList>;
72
91
  getFlow(flowId: string): Promise<FlowDocument>;
92
+ // What a flow calls, read out of its graph. It answers a different question from `listTreeChildren`
93
+ // and deliberately gives a different answer: a shared sub-flow is listed under every caller.
94
+ listFlowCalls(flowId: string): Promise<FlowList>;
95
+ // What accesses what, for one level of the shared tree: a folder for its contents, a flow for
96
+ // itself. ⚠️ Only nodes the signed-in user may see come back, and one they may not is absent
97
+ // altogether — never a placeholder, because the edge into one would already say that it exists.
98
+ getRelationGraph(scope: RelationGraphScope, limit?: number): Promise<RelationGraph>;
99
+ // What a flow touches: the documents and tools its graph names. Documents the signed-in user may
100
+ // not see are counted rather than named, and nothing here claims anybody may reach them.
101
+ getFlowRequirements(flowId: string): Promise<FlowRequirements>;
73
102
  createFlow(input: CreateFlowInput): Promise<Flow>;
74
103
  updateFlow(input: UpdateFlowInput): Promise<Flow>;
75
- listFlowGrants(flowId: string): Promise<ResourceGrantList>;
76
- shareFlow(input: ShareFlowInput): Promise<ResourceGrant>;
77
- revokeFlowGrant(input: RevokeFlowGrantInput): Promise<RevokeGrantResult>;
78
104
  saveFlow(input: SaveFlowVersionInput): Promise<FlowDocument>;
105
+ // Which version each sub-flow call will take once published, and which of them publishing
106
+ // freezes. Read before publishing, so the author agrees to the pins rather than discovering them.
107
+ previewFlowPublish(input: PreviewFlowPublishInput): Promise<FlowPublishPreview>;
79
108
  publishFlow(input: PublishFlowInput): Promise<Flow>;
80
109
  startFlow(input: StartFlowRunInput): Promise<FlowRunStep>;
110
+ // What this flow has done, newest first, one page at a time. ⚠️ It carries what a run did and
111
+ // never what it produced: a run reads Knowledge with the rights of whoever started it, so its
112
+ // result is not automatically readable for everyone who may read the flow.
113
+ listFlowRuns(input: ListFlowRunsInput): Promise<FlowRunList>;
81
114
  getFlowRun(runId: string): Promise<FlowRunStep>;
115
+ // The drill-down behind one run: every step it took, and the call chain it belongs to.
116
+ getFlowRunSteps(runId: string): Promise<FlowRunHistory>;
82
117
  completeFlowStep(input: CompleteFlowRunStepInput): Promise<FlowRunStep>;
83
118
  // Reading the catalog is the whole of the tool surface here: calling a tool belongs to a flow
84
119
  // or to the Intel MCP surface, not to the screen that shows what the portal offers.
@@ -0,0 +1,132 @@
1
+ import { DocumentLinkInlineType } from "@anchrd/intel-contract";
2
+ import { BlockNoteSchema } from "@blocknote/core";
3
+ import { createReactInlineContentSpec } from "@blocknote/react";
4
+ import { FileText, Link2Off } from "lucide-react";
5
+ import { createContext, useContext } from "react";
6
+
7
+ /**
8
+ * What a document link resolves to for the person reading it.
9
+ *
10
+ * ⚠️ `titles` holds only the documents this reader may see. A missing entry is the whole answer for
11
+ * both of the reasons an entry can be missing — the target is gone, or it is not theirs to reach —
12
+ * and nothing here may ever be given a way to tell those apart. `pending` exists so the editor can
13
+ * hold back the difference between "not resolved yet" and "does not resolve", which would otherwise
14
+ * flash a broken link at every reader for one render.
15
+ */
16
+ export interface DocumentLinkResolution {
17
+ titles: ReadonlyMap<string, string>;
18
+ pending: boolean;
19
+ // The one word an unresolved link says. It travels in the context because a BlockNote inline
20
+ // element is rendered by the editor rather than by a view that could reach the i18n catalog.
21
+ unresolvedLabel: string;
22
+ }
23
+
24
+ const DocumentLinkContext = createContext<DocumentLinkResolution>({
25
+ titles: new Map(),
26
+ pending: false,
27
+ unresolvedLabel: "Unavailable document",
28
+ });
29
+
30
+ export const DocumentLinkProvider = DocumentLinkContext.Provider;
31
+
32
+ export function useDocumentLinkResolution(): DocumentLinkResolution {
33
+ return useContext(DocumentLinkContext);
34
+ }
35
+
36
+ /**
37
+ * One document link inside the text (#41).
38
+ *
39
+ * ⚠️ The element stores the target's ID and nothing else. A stored title would be wrong the moment
40
+ * the target is renamed and a stored path the moment it is moved — and both would put a name into a
41
+ * document that any reader of it could then read, whether or not they may reach the target.
42
+ *
43
+ * ⚠️ An unresolved link says that it does not resolve and nothing more: no title, no path, no ID on
44
+ * screen, no hint of which of the two reasons applies. That is the whole of the leak this feature
45
+ * could have introduced, and the reason the broken form carries no data at all.
46
+ */
47
+ export function DocumentLinkText({ nodeId }: { nodeId: string }) {
48
+ const { titles, pending, unresolvedLabel } = useDocumentLinkResolution();
49
+ const title = titles.get(nodeId);
50
+ if (title === undefined) {
51
+ return (
52
+ <span
53
+ data-document-link={pending ? "pending" : "unresolved"}
54
+ className={
55
+ pending
56
+ ? "inline-flex items-center gap-1 rounded-sm px-1 text-muted-foreground"
57
+ : "inline-flex items-center gap-1 rounded-sm bg-destructive/10 px-1 text-destructive line-through"
58
+ }
59
+ >
60
+ {pending ? null : <Link2Off aria-hidden="true" className="size-3.5" />}
61
+ {pending ? "…" : unresolvedLabel}
62
+ </span>
63
+ );
64
+ }
65
+ return (
66
+ <span
67
+ data-document-link="resolved"
68
+ data-node-id={nodeId}
69
+ className="inline-flex items-center gap-1 rounded-sm bg-muted px-1 text-foreground"
70
+ >
71
+ <FileText aria-hidden="true" className="size-3.5" />
72
+ {title}
73
+ </span>
74
+ );
75
+ }
76
+
77
+ export const documentLinkSpec = createReactInlineContentSpec(
78
+ {
79
+ type: DocumentLinkInlineType,
80
+ propSchema: { nodeId: { default: "" } },
81
+ // The link has no editable text of its own: what it reads is the target's title, and a title
82
+ // somebody could type over would stop following the target the first time they did (#41).
83
+ content: "none",
84
+ },
85
+ {
86
+ render: (props) => <DocumentLinkText nodeId={String(props.inlineContent.props.nodeId)} />,
87
+ },
88
+ );
89
+
90
+ // One schema for the editor and for everything that reads its documents back: BlockNote's defaults
91
+ // plus the one inline element #41 adds.
92
+ //
93
+ // ⚠️ `extend` rather than `create({ inlineContentSpecs: { ...defaults, documentLink } })`. Both
94
+ // build the same schema at run time, but only `extend` keeps the added type in the schema's own
95
+ // generics under this repo's `exactOptionalPropertyTypes` — with the spread form the editor infers
96
+ // BlockNote's default schema, typechecks, and then refuses to insert a document link.
97
+ export const intelEditorSchema = BlockNoteSchema.create().extend({
98
+ inlineContentSpecs: { documentLink: documentLinkSpec },
99
+ });
100
+
101
+ // The schema carries its own editor and block types as declaration-only properties, which is the
102
+ // only way to name them here: writing `BlockNoteEditor<typeof schema.blockSchema, ...>` by hand
103
+ // fails BlockNote's own constraint under `exactOptionalPropertyTypes`.
104
+ export type IntelEditor = (typeof intelEditorSchema)["BlockNoteEditor"];
105
+ export type IntelEditorPartialBlock = (typeof intelEditorSchema)["PartialBlock"];
106
+
107
+ /**
108
+ * The IDs a stored BlockNote document links to.
109
+ *
110
+ * The server reads the same thing out of the same content when the document is saved; this side
111
+ * needs it too, to ask which of them it may show a title for.
112
+ */
113
+ export function documentLinkIds(blocks: unknown): string[] {
114
+ const found = new Set<string>();
115
+ const walk = (value: unknown): void => {
116
+ if (Array.isArray(value)) {
117
+ for (const entry of value) walk(entry);
118
+ return;
119
+ }
120
+ if (typeof value !== "object" || value === null) return;
121
+ const record = value as Record<string, unknown>;
122
+ if (record.type === DocumentLinkInlineType) {
123
+ const props = record.props as Record<string, unknown> | undefined;
124
+ const nodeId = props?.nodeId;
125
+ if (typeof nodeId === "string" && nodeId.length > 0) found.add(nodeId);
126
+ }
127
+ walk(record.content);
128
+ walk(record.children);
129
+ };
130
+ walk(blocks);
131
+ return [...found];
132
+ }