@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
@@ -67,7 +67,7 @@ Rules:
67
67
 
68
68
  ### Long tables
69
69
 
70
- Split by row groups across pages. Repeat the full header row and mark the continuation in the caption ("Table 3 (continued)"). Never let a header land on one page and its rows on the next.
70
+ Inside a `flow()` section, pass `splittable` to `<DataTable rows={…} splittable />` so the framework automatically slices rows across pages, repeats the `<thead>` header row, and marks the continuation in the caption ("Table 3 (continued)"). For hand-written `<table>` elements on fixed pages, split by row groups across pages and repeat the header row yourself. Never let a header land on one page and its rows on the next.
71
71
 
72
72
  ## Stat rows
73
73
 
@@ -106,13 +106,24 @@ import costs from './data/costs.csv';
106
106
  <Chart type="pie" data={services} x="service" y="cost" values caption="費用占比" />
107
107
  ```
108
108
 
109
- - `type`: `bar` (default), `line`, `pie`. `y` takes one key or several (one series each); a pie reads the first.
110
- - `stacked` stacks bar series instead of grouping them; `values` prints each value on its bar, point or slice.
111
- - `format`: `number`, `integer`, `percent`, or a function — the same vocabulary as `<DataTable>`.
109
+ - `type`: `'bar'` (default), `'horizontal-bar'`, `'line'`, `'area'`, `'pie'`. `y` takes one key or several (one series each); a pie reads the first.
110
+ - `stacked` stacks `bar`, `horizontal-bar`, or `area` series instead of grouping/overlapping them; `values` prints each value on its bar, point or slice.
111
+ - `format`: `'number'`, `'integer'`, `'percent'`, `'currency'`, `'delta'`, or a function — the same vocabulary as `<DataTable>`.
112
112
  - `width` / `height` are the drawn size in px (default 560 × 260); it scales down to the column.
113
113
  - It lays out synchronously into a fixed box, so it paginates like any block. In Word it arrives as a picture.
114
114
 
115
- Anything `<Chart>` doesn't draw — a sparkline in a stat row, an annotated timeline — write as **inline SVG** sized in absolute px:
115
+ ### Inline sparklines (`<Sparkline>`)
116
+
117
+ For compact trend lines or mini bar strips inside a `<DataTable>` cell, stat card, or prose paragraph, use **`<Sparkline>`**:
118
+
119
+ ```tsx
120
+ import { Sparkline } from '@open-document/core';
121
+
122
+ <Sparkline data={[38, 42, 40, 49, 55, 61]} type="area" width={88} height={22} showEndDot />
123
+ <Sparkline data={[12, 18, 15, 24, 29]} type="bar" width={72} height={20} />
124
+ ```
125
+
126
+ Anything `<Chart>` or `<Sparkline>` doesn't draw — an annotated timeline or bespoke diagram — write as **inline SVG** sized in absolute px:
116
127
 
117
128
  ```tsx
