@dudousxd/nestjs-catalog-react 0.15.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.
package/dist/routes.d.ts CHANGED
@@ -2,22 +2,35 @@
2
2
  * The paths behind the pipeline and access screens — and, for now, the embed
3
3
  * components, which are the documented exception at the top of the file.
4
4
  *
5
- * These deliberately do **not** live in `@dudousxd/nestjs-catalog/client` beside
6
- * `catalogRoutes`, and the difference is worth being precise about, because it
7
- * is the difference between a route builder that is a promise and one that is a
8
- * guess.
5
+ * Most of these deliberately do **not** live in
6
+ * `@dudousxd/nestjs-catalog/client` beside `catalogRoutes`, and the difference
7
+ * is worth being precise about, because it is the difference between a route
8
+ * builder that is a promise and one that is a default.
9
9
  *
10
- * `catalogRoutes` describes paths the catalog library's own controller serves.
11
- * Install the library, register the module, and `/catalog/objects/...` exists —
12
- * the builder is the library documenting itself, and it cannot be wrong.
10
+ * `catalogRoutes` is a frozen object of builders that take no base path: the
11
+ * paths the catalog library's own controller serves, at the segment it serves
12
+ * them under. Install the library, register the module, and
13
+ * `/catalog/objects/...` exists — the builder is the library documenting itself.
13
14
  *
14
- * Connectors, transforms and access are the other shape. The library defines
15
- * their *model* — `CatalogPipelineStore`, `CatalogConnection`, `CatalogPrincipal`
16
- * — but ships no controller for any of them, because how a deployment exposes
17
- * the code that reshapes its data, and who may create an account, are decisions
18
- * that belong to the deployment. Putting `pipelineRoutes` next to `catalogRoutes`
19
- * would tell a reader that installing the library makes `/pipeline/connectors`
20
- * answer, and it does not: they would get a 404 with nothing to point at.
15
+ * Connectors, transforms and access are the other shape, and what makes them so
16
+ * is not that nothing serves them. It is that WHERE they are served is the
17
+ * host's decision, which a frozen builder cannot express:
18
+ *
19
+ * - Connectors, transforms, workflows and runs are served by
20
+ * `createPipelineController`, which ships in
21
+ * `@dudousxd/nestjs-catalog-pipeline` — a *separate* package, mounted under
22
+ * whatever `path` its `forRoot` was given, and mounted nowhere at all if it
23
+ * was given none. Installing `@dudousxd/nestjs-catalog` does not make
24
+ * `/pipeline/connectors` answer, so putting `pipelineRoutes` beside
25
+ * `catalogRoutes` would tell a reader it does, and they would get a 404 with
26
+ * nothing to point at.
27
+ * - Access is the one that used to be described here as having no controller
28
+ * either, and it does have one: `createAccessController` is in the catalog
29
+ * library and `CatalogModule.forRoot` mounts it unless the host passes
30
+ * `controller: false`. What it does not have is a fixed path — it mounts
31
+ * under `accessPath`, a sibling of the catalog's own mount point — so it is
32
+ * still a default rather than a promise, for the second reason rather than
33
+ * the first.
21
34
  *
22
35
  * So the builders live here, in the package that ships the screens that need
23
36
  * them, and are stated as a *default* the host can move. The defaults are
@@ -25,6 +38,19 @@
25
38
  * `/api/pipeline` — because the transport is what knows the API prefix, and a
26
39
  * screen that hardcoded one app's mount point would be unusable in the next app.
27
40
  *
41
+ * The two load-expectation paths are the case that says what the rule above
42
+ * really is. They are served by that same pipeline controller in that same
43
+ * separate package, yet their builder — `pipelineExpectationRoutes` — is in
44
+ * `@dudousxd/nestjs-catalog/client`, and `pipelineRoutes` below borrows it
45
+ * instead of writing the strings again. That is not an exception, because the
46
+ * test was never which package a builder lives in: it is whether the builder
47
+ * takes a base path. `pipelineExpectationRoutes` does, so it promises nothing
48
+ * about where the routes are mounted no matter where it sits. It sits there
49
+ * because the wire types it goes with — `LoadExpectationInput`,
50
+ * `ResolvedLoadExpectation` — are declared in that entry point and the pipeline
51
+ * controller reads them from there too, and a path split from the shapes it
52
+ * returns is how the two halves of one contract come to be moved separately.
53
+ *
28
54
  * What this package therefore asks of a host is an HTTP surface with these
