@open-document/core 0.11.0 → 0.13.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 (105) hide show
  1. package/dist/{build-BHFGY8eF.js → build-CbgIk6bA.js} +1 -1
  2. package/dist/{check-UEBmDfT_.js → check-BTroj-5Z.js} +3 -3
  3. package/dist/cli/bin.js +58 -34
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-B_pdNbYg.js → config-DKKNIbvO.js} +1458 -983
  6. package/dist/{context-BM9_-u9P.js → context-DXNP8v9I.js} +3 -2
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-DX3QMIRi.js → dev-YXumw5iX.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-DayvbXfX.js → diff-CTFfU4Tz.js} +2 -2
  11. package/dist/{export-BPsXj1i6.js → export-D2QLtF84.js} +11 -4
  12. package/dist/flow-CS5apebG.d.ts +252 -0
  13. package/dist/{import-71wlAsrd.js → import-CcmrFetU.js} +3 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +945 -104
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +112 -3
  18. package/dist/ops/index.js +3 -3
  19. package/dist/{ops-BUo67DaP.js → ops-DmEecq1k.js} +86 -164
  20. package/dist/package-version-C89gtYSk.js +36 -0
  21. package/dist/{preview-D3m1-gUL.js → preview-_mHpBhMk.js} +1 -1
  22. package/dist/templates-MMblHwmT.js +34 -0
  23. package/dist/vite/index.d.ts +1 -1
  24. package/dist/vite/index.js +2 -1
  25. package/package.json +2 -1
  26. package/skills/apply-comments/SKILL.md +3 -1
  27. package/skills/create-doc/SKILL.md +2 -0
  28. package/skills/doc-authoring/SKILL.md +17 -16
  29. package/skills/doc-authoring/references/long-form.md +43 -2
  30. package/skills/doc-authoring/references/pagination.md +14 -2
  31. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  32. package/src/app/components/browser/browser-ui.tsx +21 -0
  33. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  34. package/src/app/components/callout.tsx +101 -0
  35. package/src/app/components/changes/changes-overlay.tsx +68 -0
  36. package/src/app/components/changes/changes-panel.tsx +341 -0
  37. package/src/app/components/changes/use-changes.ts +85 -0
  38. package/src/app/components/chart.tsx +191 -33
  39. package/src/app/components/code-block.tsx +249 -0
  40. package/src/app/components/comments/comments-overlay.tsx +50 -0
  41. package/src/app/components/comments/comments-panel.tsx +272 -0
  42. package/src/app/components/comments/use-comments.ts +61 -0
  43. package/src/app/components/data-table.tsx +146 -18
  44. package/src/app/components/doc-sidebar.tsx +32 -2
  45. package/src/app/components/flow-page.tsx +57 -8
  46. package/src/app/components/inspector/field-source.tsx +41 -0
  47. package/src/app/components/inspector/inspector.tsx +64 -65
  48. package/src/app/components/numbering.tsx +226 -12
  49. package/src/app/components/overlay-frame.tsx +79 -0
  50. package/src/app/components/page-frame.tsx +46 -0
  51. package/src/app/components/page-placement.ts +68 -0
  52. package/src/app/components/record-picker.tsx +79 -0
  53. package/src/app/components/themes/theme-preview.tsx +5 -4
  54. package/src/app/lib/agent-bridge.ts +29 -1
  55. package/src/app/lib/chart.test.ts +15 -0
  56. package/src/app/lib/chart.ts +134 -9
  57. package/src/app/lib/diagnostics.ts +45 -1
  58. package/src/app/lib/docx/ooxml.test.ts +24 -1
  59. package/src/app/lib/docx/ooxml.ts +27 -1
  60. package/src/app/lib/export-docx.ts +3 -1
  61. package/src/app/lib/export-dom.ts +17 -3
  62. package/src/app/lib/export-html.ts +4 -2
  63. package/src/app/lib/export-image.ts +2 -1
  64. package/src/app/lib/export-pdf.ts +9 -1
  65. package/src/app/lib/flow-measure.test.ts +30 -0
  66. package/src/app/lib/flow-measure.ts +68 -14
  67. package/src/app/lib/flow.test.ts +20 -1
  68. package/src/app/lib/flow.ts +120 -20
  69. package/src/app/lib/i18n-ja/browser.ts +10 -0
  70. package/src/app/lib/i18n-ja/doc.ts +4 -0
  71. package/src/app/lib/i18n-ja/panels.ts +40 -0
  72. package/src/app/lib/i18n-ko/browser.ts +10 -0
  73. package/src/app/lib/i18n-ko/doc.ts +4 -0
  74. package/src/app/lib/i18n-ko/panels.ts +39 -0
  75. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  76. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  77. package/src/app/lib/i18n-zh-cn/panels.ts +38 -0
  78. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  79. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  80. package/src/app/lib/i18n-zh-tw/panels.ts +38 -0
  81. package/src/app/lib/labels.ts +29 -10
  82. package/src/app/lib/records.test.ts +38 -0
  83. package/src/app/lib/records.ts +127 -0
  84. package/src/app/lib/sdk.ts +35 -0
  85. package/src/app/lib/use-doc-module.ts +7 -0
  86. package/src/app/lib/use-doc-pages.ts +38 -17
  87. package/src/app/routes/doc.tsx +275 -13
  88. package/src/app/routes/home.tsx +30 -5
  89. package/src/app/styles.css +23 -0
  90. package/templates/blank/index.tsx +63 -0
  91. package/templates/blank/template.json +6 -0
  92. package/templates/certificate/data/recipients.csv +4 -0
  93. package/templates/certificate/index.tsx +128 -0
  94. package/templates/certificate/template.json +6 -0
  95. package/templates/letter/index.tsx +106 -0
  96. package/templates/letter/template.json +5 -0
  97. package/templates/meeting-notes/index.tsx +194 -0
  98. package/templates/meeting-notes/template.json +6 -0
  99. package/templates/proposal/index.tsx +264 -0
  100. package/templates/proposal/template.json +6 -0
  101. package/templates/report/data/metrics.csv +5 -0
  102. package/templates/report/index.tsx +224 -0
  103. package/templates/report/template.json +6 -0
  104. package/dist/config-P61niZMf.d.ts +0 -24
  105. package/dist/sdk-CpDEGRIo.d.ts +0 -138