118
129
  const Bars = () => {
@@ -158,21 +169,14 @@ Rules:
158
169
 
159
170
  ## Callouts
160
171
 
161
- One box style, used sparingly (at most one or two per page):
172
+ Use the built-in **`<Callout>`** primitive (`type`: `'note' | 'tip' | 'warning' | 'danger'`, default `'note'`) sparingly — at most one or two per page:
162
173
 
163
174
  ```tsx
164
- <div
165
- style={{
166
- borderLeft: '3px solid var(--od-accent)',
167
- background: '#f8fafc',
168
- padding: '12px 14px',
169
- borderRadius: 'var(--od-radius)',
170
- fontSize: 12,
171
- }}
172
- >
173
- <strong style={{ display: 'block', marginBottom: 4 }}>Recommendation</strong>
175
+ import { Callout } from '@open-document/core';
176
+
177
+ <Callout type="warning" title="Recommendation">
174
178
  Move the checkout queue to its own cluster before the November peak.
175
- </div>
179
+ </Callout>
176
180
  ```
177
181
 
178
182
  Reserve callouts for recommendations, risks, and definitions. A page where everything is boxed emphasizes nothing.
@@ -19,6 +19,27 @@ export const CARD_GRID =
19
19
  * card has to know how wide its column came out. Starts at the narrowest width
20
20
  * so the first paint already has the right shape.
21
21
  */
22
+ /** Every card's preview box: a portrait A4, the sheet most documents print on. */
23
+ const FRAME_RATIO = 297 / 210;
24
+
25
+ /**
26
+ * How a sheet sits in a card's preview box. The box is the same for every
27
+ * card, so titles line up along a row; the sheet is scaled to fit inside it
28
+ * whole and centred — a landscape page is letterboxed on the canvas colour,
29
+ * never cropped, since a preview that hides part of the page misreports it.
30
+ */
31
+ export function fitInCard(
32
+ cardWidth: number,
33
+ sheet: { width: number; height: number },
34
+ ): { frameHeight: number; scale: number } {
35
+ const frameHeight = cardWidth * FRAME_RATIO;
36
+ const scale =
37
+ sheet.width > 0 && sheet.height > 0
38
+ ? Math.min(cardWidth / sheet.width, frameHeight / sheet.height)
39
+ : 0;
40
+ return { frameHeight, scale };
41
+ }
42
+
22
43
  export function useCardWidth<T extends HTMLElement>(): [RefObject<T>, number] {
23
44
  const ref = useRef<T>(null);
24
45
  const [width, setWidth] = useState(CARD_WIDTH);
@@ -0,0 +1,208 @@
1
+ import {
2
+ Award,
3
+ FileText,
4
+ type LucideIcon,
5
+ Mail,
6
+ NotebookPen,
7
+ Presentation,
8
+ Square,
9
+ Users,
10
+ X,
11
+ } from 'lucide-react';
12
+ import { type FormEvent, useEffect, useRef, useState } from 'react';
13
+ import { useNavigate } from 'react-router-dom';
14
+ import type { TemplateSummary } from '../../../ops/templates';
15
+ import { useT } from '../../lib/i18n';
16
+
17
+ const ICONS: Record<string, LucideIcon> = {
18
+ blank: Square,
19
+ report: FileText,
20
+ proposal: Presentation,
21
+ 'meeting-notes': Users,
22
+ letter: Mail,
23
+ certificate: Award,
24
+ };
25
+
26
+ const iconOf = (template: TemplateSummary) => ICONS[template.name] ?? NotebookPen;
27
+
28
+ /**
29
+ * Starting a document: the templates as cards, each with the name the CLI and
30
+ * an agent use for it, and a title. A native modal dialog, so focus is trapped
31
+ * while it is open and goes back to the button that opened it.
32
+ */
33
+ export function NewDocumentDialog({
34
+ open,
35
+ folderId,
36
+ onClose,
37
+ }: {
38
+ open: boolean;
39
+ /** The folder being viewed, which the new document is filed into. */
40
+ folderId: string | null;
41
+ onClose: () => void;
42
+ }) {
43
+ const t = useT();
44
+ const navigate = useNavigate();
45
+ const dialogRef = useRef<HTMLDialogElement>(null);
46
+ const [templates, setTemplates] = useState<TemplateSummary[] | null>(null);
47
+ const [chosen, setChosen] = useState('blank');
48
+ const [title, setTitle] = useState('');
49
+ const [busy, setBusy] = useState(false);
50
+ const [error, setError] = useState<string | null>(null);
51
+
52
+ useEffect(() => {
53
+ const dialog = dialogRef.current;
54
+ if (!dialog) return;
55
+ if (open && !dialog.open) dialog.showModal();
56
+ if (!open && dialog.open) dialog.close();
57
+ }, [open]);
58
+
59
+ useEffect(() => {
60
+ if (!open) return;
61
+ setError(null);
62
+ setTitle('');
63
+ let cancelled = false;
64
+ fetch('/__templates')
65
+ .then((res) => res.json())
66
+ .then((body: { templates?: TemplateSummary[] }) => {
67
+ if (cancelled) return;
68
+ const list = body.templates ?? [];
69
+ setTemplates(list);
70
+ setChosen((current) =>
71
+ list.some((entry) => entry.name === current) ? current : (list[0]?.name ?? 'blank'),
72
+ );
73
+ })
74
+ .catch(() => {
75
+ if (!cancelled) setTemplates([]);
76
+ });
77
+ return () => {
78
+ cancelled = true;
79
+ };
80
+ }, [open]);
81
+
82
+ const create = async (event: FormEvent) => {
83
+ event.preventDefault();
84
+ if (busy) return;
85
+ setBusy(true);
86
+ setError(null);
87
+ try {
88
+ const res = await fetch(`/__templates/${encodeURIComponent(chosen)}/create`, {
89
+ method: 'POST',
90
+ headers: { 'content-type': 'application/json' },
91
+ body: JSON.stringify({
92
+ ...(title.trim() ? { title: title.trim() } : {}),
93
+ ...(folderId ? { folderId } : {}),
94
+ }),
95
+ });
96
+ const body = (await res.json()) as { docId?: string; error?: string };
97
+ if (!res.ok || !body.docId) {
98
+ setError(body.error ?? t('Could not create the document'));
99
+ return;
100
+ }
101
+ onClose();
102
+ navigate(`/d/${body.docId}`);
103
+ } catch {
104
+ setError(t('Could not create the document'));
105
+ } finally {
106
+ setBusy(false);
107
+ }
108
+ };
109
+
110
+ const selected = templates?.find((entry) => entry.name === chosen);
111
+
112
+ return (
113
+ <dialog
114
+ ref={dialogRef}
115
+ aria-labelledby="new-document-title"
116
+ onClose={onClose}
117
+ onCancel={onClose}
118
+ className="m-auto w-[min(720px,calc(100vw-32px))] rounded-xl border border-border bg-background p-0 text-foreground shadow-2xl backdrop:bg-black/40"
119
+ >
120
+ <form onSubmit={create} className="flex max-h-[min(640px,calc(100vh-64px))] flex-col">
121
+ <header className="flex h-12 flex-none items-center justify-between border-border border-b px-4">
122
+ <h2 id="new-document-title" className="font-medium text-sm">
123
+ {t('New document')}
124
+ </h2>
125
+ <button
126
+ type="button"
127
+ aria-label={t('Close')}
128
+ onClick={onClose}
129
+ className="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"
130
+ >
131
+ <X className="size-4" />
132
+ </button>
133
+ </header>
134
+
135
+ <fieldset className="m-0 min-h-0 flex-1 overflow-y-auto border-0 p-4">
136
+ <legend className="sr-only">{t('Template')}</legend>
137
+ {templates === null ? (
138
+ <div className="h-0.5 overflow-hidden rounded bg-muted">
139
+ <div className="h-full w-1/3 animate-pulse bg-foreground/20" />
140
+ </div>
141
+ ) : (
142
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2">
143
+ {templates.map((template) => {
144
+ const Icon = iconOf(template);
145
+ return (
146
+ <label
147
+ key={template.name}
148
+ className="flex cursor-pointer flex-col gap-1.5 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50 has-[:checked]:border-foreground/60 has-[:checked]:bg-accent has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-foreground/60"
149
+ >
150
+ <input
151
+ type="radio"
152
+ name="template"
153
+ value={template.name}
154
+ checked={chosen === template.name}
155
+ onChange={() => setChosen(template.name)}
156
+ className="sr-only"
157
+ />
158
+ <span className="flex items-center gap-2">
159
+ <Icon aria-hidden className="size-4 text-muted-foreground" />
160
+ <span className="flex-1 font-medium text-xs">{t(template.title)}</span>
161
+ {template.source === 'workspace' && (
162
+ <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
163
+ {t('This workspace')}
164
+ </span>
165
+ )}
166
+ </span>
167
+ <span className="line-clamp-2 text-[11px] text-muted-foreground leading-snug">
168
+ {template.description}
169
+ </span>
170
+ <code className="font-mono text-[10px] text-muted-foreground/80">
171
+ {template.name}
172
+ </code>
173
+ </label>
174
+ );
175
+ })}
176
+ </div>
177
+ )}
178
+ </fieldset>
179
+
180
+ <footer className="flex flex-none flex-col gap-2 border-border border-t p-4">
181
+ <div className="flex items-center gap-2">
182
+ <input
183
+ autoFocus
184
+ type="text"
185
+ value={title}
186
+ onChange={(event) => setTitle(event.target.value)}
187
+ placeholder={selected ? t(selected.title) : t('Title')}
188
+ aria-label={t('Title')}
189
+ className="h-9 min-w-0 flex-1 rounded-md border border-border bg-transparent px-3 text-sm outline-none focus:border-foreground/40"
190
+ />
191
+ <button
192
+ type="submit"
193
+ disabled={busy || templates === null}
194
+ className="h-9 rounded-md bg-primary px-4 text-primary-foreground text-sm transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground/60 disabled:opacity-60"
195
+ >
196
+ {t('Create')}
197
+ </button>
198
+ </div>
199
+ {error && (
200
+ <p role="alert" className="text-xs" style={{ color: 'var(--change-removed)' }}>
201
+ {error}
202
+ </p>
203
+ )}
204
+ </footer>
205
+ </form>
206
+ </dialog>
207
+ );
208
+ }
@@ -0,0 +1,101 @@
1
+ import type { CSSProperties, ReactNode } from 'react';
2
+ import { LOC_PROP, sourceAttrs } from '../lib/source-loc';
3
+
4
+ export type CalloutVariant = 'info' | 'tip' | 'warning' | 'danger' | 'neutral';
5
+
6
+ export type CalloutProps = {
7
+ variant?: CalloutVariant;
8
+ title?: ReactNode;
9
+ children?: ReactNode;
10
+ style?: CSSProperties;
11
+ className?: string;
12
+ [LOC_PROP]?: string;
13
+ };
14
+
15
+ const PALETTES: Record<
16
+ CalloutVariant,
17
+ { border: string; bg: string; badge: string; label: string }
18
+ > = {
19
+ info: {
20
+ border: 'var(--od-accent, #2563eb)',
21
+ bg: 'color-mix(in srgb, var(--od-accent, #2563eb) 7%, var(--od-bg, #ffffff))',
22
+ badge: 'var(--od-accent, #2563eb)',
23
+ label: 'NOTE',
24
+ },
25
+ tip: {
26
+ border: '#15803d',
27
+ bg: 'color-mix(in srgb, #15803d 7%, var(--od-bg, #ffffff))',
28
+ badge: '#15803d',
29
+ label: 'TIP',
30
+ },
31
+ warning: {
32
+ border: '#b45309',
33
+ bg: 'color-mix(in srgb, #d97706 8%, var(--od-bg, #ffffff))',
34
+ badge: '#b45309',
35
+ label: 'WARNING',
36
+ },
37
+ danger: {
38
+ border: '#b91c1c',
39
+ bg: 'color-mix(in srgb, #dc2626 7%, var(--od-bg, #ffffff))',
40
+ badge: '#b91c1c',
41
+ label: 'CRITICAL',
42
+ },
43
+ neutral: {
44
+ border: 'var(--od-muted, #6b7280)',
45
+ bg: 'color-mix(in srgb, var(--od-text, #16181d) 4%, var(--od-bg, #ffffff))',
46
+ badge: 'var(--od-muted, #6b7280)',
47
+ label: 'SUMMARY',
48
+ },
49
+ };
50
+
51
+ /**
52
+ * A structured admonition box (`info`, `tip`, `warning`, `danger`, `neutral`)
53
+ * rendered as a `<blockquote data-od-callout>` so Word and PDF exporters keep
54
+ * its panel border and shading intact.
55
+ */
56
+ export function Callout({
57
+ variant = 'info',
58
+ title,
59
+ children,
60
+ style,
61
+ className,
62
+ [LOC_PROP]: loc,
63
+ }: CalloutProps) {
64
+ const palette = PALETTES[variant] ?? PALETTES.info;
65
+
66
+ return (
67
+ <blockquote
68
+ {...sourceAttrs(loc)}
69
+ data-od-callout={variant}
70
+ className={className}
71
+ style={{
72
+ margin: '4px 0 12px',
73
+ padding: '10px 14px',
74
+ borderLeft: `3px solid ${palette.border}`,
75
+ background: palette.bg,
76
+ borderRadius: '0 var(--od-radius, 4px) var(--od-radius, 4px) 0',
77
+ color: 'var(--od-text, #16181d)',
78
+ fontStyle: 'normal',
79
+ fontSize: '0.95em',
80
+ lineHeight: 1.55,
81
+ ...style,
82
+ }}
83
+ >
84
+ {title !== undefined && (
85
+ <div
86
+ style={{
87
+ fontFamily: 'var(--od-font-heading, sans-serif)',
88
+ fontWeight: 650,
89
+ fontSize: '0.92em',
90
+ color: palette.badge,
91
+ marginBottom: 4,
92
+ letterSpacing: '0.01em',
93
+ }}
94
+ >
95
+ {typeof title === 'string' ? <span {...sourceAttrs(loc, 'title')}>{title}</span> : title}
96
+ </div>
97
+ )}
98
+ <div>{children}</div>
99
+ </blockquote>
100
+ );
101
+ }
@@ -0,0 +1,68 @@
1
+ import type { CSSProperties } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import type { ChangeMark } from '../../../ops/changes-diff';
4
+ import { OverlayFrame } from '../overlay-frame';
5
+ import { elementsAtLoc } from '../page-placement';
6
+ import type { ChangeItem } from './use-changes';
7
+
8
+ /** Every element on the page that one change touches, with how it is marked. */
9
+ export function elementsOf(
10
+ container: ParentNode,
11
+ item: ChangeItem,
12
+ ): Array<{ el: HTMLElement; mark: ChangeMark }> {
13
+ return item.hunk.targets.flatMap((target) =>
14
+ elementsAtLoc(container, target.loc).map((el) => ({ el, mark: target.mark })),
15
+ );
16
+ }
17
+
18
+ const COLOR: Record<ChangeMark, string> = {
19
+ added: 'var(--change-added)',
20
+ changed: 'var(--change-changed)',
21
+ 'removed-before': 'var(--change-removed)',
22
+ 'removed-after': 'var(--change-removed)',
23
+ };
24
+
25
+ function markStyle(mark: ChangeMark, active: boolean): CSSProperties {
26
+ const color = COLOR[mark];
27
+ // Something taken out has no box of its own: a bar where it used to be.
28
+ if (mark === 'removed-before' || mark === 'removed-after') {
29
+ return {
30
+ [mark === 'removed-before' ? 'borderTop' : 'borderBottom']:
31
+ `${active ? 3 : 2}px dashed ${color}`,
32
+ transform: `translateY(${mark === 'removed-before' ? -5 : 5}px)`,
33
+ };
34
+ }
35
+ return {
36
+ outline: `${active ? 2 : 1.5}px solid ${color}`,
37
+ outlineOffset: active ? 3 : 2,
38
+ background: `color-mix(in oklch, ${color} ${active ? 14 : 8}%, transparent)`,
39
+ };
40
+ }
41
+
42
+ /** The changes drawn onto the sheets: a box for what is new or rewritten, a bar where something went. */
43
+ export function ChangesOverlay({
44
+ container,
45
+ items,
46
+ activeId,
47
+ }: {
48
+ container: HTMLElement;
49
+ items: ChangeItem[];
50
+ activeId: string | null;
51
+ }) {
52
+ return createPortal(
53
+ <div aria-hidden className="pointer-events-none absolute inset-0 z-20">
54
+ {items.flatMap((item) =>
55
+ elementsOf(container, item).map(({ el, mark }, at) => (
56
+ <OverlayFrame
57
+ // biome-ignore lint/suspicious/noArrayIndexKey: one hunk can print the same loc twice
58
+ key={`${item.hunk.id}:${at}`}
59
+ anchor={el}
60
+ container={container}
61
+ style={markStyle(mark, item.hunk.id === activeId)}
62
+ />
63
+ )),
64
+ )}
65
+ </div>,
66
+ container,
67
+ );
68
+ }