@astra-spec/ui 0.0.2 → 0.0.4

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 (247) hide show
  1. package/README.md +231 -20
  2. package/TOKENS.md +10 -3
  3. package/components.css +2 -0
  4. package/dist/blocks/decisions-list.d.ts +0 -1
  5. package/dist/blocks/decisions-list.d.ts.map +1 -1
  6. package/dist/blocks/decisions-list.js +1 -5
  7. package/dist/blocks/decisions-list.js.map +1 -1
  8. package/dist/blocks/index.d.ts +3 -3
  9. package/dist/blocks/index.d.ts.map +1 -1
  10. package/dist/blocks/index.js +2 -2
  11. package/dist/blocks/index.js.map +1 -1
  12. package/dist/blocks/inputs-list.js +1 -1
  13. package/dist/blocks/inputs-list.js.map +1 -1
  14. package/dist/blocks/outputs-list.d.ts +2 -2
  15. package/dist/blocks/outputs-list.d.ts.map +1 -1
  16. package/dist/blocks/outputs-list.js +15 -19
  17. package/dist/blocks/outputs-list.js.map +1 -1
  18. package/dist/blocks/section.d.ts +1 -4
  19. package/dist/blocks/section.d.ts.map +1 -1
  20. package/dist/blocks/section.js +1 -12
  21. package/dist/blocks/section.js.map +1 -1
  22. package/dist/components/artifact-preview.d.ts +2 -54
  23. package/dist/components/artifact-preview.d.ts.map +1 -1
  24. package/dist/components/artifact-preview.js +2 -107
  25. package/dist/components/artifact-preview.js.map +1 -1
  26. package/dist/components/decision-detail.d.ts +1 -1
  27. package/dist/components/decision-detail.d.ts.map +1 -1
  28. package/dist/components/decision-detail.js.map +1 -1
  29. package/dist/components/finding-detail.d.ts +2 -2
  30. package/dist/components/finding-detail.d.ts.map +1 -1
  31. package/dist/components/finding-detail.js.map +1 -1
  32. package/dist/components/index.d.ts +11 -13
  33. package/dist/components/index.d.ts.map +1 -1
  34. package/dist/components/index.js +7 -8
  35. package/dist/components/index.js.map +1 -1
  36. package/dist/components/input-detail.d.ts +1 -2
  37. package/dist/components/input-detail.d.ts.map +1 -1
  38. package/dist/components/input-detail.js +0 -3
  39. package/dist/components/input-detail.js.map +1 -1
  40. package/dist/components/insight-detail.d.ts +2 -8
  41. package/dist/components/insight-detail.d.ts.map +1 -1
  42. package/dist/components/insight-detail.js +5 -11
  43. package/dist/components/insight-detail.js.map +1 -1
  44. package/dist/components/insight-trigger.d.ts +1 -1
  45. package/dist/components/insight-trigger.d.ts.map +1 -1
  46. package/dist/components/insight-trigger.js.map +1 -1
  47. package/dist/components/output-detail.d.ts +2 -7
  48. package/dist/components/output-detail.d.ts.map +1 -1
  49. package/dist/components/output-detail.js +3 -30
  50. package/dist/components/output-detail.js.map +1 -1
  51. package/dist/components/output-dialog.d.ts +2 -2
  52. package/dist/components/output-dialog.d.ts.map +1 -1
  53. package/dist/components/output-dialog.js +2 -1
  54. package/dist/components/output-dialog.js.map +1 -1
  55. package/dist/components/paper-detail.d.ts +14 -14
  56. package/dist/components/paper-detail.d.ts.map +1 -1
  57. package/dist/components/paper-detail.js +49 -29
  58. package/dist/components/paper-detail.js.map +1 -1
  59. package/dist/components/paper-pdf-viewer.d.ts +19 -0
  60. package/dist/components/paper-pdf-viewer.d.ts.map +1 -0
  61. package/dist/components/paper-pdf-viewer.js +250 -0
  62. package/dist/components/paper-pdf-viewer.js.map +1 -0
  63. package/dist/components/record-dialog.d.ts +7 -5
  64. package/dist/components/record-dialog.d.ts.map +1 -1
  65. package/dist/components/record-dialog.js +7 -5
  66. package/dist/components/record-dialog.js.map +1 -1
  67. package/dist/components/record-preview.d.ts +61 -0
  68. package/dist/components/record-preview.d.ts.map +1 -0
  69. package/dist/components/record-preview.js +177 -0
  70. package/dist/components/record-preview.js.map +1 -0
  71. package/dist/components/relation-items.d.ts +1 -1
  72. package/dist/components/relation-items.d.ts.map +1 -1
  73. package/dist/components/relation-items.js +10 -3
  74. package/dist/components/relation-items.js.map +1 -1
  75. package/dist/{components/use-detail-stack.d.ts → lib/detail-stack.d.ts} +17 -2
  76. package/dist/lib/detail-stack.d.ts.map +1 -0
  77. package/dist/{components/use-detail-stack.js → lib/detail-stack.js} +15 -2
  78. package/dist/lib/detail-stack.js.map +1 -0
  79. package/dist/lib/index.d.ts +14 -0
  80. package/dist/lib/index.d.ts.map +1 -0
  81. package/dist/lib/index.js +9 -0
  82. package/dist/lib/index.js.map +1 -0
  83. package/dist/lib/labels.d.ts +32 -0
  84. package/dist/lib/labels.d.ts.map +1 -1
  85. package/dist/lib/labels.js +32 -0
  86. package/dist/lib/labels.js.map +1 -1
  87. package/dist/lib/pdf-quote.d.ts +47 -0
  88. package/dist/lib/pdf-quote.d.ts.map +1 -0
  89. package/dist/lib/pdf-quote.js +154 -0
  90. package/dist/lib/pdf-quote.js.map +1 -0
  91. package/dist/lib/pdf-runtime.d.ts +102 -0
  92. package/dist/lib/pdf-runtime.d.ts.map +1 -0
  93. package/dist/lib/pdf-runtime.js +48 -0
  94. package/dist/lib/pdf-runtime.js.map +1 -0
  95. package/dist/lib/preview-data.d.ts +55 -0
  96. package/dist/lib/preview-data.d.ts.map +1 -0
  97. package/dist/lib/preview-data.js +108 -0
  98. package/dist/lib/preview-data.js.map +1 -0
  99. package/dist/lib/prose.d.ts +37 -0
  100. package/dist/lib/prose.d.ts.map +1 -0
  101. package/dist/lib/prose.js +60 -0
  102. package/dist/lib/prose.js.map +1 -0
  103. package/dist/lib/use-isomorphic-layout-effect.d.ts +4 -0
  104. package/dist/lib/use-isomorphic-layout-effect.d.ts.map +1 -0
  105. package/dist/lib/use-isomorphic-layout-effect.js +4 -0
  106. package/dist/lib/use-isomorphic-layout-effect.js.map +1 -0
  107. package/dist/lib/use-output-expanded.d.ts +7 -0
  108. package/dist/lib/use-output-expanded.d.ts.map +1 -0
  109. package/dist/lib/use-output-expanded.js +29 -0
  110. package/dist/lib/use-output-expanded.js.map +1 -0
  111. package/dist/model/index.d.ts +5 -3
  112. package/dist/model/index.d.ts.map +1 -1
  113. package/dist/model/index.js +3 -2
  114. package/dist/model/index.js.map +1 -1
  115. package/dist/{primitives → model}/kind.d.ts +3 -0
  116. package/dist/model/kind.d.ts.map +1 -0
  117. package/dist/model/kind.js +25 -0
  118. package/dist/model/kind.js.map +1 -0
  119. package/dist/model/papers.d.ts +6 -6
  120. package/dist/model/papers.d.ts.map +1 -1
  121. package/dist/model/papers.js +8 -0
  122. package/dist/model/papers.js.map +1 -1
  123. package/dist/model/records.d.ts +5 -1
  124. package/dist/model/records.d.ts.map +1 -1
  125. package/dist/model/records.js +9 -0
  126. package/dist/model/records.js.map +1 -1
  127. package/dist/primitives/badge.d.ts +1 -1
  128. package/dist/primitives/badge.d.ts.map +1 -1
  129. package/dist/primitives/button.js +1 -1
  130. package/dist/primitives/button.js.map +1 -1
  131. package/dist/primitives/dialog.d.ts +1 -1
  132. package/dist/primitives/dialog.d.ts.map +1 -1
  133. package/dist/primitives/dialog.js +3 -3
  134. package/dist/primitives/dialog.js.map +1 -1
  135. package/dist/primitives/index.d.ts +6 -9
  136. package/dist/primitives/index.d.ts.map +1 -1
  137. package/dist/primitives/index.js +3 -5
  138. package/dist/primitives/index.js.map +1 -1
  139. package/dist/primitives/preview-popover.d.ts +30 -0
  140. package/dist/primitives/preview-popover.d.ts.map +1 -0
  141. package/dist/primitives/preview-popover.js +132 -0
  142. package/dist/primitives/preview-popover.js.map +1 -0
  143. package/dist/primitives/prose.d.ts +1 -29
  144. package/dist/primitives/prose.d.ts.map +1 -1
  145. package/dist/primitives/prose.js +2 -50
  146. package/dist/primitives/prose.js.map +1 -1
  147. package/dist/primitives/record-list.d.ts +1 -1
  148. package/dist/primitives/record-list.d.ts.map +1 -1
  149. package/dist/primitives/record-list.js +1 -1
  150. package/dist/primitives/record-list.js.map +1 -1
  151. package/dist/primitives/relation-list.d.ts +1 -1
  152. package/dist/primitives/relation-list.d.ts.map +1 -1
  153. package/dist/primitives/relation-list.js +1 -1
  154. package/dist/primitives/relation-list.js.map +1 -1
  155. package/dist/primitives/slot.d.ts.map +1 -0
  156. package/dist/{lib → primitives}/slot.js +1 -1
  157. package/dist/primitives/slot.js.map +1 -0
  158. package/dist/primitives/surface-header.d.ts +1 -1
  159. package/dist/primitives/surface-header.d.ts.map +1 -1
  160. package/dist/views/inventory.d.ts +7 -5
  161. package/dist/views/inventory.d.ts.map +1 -1
  162. package/dist/views/inventory.js +5 -4
  163. package/dist/views/inventory.js.map +1 -1
  164. package/package.json +12 -1
  165. package/primitives.css +1 -0
  166. package/src/blocks/decisions-list.tsx +1 -6
  167. package/src/blocks/index.ts +2 -3
  168. package/src/blocks/inputs-list.tsx +1 -1
  169. package/src/blocks/outputs-list.tsx +53 -30
  170. package/src/blocks/section.tsx +1 -14
  171. package/src/components/artifact-preview.tsx +6 -161
  172. package/src/components/decision-detail.tsx +2 -1
  173. package/src/components/finding-detail.tsx +3 -2
  174. package/src/components/index.ts +19 -29
  175. package/src/components/input-detail.tsx +2 -5
  176. package/src/components/insight-detail.tsx +20 -35
  177. package/src/components/insight-trigger.tsx +2 -1
  178. package/src/components/output-detail.tsx +17 -38
  179. package/src/components/output-dialog.tsx +4 -3
  180. package/src/components/paper-detail.tsx +121 -66
  181. package/src/components/paper-pdf-viewer.tsx +319 -0
  182. package/src/components/record-dialog.tsx +15 -10
  183. package/src/components/record-preview.tsx +762 -0
  184. package/src/components/relation-items.ts +15 -5
  185. package/src/{components/use-detail-stack.ts → lib/detail-stack.ts} +24 -1
  186. package/src/lib/index.ts +22 -0
  187. package/src/lib/labels.tsx +67 -0
  188. package/src/lib/pdf-quote.ts +189 -0
  189. package/src/lib/pdf-runtime.ts +131 -0
  190. package/src/lib/preview-data.ts +155 -0
  191. package/src/lib/prose.tsx +87 -0
  192. package/src/lib/use-isomorphic-layout-effect.ts +4 -0
  193. package/src/lib/use-output-expanded.ts +27 -0
  194. package/src/model/index.ts +4 -2
  195. package/src/{primitives → model}/kind.ts +14 -0
  196. package/src/model/papers.ts +9 -7
  197. package/src/model/records.ts +12 -0
  198. package/src/primitives/badge.tsx +1 -1
  199. package/src/primitives/button.tsx +1 -1
  200. package/src/primitives/dialog.tsx +3 -5
  201. package/src/primitives/index.ts +9 -9
  202. package/src/primitives/preview-popover.tsx +278 -0
  203. package/src/primitives/prose.tsx +1 -63
  204. package/src/primitives/record-list.tsx +1 -1
  205. package/src/primitives/relation-list.tsx +1 -1
  206. package/src/{lib → primitives}/slot.tsx +1 -1
  207. package/src/primitives/surface-header.tsx +1 -1
  208. package/src/views/inventory.tsx +12 -8
  209. package/styles/blocks/analysis-tree.css +2 -2
  210. package/styles/blocks/decisions-list.css +4 -4
  211. package/styles/blocks/outputs-list.css +246 -19
  212. package/styles/blocks/papers-list.css +2 -2
  213. package/styles/components/artifact-preview.css +6 -6
  214. package/styles/components/decision-detail.css +2 -2
  215. package/styles/components/evidence.css +2 -2
  216. package/styles/components/input-detail.css +4 -4
  217. package/styles/components/insight-detail.css +56 -94
  218. package/styles/components/insight-list.css +3 -3
  219. package/styles/components/insight-trigger.css +1 -4
  220. package/styles/components/output-detail.css +25 -140
  221. package/styles/components/paper-detail.css +76 -95
  222. package/styles/components/paper-doi.css +3 -12
  223. package/styles/components/paper-pdf-viewer.css +120 -0
  224. package/styles/components/record-preview.css +316 -0
  225. package/styles/primitives/badge.css +1 -1
  226. package/styles/primitives/count-heading.css +2 -2
  227. package/styles/primitives/detail-layout.css +5 -5
  228. package/styles/primitives/dialog.css +9 -9
  229. package/styles/primitives/preview-popover.css +76 -0
  230. package/styles/primitives/record-list.css +17 -17
  231. package/styles/primitives/relation-list.css +6 -6
  232. package/styles/primitives/surface-header.css +5 -5
  233. package/styles/tokens.css +16 -3
  234. package/styles/views/inventory.css +3 -3
  235. package/dist/components/detail-entry.d.ts +0 -15
  236. package/dist/components/detail-entry.d.ts.map +0 -1
  237. package/dist/components/detail-entry.js +0 -14
  238. package/dist/components/detail-entry.js.map +0 -1
  239. package/dist/components/use-detail-stack.d.ts.map +0 -1
  240. package/dist/components/use-detail-stack.js.map +0 -1
  241. package/dist/lib/slot.d.ts.map +0 -1
  242. package/dist/lib/slot.js.map +0 -1
  243. package/dist/primitives/kind.d.ts.map +0 -1
  244. package/dist/primitives/kind.js +0 -14
  245. package/dist/primitives/kind.js.map +0 -1
  246. package/src/components/detail-entry.ts +0 -19
  247. /package/dist/{lib → primitives}/slot.d.ts +0 -0