@@ -0,0 +1,341 @@
1
+ import { ChevronDown, ChevronUp, CircleCheck, FileText, GitCompare, Undo2, X } from 'lucide-react';
2
+ import { type ReactNode, useState } from 'react';
3
+ import { useT } from '../../lib/i18n';
4
+ import { PanelIconButton, PanelShell } from '../panel/panel-shell';
5
+ import type { ChangeItem, ChangesState, Revision } from './use-changes';
6
+
7
+ /**
8
+ * A source line as a reader sees it: tags and braces off, so the words are
9
+ * what show. A line that is only markup reads as nothing and is left out.
10
+ */
11
+ function readable(line: string): string {
12
+ return line
13
+ .replace(/<\/?[A-Za-z][^>]*>/g, ' ')
14
+ .replace(/[{}]/g, '')
15
+ .replace(/\s+/g, ' ')
16
+ .trim();
17
+ }
18
+
19
+ const MAX_LINES = 3;
20
+
21
+ function Lines({
22
+ lines,
23
+ kind,
24
+ raw = false,
25
+ }: {
26
+ lines: string[];
27
+ kind: 'added' | 'removed';
28
+ /** Show the source as written — for a change that is markup only, with no words to show. */
29
+ raw?: boolean;
30
+ }) {
31
+ const shown = raw
32
+ ? lines.map((line) => line.trim()).filter(Boolean)
33
+ : lines.map(readable).filter(Boolean);
34
+ if (shown.length === 0) return null;
35
+ return (
36
+ <div className="flex flex-col gap-0.5">
37
+ {shown.slice(0, MAX_LINES).map((line, at) => (
38
+ <p
39
+ // biome-ignore lint/suspicious/noArrayIndexKey: lines are positional
40
+ key={at}
41
+ className={`line-clamp-2 break-words text-[11px] leading-snug ${raw ? 'font-mono' : ''} ${
42
+ kind === 'removed' ? 'text-muted-foreground line-through' : 'text-foreground'
43
+ }`}
44
+ style={{
45
+ textDecorationColor: kind === 'removed' ? 'var(--change-removed)' : undefined,
46
+ }}
47
+ >
48
+ <span
49
+ aria-hidden
50
+ className="mr-1 font-mono"
51
+ style={{ color: kind === 'removed' ? 'var(--change-removed)' : 'var(--change-added)' }}
52
+ >
53
+ {kind === 'removed' ? '−' : '+'}
54
+ </span>
55
+ {line}
56
+ </p>
57
+ ))}
58
+ {shown.length > MAX_LINES && (
59
+ <span className="pl-3 font-mono text-[10px] text-muted-foreground">
60
+ +{shown.length - MAX_LINES}
61
+ </span>
62
+ )}
63
+ </div>
64
+ );
65
+ }
66
+
67
+ function markColor(item: ChangeItem): string {
68
+ const { hunk } = item;
69
+ if (hunk.newLines === 0) return 'var(--change-removed)';
70
+ if (hunk.oldLines === 0) return 'var(--change-added)';
71
+ return 'var(--change-changed)';
72
+ }
73
+
74
+ function Item({
75
+ item,
76
+ active,
77
+ onSelect,
78
+ onRevert,
79
+ }: {
80
+ item: ChangeItem;
81
+ active: boolean;
82
+ onSelect: () => void;
83
+ onRevert: () => Promise<string | null>;
84
+ }) {
85
+ const t = useT();
86
+ const [busy, setBusy] = useState(false);
87
+ const [error, setError] = useState<string | null>(null);
88
+ const markupOnly = [...item.hunk.removed, ...item.hunk.added].every((line) => !readable(line));
89
+ return (
90
+ <li className="group relative">
91
+ <button
92
+ type="button"
93
+ aria-current={active || undefined}
94
+ onClick={onSelect}
95
+ className="flex w-full gap-2 rounded-md py-2 pr-9 pl-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-2 focus-visible:outline-foreground/60 aria-[current]:bg-accent"
96
+ >
97
+ <span
98
+ aria-hidden
99
+ className="w-0.5 flex-none self-stretch rounded-full"
100
+ style={{ background: markColor(item) }}
101
+ />
102
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
103
+ <Lines lines={item.hunk.removed} kind="removed" raw={markupOnly} />
104
+ <Lines lines={item.hunk.added} kind="added" raw={markupOnly} />
105
+ </span>
106
+ </button>
107
+ {item.file.status !== 'added' && (
108
+ <button
109
+ type="button"
110
+ aria-label={t('Revert this change')}
111
+ title={t('Revert this change')}
112
+ disabled={busy}
113
+ onClick={async () => {
114
+ setBusy(true);
115
+ setError(await onRevert());
116
+ setBusy(false);
117
+ }}
118
+ className="absolute top-1.5 right-1 flex size-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-foreground/60 disabled:opacity-50"
119
+ >
120
+ <Undo2 className="size-3.5" />
121
+ </button>
122
+ )}
123
+ {error && (
124
+ <p
125
+ role="alert"
126
+ className="px-3 pb-2 text-[11px]"
127
+ style={{ color: 'var(--change-removed)' }}
128
+ >
129
+ {t(error)}
130
+ </p>
131
+ )}
132
+ </li>
133
+ );
134
+ }
135
+
136
+ function Group({ title, children }: { title: ReactNode; children: ReactNode }) {
137
+ return (
138
+ <section className="border-border border-b px-2 py-2 last:border-b-0">
139
+ <h3 className="px-2 pb-1 font-mono text-[10px] text-muted-foreground uppercase tracking-wider">
140
+ {title}
141
+ </h3>
142
+ <ul className="flex flex-col">{children}</ul>
143
+ </section>
144
+ );
145
+ }
146
+
147
+ function Empty({ icon, children }: { icon: ReactNode; children: ReactNode }) {
148
+ return (
149
+ <div className="flex flex-col items-center gap-2 px-6 py-12 text-center text-muted-foreground text-xs">
150
+ {icon}
151
+ {children}
152
+ </div>
153
+ );
154
+ }
155
+
156
+ export type ChangesPanelProps = {
157
+ state: ChangesState;
158
+ items: ChangeItem[];
159
+ placement: Map<string, number[]>;
160
+ since: string;
161
+ revisions: Revision[];
162
+ activeId: string | null;
163
+ onSince: (since: string) => void;
164
+ onSelect: (item: ChangeItem) => void;
165
+ onRevert: (item: ChangeItem) => Promise<string | null>;
166
+ onClose: () => void;
167
+ };
168
+
169
+ /**
170
+ * What changed since a revision, in reading order, each change a way to its
171
+ * place on the page and a way back to how it was. The page carries the marks;
172
+ * this is their index.
173
+ */
174
+ export function ChangesPanel({
175
+ state,
176
+ items,
177
+ placement,
178
+ since,
179
+ revisions,
180
+ activeId,
181
+ onSince,
182
+ onSelect,
183
+ onRevert,
184
+ onClose,
185
+ }: ChangesPanelProps) {
186
+ const t = useT();
187
+ const result = state.status === 'ready' ? state.result : null;
188
+
189
+ const onPage = items
190
+ .filter((item) => (placement.get(item.hunk.id) ?? []).length > 0)
191
+ .sort(
192
+ (a, b) =>
193
+ (placement.get(a.hunk.id)?.[0] ?? 0) - (placement.get(b.hunk.id)?.[0] ?? 0) ||
194
+ a.hunk.newStart - b.hunk.newStart,
195
+ );
196
+ const elsewhere = items.filter((item) => !onPage.includes(item));
197
+ const binary = result?.available ? result.files.filter((file) => file.binary) : [];
198
+ const pages = [...new Set(onPage.map((item) => placement.get(item.hunk.id)?.[0] ?? 0))];
199
+
200
+ const at = onPage.findIndex((item) => item.hunk.id === activeId);
201
+ const step = (by: number) => {
202
+ if (onPage.length === 0) return;
203
+ const next = onPage[(at + by + onPage.length) % onPage.length];
204
+ if (next) onSelect(next);
205
+ };
206
+
207
+ return (
208
+ <PanelShell
209
+ label={t('Changes')}
210
+ header={
211
+ <>
212
+ <GitCompare aria-hidden className="size-3.5 flex-none text-muted-foreground" />
213
+ <span className="truncate font-medium text-xs">{t('Changes')}</span>
214
+ {items.length > 0 && (
215
+ <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground tabular-nums">
216
+ {items.length}
217
+ </span>
218
+ )}
219
+ </>
220
+ }
221
+ actions={
222
+ <>
223
+ {onPage.length > 1 && (
224
+ <>
225
+ <PanelIconButton label={t('Previous change')} onClick={() => step(-1)}>
226
+ <ChevronUp className="size-3.5" />
227
+ </PanelIconButton>
228
+ <PanelIconButton label={t('Next change')} onClick={() => step(at === -1 ? 0 : 1)}>
229
+ <ChevronDown className="size-3.5" />
230
+ </PanelIconButton>
231
+ </>
232
+ )}
233
+ <PanelIconButton label={t('Close')} onClick={onClose}>
234
+ <X className="size-3.5" />
235
+ </PanelIconButton>
236
+ </>
237
+ }
238
+ banner={
239
+ result?.available !== false && (
240
+ <div className="border-border border-b px-3 py-2">
241
+ <label className="relative flex h-8 items-center rounded border border-border focus-within:border-foreground/40">
242
+ <span className="pl-2 text-[11px] text-muted-foreground">{t('Since')}</span>
243
+ <select
244
+ aria-label={t('Compare with')}
245
+ value={since}
246
+ onChange={(e) => onSince(e.target.value)}
247
+ className="h-8 min-w-0 flex-1 cursor-pointer appearance-none truncate bg-transparent pr-7 pl-1.5 text-xs outline-none"
248
+ >
249
+ <option value="HEAD">{t('Last commit')}</option>
250
+ {revisions.map((revision) => (
251
+ <option key={revision.commit} value={revision.commit}>
252
+ {`${revision.short} · ${revision.subject} · ${revision.when}`}
253
+ </option>
254
+ ))}
255
+ </select>
256
+ <ChevronDown
257
+ aria-hidden
258
+ className="pointer-events-none absolute right-2 size-3.5 text-muted-foreground"
259
+ />
260
+ </label>
261
+ </div>
262
+ )
263
+ }
264
+ >
265
+ {state.status === 'loading' ? (
266
+ <div className="m-3 h-0.5 overflow-hidden rounded bg-muted">
267
+ <div className="h-full w-1/3 animate-pulse bg-foreground/20" />
268
+ </div>
269
+ ) : state.status === 'error' ? (
270
+ <Empty icon={<GitCompare className="size-5" />}>{state.error}</Empty>
271
+ ) : !state.result.available ? (
272
+ <Empty icon={<GitCompare className="size-5" />}>
273
+ {state.result.reason === 'no-git' ? (
274
+ t('git is not installed')
275
+ ) : (
276
+ <>
277
+ {t('Not a git repository')}
278
+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[11px]">git init</code>
279
+ </>
280
+ )}
281
+ </Empty>
282
+ ) : items.length === 0 && binary.length === 0 ? (
283
+ <Empty icon={<CircleCheck className="size-5" />}>{t('No changes')}</Empty>
284
+ ) : (
285
+ <>
286
+ {pages.map((page) => (
287
+ <Group key={page} title={t('Page {page}', { page })}>
288
+ {onPage
289
+ .filter((item) => placement.get(item.hunk.id)?.[0] === page)
290
+ .map((item) => (
291
+ <Item
292
+ key={item.hunk.id}
293
+ item={item}
294
+ active={item.hunk.id === activeId}
295
+ onSelect={() => onSelect(item)}
296
+ onRevert={() => onRevert(item)}
297
+ />
298
+ ))}
299
+ </Group>
300
+ ))}
301
+ {[...new Set(elsewhere.map((item) => item.file.path))].map((path) => (
302
+ <Group
303
+ key={path}
304
+ title={
305
+ <span className="flex items-center gap-1 normal-case tracking-normal">
306
+ <FileText aria-hidden className="size-3" />
307
+ {path}
308
+ </span>
309
+ }
310
+ >
311
+ {elsewhere
312
+ .filter((item) => item.file.path === path)
313
+ .map((item) => (
314
+ <Item
315
+ key={item.hunk.id}
316
+ item={item}
317
+ active={item.hunk.id === activeId}
318
+ onSelect={() => onSelect(item)}
319
+ onRevert={() => onRevert(item)}
320
+ />
321
+ ))}
322
+ </Group>
323
+ ))}
324
+ {binary.length > 0 && (
325
+ <Group title={t('Files')}>
326
+ {binary.map((file) => (
327
+ <li
328
+ key={file.path}
329
+ className="flex items-center gap-2 px-2 py-1.5 font-mono text-[11px] text-muted-foreground"
330
+ >
331
+ <FileText aria-hidden className="size-3" />
332
+ {file.path}
333
+ </li>
334
+ ))}
335
+ </Group>
336
+ )}
337
+ </>
338
+ )}
339
+ </PanelShell>
340
+ );
341
+ }
@@ -0,0 +1,85 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import type { ChangesResult, Revision } from '../../../ops/changes';
3
+ import type { FileChange, Hunk } from '../../../ops/changes-diff';
4
+
5
+ export type { FileChange, Hunk, Revision };
6
+
7
+ export type ChangesState =
8
+ | { status: 'loading' }
9
+ | { status: 'error'; error: string }
10
+ | { status: 'ready'; result: ChangesResult };
11
+
12
+ /** Every hunk, flattened, with the file it belongs to. */
13
+ export type ChangeItem = { file: FileChange; hunk: Hunk };
14
+
15
+ export function itemsOf(state: ChangesState): ChangeItem[] {
16
+ if (state.status !== 'ready' || !state.result.available) return [];
17
+ return state.result.files.flatMap((file) => file.hunks.map((hunk) => ({ file, hunk })));
18
+ }
19
+
20
+ /**
21
+ * The document's changes since a revision, read again whenever the document
22
+ * reloads — an agent writing the file, a revert, a save — so the marks follow
23
+ * the source without anyone asking.
24
+ */
25
+ export function useChanges(docId: string | undefined, reloadKey: unknown, enabled: boolean) {
26
+ const [since, setSince] = useState('HEAD');
27
+ const [state, setState] = useState<ChangesState>({ status: 'loading' });
28
+ const [revisions, setRevisions] = useState<Revision[]>([]);
29
+ const request = useRef(0);
30
+
31
+ const load = useCallback(async () => {
32
+ if (!docId || !enabled) return;
33
+ const id = ++request.current;
34
+ try {
35
+ const params = new URLSearchParams({ docId, since });
36
+ const res = await fetch(`/__changes?${params}`);
37
+ const body = (await res.json()) as ChangesResult & { error?: string };
38
+ if (id !== request.current) return;
39
+ setState(
40
+ res.ok ? { status: 'ready', result: body } : { status: 'error', error: body.error ?? '' },
41
+ );
42
+ } catch (err) {
43
+ if (id === request.current) setState({ status: 'error', error: String(err) });
44
+ }
45
+ }, [docId, since, enabled]);
46
+
47
+ useEffect(() => {
48
+ void reloadKey;
49
+ void load();
50
+ }, [load, reloadKey]);
51
+
52
+ useEffect(() => {
53
+ void reloadKey;
54
+ if (!docId || !enabled) return;
55
+ let cancelled = false;
56
+ fetch(`/__changes/revisions?${new URLSearchParams({ docId })}`)
57
+ .then((res) => res.json())
58
+ .then((body: { revisions?: Revision[] }) => {
59
+ if (!cancelled) setRevisions(body.revisions ?? []);
60
+ })
61
+ .catch(() => {});
62
+ return () => {
63
+ cancelled = true;
64
+ };
65
+ }, [docId, enabled, reloadKey]);
66
+
67
+ const revert = useCallback(
68
+ async (item: ChangeItem): Promise<string | null> => {
69
+ if (!docId) return null;
70
+ const res = await fetch('/__changes/revert', {
71
+ method: 'POST',
72
+ headers: { 'content-type': 'application/json' },
73
+ body: JSON.stringify({ docId, since, file: item.file.path, hunk: item.hunk.id }),
74
+ });
75
+ const body = (await res.json()) as { error?: string };
76
+ // The write reloads the document, which reads the changes again; a
77
+ // revert outside the document's own source reloads nothing, so ask.
78
+ void load();
79
+ return res.ok ? null : (body.error ?? 'revert failed');
80
+ },
81
+ [docId, since, load],
82
+ );
83
+
84
+ return { since, setSince, state, revisions, revert, reload: load };
85
+ }
@@ -114,26 +114,47 @@ export function Chart({
114
114
  }}
