@dudousxd/nestjs-catalog-react 0.16.0 → 0.17.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.
@@ -1,14 +1,17 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { CATALOG_REVISION_LIMIT } from '@dudousxd/nestjs-catalog/client';
3
+ import { parseDiffFromFile } from '@pierre/diffs';
4
+ import { MultiFileDiff } from '@pierre/diffs/react';
3
5
  import { useQuery } from '@tanstack/react-query';
4
6
  import { GitCompare, History } from 'lucide-react';
5
7
  import { useMemo, useState } from 'react';
6
8
  import { cn } from '../cn';
7
9
  import { catalogQueryKeys, useCatalogClient } from '../context';
8
10
  import { Button } from '../ui/button';
11
+ import { codeOptions } from '../ui/code-editor';
12
+ import { useCodeThemeType } from '../ui/code-theme';
9
13
  import { SelectField } from '../ui/select';
10
14
  import { Sheet } from '../ui/sheet';
11
- import { diffLines, foldUnchanged } from './line-diff';
12
15
  /**
13
16
  * Why a load came out different from the last one.
14
17
  *
@@ -47,29 +50,11 @@ import { diffLines, foldUnchanged } from './line-diff';
47
50
  const MUTED = 'text-zinc-400 dark:text-zinc-500';
48
51
  const RULE = 'border-zinc-200 dark:border-zinc-800';
49
52
  const PANEL = 'bg-white dark:bg-zinc-900';
50
- /**
51
- * How many diff rows are painted before the rest go behind a control.
52
- *
53
- * The same number `QueryConsole` caps a result set at, and for the same reason:
54
- * past a few hundred rows a browser is painting a wall nobody reads, and the
55
- * screen appears frozen — which is its own kind of dishonesty about what is
56
- * happening. The remaining rows are one click away and the control says how many
57
- * there are.
58
- *
59
- * WHY THIS IS NOT `capLines`, and it is worth being precise. `capLines` in the
60
- * pipeline package bounds both axes — lines AND characters within a line — of
61
- * text on its way into a durable checkpoint and a run row, because an unbounded
62
- * string there makes the size of a write a property of somebody's source data.
63
- * Neither half of that argument reaches here. The bodies have already been
64
- * fetched whole, so nothing is saved by rendering fewer, and — this is the part
65
- * that matters — a character cap would be actively WRONG: two lines that differ
66
- * only past the cap would be truncated into equality and the diff would report
67
- * them as unchanged. A diff view must never compare anything but the whole line.
68
- * So long lines wrap, exactly as they do in the code editor, and the only cap is
69
- * on rows.
70
- */
71
- const DIFF_MAX_ROWS = 500;
72
- export function RevisionHistory({ subject, current, ranVersion }) {
53
+ /** What a side is picked by. Versions are numbers and the buffer is not. */
54
+ function keyOf(side) {
55
+ return side.origin === 'buffer' ? 'buffer' : String(side.version);
56
+ }
57
+ export function RevisionHistory({ subject, current, buffer, ranVersion }) {
73
58
  const client = useCatalogClient();
74
59
  const revisions = useQuery({
75
60
  queryKey: subject.kind === 'transform'
@@ -79,20 +64,26 @@ export function RevisionHistory({ subject, current, ranVersion }) {
79
64
  ? client.listTransformRevisions(subject.id)
80
65
  : client.listSavedQueryRevisions(subject.id),
81
66
  });
82
- const sides = useMemo(() => sidesFrom(revisions.data ?? [], current), [revisions.data, current]);
67
+ const sides = useMemo(() => sidesFrom(revisions.data ?? [], current, buffer), [revisions.data, current, buffer]);
83
68
  /**
84
- * Which two are on screen, as VERSION NUMBERS rather than indices.
69
+ * Which two are on screen, as SIDE KEYS rather than indices.
85
70
  *
86
71
  * `null` means "whatever the default is", so a background refetch that adds a
87
72
  * newer revision moves the right-hand side onto it — which is what somebody
88
73
  * who has not touched the selects expects. Storing an index instead would
89
74
  * silently repoint both sides at different versions when the list grew, and an
90
75
  * index is not a thing anybody chose.
76
+ *
77
+ * A key rather than a version number because the buffer has no version, and a
78
+ * `number | null` state could not tell "the unsaved buffer" apart from "no
79
+ * choice made yet".
91
80
  */
92
- const [leftVersion, setLeftVersion] = useState(null);
93
- const [rightVersion, setRightVersion] = useState(null);
94
- const right = pick(sides, rightVersion) ?? sides[0];
95
- const left = pick(sides, leftVersion) ?? pick(sides, ranVersion ?? null) ?? sides[1];
81
+ const [leftKey, setLeftKey] = useState(null);
82
+ const [rightKey, setRightKey] = useState(null);
83
+ const right = pick(sides, rightKey) ?? sides[0];
84
+ const left = pick(sides, leftKey) ??
85
+ pick(sides, ranVersion === undefined ? null : String(ranVersion)) ??
86
+ sides[1];
96
87
  if (revisions.isPending) {
97
88
  return _jsx(Notice, { children: "Reading the history\u2026" });
98
89
  }
@@ -105,7 +96,7 @@ export function RevisionHistory({ subject, current, ranVersion }) {
105
96
  if (sides.length === 1 || !left || !right) {
106
97
  return _jsx(OnlyOneVersion, { subject: subject, only: sides[0] });
107
98
  }
108
- return (_jsxs("div", { className: "space-y-3", children: [ranVersion !== undefined && !sides.some((side) => side.version === ranVersion) && (_jsxs(Notice, { tone: "warn", children: ["This load ran ", _jsxs("span", { className: "font-mono", children: ["v", ranVersion] }), ", which the recorded history does not contain \u2014 it predates this catalog keeping revisions, or it has been pushed out by the ", CATALOG_REVISION_LIMIT, " newer ones that are kept. Nothing below is the", ' ', body(subject.kind), " that produced that load."] })), _jsxs("div", { className: "flex flex-wrap items-end gap-2", children: [_jsx(SidePicker, { label: "Compare", ariaLabel: "Compare version", sides: sides, value: left.version, onChange: setLeftVersion }), _jsx("span", { className: cn('pb-1.5 font-mono text-[11px]', MUTED), children: "\u2192" }), _jsx(SidePicker, { label: "Against", ariaLabel: "Against version", sides: sides, value: right.version, onChange: setRightVersion })] }), _jsx(Authorship, { left: left, right: right }), _jsx(DiffBody, { before: left.body, after: right.body })] }));
99
+ return (_jsxs("div", { className: "space-y-3", children: [ranVersion !== undefined && !sides.some((side) => side.version === ranVersion) && (_jsxs(Notice, { tone: "warn", children: ["This load ran ", _jsxs("span", { className: "font-mono", children: ["v", ranVersion] }), ", which the recorded history does not contain \u2014 it predates this catalog keeping revisions, or it has been pushed out by the ", CATALOG_REVISION_LIMIT, " newer ones that are kept. Nothing below is the", ' ', body(subject.kind), " that produced that load."] })), _jsxs("div", { className: "flex flex-wrap items-end gap-2", children: [_jsx(SidePicker, { label: "Compare", ariaLabel: "Compare version", sides: sides, value: keyOf(left), onChange: setLeftKey }), _jsx("span", { className: cn('pb-1.5 font-mono text-[11px]', MUTED), children: "\u2192" }), _jsx(SidePicker, { label: "Against", ariaLabel: "Against version", sides: sides, value: keyOf(right), onChange: setRightKey })] }), _jsx(Authorship, { left: left, right: right }), _jsx(DiffBody, { before: left.body, after: right.body, ...(subject.kind === 'saved-query' ? { language: 'sql' } : {}), name: subject.name })] }));
109
100
  }
110
101
  /**
111
102
  * The saved-query history key, which lives on the OTHER prefix.
@@ -131,51 +122,72 @@ function savedQueryRevisionKey(id) {
131
122
  * every addition as a deletion — a comparison that is exactly backwards and
132
123
  * looks entirely plausible.
133
124
  */
134
- function sidesFrom(revisions, current) {
125
+ function sidesFrom(revisions, current, buffer) {
135
126
  const sides = revisions
136
127
  .map((revision) => ({
128
+ origin: 'recorded',
137
129
  version: revision.version,
138
130
  body: revision.body,
139
131
  authoredBy: revision.authoredBy,
140
132
  authoredAt: revision.authoredAt,
141
- live: false,
142
133
  }))
143
134
  .sort((a, b) => b.version - a.version);
144
135
  if (current && !sides.some((side) => side.version === current.version)) {
145
136
  sides.unshift({
137
+ origin: 'current',
146
138
  version: current.version,
147
139
  body: current.body,
148
140
  authoredBy: null,
149
141
  authoredAt: null,
150
- live: true,
142
+ });
143
+ }
144
+ // Only with something to compare against — see `RevisionHistoryProps.buffer`.
145
+ if (buffer && sides.length > 0) {
146
+ sides.unshift({
147
+ origin: 'buffer',
148
+ version: null,
149
+ body: buffer.body,
150
+ authoredBy: null,
151
+ authoredAt: null,
151
152
  });
152
153
  }
153
154
  return sides;
154
155
  }
155
- function pick(sides, version) {
156
- if (version === null)
156
+ function pick(sides, key) {
157
+ if (key === null)
157
158
  return undefined;
158
- return sides.find((side) => side.version === version);
159
+ return sides.find((side) => keyOf(side) === key);
159
160
  }
160
161
  function SidePicker({ label, ariaLabel, sides, value, onChange, }) {
161
- return (_jsx(SelectField, { label: label, ariaLabel: ariaLabel, value: String(value),
162
- // The select speaks strings and versions are numbers, so the parse happens
163
- // here rather than anywhere a type assertion could hide it. A value that
164
- // did not come from the options below cannot arrive, and if one somehow
165
- // did, `Number` would produce NaN, `pick` would find nothing, and the
166
- // default comparison would stand — rather than a blank panel.
167
- onValueChange: (next) => onChange(Number(next)), className: "min-w-[10rem]", options: sides.map((side) => ({
168
- value: String(side.version),
169
- label: `v${side.version}`,
170
- hint: side.live ? 'current, not yet recorded' : (side.authoredBy ?? undefined),
162
+ return (_jsx(SelectField, { label: label, ariaLabel: ariaLabel, value: value,
163
+ // No parse. The select speaks strings and so does a side key, which is
164
+ // half the reason the key exists: the version was `Number`-ed back out of
165
+ // this callback, and the buffer has no number to produce.
166
+ onValueChange: onChange, className: "min-w-[10rem]", options: sides.map((side) => ({
167
+ value: keyOf(side),
168
+ label: labelOf(side),
169
+ hint: hintOf(side),
171
170
  })) }));
172
171
  }
173
172
  /** Who wrote each side and when, which is half of what "why did this change" means. */
174
173
  function Authorship({ left, right }) {
175
- return (_jsxs("p", { className: cn('font-mono text-[10px] leading-relaxed', MUTED), children: ["v", left.version, " ", describeAuthor(left), " \u2192 v", right.version, " ", describeAuthor(right)] }));
174
+ return (_jsxs("p", { className: cn('font-mono text-[10px] leading-relaxed', MUTED), children: [labelOf(left), " ", describeAuthor(left), " \u2192 ", labelOf(right), " ", describeAuthor(right)] }));
175
+ }
176
+ /** What a side is called. The buffer is named by what it is, having no number. */
177
+ function labelOf(side) {
178
+ return side.origin === 'buffer' ? 'Unsaved edits' : `v${side.version}`;
179
+ }
180
+ function hintOf(side) {
181
+ if (side.origin === 'buffer')
182
+ return 'in the editor, not saved';
183
+ if (side.origin === 'current')
184
+ return 'current, not yet recorded';
185
+ return side.authoredBy ?? undefined;
176
186
  }
177
187
  function describeAuthor(side) {
178
- if (side.live)
188
+ if (side.origin === 'buffer')
189
+ return '(this browser tab)';
190
+ if (side.origin === 'current')
179
191
  return '(current)';
180
192
  const who = side.authoredBy ?? 'unknown';
181
193
  // The locale's own format. A console rendering an ISO string at somebody is
@@ -183,54 +195,77 @@ function describeAuthor(side) {
183
195
  const when = side.authoredAt ? new Date(side.authoredAt).toLocaleString() : 'unknown date';
184
196
  return `by ${who}, ${when}`;
185
197
  }
186
- export function DiffBody({ before, after }) {
187
- const diff = useMemo(() => diffLines(before, after), [before, after]);
188
- const sections = useMemo(() => foldUnchanged(diff.lines), [diff.lines]);
189
- const [expanded, setExpanded] = useState(() => new Set());
190
- const [showAllRows, setShowAllRows] = useState(false);
191
- const rows = useMemo(() => sections.flatMap((section, index) => section.kind === 'shown' || expanded.has(index)
192
- ? section.lines.map((line) => ({ kind: 'line', line }))
193
- : [{ kind: 'fold', index, count: section.lines.length }]), [sections, expanded]);
194
- const visible = showAllRows ? rows : rows.slice(0, DIFF_MAX_ROWS);
195
- const withheld = rows.length - visible.length;
196
- return (_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center gap-3 border-b px-3 py-1.5', RULE), children: [_jsx(GitCompare, { size: 11, className: MUTED }), diff.identical ? (
197
- // The ONLY state that gets to say nothing changed, and it earns it:
198
- // the two bodies are byte-for-byte the same. See this file's header
199
- // for the three other nothings that must not borrow this sentence.
200
- _jsx("span", { className: "font-mono text-[10px] text-zinc-500 dark:text-zinc-400", children: "These two versions are identical." })) : (_jsxs("span", { className: "font-mono text-[10px]", children: [_jsxs("span", { className: "text-emerald-600", children: ["+", diff.added] }), ' ', _jsxs("span", { className: "text-red-600", children: ["\u2212", diff.removed] })] }))] }), diff.alignment === 'coarse' && (_jsx("p", { className: "border-b border-amber-200 bg-amber-50/70 px-3 py-1.5 text-[11px] text-amber-800 dark:border-amber-900 dark:bg-amber-950/25 dark:text-amber-300", children: "These two versions are too far apart to line up line by line, so the whole changed region is shown as removed and re-added. Nothing below is wrong; it is blunter than usual." })), _jsx("div", { className: "overflow-x-auto", children: visible.map((row) => row.kind === 'fold' ? (_jsx(FoldRow, { count: row.count, onExpand: () => setExpanded((current) => new Set(current).add(row.index)) }, `fold-${row.index}`)) : (_jsx(DiffRow, { line: row.line }, rowKey(row.line)))) }), withheld > 0 && (_jsx("div", { className: cn('border-t px-3 py-2', RULE), children: _jsxs(Button, { variant: "outline", size: "sm", onClick: () => setShowAllRows(true), children: ["Show the remaining ", withheld, " lines"] }) }))] }));
201
- }
202
198
  /**
203
- * A stable key for a diff row, out of the numbering it already carries.
199
+ * The comparison itself.
200
+ *
201
+ * Split out from the fetching above so it can be rendered — and tested — from
202
+ * two plain strings, which is what the thing actually being asserted is.
203
+ *
204
+ * WHY THIS IS NO LONGER HAND-ROLLED
205
+ * ---------------------------------
206
+ * It used to be `line-diff.ts` — forty lines of LCS, a fold, and a row
207
+ * renderer — whose docblock argued that the two strings a catalog diffs are a
208
+ * transform's code and somebody's SQL against military logistics data, and that
209
+ * there was no version of this screen worth a supply-chain question mark on
210
+ * that content, so there was no dependency at all. That argument is dead, and it
211
+ * was not this file that killed it: `@pierre/diffs` is now the EDITOR, so it
212
+ * already sees every one of those strings on every keystroke. Keeping a second,
213
+ * weaker differ beside it to avoid a dependency that is already there would buy
214
+ * nothing and cost a divergence — two components disagreeing about what changed,
215
+ * which is the one thing a diff must not do. `line-diff.ts` and its spec are
216
+ * gone; the argument went with them rather than being left standing next to a
217
+ * package that refutes it.
218
+ *
219
+ * What is lost with it: the `coarse` fallback past `DIFF_MAX_CELLS` and the
220
+ * explicit row cap. Both were bounds on a hand-rolled algorithm. The renderer
221
+ * here is virtualised — it draws the rows in view and no more — so the wall of
222
+ * paint the cap existed to prevent is not reachable the same way.
204
223
  *
205
- * Not the array index, which is what this looked like first. A row's pair of
206
- * line numbers is unique across the whole comparison and does not move when a
207
- * fold above it opens: two removed lines have different `before`, two added
208
- * lines have different `after`, and an unchanged line has both. An index key
209
- * would renumber every row below an expanded fold, so React would reconcile
210
- * hundreds of rows that did not change.
224
+ * What is gained: word-level highlighting inside a changed line, which the old
225
+ * one explicitly could not do and which is most of the value when the answer to
226
+ * "why did Tuesday's load differ" is one renamed column.
211
227
  */
212
- function rowKey(line) {
213
- return `${line.before ?? '-'}:${line.after ?? '-'}`;
214
- }
228
+ export function DiffBody({ before, after,
215
229
  /**
216
- * One line.
230
+ * What to highlight it as.
217
231
  *
218
- * The `+`/`−`/space gutter is not decoration and it is not a duplicate of the
219
- * colour: it is the only marker that survives a colourblind reader, a printout,
220
- * a high-contrast theme and a screen reader, all of which the background tint
221
- * does not. Diffs have been read this way for forty years, so it is also the
222
- * marker nobody has to learn.
232
+ * Optional and defaulting to nothing, because this component is reached from
233
+ * both subjects: a transform's code could be any of three languages and the
234
+ * sheet does not carry which, while a saved query is always SQL. Left unset,
235
+ * the name below carries no extension and the diff renders unhighlighted —
236
+ * which is honest, and better than colouring Python as SQL.
223
237
  *
224
- * `whitespace-pre-wrap break-words` matches the code editor exactly, which is
225
- * what lets a four-hundred-character line be READ rather than truncated. See
226
- * `DIFF_MAX_ROWS` for why truncating a line here would make the comparison lie.
238
+ * Narrowed to {@link CatalogCodeLanguage} rather than left as `string`,
239
+ * because only the grammars in `ui/code-languages.ts` are in the bundle: a
240
+ * name outside them would render exactly like the `undefined` above, and the
241
+ * two nothings mean opposite things.
227
242
  */
228
- function DiffRow({ line }) {
229
- return (_jsxs("div", { className: cn('flex items-start gap-2 px-2 font-mono text-[11px] leading-[1.5]', line.op === 'added' && 'bg-emerald-50 dark:bg-emerald-950/30', line.op === 'removed' && 'bg-red-50 dark:bg-red-950/30'), children: [_jsx("span", { className: cn('w-8 shrink-0 select-none text-right', MUTED), children: line.before ?? '' }), _jsx("span", { className: cn('w-8 shrink-0 select-none text-right', MUTED), children: line.after ?? '' }), _jsx("span", { className: cn('w-3 shrink-0 select-none', line.op === 'added' && 'text-emerald-600', line.op === 'removed' && 'text-red-600'), children: line.op === 'added' ? '+' : line.op === 'removed' ? '−' : ' ' }), _jsx("span", { className: "min-w-0 whitespace-pre-wrap break-words", children: line.text })] }));
230
- }
231
- /** A collapsed run of unchanged lines, and the way to see it anyway. */
232
- function FoldRow({ count, onExpand }) {
233
- return (_jsx("div", { className: cn('border-y bg-zinc-50/60 px-2 py-0.5 dark:bg-zinc-800/30', RULE), children: _jsxs(Button, { variant: "ghost", size: "sm", onClick: onExpand, className: "font-mono text-[10px] font-normal", children: ["\u22EF ", count, " unchanged ", count === 1 ? 'line' : 'lines'] }) }));
243
+ language, name = 'version', }) {
244
+ const themeType = useCodeThemeType();
245
+ /**
246
+ * The counts in the header, from the same parse the renderer performs.
247
+ *
248
+ * Recomputed here rather than read off the rendered DOM, and that is the
249
+ * cheap half: `parseDiffFromFile` is memoised on the two bodies, and the
250
+ * hunks carry their own `+`/`-` line counts. `identical` is "no hunks", which
251
+ * is the only thing that means byte-for-byte equal — see this file's header
252
+ * for the three other nothings that must not borrow that sentence.
253
+ */
254
+ const summary = useMemo(() => {
255
+ const parsed = parseDiffFromFile({ name, contents: before, ...(language ? { lang: language } : {}) }, { name, contents: after, ...(language ? { lang: language } : {}) });
256
+ let added = 0;
257
+ let removed = 0;
258
+ for (const hunk of parsed.hunks) {
259
+ added += hunk.additionLines;
260
+ removed += hunk.deletionLines;
261
+ }
262
+ return { added, removed, identical: parsed.hunks.length === 0 };
263
+ }, [before, after, language, name]);
264
+ return (_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center gap-3 border-b px-3 py-1.5', RULE), children: [_jsx(GitCompare, { size: 11, className: MUTED }), summary.identical ? (_jsx("span", { className: "font-mono text-[10px] text-zinc-500 dark:text-zinc-400", children: "These two versions are identical." })) : (_jsxs("span", { className: "font-mono text-[10px]", children: [_jsxs("span", { className: "text-emerald-600", children: ["+", summary.added] }), ' ', _jsxs("span", { className: "text-red-600", children: ["\u2212", summary.removed] })] }))] }), _jsx(MultiFileDiff, { oldFile: { name, contents: before, ...(language ? { lang: language } : {}) }, newFile: { name, contents: after, ...(language ? { lang: language } : {}) },
265
+ // `unified`, not `split`: this sheet is already the width it is, and a
266
+ // side-by-side diff of code at half of it wraps every line back into the
267
+ // shape the editor was rewritten to escape.
268
+ options: { ...codeOptions(themeType), diffStyle: 'unified' } })] }));
234
269
  }
235
270
  function Notice({ children, tone = 'plain', }) {
236
271
  return (_jsx("div", { className: cn('rounded-lg border px-3 py-2 text-[11px] leading-relaxed', tone === 'plain' && cn(RULE, MUTED), tone === 'warn' &&
@@ -253,7 +288,7 @@ function NoHistory({ subject }) {
253
288
  }
254
289
  /** One version recorded. Also not a claim that nothing changed. */
255
290
  function OnlyOneVersion({ subject, only }) {
256
- return (_jsxs("div", { className: cn('rounded-lg border border-dashed px-4 py-8 text-center text-sm', RULE, MUTED), children: [_jsx(History, { size: 16, className: "mx-auto mb-2", "aria-hidden": true }), _jsxs("p", { children: ["One version of ", _jsx("span", { className: "font-medium", children: subject.name }), " is recorded", only ? _jsxs("span", { className: "font-mono", children: [" (v", only.version, ")"] }) : null, ", so there is nothing before it to compare against."] }), _jsxs("p", { className: "mx-auto mt-2 max-w-md text-[11px] leading-relaxed", children: ["Any earlier ", body(subject.kind), " was overwritten before this catalog kept revisions \u2014 again, not a statement that it never changed. The next save gives this screen two versions to work with; the ", CATALOG_REVISION_LIMIT, " most recent are kept."] })] }));
291
+ return (_jsxs("div", { className: cn('rounded-lg border border-dashed px-4 py-8 text-center text-sm', RULE, MUTED), children: [_jsx(History, { size: 16, className: "mx-auto mb-2", "aria-hidden": true }), _jsxs("p", { children: ["One version of ", _jsx("span", { className: "font-medium", children: subject.name }), " is recorded", only ? _jsxs("span", { className: "font-mono", children: [" (", labelOf(only), ")"] }) : null, ", so there is nothing before it to compare against."] }), _jsxs("p", { className: "mx-auto mt-2 max-w-md text-[11px] leading-relaxed", children: ["Any earlier ", body(subject.kind), " was overwritten before this catalog kept revisions \u2014 again, not a statement that it never changed. The next save gives this screen two versions to work with; the ", CATALOG_REVISION_LIMIT, " most recent are kept."] })] }));
257
292
  }
258
293
  /**
259
294
  * The history, in the panel every entry point opens it in.
package/dist/index.d.ts CHANGED
@@ -19,7 +19,6 @@ export { ConnectionPanel, type ConnectionPanelProps, connectionOptionsFor, descr
19
19
  export { type ColumnChoice, type ConnectorSchemaDiscovery, type DiscoveredColumn, type DiscoveredTypeDraft, initialChoices, PipelineConsole, type PipelineConsoleProps, proposalFrom, type SchemaDiscoveryBridge, type SchemaDrift, } from './PipelineConsole';
20
20
  export { TransformEditor, type TransformEditorProps } from './TransformEditor';
21
21
  export { DiffBody, RevisionHistory, type RevisionHistoryProps, RevisionHistoryButton, RevisionHistorySheet, type RevisionHistorySheetProps, type RevisionSubject, type RevisionSubjectKind, } from './diff/RevisionDiff';
22
- export { DIFF_CONTEXT_LINES, DIFF_MAX_CELLS, DIFF_MIN_FOLD, type DiffLine, type DiffOp, type DiffSection, diffLines, foldUnchanged, type LineDiff, } from './diff/line-diff';
23
22
  export { AccessConsole, type AccessConsoleProps } from './AccessConsole';
24
23
  export { type CatalogWorkflow, describeDurability, type DurabilityCopy, isWorkflowNodeKind, newLocalId, nodeName, producedTypes, WORKFLOW_NODE_ID_PATTERN, WORKFLOW_NODE_KINDS, type WorkflowDurability, type WorkflowEdge, type WorkflowGraph, type WorkflowInput, type WorkflowNode, type WorkflowNodeKind, type WorkflowRun, type WorkflowRunNode, type WorkflowSinkNode, type WorkflowSourceNode, type WorkflowTransformNode, } from './workflow/model';
25
24
  export { WORKFLOW_NAME } from './workflow/name';
@@ -31,7 +30,8 @@ export { FieldGroup, TextAreaField, TextField } from './ui/field';
31
30
  export { Select, SelectField, type SelectOption } from './ui/select';
32
31
  export { Switch } from './ui/switch';
33
32
  export { Sheet } from './ui/sheet';
34
- export { CodeEditor, type CodeEditorProps } from './ui/code-editor';
33
+ export { CodeEditor, type CodeEditorHandle, type CodeEditorProps, codeEditorRoot, codeEditorText, } from './ui/code-editor';
34
+ export { CATALOG_CODE_LANGUAGES, CATALOG_CODE_THEMES, type CatalogCodeLanguage, type CatalogCodeTheme, TRANSFORM_HIGHLIGHTED_AS, } from './ui/code-languages';
35
35
  export { RichTextField, RichTextView, type RichTextFieldProps, } from './ui/rich-text-field';
36
36
  export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './ui/button';
37
37
  export { Tabs, TabsList, TabsPanel, TabsTab } from './ui/tabs';
package/dist/index.js CHANGED
@@ -53,12 +53,13 @@ export { TransformEditor } from './TransformEditor';
53
53
  // comparison somewhere else: beside its own deploy log, in an approval flow, or
54
54
  // on a page this package does not ship.
55
55
  //
56
- // `diffLines` and `foldUnchanged` are pure and come with it deliberately. They
57
- // are the whole of the algorithm, they take no dependency and reach no network,
58
- // and a host that wants to render a comparison its own way should not have to
59
- // choose between this package's markup and writing an LCS.
56
+ // `diffLines` and `foldUnchanged` used to be exported alongside it, on the
57
+ // argument that a host wanting to render its own comparison should not have to
58
+ // choose between this package's markup and writing an LCS. They are gone: the
59
+ // diff is `@pierre/diffs` now, which is a peer dependency a host already has
60
+ // installed, and re-exporting a weaker second differ from here would be handing
61
+ // out an answer that can disagree with the one this screen shows.
60
62
  export { DiffBody, RevisionHistory, RevisionHistoryButton, RevisionHistorySheet, } from './diff/RevisionDiff';
61
- export { DIFF_CONTEXT_LINES, DIFF_MAX_CELLS, DIFF_MIN_FOLD, diffLines, foldUnchanged, } from './diff/line-diff';
62
63
  export { AccessConsole } from './AccessConsole';
63
64
  // The authored graph: sources wired through transforms into sinks.
64
65
  //
@@ -108,7 +109,16 @@ export { FieldGroup, TextAreaField, TextField } from './ui/field';
108
109
  export { Select, SelectField } from './ui/select';
109
110
  export { Switch } from './ui/switch';
110
111
  export { Sheet } from './ui/sheet';
111
- export { CodeEditor } from './ui/code-editor';
112
+ // `codeEditorRoot` and `codeEditorText` come with it because the editor renders
113
+ // into a shadow root: without them a host cannot assert on its own screen, and
114
+ // every consumer would rediscover the tag name by reading our source.
115
+ export { CodeEditor, codeEditorRoot, codeEditorText, } from './ui/code-editor';
116
+ // The grammars and themes the editor above can be given, which is a shorter list
117
+ // than Shiki's and is the reason `dist/spa` is not nine tenths grammar files. A
118
+ // host reads `CatalogCodeLanguage` off `CodeEditorProps` anyway; it is named here
119
+ // so the set can be asserted against, and so the build plugin that enforces it —
120
+ // `@dudousxd/nestjs-catalog-react/bundler` — has something to point at.
121
+ export { CATALOG_CODE_LANGUAGES, CATALOG_CODE_THEMES, TRANSFORM_HIGHLIGHTED_AS, } from './ui/code-languages';
112
122
  export { RichTextField, RichTextView, } from './ui/rich-text-field';
113
123
  export { Button } from './ui/button';
114
124
  export { Tabs, TabsList, TabsPanel, TabsTab } from './ui/tabs';
@@ -1,17 +1,163 @@
1
1
  import type { KeyboardEvent, Ref } from 'react';
2
+ import type { CatalogCodeLanguage } from './code-languages';
3
+ import { type CodeThemeType } from './code-theme';
4
+ /**
5
+ * A code editor: `@pierre/diffs` in edit mode, wrapped so the rest of this
6
+ * package can hand it a string and get one back.
7
+ *
8
+ * WHAT THIS REPLACED, AND THE BUG THAT ENDED IT
9
+ * ---------------------------------------------
10
+ * A transparent `<textarea>` over a Prism-highlighted `<pre>`, both wearing
11
+ * `whitespace-pre-wrap break-words`. The docblock that used to be here argued
12
+ * that a textarea is the best plain-text input the platform has — caret,
13
+ * selection, undo, IME, accessibility, all free — and that argument was correct
14
+ * and is why it survived so long. What it did not account for is that a
15
+ * SOFT-WRAPPED textarea is not editing the lines you can see. `Home`, `End`,
16
+ * `Shift+End` and the vertical arrows all work on VISUAL rows, so a SQL line
17
+ * that wrapped after `checked_fields-` answered "select to the end of the line"
18
+ * with `checked_fields-`: one character more than the identifier, because the
19
+ * hyphen was the last glyph on that row. The same wrapping is why a thirteen-line
20
+ * query put the caret on a fourteenth line. Neither is a bug in the textarea;
21
+ * both are what soft wrap means when nothing on screen admits it is happening.
22
+ *
23
+ * The two layers were never the problem, which is worth recording because they
24
+ * were the obvious suspect. Measured in Chrome against this exact CSS, the
25
+ * `<pre>` and the `<textarea>` chose IDENTICAL break positions on 3,725 fuzzed
26
+ * bodies across fifteen container widths, and on tabs, CJK, emoji, RTL,
27
+ * combining marks, unbreakable runs, trailing spaces at a wrap point, blank
28
+ * lines and a trailing newline; overlaid, their glyphs coincided to the pixel.
29
+ * Aligning them harder would have fixed nothing.
30
+ *
31
+ * So the fix is {@link CODE_OPTIONS}'s `overflow: 'scroll'` — real horizontal
32
+ * scrolling, one visual row per line — plus the line numbers a gutter-less box
33
+ * could never draw. Scrolling code well needs a document model, and that is what
34
+ * the dependency buys.
35
+ *
36
+ * WHAT CONTENTEDITABLE COSTS
37
+ * --------------------------
38
+ * `@pierre/diffs` edits through `contentEditable`, which the old docblock
39
+ * rejected outright. Measured rather than assumed — see `code-editor.spec.tsx`:
40
+ *
41
+ * - **Undo/redo, IME, selection, clipboard and word motion survive**, but as the
42
+ * editor's code rather than the browser's. Undo is a real edit stack, and
43
+ * {@link CodeEditorHandle.insertAtCursor} joins it — which the textarea's
44
+ * `selectionStart` splice never did, because React rewrote the whole value and
45
+ * the native undo stack lost its boundary.
46
+ * - **Tab indents instead of leaving.** That is correct for a code editor and it
47
+ * is also a keyboard trap, because the editor's `Escape` is bound to "simplify
48
+ * selection" rather than to letting go. {@link CodeEditor} adds the way out —
49
+ * see `onWrapperKeyDown`.
50
+ * - **Screen readers still get a labelled multiline textbox**, which is the part
51
+ * the old docblock feared most and is the part that turned out fine. Read out
52
+ * of Chrome's accessibility tree rather than guessed: the editable element is
53
+ * `role="textbox" aria-multiline="true" aria-label="<label>"`, and its
54
+ * accessible VALUE is the whole document — all six hundred lines of a
55
+ * six-hundred-line one, since nothing here is virtualised. That is why the
56
+ * label is passed as the file's `name`: the editor copies the name onto
57
+ * `aria-label`, and it is the element's only accessible name.
58
+ * - **What is genuinely gone is form-control semantics.** It is a `<div>`. There
59
+ * is no `value` property, no form participation, no `<label>` to associate,
60
+ * and each line is a row of per-token `<span>`s rather than one text node, so
61
+ * assistive line and word navigation runs over a token grid instead of over
62
+ * plain text. None of that is repaired here.
63
+ * - **The editor lives in a shadow root** (`<diffs-container>`), so nothing
64
+ * outside can style it, query it, or reach it with Testing Library. Specs go
65
+ * through {@link codeEditorRoot}.
66
+ * - **It does not render at all without layout** — canvas text metrics, a
67
+ * `ResizeObserver`, a real box. Under jsdom that means polyfills; see
68
+ * `code-editor-test-dom.ts`.
69
+ */
70
+ /** What a caller can do to a live editor. */
71
+ export interface CodeEditorHandle {
72
+ focus(): void;
73
+ /**
74
+ * Replace the selection with `text`, as one undoable edit.
75
+ *
76
+ * The relations sidebar's click-to-insert. `applyEdits` joins the undo
77
+ * timeline, so an inserted table name comes back out with Ctrl+Z exactly like
78
+ * a typed one.
79
+ */
80
+ insertAtCursor(text: string): void;
81
+ }
2
82
  export interface CodeEditorProps {
3
83
  value: string;
4
84
  onChange: (next: string) => void;
5
- /** Anything Prism knows: `sql`, `json`, `python`, `tsx`, … */
6
- language: string;
7
- /** Required. This is an input, and an unlabelled one is unusable by name. */
85
+ /**
86
+ * What to highlight it as — one of the four grammars this package ships.
87
+ *
88
+ * Not `string`, and that is a size decision as much as a typing one. Shiki
89
+ * knows ~240 languages and the bundle carries the ones named in
90
+ * `CATALOG_CODE_LANGUAGES`; a `language` outside that set would render as
91
+ * plain text with nothing on screen to say why. Narrowing the prop to
92
+ * {@link CatalogCodeLanguage} makes it a compile error at the call site
93
+ * instead — see `ui/code-languages.ts` for the rest of that argument.
94
+ */
95
+ language: CatalogCodeLanguage;
96
+ /**
97
+ * Required, and it is the editable element's accessible name.
98
+ *
99
+ * Passed through as the file's `name`, because that is the string the editor
100
+ * copies onto `aria-label`. An unlabelled input is unusable by name, and the
101
+ * language is given separately, so the name is free to be a human phrase
102
+ * rather than a filename.
103
+ */
8
104
  label: string;
9
- onKeyDown?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
10
- textareaRef?: Ref<HTMLTextAreaElement>;
105
+ /**
106
+ * Keydown, from the wrapper and in the CAPTURE phase.
107
+ *
108
+ * Two facts make this the only workable shape. The editor's keymap binds a
109
+ * fixed set of built-in commands and "run this query" is not one of them, so a
110
+ * host shortcut has to be caught outside it — and events cross an open shadow
111
+ * boundary retargeted at the host, so the wrapper does see `⌘↵` typed inside
112
+ * the editor. But the editor ALREADY binds `⌘↵`, to "insert a blank line", and
113
+ * listening in the bubble phase would run the query and leave a blank line
114
+ * behind. Capture runs first, so a handler that calls `preventDefault` claims
115
+ * the key outright: {@link CodeEditor} stops propagation for it, and the
116
+ * keystroke never reaches the editor at all.
117
+ */
118
+ onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;
119
+ handleRef?: Ref<CodeEditorHandle | null>;
11
120
  /** Metrics differ by caller — the query box is roomier than a sample pane. */
12
121
  className?: string;
13
- padding?: string;
14
- fontSize?: string;
15
122
  readOnly?: boolean;
16
123
  }
17
- export declare function CodeEditor({ value, onChange, language, label, onKeyDown, textareaRef, className, padding, fontSize, readOnly, }: CodeEditorProps): import("react/jsx-runtime").JSX.Element;
124
+ /**
125
+ * The options every code surface in this package shares.
126
+ *
127
+ * `overflow: 'scroll'` is the fix this file's header describes and must not
128
+ * become `'wrap'` without re-reading it. Line numbers are the other half and are
129
+ * conspicuously ABSENT from this object: they are on unless `disableLineNumbers`
130
+ * turns them off, so the way to keep them is to not write it. `code-editor.spec`
131
+ * asserts both, because "an option nobody added" is not something a reader can
132
+ * see here.
133
+ *
134
+ * The file header is off because every caller draws its own — the query
135
+ * console's toolbar, the transform editor's "Code" strip — and a second filename
136
+ * bar inside those says nothing new.
137
+ */
138
+ export declare function codeOptions(themeType: CodeThemeType): {
139
+ readonly overflow: "scroll";
140
+ readonly disableFileHeader: true;
141
+ readonly themeType: CodeThemeType;
142
+ };
143
+ export declare function CodeEditor({ value, onChange, language, label, onKeyDown, handleRef, className, readOnly, }: CodeEditorProps): import("react/jsx-runtime").JSX.Element;
144
+ /**
145
+ * The shadow root a code surface renders into.
146
+ *
147
+ * Exported from the component rather than rewritten in every spec, because the
148
+ * boundary is a property of the dependency and not of any one test: Testing
149
+ * Library's queries stop at the host element, so `getByLabelText` and
150
+ * `getByText` cannot see a single line of code. Everything that asserts on
151
+ * rendered code goes through here, and the day the tag name changes there is one
152
+ * place to fix.
153
+ */
154
+ export declare function codeEditorRoot(container: ParentNode): ShadowRoot | null;
155
+ /**
156
+ * The code a surface is showing, as text.
157
+ *
158
+ * `[data-content]` rather than the whole `<pre>`, which also holds the line
159
+ * numbers — reading those back would make `'1select 1'` the expected value of a
160
+ * one-line query, and the first person to add a line would not know why the
161
+ * assertion moved.
162
+ */
163
+ export declare function codeEditorText(container: ParentNode): string;