29
55
  * shapes, wherever it wants to mount it. That contract is the response types on
30
56
  * `CatalogClient` plus these paths, and a host that would rather satisfy it from
@@ -121,6 +147,25 @@ export interface PipelineRoutes {
121
147
  workflows(): string;
122
148
  workflow(id: string): string;
123
149
  runWorkflow(id: string): string;
150
+ /**
151
+ * Every per-type load expectation an operator has stored.
152
+ *
153
+ * Keyed by object type and nothing else. A connector, a workflow sink and an
154
+ * application POSTing to the publish API all end at the same publish methods
155
+ * and all have the same delete problem, so a per-connector route would have
156
+ * given one dataset two answers to one question.
157
+ */
158
+ loadExpectations(): string;
159
+ /**
160
+ * One type's expectation. GET resolves it and says where each field came
161
+ * from; PUT stores one; DELETE drops the stored row and leaves the host's.
162
+ *
163
+ * The GET answers a merge rather than the stored row, because the stored row
164
+ * alone cannot tell a screen whether it is the one in force — a host that
165
+ * declared the same type in code wins, and a screen that showed the stored
166
+ * value would offer an edit that is refused.
167
+ */
168
+ loadExpectation(typeName: string): string;
124
169
  }
125
170
  export declare function pipelineRoutes(basePath?: string): PipelineRoutes;