115
115
  className={caption ? undefined : className}
116
116
  >
117
- {chart.ticks.map((tick) => (
118
- <g key={tick.value}>
119
- <line
120
- x1={chart.plot.x}
121
- x2={chart.plot.x + chart.plot.width}
122
- y1={tick.at}
123
- y2={tick.at}
124
- style={{ stroke: RULE }}
125
- strokeWidth={1}
126
- />
127
- <text
128
- x={chart.plot.x - 6}
129
- y={tick.at + CHART_FONT_SIZE * 0.35}
130
- textAnchor="end"
131
- style={{ ...text, fill: MUTED }}
132
- >
133
- {tick.label}
134
- </text>
135
- </g>
136
- ))}
117
+ {chart.ticks.map((tick) =>
118
+ chart.horizontal ? (
119
+ <g key={tick.value}>
120
+ <line
121
+ x1={tick.at}
122
+ x2={tick.at}
123
+ y1={chart.plot.y}
124
+ y2={chart.plot.y + chart.plot.height}
125
+ style={{ stroke: RULE }}
126
+ strokeWidth={1}
127
+ />
128
+ <text
129
+ x={tick.at}
130
+ y={chart.plot.y + chart.plot.height + CHART_FONT_SIZE * 1.4}
131
+ textAnchor="middle"
132
+ style={{ ...text, fill: MUTED }}
133
+ >
134
+ {tick.label}
135
+ </text>
136
+ </g>
137
+ ) : (
138
+ <g key={tick.value}>
139
+ <line
140
+ x1={chart.plot.x}
141
+ x2={chart.plot.x + chart.plot.width}
142
+ y1={tick.at}
143
+ y2={tick.at}
144
+ style={{ stroke: RULE }}
145
+ strokeWidth={1}
146
+ />
147
+ <text
148
+ x={chart.plot.x - 6}
149
+ y={tick.at + CHART_FONT_SIZE * 0.35}
150
+ textAnchor="end"
151
+ style={{ ...text, fill: MUTED }}
152
+ >
153
+ {tick.label}
154
+ </text>
155
+ </g>
156
+ ),
157
+ )}
137
158
  {chart.bars.map((bar) => (
138
159
  <rect
139
160
  key={`${bar.series}-${bar.x}-${bar.y}`}
@@ -144,18 +165,38 @@ export function Chart({
144
165
  style={{ fill: colorOf(bar.series, colors) }}
145
166
  />
146
167
  ))}
147
- {chart.baseline !== null && chart.bars.length > 0 && (
148
- <line
149
- x1={chart.plot.x}
150
- x2={chart.plot.x + chart.plot.width}
151
- y1={chart.baseline}
152
- y2={chart.baseline}
153
- style={{ stroke: MUTED }}
154
- strokeWidth={1}
155
- />
156
- )}
168
+ {chart.baseline !== null &&
169
+ chart.bars.length > 0 &&
170
+ (chart.horizontal ? (
171
+ <line
172
+ x1={chart.baseline}
173
+ x2={chart.baseline}
174
+ y1={chart.plot.y}
175
+ y2={chart.plot.y + chart.plot.height}
176
+ style={{ stroke: MUTED }}
177
+ strokeWidth={1}
178
+ />
179
+ ) : (
180
+ <line
181
+ x1={chart.plot.x}
182
+ x2={chart.plot.x + chart.plot.width}
183
+ y1={chart.baseline}
184
+ y2={chart.baseline}
185
+ style={{ stroke: MUTED }}
186
+ strokeWidth={1}
187
+ />
188
+ ))}
157
189
  {chart.lines.map((line) => (
158
190
  <g key={line.series} style={{ stroke: colorOf(line.series, colors) }}>
191
+ {line.areaPath && (
192
+ <path
193
+ d={line.areaPath}
194
+ stroke="none"
195
+ style={{
196
+ fill: `color-mix(in srgb, ${colorOf(line.series, colors)} 20%, transparent)`,
197
+ }}
198
+ />
199
+ )}
159
200
  <polyline
160
201
  points={line.points.map((point) => `${point.x},${point.y}`).join(' ')}
161
202
  fill="none"
@@ -184,10 +225,10 @@ export function Chart({
184
225
  ))}
185
226
  {chart.categories.map((category) => (
186
227
  <text
187
- key={category.x}
228
+ key={`${category.x}-${category.y ?? 0}-${category.text}`}
188
229
  x={category.x}
189
- y={chart.plot.y + chart.plot.height + CHART_FONT_SIZE * 1.5}
190
- textAnchor="middle"
230
+ y={category.y ?? chart.plot.y + chart.plot.height + CHART_FONT_SIZE * 1.5}
231
+ textAnchor={chart.horizontal ? 'end' : 'middle'}
191
232
  style={{ ...text, fill: MUTED }}
192
233
  >
193
234
  {category.text}
@@ -237,3 +278,120 @@ export function Chart({
237
278
  </Figure>
238
279
  );
239
280
  }
281
+
282
+ export type SparklineProps = {
283
+ /** Numeric values to plot in order. */
284
+ data: number[];
285
+ /** Line with subtle fill, or compact inline bars. Defaults to 'line'. */
286
+ type?: 'line' | 'bar';
287
+ width?: number;
288
+ height?: number;
289
+ color?: string;
290
+ /** Highlight the final data point with a dot on line sparklines. Defaults to true. */
291
+ showEndDot?: boolean;
292
+ style?: CSSProperties;
293
+ className?: string;
294
+ };
295
+
296
+ /**
297
+ * A compact word-sized chart that sits inline inside a paragraph or table cell.
298
+ */
299
+ export function Sparkline({
300
+ data,
301
+ type = 'line',
302
+ width = 76,
303
+ height = 20,
304
+ color = ACCENT,
305
+ showEndDot = true,
306
+ style,
307
+ className,
308
+ }: SparklineProps) {
309
+ const nums = data.filter((v) => typeof v === 'number' && Number.isFinite(v));
310
+ if (nums.length === 0) return null;
311
+
312
+ const min = Math.min(...nums);
313
+ const max = Math.max(...nums);
314
+ const span = max - min || 1;
315
+ const pad = 2.5;
316
+ const w = Math.max(4, width - pad * 2);
317
+ const h = Math.max(4, height - pad * 2);
318
+
319
+ if (type === 'bar') {
320
+ const baseMin = Math.min(0, min);
321
+ const baseMax = Math.max(0, max) || 1;
322
+ const baseSpan = baseMax - baseMin || 1;
323
+ const step = w / nums.length;
324
+ const barW = Math.max(1.5, step * 0.72);
325
+ return (
326
+ <svg
327
+ viewBox={`0 0 ${width} ${height}`}
328
+ width={width}
329
+ height={height}
330
+ aria-hidden="true"
331
+ className={className}
332
+ style={{
333
+ display: 'inline-block',
334
+ verticalAlign: 'middle',
335
+ overflow: 'visible',
336
+ ...style,
337
+ }}
338
+ >
339
+ {nums.map((val, idx) => {
340
+ const bh = Math.max(1.5, (Math.abs(val) / baseSpan) * h);
341
+ const x = pad + idx * step + (step - barW) / 2;
342
+ const y = pad + h - bh;
343
+ return (
344
+ // biome-ignore lint/suspicious/noArrayIndexKey: index is data order
345
+ <rect key={idx} x={x} y={y} width={barW} height={bh} rx={1} style={{ fill: color }} />
346
+ );
347
+ })}
348
+ </svg>
349
+ );
350
+ }
351
+
352
+ const pts = nums.map((val, idx) => {
353
+ const x = pad + (nums.length === 1 ? w / 2 : (idx / (nums.length - 1)) * w);
354
+ const y = pad + h - ((val - min) / span) * h;
355
+ return { x: Math.round(x * 10) / 10, y: Math.round(y * 10) / 10 };
356
+ });
357
+ const poly = pts.map((p) => `${p.x},${p.y}`).join(' ');
358
+ const first = pts[0];
359
+ const last = pts[pts.length - 1];
360
+ const area =
361
+ pts.length >= 2 && first && last
362
+ ? `M${pts.map((p) => `${p.x},${p.y}`).join(' L')} L${last.x},${pad + h} L${first.x},${pad + h} Z`
363
+ : null;
364
+
365
+ return (
366
+ <svg
367
+ viewBox={`0 0 ${width} ${height}`}
368
+ width={width}
369
+ height={height}
370
+ aria-hidden="true"
371
+ className={className}
372
+ style={{
373
+ display: 'inline-block',
374
+ verticalAlign: 'middle',
375
+ overflow: 'visible',
376
+ ...style,
377
+ }}
378
+ >
379
+ {area && (
380
+ <path
381
+ d={area}
382
+ stroke="none"
383
+ style={{ fill: `color-mix(in srgb, ${color} 18%, transparent)` }}
384
+ />
385
+ )}
386
+ <polyline
387
+ points={poly}
388
+ fill="none"
389
+ strokeWidth={1.6}
390
+ strokeLinecap="round"
391
+ strokeLinejoin="round"
392
+ style={{ stroke: color }}
393
+ />
394
+ {showEndDot && last && <circle cx={last.x} cy={last.y} r={2.2} style={{ fill: color }} />}
395
+ </svg>
396
+ );
397
+ }