@@ -2,8 +2,11 @@ import type { ResolvedAnalysisNode, ResolvedRecord } from '@astra-spec/sdk';
2
2
  import type { LinkedRecord } from '../model/relations.js';
3
3
  import { recordTitle } from '../model/records.js';
4
4
  import type { RelationItem } from '../primitives/relation-list.js';
5
+ import type { OpenRecordHandler } from '../lib/detail-stack.js';
5
6
 
6
- export type OpenRecordHandler = (record: ResolvedRecord, analysis: ResolvedAnalysisNode) => void;
7
+ // Glue between model records and the RelationList primitive: it needs both
8
+ // `recordTitle` from model and the item shape from primitives, which no lower
9
+ // layer can see together, so it stays here beside the components that use it.
7
10
 
8
11
  /** Builds a relation-list item for a record, with navigation when the caller handles it. */
9
12
  export function relationItemForRecord(
@@ -24,8 +27,15 @@ export function relationItemForRecord(
24
27
  }
25
28
 
26
29
  /** Builds relation-list items for linked records; unresolved links show their path. */
27
- export function relationItemsForLinks(links: LinkedRecord[], onOpen: OpenRecordHandler | undefined): RelationItem[] {
28
- return links.map((link) => (link.record
29
- ? relationItemForRecord(link.record, link.analysis, onOpen, { identifier: link.canonicalPath })
30
- : { key: link.canonicalPath, label: link.canonicalPath, identifier: link.canonicalPath }));
30
+ export function relationItemsForLinks(
31
+ links: LinkedRecord[],
32
+ onOpen: OpenRecordHandler | undefined,
33
+ ): RelationItem[] {
34
+ return links.map((link) => {
35
+ const { record, analysis } = link;
36
+ if (!record) {
37
+ return { key: link.canonicalPath, label: link.canonicalPath, identifier: link.canonicalPath };
38
+ }
39
+ return relationItemForRecord(record, analysis, onOpen);
40
+ });
31
41
  }
@@ -1,6 +1,29 @@
1
+ /** Navigation state for record details: what a detail surface shows, and the stack that drives drill-down. */
1
2
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
3
  import type { ResolvedAnalysisNode, ResolvedRecord } from '@astra-spec/sdk';
3
- import { paperEntry, recordEntry, type DetailEntry } from './detail-entry.js';
4
+
5
+ /** What a detail surface is showing: a record, or a paper (optionally focused on an insight). */
6
+ export type DetailEntry =
7
+ | { kind: 'record'; canonicalPath: string; analysisPath: string }
8
+ | { kind: 'paper'; doi: string; analysisPath: string; focusInsightPath?: string | undefined };
9
+
10
+ export function recordEntry(canonicalPath: string, analysisPath: string): DetailEntry {
11
+ return { kind: 'record', canonicalPath, analysisPath };
12
+ }
13
+
14
+ export function paperEntry(doi: string, analysisPath: string, focusInsightPath?: string): DetailEntry {
15
+ return { kind: 'paper', doi, analysisPath, ...(focusInsightPath ? { focusInsightPath } : {}) };
16
+ }
17
+
18
+ export function sameEntry(left: DetailEntry, right: DetailEntry): boolean {
19
+ if (left.kind !== right.kind || left.analysisPath !== right.analysisPath) return false;
20
+ return left.kind === 'record'
21
+ ? left.canonicalPath === (right as Extract<DetailEntry, { kind: 'record' }>).canonicalPath
22
+ : left.doi === (right as Extract<DetailEntry, { kind: 'paper' }>).doi;
23
+ }
24
+
25
+ /** Opens a record, shown within the analysis that owns it; the shape every drill-down callback shares. */
26
+ export type OpenRecordHandler = (record: ResolvedRecord, analysis: ResolvedAnalysisNode) => void;
4
27
 
5
28
  export interface DetailStackOptions {
6
29
  /** Controlled stack; pair with `onChange`. */
@@ -0,0 +1,22 @@
1
+ /** Machinery behind the elements: class names, labels, navigation state, prose rendering, preview data, and the pdf.js contract. */
2
+ export { cn } from './cn.js';
3
+ export { LabelsProvider, defaultLabels, mergeLabels, useLabels } from './labels.js';
4
+ export type { AstraLabelOverrides, AstraLabels, LabelsProviderProps } from './labels.js';
5
+ export { paperEntry, recordEntry, sameEntry, useDetailStack } from './detail-stack.js';
6
+ export type { DetailEntry, DetailStack, DetailStackOptions, OpenRecordHandler } from './detail-stack.js';
7
+ export { parseProse, renderProse } from './prose.js';
8
+ export type { ProseContext, ProseField, ProseMathMacros, ProseRenderOptions, ProseToken, TextRenderer } from './prose.js';
9
+ export { metricPreviewFromJson, tablePreviewFromDelimited, tablePreviewFromRows } from './preview-data.js';
10
+ export type {
11
+ ArtifactPreviewData,
12
+ DelimitedPreviewOptions,
13
+ ImagePreviewData,
14
+ LoadingPreviewData,
15
+ MetricPreviewData,
16
+ TablePreviewData,
17
+ TextPreviewData,
18
+ UnavailablePreviewData,
19
+ } from './preview-data.js';
20
+ export { useOutputExpanded } from './use-output-expanded.js';
21
+ export { pdfJsWithWorker } from './pdf-runtime.js';
22
+ export type { PdfJs, PdfJsLoader, PdfJsWorkerModule } from './pdf-runtime.js';
@@ -44,6 +44,38 @@ export interface AstraLabels {
44
44
  openPaper: string;
45
45
  locate: string;
46
46
  };
47
+ /** PDF reading, evidence navigation, and accessible viewer controls. */
48
+ pdf: {
49
+ loading: string;
50
+ loadError: string;
51
+ unavailable: string;
52
+ searching: string;
53
+ quoteNotFound: string;
54
+ pages: string;
55
+ zoomIn: string;
56
+ zoomOut: string;
57
+ zoomLevel: (percent: number) => string;
58
+ viewer: (title: string) => string;
59
+ page: (page: number) => string;
60
+ pageError: (page: number) => string;
61
+ pageCount: (count: number) => string;
62
+ quoteHighlighted: (page: number, count: number) => string;
63
+ partialQuoteHighlighted: (page: number, count: number) => string;
64
+ citedPageFallback: (page: number, count: number) => string;
65
+ locatePassage: (passage: number) => string;
66
+ };
67
+ /** Copy used only by the compact RecordPreview surface. */
68
+ preview: {
69
+ optionDetail: string;
70
+ supportedBy: string;
71
+ evidence: string;
72
+ provenance: string;
73
+ source: string;
74
+ openRecord: (kindLabel: string, recordLabel: string) => string;
75
+ optionStatus: (selected: boolean, excluded: boolean) => string;
76
+ remainingDecisionDetails: (count: number) => string;
77
+ valueSource: (product: string) => string;
78
+ };
47
79
  }
48
80
 
49
81
  const SECTION_NOUNS: Record<keyof AstraLabels['sections'], [string, string]> = {
@@ -97,6 +129,39 @@ export const defaultLabels: AstraLabels = {
97
129
  openPaper: 'Open',
98
130
  locate: 'Locate',
99
131
  },
132
+ pdf: {
133
+ loading: 'Loading PDF…',
134
+ loadError: 'The PDF could not be loaded.',
135
+ unavailable: 'Embedded PDF viewing is unavailable. Open the PDF to read it.',
136
+ searching: 'Locating quote in the PDF…',
137
+ quoteNotFound: 'The quoted passage was not found in the PDF text.',
138
+ pages: 'PDF pages',
139
+ zoomIn: 'Zoom PDF in',
140
+ zoomOut: 'Zoom PDF out',
141
+ zoomLevel: (percent) => `${percent}%`,
142
+ viewer: (title) => `PDF viewer for ${title}`,
143
+ page: (page) => `Page ${page}`,
144
+ pageError: (page) => `Page ${page} could not be rendered.`,
145
+ pageCount: (count) => (count === 1 ? '1 page' : `${count} pages`),
146
+ quoteHighlighted: (page, count) => `Quote highlighted on page ${page} of ${count}`,
147
+ partialQuoteHighlighted: (page, count) => `Partial quote highlighted on page ${page} of ${count}`,
148
+ citedPageFallback: (page, count) => `Exact quote not found; showing cited page ${page} of ${count}`,
149
+ locatePassage: (passage) => `Locate source passage ${passage} in paper`,
150
+ },
151
+ preview: {
152
+ optionDetail: 'Option detail',
153
+ supportedBy: 'Supported by',
154
+ evidence: 'Evidence',
155
+ provenance: 'Provenance',
156
+ source: 'Source',
157
+ openRecord: (kindLabel, recordLabel) =>
158
+ `Open ${kindLabel.toLowerCase()} details: ${recordLabel}`,
159
+ optionStatus: (selected, excluded) =>
160
+ `${selected ? 'Selected.' : 'Not selected.'}${excluded ? ' Excluded.' : ''}`,
161
+ remainingDecisionDetails: (count) =>
162
+ `+ ${count} more in the decision details`,
163
+ valueSource: (product) => `from ${product}`,
164
+ },
100
165
  };
101
166
 
102
167
  /** Deep partial of the label set, for host overrides. */
@@ -122,6 +187,8 @@ function merge(base: AstraLabels, overrides: AstraLabelOverrides): AstraLabels {
122
187
  kinds: { ...base.kinds, ...defined(overrides.kinds ?? {}) },
123
188
  empty: { ...base.empty, ...defined(overrides.empty ?? {}) },
124
189
  actions: { ...base.actions, ...defined(overrides.actions ?? {}) },
190
+ pdf: { ...base.pdf, ...defined(overrides.pdf ?? {}) },
191
+ preview: { ...base.preview, ...defined(overrides.preview ?? {}) },
125
192
  } as AstraLabels;
126
193
  }
127
194
 
@@ -0,0 +1,189 @@
1
+ import type { PdfDocument, PdfTextContent } from './pdf-runtime.js';
2
+
3
+ /** A passage to locate in a PDF: its quoted text and/or the cited one-based physical page. */
4
+ export interface PdfPassage {
5
+ /** Distinguishes requests; repeat a passage under a new key to scroll to it again. */
6
+ key: string;
7
+ quote?: string | undefined;
8
+ page?: number | undefined;
9
+ }
10
+
11
+ /** The page a passage was found on; `match` is absent for a cited-page fallback. */
12
+ export interface PdfPassageLocation {
13
+ page: number;
14
+ match?: QuoteMatch | undefined;
15
+ }
16
+
17
+ interface MatchOrigin {
18
+ itemIndex: number;
19
+ rawStart: number;
20
+ rawEnd: number;
21
+ }
22
+
23
+ /** Where a quote sits in a page's text runs: offsets into the folded text, each mapped back to its raw run. */
24
+ export interface QuoteMatch {
25
+ origin: MatchOrigin[];
26
+ start: number;
27
+ length: number;
28
+ /** False when only a shortened prefix of the quote was found. */
29
+ complete: boolean;
30
+ }
31
+
32
+ /**
33
+ * Text content per page of one open document, shared by the text layers and
34
+ * passage search so each page is extracted once. There is no timeout: an
35
+ * extraction that never settles means the worker is gone, and rendering has
36
+ * stopped with it.
37
+ */
38
+ export type PdfTextCache = Map<number, Promise<PdfTextContent>>;
39
+
40
+ export function pageText(pdf: PdfDocument, page: number, cache: PdfTextCache): Promise<PdfTextContent> {
41
+ const cached = cache.get(page);
42
+ if (cached) return cached;
43
+ const attempt = pdf.getPage(page).then((value) => value.getTextContent());
44
+ cache.set(page, attempt);
45
+ // A failed extraction is forgotten so a later request can retry it.
46
+ void attempt.catch(() => cache.delete(page));
47
+ return attempt;
48
+ }
49
+
50
+ export function textStrings(content: PdfTextContent): string[] {
51
+ return content.items.flatMap((item) => (
52
+ typeof item === 'object' && item !== null && 'str' in item && typeof item.str === 'string'
53
+ ? [item.str]
54
+ : []
55
+ ));
56
+ }
57
+
58
+ const DASHES = '-‐‑‒–—―';
59
+ const SINGLE_QUOTES = '‘’‚‛';
60
+ const DOUBLE_QUOTES = '“”„‟';
61
+
62
+ /**
63
+ * The comparable form of one code point: compatibility forms (ligatures, full
64
+ * width) decompose; accents and other marks, dashes, whitespace and invisible
65
+ * format characters (soft hyphens, zero-width spaces and joiners, invisible
66
+ * operators) vanish; case folds. Extracted text then matches an authored quote
67
+ * whether the PDF kept, decomposed or lost its diacritics.
68
+ */
69
+ function fold(codePoint: string): string {
70
+ let folded = '';
71
+ for (const part of codePoint.normalize('NFKD')) {
72
+ if (/[\s\p{M}\p{Cf}]/u.test(part) || DASHES.includes(part)) continue;
73
+ folded += SINGLE_QUOTES.includes(part) ? "'" : DOUBLE_QUOTES.includes(part) ? '"' : part.toLowerCase();
74
+ }
75
+ return folded;
76
+ }
77
+
78
+ function foldWords(quote: string): string[] {
79
+ const words: string[] = [];
80
+ let word = '';
81
+ for (const codePoint of quote) {
82
+ if (/\s/u.test(codePoint)) {
83
+ if (word) words.push(word);
84
+ word = '';
85
+ } else {
86
+ word += fold(codePoint);
87
+ }
88
+ }
89
+ if (word) words.push(word);
90
+ return words;
91
+ }
92
+
93
+ /**
94
+ * Finds a quote in a page's text runs, keeping raw offsets for highlighting.
95
+ * The whole quote wins; otherwise the longest word prefix of at least 16
96
+ * characters is reported as a partial match.
97
+ */
98
+ export function findQuoteMatch(strings: string[], quote: string): QuoteMatch | undefined {
99
+ let flat = '';
100
+ const origin: MatchOrigin[] = [];
101
+ strings.forEach((raw, itemIndex) => {
102
+ let rawStart = 0;
103
+ for (const codePoint of raw) {
104
+ const rawEnd = rawStart + codePoint.length;
105
+ const folded = fold(codePoint);
106
+ flat += folded;
107
+ origin.push(...Array.from({ length: folded.length }, () => ({ itemIndex, rawStart, rawEnd })));
108
+ // A combining mark stays with its base, so a highlight boundary never splits the glyph.
109
+ const base = origin.at(-1);
110
+ if (!folded && base?.itemIndex === itemIndex && /\p{M}/u.test(codePoint)) base.rawEnd = rawEnd;
111
+ rawStart = rawEnd;
112
+ }
113
+ });
114
+
115
+ const words = foldWords(quote);
116
+ const full = words.join('');
117
+ if (!full) return undefined;
118
+ const probes = [full];
119
+ for (let count = words.length - 1; count > 0; count -= 1) {
120
+ const probe = words.slice(0, count).join('');
121
+ if (probe.length < 16) break;
122
+ probes.push(probe);
123
+ }
124
+ for (const probe of probes) {
125
+ const start = flat.indexOf(probe);
126
+ if (start !== -1) return { origin, start, length: probe.length, complete: probe === full };
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ /** Wraps the matched characters of a rendered text layer in `<mark>` elements and returns the first. */
132
+ export function highlightMatch(strings: string[], textDivs: HTMLElement[], match: QuoteMatch): HTMLElement | undefined {
133
+ const ranges = new Map<number, { rawStart: number; rawEnd: number }>();
134
+ for (let index = match.start; index < match.start + match.length; index += 1) {
135
+ const item = match.origin[index];
136
+ if (!item) continue;
137
+ const range = ranges.get(item.itemIndex);
138
+ if (range) {
139
+ range.rawStart = Math.min(range.rawStart, item.rawStart);
140
+ range.rawEnd = Math.max(range.rawEnd, item.rawEnd);
141
+ } else {
142
+ ranges.set(item.itemIndex, { rawStart: item.rawStart, rawEnd: item.rawEnd });
143
+ }
144
+ }
145
+ let first: HTMLElement | undefined;
146
+ for (const [itemIndex, range] of ranges) {
147
+ const textDiv = textDivs[itemIndex];
148
+ if (!textDiv) continue;
149
+ const raw = strings[itemIndex] ?? '';
150
+ const mark = document.createElement('mark');
151
+ mark.className = 'astra-paper-pdf__match';
152
+ mark.textContent = raw.slice(range.rawStart, range.rawEnd);
153
+ textDiv.replaceChildren(raw.slice(0, range.rawStart), mark, raw.slice(range.rawEnd));
154
+ first ??= mark;
155
+ }
156
+ return first;
157
+ }
158
+
159
+ /** Cited page first; a complete match anywhere outranks a partial one; a valid cited page is the last resort. */
160
+ export async function locateQuote(
161
+ pdf: PdfDocument,
162
+ passage: Pick<PdfPassage, 'quote' | 'page'>,
163
+ cache: PdfTextCache,
164
+ signal: AbortSignal,
165
+ ): Promise<PdfPassageLocation | undefined> {
166
+ const { quote, page: cited } = passage;
167
+ const fallback = cited !== undefined && Number.isInteger(cited) && cited >= 1 && cited <= pdf.numPages
168
+ ? { page: cited }
169
+ : undefined;
170
+ if (!quote) return fallback;
171
+ const order = [...new Set([
172
+ ...(fallback ? [fallback.page] : []),
173
+ ...Array.from({ length: pdf.numPages }, (_, index) => index + 1),
174
+ ])];
175
+ let partial: PdfPassageLocation | undefined;
176
+ for (const page of order) {
177
+ if (signal.aborted) return undefined;
178
+ try {
179
+ const strings = textStrings(await pageText(pdf, page, cache));
180
+ if (signal.aborted) return undefined;
181
+ const match = findQuoteMatch(strings, quote);
182
+ if (match?.complete) return { page, match };
183
+ if (match) partial ??= { page, match };
184
+ } catch {
185
+ // An unreadable page must not stop the search through the rest of the paper.
186
+ }
187
+ }
188
+ return partial ?? fallback;
189
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The pdf.js surface the viewer uses, as structural types. The `pdfjs-dist`
3
+ * module satisfies `PdfJs`: a host's `loadPdfJs` imports the module, points
4
+ * `GlobalWorkerOptions.workerSrc` at the matching worker script and returns
5
+ * the module. Nothing here imports pdf.js or React; the components layer
6
+ * re-exports what hosts need.
7
+ */
8
+
9
+ /** Always the object `getViewport()` returned; pdf.js reads more of it than these fields. Never construct one. */
10
+ export interface PdfViewport {
11
+ width: number;
12
+ height: number;
13
+ scale: number;
14
+ }
15
+
16
+ /** A `getTextContent()` result. Only `str` items are read; the object goes back to pdf.js unchanged. */
17
+ export interface PdfTextContent {
18
+ items: unknown[];
19
+ }
20
+
21
+ export interface PdfRenderTask {
22
+ promise: Promise<void>;
23
+ cancel(): void;
24
+ }
25
+
26
+ export interface PdfPage {
27
+ getViewport(options: { scale: number }): PdfViewport;
28
+ getTextContent(): Promise<PdfTextContent>;
29
+ render(options: {
30
+ canvasContext: CanvasRenderingContext2D;
31
+ viewport: PdfViewport;
32
+ transform?: number[] | undefined;
33
+ }): PdfRenderTask;
34
+ }
35
+
36
+ export interface PdfDocument {
37
+ numPages: number;
38
+ getPage(page: number): Promise<PdfPage>;
39
+ }
40
+
41
+ export interface PdfLoadingTask {
42
+ /** May stay pending forever once `destroy()` has been called; never await it after that. */
43
+ promise: Promise<PdfDocument>;
44
+ /** Aborts loading and releases the document together with the worker pdf.js started for it. */
45
+ destroy(): Promise<void>;
46
+ }
47
+
48
+ export interface PdfTextLayerOptions {
49
+ /** The `getTextContent()` result, passed back as pdf.js produced it. */
50
+ textContentSource: object;
51
+ container: HTMLElement;
52
+ viewport: PdfViewport;
53
+ }
54
+
55
+ /**
56
+ * pdf.js's `TextLayer`. An ambient class rather than a construct signature
57
+ * because TypeScript relates class constructor parameters bivariantly, which
58
+ * lets the real class (whose constructor takes pdf.js's own wider types)
59
+ * satisfy `PdfJs`. Only its types are exported: the class has no runtime
60
+ * binding.
61
+ */
62
+ declare class PdfTextLayerClass {
63
+ constructor(options: PdfTextLayerOptions);
64
+ readonly textDivs: HTMLElement[];
65
+ readonly textContentItemsStr: string[];
66
+ render(): Promise<void>;
67
+ cancel(): void;
68
+ }
69
+
70
+ export type PdfTextLayer = PdfTextLayerClass;
71
+ export type PdfTextLayerConstructor = typeof PdfTextLayerClass;
72
+
73
+ /** What `loadPdfJs` resolves to: the `pdfjs-dist` module, or anything shaped like it. */
74
+ export interface PdfJs {
75
+ getDocument(options: { url: string }): PdfLoadingTask;
76
+ TextLayer: PdfTextLayerConstructor;
77
+ }
78
+
79
+ /**
80
+ * Imports pdf.js in the browser and returns it with `GlobalWorkerOptions.workerSrc`
81
+ * set to the matching worker script; pdf.js then starts one worker per document
82
+ * and terminates it with the document. Import inside the callback so server
83
+ * rendering never touches browser APIs.
84
+ */
85
+ export type PdfJsLoader = () => Promise<PdfJs>;
86
+
87
+ /** The extra pdf.js exports `pdfJsWithWorker` needs. */
88
+ export interface PdfJsWorkerModule extends PdfJs {
89
+ /** pdf.js only accepts its own worker objects; the helper never inspects one. */
90
+ getDocument(options: { url: string; worker?: never }): PdfLoadingTask;
91
+ PDFWorker: { fromPort(params: { port: Worker }): { destroy(): void } };
92
+ }
93
+
94
+ /**
95
+ * For bundlers that emit a worker only through `new Worker(new URL(...))`:
96
+ * starts one worker per document with `createWorker`, lets it fail loading
97
+ * instead of hanging when the script cannot start, and terminates it when the
98
+ * viewer releases the document.
99
+ */
100
+ export function pdfJsWithWorker(pdfjs: PdfJsWorkerModule, createWorker: () => Worker): PdfJs {
101
+ return {
102
+ TextLayer: pdfjs.TextLayer,
103
+ getDocument(options) {
104
+ const port = createWorker();
105
+ const worker = pdfjs.PDFWorker.fromPort({ port });
106
+ let task: PdfLoadingTask;
107
+ try {
108
+ task = pdfjs.getDocument({ ...options, worker: worker as never });
109
+ } catch (error) {
110
+ // pdf.js rejects some options synchronously (an unparsable URL, say); the worker must not outlive that.
111
+ worker.destroy();
112
+ port.terminate();
113
+ throw error;
114
+ }
115
+ const startup = new Promise<never>((_, reject) => {
116
+ port.addEventListener('error', () => { reject(new Error('The PDF worker could not start.')); });
117
+ });
118
+ return {
119
+ promise: Promise.race([task.promise, startup]),
120
+ async destroy() {
121
+ try {
122
+ await task.destroy();
123
+ } finally {
124
+ worker.destroy();
125
+ port.terminate();
126
+ }
127
+ },
128
+ };
129
+ },
130
+ };
131
+ }
@@ -0,0 +1,155 @@
1
+ /** Host-safe artifact preview data, and pure builders (no I/O) hosts use to produce it from data they already loaded. */
2
+
3
+ export interface TablePreviewData {
4
+ kind: 'table';
5
+ headers: string[];
6
+ rows: (string | number | boolean | null)[][];
7
+ /** Exact number of rows in the source. Leave unset when the source was sampled and the total is unknown. */
8
+ totalRows?: number | undefined;
9
+ totalColumns?: number | undefined;
10
+ /** The preview does not show everything: rows or columns were cut, or the source itself was a sample. */
11
+ truncated?: boolean | undefined;
12
+ }
13
+
14
+ export interface ImagePreviewData {
15
+ kind: 'image';
16
+ url: string;
17
+ alt?: string | undefined;
18
+ width?: number | undefined;
19
+ height?: number | undefined;
20
+ }
21
+
22
+ export interface MetricPreviewData {
23
+ kind: 'metric';
24
+ value: number | string;
25
+ uncertainty?: number | string | undefined;
26
+ unit?: string | undefined;
27
+ label?: string | undefined;
28
+ }
29
+
30
+ export interface TextPreviewData {
31
+ kind: 'text';
32
+ text: string;
33
+ language?: string | undefined;
34
+ truncated?: boolean | undefined;
35
+ }
36
+
37
+ export interface LoadingPreviewData {
38
+ kind: 'loading';
39
+ message?: string | undefined;
40
+ }
41
+
42
+ export interface UnavailablePreviewData {
43
+ kind: 'unavailable';
44
+ reason?: string | undefined;
45
+ }
46
+
47
+ /** Host-safe data that a portable component can render without reading a file. */
48
+ export type ArtifactPreviewData =
49
+ | TablePreviewData
50
+ | ImagePreviewData
51
+ | MetricPreviewData
52
+ | TextPreviewData
53
+ | LoadingPreviewData
54
+ | UnavailablePreviewData;
55
+
56
+ export interface DelimitedPreviewOptions {
57
+ delimiter?: string | undefined;
58
+ maxRows?: number | undefined;
59
+ maxColumns?: number | undefined;
60
+ /** Set when the source text was itself cut short by the host. */
61
+ sourceTruncated?: boolean | undefined;
62
+ }
63
+
64
+ /** RFC 4180-style rows: quoted cells may hold delimiters, doubled quotes, and line breaks. Blank rows are dropped. */
65
+ function parseDelimited(text: string, delimiter: string): { rows: string[][]; unterminated: boolean } {
66
+ const rows: string[][] = [];
67
+ let row: string[] = [];
68
+ let cell = '';
69
+ let quoted = false;
70
+ const endCell = () => { row.push(cell.trim()); cell = ''; };
71
+ const endRow = () => {
72
+ endCell();
73
+ if (row.some((value) => value.length > 0)) rows.push(row);
74
+ row = [];
75
+ };
76
+ for (let index = 0; index < text.length; index += 1) {
77
+ const character = text.charAt(index);
78
+ if (quoted) {
79
+ if (character !== '"') cell += character;
80
+ else if (text.charAt(index + 1) === '"') { cell += '"'; index += 1; } else quoted = false;
81
+ } else if (character === '"') quoted = true;
82
+ else if (character === delimiter) endCell();
83
+ else if (character === '\n' || character === '\r') {
84
+ if (character === '\r' && text.charAt(index + 1) === '\n') index += 1;
85
+ endRow();
86
+ } else cell += character;
87
+ }
88
+ endRow();
89
+ return { rows, unterminated: quoted };
90
+ }
91
+
92
+ /** Turns delimited text (CSV, TSV) into table preview data. */
93
+ export function tablePreviewFromDelimited(text: string, options: DelimitedPreviewOptions = {}): TablePreviewData {
94
+ const delimiter = options.delimiter ?? ',';
95
+ const maxRows = options.maxRows ?? 30;
96
+ const maxColumns = options.maxColumns ?? 30;
97
+ const parsed = parseDelimited(text, delimiter);
98
+ const [allHeaders = [], ...records] = parsed.rows;
99
+ // A byte-limited sample may end inside a record (or inside a quoted cell);
100
+ // that record is dropped, and the total row count is unknown.
101
+ const sampled = Boolean(options.sourceTruncated);
102
+ const lastComplete = /\r?\n$/.test(text) && !parsed.unterminated;
103
+ const body = sampled && !lastComplete ? records.slice(0, -1) : records;
104
+ const headers = allHeaders.slice(0, maxColumns);
105
+ const rows = body.slice(0, maxRows).map((cells) => cells.slice(0, maxColumns));
106
+ return {
107
+ kind: 'table',
108
+ headers,
109
+ rows,
110
+ ...(sampled ? {} : { totalRows: body.length }),
111
+ totalColumns: allHeaders.length,
112
+ truncated: sampled || body.length > maxRows || allHeaders.length > maxColumns,
113
+ };
114
+ }
115
+
116
+ /** Turns an array of flat objects (e.g. parsed JSON records) into table preview data. */
117
+ export function tablePreviewFromRows(
118
+ records: readonly Record<string, unknown>[],
119
+ options: Pick<DelimitedPreviewOptions, 'maxRows' | 'maxColumns' | 'sourceTruncated'> = {},
120
+ ): TablePreviewData {
121
+ const maxRows = options.maxRows ?? 30;
122
+ const maxColumns = options.maxColumns ?? 30;
123
+ const allHeaders = [...new Set(records.flatMap((record) => Object.keys(record)))];
124
+ const headers = allHeaders.slice(0, maxColumns);
125
+ const rows = records.slice(0, maxRows).map((record) => headers.map((header) => {
126
+ const value = record[header];
127
+ if (value == null) return null;
128
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') return value;
129
+ return JSON.stringify(value);
130
+ }));
131
+ return {
132
+ kind: 'table',
133
+ headers,
134
+ rows,
135
+ totalRows: records.length,
136
+ totalColumns: allHeaders.length,
137
+ truncated: Boolean(options.sourceTruncated) || records.length > maxRows || allHeaders.length > maxColumns,
138
+ };
139
+ }
140
+
141
+ /** Reads a metric from a scalar or a `{ value, uncertainty?, unit?, label? }` object; `undefined` when the shape is not a metric. */
142
+ export function metricPreviewFromJson(value: unknown): MetricPreviewData | undefined {
143
+ if (typeof value === 'number' || typeof value === 'string') return { kind: 'metric', value };
144
+ if (value && typeof value === 'object' && 'value' in value) {
145
+ const record = value as Record<string, unknown>;
146
+ const metric = record.value;
147
+ if (typeof metric !== 'number' && typeof metric !== 'string') return undefined;
148
+ const result: MetricPreviewData = { kind: 'metric', value: metric };
149
+ if (typeof record.uncertainty === 'number' || typeof record.uncertainty === 'string') result.uncertainty = record.uncertainty;
150
+ if (typeof record.unit === 'string') result.unit = record.unit;
151
+ if (typeof record.label === 'string') result.label = record.label;
152
+ return result;
153
+ }
154
+ return undefined;
155
+ }