126
171
  export interface AccessRoutes {
package/dist/routes.js CHANGED
@@ -2,22 +2,35 @@
2
2
  * The paths behind the pipeline and access screens — and, for now, the embed
3
3
  * components, which are the documented exception at the top of the file.
4
4
  *
5
- * These deliberately do **not** live in `@dudousxd/nestjs-catalog/client` beside
6
- * `catalogRoutes`, and the difference is worth being precise about, because it
7
- * is the difference between a route builder that is a promise and one that is a
8
- * guess.
5
+ * Most of these deliberately do **not** live in
6
+ * `@dudousxd/nestjs-catalog/client` beside `catalogRoutes`, and the difference
7
+ * is worth being precise about, because it is the difference between a route
8
+ * builder that is a promise and one that is a default.
9
9
  *
10
- * `catalogRoutes` describes paths the catalog library's own controller serves.
11
- * Install the library, register the module, and `/catalog/objects/...` exists —
12
- * the builder is the library documenting itself, and it cannot be wrong.
10
+ * `catalogRoutes` is a frozen object of builders that take no base path: the
11
+ * paths the catalog library's own controller serves, at the segment it serves
12
+ * them under. Install the library, register the module, and
13
+ * `/catalog/objects/...` exists — the builder is the library documenting itself.
13
14
  *
14
- * Connectors, transforms and access are the other shape. The library defines
15
- * their *model* — `CatalogPipelineStore`, `CatalogConnection`, `CatalogPrincipal`
16
- * — but ships no controller for any of them, because how a deployment exposes
17
- * the code that reshapes its data, and who may create an account, are decisions
18
- * that belong to the deployment. Putting `pipelineRoutes` next to `catalogRoutes`
19
- * would tell a reader that installing the library makes `/pipeline/connectors`
20
- * answer, and it does not: they would get a 404 with nothing to point at.
15
+ * Connectors, transforms and access are the other shape, and what makes them so
16
+ * is not that nothing serves them. It is that WHERE they are served is the
17
+ * host's decision, which a frozen builder cannot express:
18
+ *
19
+ * - Connectors, transforms, workflows and runs are served by
20
+ * `createPipelineController`, which ships in
21
+ * `@dudousxd/nestjs-catalog-pipeline` — a *separate* package, mounted under
22
+ * whatever `path` its `forRoot` was given, and mounted nowhere at all if it
23
+ * was given none. Installing `@dudousxd/nestjs-catalog` does not make
24
+ * `/pipeline/connectors` answer, so putting `pipelineRoutes` beside
25
+ * `catalogRoutes` would tell a reader it does, and they would get a 404 with
26
+ * nothing to point at.
27
+ * - Access is the one that used to be described here as having no controller
28
+ * either, and it does have one: `createAccessController` is in the catalog
29
+ * library and `CatalogModule.forRoot` mounts it unless the host passes
30
+ * `controller: false`. What it does not have is a fixed path — it mounts
31
+ * under `accessPath`, a sibling of the catalog's own mount point — so it is
32
+ * still a default rather than a promise, for the second reason rather than
33
+ * the first.
21
34
  *
22
35
  * So the builders live here, in the package that ships the screens that need
23
36
  * them, and are stated as a *default* the host can move. The defaults are
@@ -25,11 +38,25 @@
25
38
  * `/api/pipeline` — because the transport is what knows the API prefix, and a
26
39
  * screen that hardcoded one app's mount point would be unusable in the next app.
27
40
  *
41
+ * The two load-expectation paths are the case that says what the rule above
42
+ * really is. They are served by that same pipeline controller in that same
43
+ * separate package, yet their builder — `pipelineExpectationRoutes` — is in
44
+ * `@dudousxd/nestjs-catalog/client`, and `pipelineRoutes` below borrows it
45
+ * instead of writing the strings again. That is not an exception, because the
46
+ * test was never which package a builder lives in: it is whether the builder
47
+ * takes a base path. `pipelineExpectationRoutes` does, so it promises nothing
48
+ * about where the routes are mounted no matter where it sits. It sits there
49
+ * because the wire types it goes with — `LoadExpectationInput`,
50
+ * `ResolvedLoadExpectation` — are declared in that entry point and the pipeline
51
+ * controller reads them from there too, and a path split from the shapes it
52
+ * returns is how the two halves of one contract come to be moved separately.
53
+ *
28
54
  * What this package therefore asks of a host is an HTTP surface with these
29
55
  * shapes, wherever it wants to mount it. That contract is the response types on
30
56
  * `CatalogClient` plus these paths, and a host that would rather satisfy it from
31
57
  * somewhere else entirely can pass its own base path, or replace the client.
32
58
  */
59
+ import { pipelineExpectationRoutes } from '@dudousxd/nestjs-catalog/client';
33
60
  /**
34
61
  * The embed API, which is the exception to everything above.
35
62
  *
@@ -97,6 +124,12 @@ function normalise(basePath) {
97
124
  }
98
125
  export function pipelineRoutes(basePath = DEFAULT_PIPELINE_BASE_PATH) {
99
126
  const base = normalise(basePath);
127
+ // The two expectation paths are BORROWED rather than written out again — two
128
+ // copies of a path is how a route ends up moved on one side and 404ing on the
129
+ // other. The header's load-expectation paragraph is why the copy that wins
130
+ // lives in `@dudousxd/nestjs-catalog/client` while everything else here is
131
+ // built in place.
132
+ const expectations = pipelineExpectationRoutes(base);
100
133
  return {
101
134
  capabilities: () => `${base}/capabilities`,
102
135
  connections: () => `${base}/connections`,
@@ -115,6 +148,8 @@ export function pipelineRoutes(basePath = DEFAULT_PIPELINE_BASE_PATH) {
115
148
  workflows: () => `${base}/workflows`,
116
149
  workflow: (id) => `${base}/workflows/${encodeURIComponent(id)}`,
117
150
  runWorkflow: (id) => `${base}/workflows/${encodeURIComponent(id)}/run`,
151
+ loadExpectations: () => expectations.expectations(),
152
+ loadExpectation: (typeName) => expectations.expectation(typeName),
118
153
  };
119
154
  }
120
155
  export function accessRoutes(basePath = DEFAULT_ACCESS_BASE_PATH) {
@@ -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;
@@ -1,81 +1,185 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Highlight } from 'prism-react-renderer';
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Editor } from '@pierre/diffs/edit';
3
+ import { EditProvider, File } from '@pierre/diffs/react';
4
+ import { useImperativeHandle, useRef } from 'react';
3
5
  import { cn } from '../cn';
6
+ import { useCodeThemeType } from './code-theme';
4
7
  /**
5
- * A code editor: a transparent `<textarea>` over a highlighted `<pre>`.
8
+ * The options every code surface in this package shares.
6
9
  *
7
- * Written out once here because it was written out twice — the query console
8
- * and the transform editor each carried their own copy, with the same two boxes
9
- * and the same three comments, and only one of them had been taught about JSON.
10
+ * `overflow: 'scroll'` is the fix this file's header describes and must not
11
+ * become `'wrap'` without re-reading it. Line numbers are the other half and are
12
+ * conspicuously ABSENT from this object: they are on unless `disableLineNumbers`
13
+ * turns them off, so the way to keep them is to not write it. `code-editor.spec`
14
+ * asserts both, because "an option nobody added" is not something a reader can
15
+ * see here.
10
16
  *
11
- * Not CodeMirror, and that is a decision rather than an omission. A textarea is
12
- * already the best plain-text input the platform has: it has the caret, the
13
- * selection, undo, IME, autofill and every accessibility affordance for free,
14
- * and a controlled editor built on a document model has to reimplement the lot
15
- * — the classic symptom being a caret that jumps to the end whenever the value
16
- * is updated from outside. What is missing here is autocomplete and bracket
17
- * matching, which nothing in this console asks for.
17
+ * The file header is off because every caller draws its own — the query
18
+ * console's toolbar, the transform editor's "Code" strip — and a second filename
19
+ * bar inside those says nothing new.
18
20
  */
21
+ export function codeOptions(themeType) {
22
+ return { overflow: 'scroll', disableFileHeader: true, themeType };
23
+ }
24
+ export function CodeEditor({ value, onChange, language, label, onKeyDown, handleRef, className, readOnly, }) {
25
+ const editorRef = useRef(null);
26
+ const wrapperRef = useRef(null);
27
+ const themeType = useCodeThemeType();
28
+ /**
29
+ * The last text this editor and this prop agreed on, and how many times the
30
+ * PROP has moved on its own.
31
+ *
32
+ * The editor owns a document once it is attached, and it substitutes its own
33
+ * cached text for whatever `contents` it is handed — which is right for
34
+ * typing, and wrong for the two moments a caller genuinely replaces the body:
35
+ * opening a saved query, and switching a transform's language. Those bump the
36
+ * revision, which keys the editor, which gives the new body a fresh document.
37
+ * An echo of what the editor itself just reported does not, so typing never
38
+ * remounts.
39
+ *
40
+ * Written during render deliberately: `contents` and `key` have to agree in
41
+ * the SAME render, and an effect would ship one render showing the old body.
42
+ */
43
+ const agreed = useRef(value);
44
+ const revision = useRef(0);
45
+ if (agreed.current !== value) {
46
+ agreed.current = value;
47
+ revision.current += 1;
48
+ }
49
+ useImperativeHandle(handleRef, () => ({
50
+ focus: () => editorRef.current?.focus(),
51
+ insertAtCursor: (text) => {
52
+ const editor = editorRef.current;
53
+ const selection = editor?.getState().selections?.[0];
54
+ if (!editor || !selection) {
55
+ // No caret: nobody has focused the editor yet. Appending is what the
56
+ // old implementation did in the same case, and it is the only place a
57
+ // click on a relation name can honestly put the text.
58
+ onChange(`${value}${text}`);
59
+ return;
60
+ }
61
+ editor.applyEdits([{ range: selection, newText: text }]);
62
+ editor.focus();
63
+ },
64
+ }), [onChange, value]);
65
+ /**
66
+ * The escape hatch, and it is not optional.
67
+ *
68
+ * The editor binds `Tab` to "indent", which is what a code editor should do
69
+ * and also means Tab no longer leaves the control. Without something else that
70
+ * does, a keyboard user who focuses this box cannot get out of it — a keyboard
71
+ * trap, WCAG 2.1.2, and the one accessibility failure in this swap serious
72
+ * enough to repair rather than merely record.
73
+ *
74
+ * Escape parks focus on the wrapper, which is `tabIndex={-1}` so it can hold
75
+ * focus without joining the tab order, and Tab from THERE leaves. Tab has to
76
+ * be handled too, and that is the part that was wrong the first time: focus
77
+ * sitting on the wrapper with the editor inside it means the browser's next
78
+ * tab stop is the editor again, so Escape-then-Tab put you straight back where
79
+ * you started. Verified in Chrome, not assumed. So the Tab is taken over and
80
+ * focus is moved to the first tab stop OUTSIDE this component — which is what
81
+ * Tab was going to mean anyway.
82
+ *
83
+ * The cost is the editor's own Escape binding, "simplify selection", which
84
+ * never arrives. Collapsing a multi-cursor is worth less than being able to
85
+ * leave.
86
+ */
87
+ function onWrapperKeyDown(event) {
88
+ onKeyDown?.(event);
89
+ const wrapper = wrapperRef.current;
90
+ if (event.key === 'Escape' && !event.defaultPrevented && wrapper) {
91
+ event.preventDefault();
92
+ wrapper.focus();
93
+ }
94
+ else if (event.key === 'Tab' &&
95
+ !event.defaultPrevented &&
96
+ wrapper &&
97
+ // Only once focus has been parked. While the caret is in the editor, Tab
98
+ // still indents — that is the behaviour the hatch exists to make safe, not
99
+ // one to undo.
100
+ document.activeElement === wrapper) {
101
+ event.preventDefault();
102
+ focusOutside(wrapper, event.shiftKey ? 'backward' : 'forward');
103
+ }
104
+ // A host that claimed the key gets it exclusively — see `onKeyDown`.
105
+ if (event.defaultPrevented)
106
+ event.stopPropagation();
107
+ }
108
+ return (
109
+ // Capture, not bubble, and on the wrapper rather than on the editable
110
+ // element, which is not ours to attach to. See `onKeyDown`.
111
+ _jsx("div", { ref: wrapperRef, tabIndex: -1, className: cn('relative overflow-hidden outline-none', className), onKeyDownCapture: onWrapperKeyDown, children: _jsx(EditProvider, { createEditor: (options) => new Editor(options), children: _jsx(File, { edit: !readOnly, file: { name: label, contents: value, lang: language, cacheKey: label }, options: codeOptions(themeType), editorOptions: {
112
+ onAttach: (instance) => {
113
+ editorRef.current = instance;
114
+ },
115
+ onChange: (next) => {
116
+ agreed.current = next.contents;
117
+ onChange(next.contents);
118
+ },
119
+ }, style: { height: '100%' } }, revision.current) }) }));
120
+ }
19
121
  /**
20
- * The palette, from the console's own surface tokens.
122
+ * Everything the browser would stop at on the way through a document.
21
123
  *
22
- * The previous copies both passed `themes.github`, which is a LIGHT theme — its
23
- * plain text is near-black. That was invisible for as long as the console was
24
- * light, and turned the SQL box into dark-on-dark the day the console became
25
- * dark. So the theme is defined against the same variables the shell sets
26
- * rather than picked from a list, and the two cannot drift again.
124
+ * Deliberately a DOCUMENT query, which cannot see inside the editor's shadow
125
+ * root — so the editor's own contenteditable is excluded for free rather than by
126
+ * a rule that could drift. `[tabindex="-1"]` is excluded because that is exactly
127
+ * what "focusable, but not a tab stop" means, and it is what the wrapper is.
27
128
  */
28
- const CONSOLE_THEME = {
29
- plain: { color: 'var(--text, #e7e7ea)', backgroundColor: 'transparent' },
30
- styles: [
31
- { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { color: 'var(--muted, #76767f)' } },
32
- { types: ['punctuation'], style: { color: 'var(--muted, #76767f)' } },
33
- {
34
- types: ['keyword', 'operator', 'rule', 'important', 'atrule'],
35
- style: { color: 'var(--accent, #38bdf8)' },
36
- },
37
- { types: ['string', 'char', 'attr-value', 'regex'], style: { color: '#34d399' } },
38
- { types: ['number', 'boolean', 'constant', 'symbol'], style: { color: '#fbbf24' } },
39
- { types: ['function', 'class-name', 'builtin'], style: { color: '#a78bfa' } },
40
- { types: ['variable', 'attr-name', 'property', 'tag'], style: { color: '#7dd3fc' } },
41
- { types: ['deleted'], style: { color: '#f87171' } },
42
- ],
43
- };
44
- export function CodeEditor({ value, onChange, language, label, onKeyDown, textareaRef, className, padding = 'p-3', fontSize = 'text-[12px]', readOnly, }) {
45
- // Every property that affects where a glyph lands has to be identical on both
46
- // layers, or the caret drifts from the text it is supposed to be inside — one
47
- // character further off with every line.
48
- //
49
- // `leading` comes AFTER `fontSize` deliberately: tailwind-merge knows a
50
- // `text-{size}` utility can carry a line-height, so a `leading-*` written
51
- // before it is dropped as superseded — silently, and the browser default
52
- // applies to both layers instead of 1.5.
53
- const shared = cn('m-0 font-mono whitespace-pre-wrap break-words', padding, fontSize, 'leading-[1.5]');
54
- return (
55
- // Two boxes, and the division between them is the whole point.
56
- //
57
- // The outer one is the ONLY thing that scrolls. The inner one has no height
58
- // of its own, so it grows to whatever the highlighted code needs — which is
59
- // what lets the textarea be `inset-0` and still cover every line rather than
60
- // only the visible ones. When both scrolled, a long query produced two
61
- // scrollbars and scrolling the outer one left the caret over the wrong line,
62
- // because the highlight moved and the input did not.
63
- _jsx("div", { className: cn('relative overflow-auto', className), children: _jsxs("div", { className: "relative min-h-full w-full", children: [_jsx(Highlight, { code: value, language: language, theme: CONSOLE_THEME, children: ({ style, tokens, getLineProps, getTokenProps }) => (
64
- // `style` carries the theme's `plain`, which is what anything Prism
65
- // did NOT tokenise falls back to. Dropping it leaves that text
66
- // inheriting from whatever is above, which happens to be right on
67
- // this console and would not be on another.
68
- _jsx("pre", { style: style, className: cn(shared, 'pointer-events-none min-h-full'), "aria-hidden": true, children: tokens.map((line, i) => (
69
- // biome-ignore lint/suspicious/noArrayIndexKey: lines have no id
70
- _jsx("div", { ...getLineProps({ line }), children: line.map((token, key) => (
71
- // biome-ignore lint/suspicious/noArrayIndexKey: tokens have no id
72
- _jsx("span", { ...getTokenProps({ token }) }, key))) }, i))) })) }), _jsx("textarea", { ref: textareaRef, value: value, onChange: (event) => onChange(event.target.value), onKeyDown: onKeyDown, spellCheck: false, readOnly: readOnly, "aria-label": label, className: cn(shared,
73
- // `overflow-hidden`, not `auto`: this layer is as tall as the code
74
- // it holds, so it has nothing to scroll — and giving it the option
75
- // back is what produced the second scrollbar.
76
- 'absolute inset-0 h-full w-full resize-none overflow-hidden bg-transparent',
77
- // Transparent text over the highlighted copy, but a VISIBLE caret
78
- // and a visible selection — those are the two things the `<pre>`
79
- // underneath cannot draw.
80
- 'text-transparent caret-zinc-900 outline-none dark:caret-zinc-100', 'selection:bg-sky-500/30 selection:text-transparent') })] }) }));
129
+ const TAB_STOPS = [
130
+ 'a[href]',
131
+ 'button:not([disabled])',
132
+ 'input:not([disabled])',
133
+ 'select:not([disabled])',
134
+ 'textarea:not([disabled])',
135
+ 'audio[controls]',
136
+ 'video[controls]',
137
+ '[contenteditable]:not([contenteditable="false"])',
138
+ '[tabindex]:not([tabindex="-1"])',
139
+ ].join(',');
140
+ /**
141
+ * Move focus to the tab stop before or after `wrapper`, skipping its contents.
142
+ *
143
+ * Document order, from `compareDocumentPosition`, rather than `tabindex` order.
144
+ * They differ only for positive `tabindex` values, which this package never
145
+ * produces and which are a bug wherever they appear; modelling them here would
146
+ * be more code for a case that would be wrong anyway.
147
+ *
148
+ * Nothing to move to is a real answer — an editor last on the page — and it
149
+ * leaves focus on the wrapper rather than throwing it somewhere arbitrary.
150
+ */
151
+ function focusOutside(wrapper, direction) {
152
+ const stops = [...document.querySelectorAll(TAB_STOPS)].filter((node) => node instanceof HTMLElement && !wrapper.contains(node));
153
+ const after = direction === 'forward';
154
+ const found = (after ? stops : [...stops].reverse()).find((node) => {
155
+ const position = wrapper.compareDocumentPosition(node);
156
+ const mask = after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING;
157
+ return (position & mask) !== 0;
158
+ });
159
+ if (found instanceof HTMLElement)
160
+ found.focus();
161
+ }
162
+ /**
163
+ * The shadow root a code surface renders into.
164
+ *
165
+ * Exported from the component rather than rewritten in every spec, because the
166
+ * boundary is a property of the dependency and not of any one test: Testing
167
+ * Library's queries stop at the host element, so `getByLabelText` and
168
+ * `getByText` cannot see a single line of code. Everything that asserts on
169
+ * rendered code goes through here, and the day the tag name changes there is one
170
+ * place to fix.
171
+ */
172
+ export function codeEditorRoot(container) {
173
+ return container.querySelector('diffs-container')?.shadowRoot ?? null;
174
+ }
175
+ /**
176
+ * The code a surface is showing, as text.
177
+ *
178
+ * `[data-content]` rather than the whole `<pre>`, which also holds the line
179
+ * numbers — reading those back would make `'1select 1'` the expected value of a
180
+ * one-line query, and the first person to add a line would not know why the
181
+ * assertion moved.
182
+ */
183
+ export function codeEditorText(container) {
184
+ return codeEditorRoot(container)?.querySelector('[data-content]')?.textContent ?? '';
81
185
  }