@nibling/editor 0.0.0-stage → 0.0.1

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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -2
  3. package/dist/commands/autoclose.d.ts +13 -0
  4. package/dist/commands/autoclose.js +78 -0
  5. package/dist/commands/commands.d.ts +104 -0
  6. package/dist/commands/commands.js +442 -0
  7. package/dist/commands/comments.d.ts +3 -0
  8. package/dist/commands/comments.js +9 -0
  9. package/dist/commands/fold.d.ts +18 -0
  10. package/dist/commands/fold.js +75 -0
  11. package/dist/commands/keymap.d.ts +40 -0
  12. package/dist/commands/keymap.js +118 -0
  13. package/dist/complete/autocomplete.d.ts +35 -0
  14. package/dist/complete/autocomplete.js +386 -0
  15. package/dist/complete/source.d.ts +72 -0
  16. package/dist/complete/source.js +52 -0
  17. package/dist/complete/words.d.ts +53 -0
  18. package/dist/complete/words.js +203 -0
  19. package/dist/element.d.ts +119 -0
  20. package/dist/element.js +1011 -0
  21. package/dist/expand/expansions.d.ts +68 -0
  22. package/dist/expand/expansions.js +143 -0
  23. package/dist/expand/projection.d.ts +73 -0
  24. package/dist/expand/projection.js +189 -0
  25. package/dist/expand/resolver.d.ts +42 -0
  26. package/dist/expand/resolver.js +585 -0
  27. package/dist/expand/slice-tokens.d.ts +25 -0
  28. package/dist/expand/slice-tokens.js +79 -0
  29. package/dist/extension.d.ts +58 -0
  30. package/dist/extension.js +1 -0
  31. package/dist/find/find.d.ts +12 -0
  32. package/dist/find/find.js +469 -0
  33. package/dist/find/search.d.ts +81 -0
  34. package/dist/find/search.js +308 -0
  35. package/dist/headless.d.ts +16 -0
  36. package/dist/headless.js +19 -0
  37. package/dist/index.d.ts +6 -0
  38. package/dist/index.js +6 -0
  39. package/dist/inline-expansion.d.ts +89 -0
  40. package/dist/inline-expansion.js +324 -0
  41. package/dist/input/edit-context.d.ts +23 -0
  42. package/dist/input/edit-context.js +102 -0
  43. package/dist/input/surface.d.ts +101 -0
  44. package/dist/input/surface.js +84 -0
  45. package/dist/input/textarea.d.ts +26 -0
  46. package/dist/input/textarea.js +125 -0
  47. package/dist/sheet.d.ts +6 -0
  48. package/dist/sheet.js +12 -0
  49. package/dist/state/core.d.ts +73 -0
  50. package/dist/state/core.js +86 -0
  51. package/dist/state/fold-ranges.d.ts +41 -0
  52. package/dist/state/fold-ranges.js +167 -0
  53. package/dist/state/folds.d.ts +45 -0
  54. package/dist/state/folds.js +240 -0
  55. package/dist/state/history.d.ts +25 -0
  56. package/dist/state/history.js +127 -0
  57. package/dist/state/indent.d.ts +33 -0
  58. package/dist/state/indent.js +121 -0
  59. package/dist/state/selection.d.ts +45 -0
  60. package/dist/state/selection.js +106 -0
  61. package/dist/state/whitespace.d.ts +16 -0
  62. package/dist/state/whitespace.js +54 -0
  63. package/dist/text/changeset.d.ts +56 -0
  64. package/dist/text/changeset.js +321 -0
  65. package/dist/text/text.d.ts +30 -0
  66. package/dist/text/text.js +321 -0
  67. package/dist/tokens/bridge.d.ts +107 -0
  68. package/dist/tokens/bridge.js +461 -0
  69. package/dist/tokens/engine.d.ts +39 -0
  70. package/dist/tokens/engine.js +360 -0
  71. package/dist/tokens/protocol.d.ts +113 -0
  72. package/dist/tokens/protocol.js +38 -0
  73. package/dist/tokens/textmate/ascii-regex.d.ts +5 -0
  74. package/dist/tokens/textmate/ascii-regex.js +156 -0
  75. package/dist/tokens/textmate/index.d.ts +7 -0
  76. package/dist/tokens/textmate/index.js +19 -0
  77. package/dist/tokens/textmate/linker.d.ts +67 -0
  78. package/dist/tokens/textmate/linker.js +238 -0
  79. package/dist/tokens/textmate/scopes.d.ts +14 -0
  80. package/dist/tokens/textmate/scopes.js +54 -0
  81. package/dist/tokens/textmate/theme.d.ts +54 -0
  82. package/dist/tokens/textmate/theme.js +138 -0
  83. package/dist/tokens/textmate/tokenizer.d.ts +29 -0
  84. package/dist/tokens/textmate/tokenizer.js +684 -0
  85. package/dist/tokens/textmate.d.ts +49 -0
  86. package/dist/tokens/textmate.js +4 -0
  87. package/dist/view/decorations.d.ts +183 -0
  88. package/dist/view/decorations.js +51 -0
  89. package/dist/view/guides.d.ts +58 -0
  90. package/dist/view/guides.js +174 -0
  91. package/dist/view/heightmap.d.ts +97 -0
  92. package/dist/view/heightmap.js +229 -0
  93. package/dist/view/line-dom.d.ts +54 -0
  94. package/dist/view/line-dom.js +168 -0
  95. package/dist/view/measure.d.ts +37 -0
  96. package/dist/view/measure.js +136 -0
  97. package/dist/view/overlays.d.ts +32 -0
  98. package/dist/view/overlays.js +135 -0
  99. package/dist/view/rail.d.ts +27 -0
  100. package/dist/view/rail.js +232 -0
  101. package/dist/view/remote.d.ts +24 -0
  102. package/dist/view/remote.js +143 -0
  103. package/dist/view/scope-focus.d.ts +27 -0
  104. package/dist/view/scope-focus.js +255 -0
  105. package/dist/view/view.d.ts +114 -0
  106. package/dist/view/view.js +1231 -0
  107. package/dist/vite.d.ts +12 -0
  108. package/dist/vite.js +64 -0
  109. package/dist/worker.d.ts +1 -0
  110. package/dist/worker.js +64 -0
  111. package/grammars/astro.mjs +2 -0
  112. package/grammars/chunks/r-90cb351dba.mjs +1 -0
  113. package/grammars/chunks/r-b92a500aab.mjs +1 -0
  114. package/grammars/chunks/r-ced5311992.mjs +1 -0
  115. package/grammars/chunks/r-ebae91d4ec.mjs +1 -0
  116. package/grammars/chunks/s-1821e66170.mjs +1 -0
  117. package/grammars/css.mjs +1 -0
  118. package/grammars/diff.mjs +1 -0
  119. package/grammars/docker.mjs +1 -0
  120. package/grammars/dotenv.mjs +1 -0
  121. package/grammars/graphql.mjs +1 -0
  122. package/grammars/html.mjs +2 -0
  123. package/grammars/ini.mjs +1 -0
  124. package/grammars/javascript.mjs +5 -0
  125. package/grammars/json.mjs +1 -0
  126. package/grammars/json5.mjs +1 -0
  127. package/grammars/jsonc.mjs +1 -0
  128. package/grammars/less.mjs +1 -0
  129. package/grammars/manifest.json +58 -0
  130. package/grammars/markdown.mjs +1 -0
  131. package/grammars/mdx.mjs +1 -0
  132. package/grammars/pug.mjs +1 -0
  133. package/grammars/scss.mjs +1 -0
  134. package/grammars/shellscript.mjs +1 -0
  135. package/grammars/sql.mjs +1 -0
  136. package/grammars/stylus.mjs +1 -0
  137. package/grammars/svelte.mjs +1 -0
  138. package/grammars/toml.mjs +1 -0
  139. package/grammars/tsx.mjs +5 -0
  140. package/grammars/typescript.mjs +2 -0
  141. package/grammars/vue.mjs +1 -0
  142. package/grammars/yaml.mjs +1 -0
  143. package/package.json +71 -3
  144. package/themes/dark-plus.json +1 -0
  145. package/themes/light-plus.json +1 -0
  146. package/themes/monokai.json +1 -0
@@ -0,0 +1,1011 @@
1
+ import { EditorCore } from "./state/core.js";
2
+ import { History } from "./state/history.js";
3
+ import { Selection, cursor, isCursor, rangeFrom, rangeTo } from "./state/selection.js";
4
+ import { ChangeSet } from "./text/changeset.js";
5
+ import { Keymap, defaultKeymap, normalizeKey, platformKeymap } from "./commands/keymap.js";
6
+ import { insertText, perRange, toggleComment } from "./commands/commands.js";
7
+ import { closeBrackets, deletePairBackward } from "./commands/autoclose.js";
8
+ import { commentSyntax } from "./commands/comments.js";
9
+ import { foldCode, unfoldCode } from "./commands/fold.js";
10
+ import { FoldState } from "./state/folds.js";
11
+ import { IndentFolds } from "./state/fold-ranges.js";
12
+ import { FoldRail } from "./view/rail.js";
13
+ import { ScopeFocus } from "./view/scope-focus.js";
14
+ import { createInputSurface, surfaceKind } from "./input/surface.js";
15
+ import { TokenBridge } from "./tokens/bridge.js";
16
+ import { isThemePair, lightDark } from "./tokens/protocol.js";
17
+ import { EditorView } from "./view/view.js";
18
+ import { isWhitespaceMode } from "./state/whitespace.js";
19
+ import { InlineExpansions } from "./expand/expansions.js";
20
+ import { sameDocumentResolver } from "./expand/resolver.js";
21
+ import { ExpansionWidgets } from "./inline-expansion.js";
22
+ import { nextVisibleLine } from "./state/folds.js";
23
+ import { findReplace } from "./find/find.js";
24
+ import { autocomplete, wordCompletions } from "./complete/autocomplete.js";
25
+ import { sheetFor } from "./sheet.js";
26
+ /** Connected elements that follow `editorDefaults`, so defaults set after connection still apply. */
27
+ const followers = new Set();
28
+ let defaultGrammars = null;
29
+ let defaultTheme = null;
30
+ let defaultThemes = null;
31
+ let defaultIndentGuides = true;
32
+ let defaultWhitespace = 'selection';
33
+ /**
34
+ * Process-wide defaults the host sets once, before or after elements exist. Per-element
35
+ * properties override them. `input` is read when an element first connects.
36
+ */
37
+ export const editorDefaults = {
38
+ get grammars() {
39
+ return defaultGrammars;
40
+ },
41
+ set grammars(v) {
42
+ defaultGrammars = v;
43
+ for (const f of followers)
44
+ f();
45
+ },
46
+ get theme() {
47
+ return defaultTheme;
48
+ },
49
+ set theme(v) {
50
+ defaultTheme = v;
51
+ for (const f of followers)
52
+ f();
53
+ },
54
+ get themes() {
55
+ return defaultThemes;
56
+ },
57
+ set themes(v) {
58
+ defaultThemes = v;
59
+ for (const f of followers)
60
+ f();
61
+ },
62
+ get indentGuides() {
63
+ return defaultIndentGuides;
64
+ },
65
+ set indentGuides(v) {
66
+ defaultIndentGuides = v;
67
+ for (const f of followers)
68
+ f();
69
+ },
70
+ get whitespace() {
71
+ return defaultWhitespace;
72
+ },
73
+ set whitespace(v) {
74
+ defaultWhitespace = v;
75
+ for (const f of followers)
76
+ f();
77
+ },
78
+ input: 'textarea',
79
+ inlineExpansion: false,
80
+ autocomplete: true,
81
+ multiCursorModifier: 'mod',
82
+ undoGroupDelay: 500,
83
+ highlightHold: 300,
84
+ worker: () => new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }),
85
+ };
86
+ /** Stands in for the worker until a language, grammars, and a theme are all known: plain text. */
87
+ const inertWorker = () => ({ postMessage() { }, addEventListener() { } });
88
+ const noGrammars = { languages: {}, modules: {} };
89
+ const noTheme = { colors: [], defaults: [0, 0, 0], trie: null, chrome: {} };
90
+ /**
91
+ * Collaborator colors when the platform has none, as [light theme, dark theme] pairs. nibling's
92
+ * `--nib-color-presence-1..8` replace them; these only keep a standalone editor distinct.
93
+ */
94
+ const PRESENCE_FALLBACK = [
95
+ ['#7c3aed', '#a78bfa'],
96
+ ['#0284c7', '#38bdf8'],
97
+ ['#059669', '#34d399'],
98
+ ['#d97706', '#fbbf24'],
99
+ ['#dc2626', '#f87171'],
100
+ ['#db2777', '#f472b6'],
101
+ ['#0d9488', '#2dd4bf'],
102
+ ['#4f46e5', '#818cf8'],
103
+ ];
104
+ /** Whether a `#rgb`/`#rrggbb` color is dark, by relative luminance. Unknown formats count as dark. */
105
+ function isDarkColor(hex) {
106
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})(?:[0-9a-f]{2})?$/i.exec(hex.trim());
107
+ if (!m)
108
+ return true;
109
+ const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1];
110
+ const lin = (i) => {
111
+ const c = parseInt(h.slice(i, i + 2), 16) / 255;
112
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
113
+ };
114
+ return 0.2126 * lin(0) + 0.7152 * lin(2) + 0.0722 * lin(4) < 0.18;
115
+ }
116
+ /** The colors the element writes on :host for one theme: `--nib-bg`, `--nib-fg`, and the
117
+ * `--nib-theme-*` fallbacks the knobs read (docs/design/theming.md). */
118
+ function chromeVars(theme) {
119
+ const chrome = theme?.chrome ?? {};
120
+ const bg = chrome['editor.background'] ?? '#1e1e1e';
121
+ // VS Code themes use the numbered guide keys; older ones (Monokai) the plain ones. Where the
122
+ // theme has no key, status, presence, selection and caret fall back to VS Code's defaults for
123
+ // the theme's kind, read from its background.
124
+ const dark = isDarkColor(bg);
125
+ const vars = [
126
+ ['--nib-bg', bg],
127
+ ['--nib-fg', chrome['editor.foreground'] ?? '#d4d4d4'],
128
+ ['--nib-theme-indent-guide', chrome['editorIndentGuide.background1'] ?? chrome['editorIndentGuide.background']],
129
+ ['--nib-theme-whitespace', chrome['editorWhitespace.foreground']],
130
+ ['--nib-theme-selection', chrome['editor.selectionBackground'] ?? (dark ? '#264f78' : '#add6ff')],
131
+ ['--nib-theme-caret', chrome['editorCursor.foreground'] ?? (dark ? '#aeafad' : '#000000')],
132
+ ['--nib-theme-error', chrome['editorError.foreground'] ?? (dark ? '#f14c4c' : '#e51400')],
133
+ ['--nib-theme-warning', chrome['editorWarning.foreground'] ?? (dark ? '#cca700' : '#bf8803')],
134
+ ['--nib-theme-info', chrome['editorInfo.foreground'] ?? (dark ? '#3794ff' : '#1a85ff')],
135
+ ['--nib-theme-match', chrome['editor.findMatchHighlightBackground']],
136
+ ['--nib-theme-match-current', chrome['editor.findMatchBackground'] ?? (dark ? '#515c6a' : '#a8ac94')],
137
+ ['--nib-theme-selection-match', chrome['editor.selectionHighlightBackground']],
138
+ ...PRESENCE_FALLBACK.map((pair, i) => [`--nib-theme-presence-${i + 1}`, pair[dark ? 1 : 0]]),
139
+ ['--nib-theme-on-presence', dark ? '#1e1e1e' : '#ffffff'],
140
+ ];
141
+ return new Map(vars.filter((e) => !!e[1]));
142
+ }
143
+ /**
144
+ * The :host rule for a theme. A pair writes `light-dark(light, dark)` wherever the two differ, so
145
+ * chrome follows the used `color-scheme` as syntax does. The element never sets color-scheme
146
+ * itself: it inherits one from the host or an ancestor, and with none declared (`normal`) the
147
+ * light theme shows, matching the page's own light canvas. A key only one theme of a pair has is
148
+ * left out, so both schemes take the knob's mix fallback rather than one side guessing.
149
+ */
150
+ function chromeCss(theme) {
151
+ let vars;
152
+ if (theme && isThemePair(theme)) {
153
+ const light = chromeVars(theme.light), dark = chromeVars(theme.dark);
154
+ vars = new Map();
155
+ for (const [k, l] of light) {
156
+ const d = dark.get(k);
157
+ if (d !== undefined)
158
+ vars.set(k, lightDark(l, d));
159
+ }
160
+ }
161
+ else
162
+ vars = chromeVars(theme);
163
+ return `:host{display:block;position:relative;${[...vars].map(([k, v]) => `${k}:${v};`).join('')}}`;
164
+ }
165
+ /** Same themes, so the worker needn't re-resolve (a host may build a fresh pair object). */
166
+ function sameTheme(a, b) {
167
+ if (a === b)
168
+ return true;
169
+ if (!a || !b || !isThemePair(a) || !isThemePair(b))
170
+ return false;
171
+ return a.light === b.light && a.dark === b.dark;
172
+ }
173
+ const apple = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
174
+ let instances = 0;
175
+ function deferred() {
176
+ let resolve;
177
+ const promise = new Promise((r) => (resolve = r));
178
+ return { promise, resolve };
179
+ }
180
+ function linked(...signals) {
181
+ return AbortSignal.any(signals.filter((s) => !!s));
182
+ }
183
+ /** The config the next NibEditor constructor takes, set only inside `createNestedEditor`. */
184
+ let pendingNested = null;
185
+ const NESTED_TAG = 'nib-inline-editor';
186
+ /** An inline expansion's editor: a NibEditor over the projection's core (see inline-expansion.ts). */
187
+ function createNestedEditor(doc, config) {
188
+ if (!customElements.get(NESTED_TAG))
189
+ customElements.define(NESTED_TAG, class extends NibEditor {
190
+ });
191
+ pendingNested = config;
192
+ try {
193
+ return doc.createElement(NESTED_TAG);
194
+ }
195
+ finally {
196
+ pendingNested = null;
197
+ }
198
+ }
199
+ function withPrimary(sel, range) {
200
+ const ranges = sel.ranges.slice();
201
+ ranges[sel.primaryIndex] = range;
202
+ return Selection.create(ranges, sel.primaryIndex);
203
+ }
204
+ /**
205
+ * `<nib-editor>`. The shell that wires the followers to one EditorCore; it holds no editing logic
206
+ * of its own beyond routing SurfaceEvents to commands.
207
+ *
208
+ * Followers, in listen order: History, TokenBridge, EditorView, then the element (surface sync,
209
+ * `change` and `selectionchange` events) and extensions. Each keeps its own state, and the view
210
+ * only reads others' state inside its rAF frame.
211
+ *
212
+ * Core, History, and Keymap live as long as the element, so moving it in the DOM keeps undo.
213
+ * Everything else lives for one connection. The tokenizer and view are rebuilt when grammars or a
214
+ * theme first become available, since the worker needs both to open the document.
215
+ *
216
+ * Attributes: `language`, `indent-guides` ("false" turns guides off), and `whitespace` (a
217
+ * WhitespaceMode), all reflected; `aria-label` (forwarded to the textarea when there is one).
218
+ * Properties: value, state, language, indentGuides, whitespace, theme, themes, grammars. Events: `change` (EditorChangeEvent, for
219
+ * docChanged updates), `selectionchange` (for selection changes).
220
+ */
221
+ export class NibEditor extends HTMLElement {
222
+ static observedAttributes = ['language', 'indent-guides', 'whitespace', 'inline-expansion', 'aria-label', 'aria-labelledby', 'aria-describedby'];
223
+ /** Set only for an inline expansion's editor. Read first: the core and undo depend on it. */
224
+ #nested = pendingNested;
225
+ #core = this.#nested?.core ?? new EditorCore();
226
+ /** Held while composing, so every preedit update and the commit fold into one undo step
227
+ * however long the user takes. */
228
+ #composeTime = null;
229
+ /** None for an inline expansion (its edits land in the source document, whose History has them)
230
+ * and while an extension owns undo (`EditorContext.undo`). */
231
+ #historyAc = null;
232
+ #history = this.#nested ? null : this.#makeHistory();
233
+ /** An extension's undo and redo, such as a collaboration binding's UndoManager (D5). */
234
+ #undoOwner = null;
235
+ /** Before the view in listen order, so the view's HeightMap reads folds already mapped. */
236
+ #folds = new FoldState(this.#core);
237
+ #foldRanges = new IndentFolds(this.#core);
238
+ /** Before the view too, so its block geometry reads call sites already mapped. Idle (one early
239
+ * return per Update) until something opens. */
240
+ #expansions = new InlineExpansions(this.#core, null);
241
+ #widgets = null;
242
+ #keymap = new Keymap();
243
+ #instance = `e${++instances}`;
244
+ #kind = null;
245
+ #bridge = null;
246
+ #view = null;
247
+ #surface = null;
248
+ #lifetime = null;
249
+ #render = null;
250
+ #geometry = null;
251
+ #focused = false;
252
+ #theme = null;
253
+ #themes = null;
254
+ #grammars = null;
255
+ /** Rebuilt from the host's window when it connects in another document; see sheetFor. */
256
+ #chrome = null;
257
+ #chromeCss = '';
258
+ #chromeDoc = null;
259
+ #overlays = [];
260
+ #lineClasses = [];
261
+ #remoteCursors = [];
262
+ #completionSources = [];
263
+ #connected = deferred();
264
+ /** The live IME preedit, in current document coordinates. */
265
+ #composition = null;
266
+ #invalidateComposition = [];
267
+ /** `change`/`selectionchange` wait for a microtask: EditorCore.apply is not reentrant, and these
268
+ * fire from inside its listener notification, so a listener that calls `apply()` (directly or
269
+ * via element.apply) would otherwise throw. */
270
+ #pendingEvents = [];
271
+ #undo = (ctx) => (this.#nested?.undo ?? this.#undoOwner?.undo ?? this.#history?.undo)?.(ctx) ?? null;
272
+ #redo = (ctx) => (this.#nested?.redo ?? this.#undoOwner?.redo ?? this.#history?.redo)?.(ctx) ?? null;
273
+ constructor() {
274
+ super();
275
+ this.#keymap.add(defaultKeymap);
276
+ this.#keymap.add(platformKeymap(apple));
277
+ this.#keymap.add([{ key: 'Mod-/', run: (ctx) => toggleComment(commentSyntax[this.language])(ctx) }]);
278
+ this.#keymap.add([
279
+ { key: 'Mod-z', run: this.#undo },
280
+ { key: 'Mod-Shift-z', run: this.#redo },
281
+ // With Shift held, KeyboardEvent.key is the shifted character on most platforms.
282
+ { key: 'Mod-Shift-Z', run: this.#redo },
283
+ { key: 'Mod-y', run: this.#redo },
284
+ ]);
285
+ // Auto-close: Backspace between an empty pair deletes both, ahead of the plain deleteBackward
286
+ // in defaultKeymap (docs/design/core.md). Declines (null) everywhere else.
287
+ this.#keymap.add([{ key: 'Backspace', run: deletePairBackward }], 1);
288
+ // VS Code's editor.fold and editor.unfold. With Shift held, `key` is the shifted character.
289
+ const fold = foldCode(this.#folds, this.#foldRanges);
290
+ const unfold = unfoldCode(this.#folds);
291
+ this.#keymap.add([
292
+ { key: 'Mod-Shift-[', run: fold },
293
+ { key: 'Mod-Shift-{', run: fold },
294
+ { key: 'Mod-Shift-]', run: unfold },
295
+ { key: 'Mod-Shift-}', run: unfold },
296
+ ]);
297
+ if (this.#nested)
298
+ this.#keymap.add(this.#nested.keymap, 1);
299
+ // Inline expansion. Each declines (null) while the option is off, so the keys behave as before.
300
+ this.#keymap.add([
301
+ { key: 'Mod-Alt-Enter', run: (ctx) => (this.#expandEnabled() && this.#expansions.toggle(ctx.state.selection.primary.head) !== 'none' ? { origin: 'select' } : null) },
302
+ { key: 'ArrowDown', run: (ctx) => this.#enterExpansion(ctx.state, 1) },
303
+ { key: 'ArrowUp', run: (ctx) => this.#enterExpansion(ctx.state, -1) },
304
+ ], 1);
305
+ this.#overlays.push({
306
+ source: {
307
+ query: (_state, from, to) => {
308
+ const c = this.#composition;
309
+ return c && c.to > c.from && c.to >= from && c.from <= to ? [{ kind: 'composition', ...c }] : [];
310
+ },
311
+ subscribe: (invalidate) => {
312
+ this.#invalidateComposition.push(invalidate);
313
+ return () => (this.#invalidateComposition = this.#invalidateComposition.filter((f) => f !== invalidate));
314
+ },
315
+ },
316
+ });
317
+ }
318
+ /** The whole document as a string. O(n); prefer `state.text` for repeated reads. */
319
+ get value() {
320
+ return this.#core.state.text.toString();
321
+ }
322
+ /** Replaces the document, puts a cursor at 0, clears undo. Works before connection. */
323
+ set value(v) {
324
+ this.#core.reset(v);
325
+ this.#hold(true);
326
+ }
327
+ /**
328
+ * Hide text while syntax colors are expected but not yet painted: a language is set, and either
329
+ * the tokenizer is running or grammars and a theme are still on their way. One deadline spans the
330
+ * switch from the plain render to the live one. `restart` starts a new deadline (new text).
331
+ */
332
+ #hold(restart) {
333
+ if (!this.language || !this.#view)
334
+ return;
335
+ // A language the manifest has no grammar for will never get colors.
336
+ const grammars = this.grammars;
337
+ if (grammars && !Object.hasOwn(grammars.languages, this.language))
338
+ return;
339
+ if (restart || this.#holdUntil === null)
340
+ this.#holdUntil = performance.now() + editorDefaults.highlightHold;
341
+ const left = this.#holdUntil - performance.now();
342
+ if (left > 0)
343
+ this.#view.awaitTokens(left);
344
+ }
345
+ get state() {
346
+ return this.#core.state;
347
+ }
348
+ /** Open inline expansions (see `inlineExpansion`). */
349
+ get expansions() {
350
+ return this.#expansions;
351
+ }
352
+ /** Whether Mod-Alt-Enter and Alt-click expand definitions inline. Reflects `inline-expansion`;
353
+ * without it, editorDefaults. A prototype; off by default. */
354
+ get inlineExpansion() {
355
+ const v = this.getAttribute('inline-expansion');
356
+ return v === null ? editorDefaults.inlineExpansion : v !== 'false';
357
+ }
358
+ set inlineExpansion(v) {
359
+ this.setAttribute('inline-expansion', String(v));
360
+ }
361
+ #expandEnabled() {
362
+ return this.inlineExpansion && !!this.#widgets;
363
+ }
364
+ /** This document as an expansion source: its core, its undo, and its tokens. */
365
+ #asSource = ((host) => ({
366
+ core: host.#core,
367
+ get history() {
368
+ return host.#nested ? { undo: host.#nested.undo, redo: host.#nested.redo } : (host.#undoOwner ?? host.#history);
369
+ },
370
+ tokens: () => host.#bridge,
371
+ }))(this);
372
+ #makeHistory() {
373
+ this.#historyAc = new AbortController();
374
+ return new History(this.#core, { groupDelay: editorDefaults.undoGroupDelay, now: () => this.#composeTime ?? performance.now() }, this.#historyAc.signal);
375
+ }
376
+ /**
377
+ * Hands undo and redo to an extension for its lifetime. History stops listening, so it no longer
378
+ * throws on 'remote' updates; when the extension goes, a fresh History starts, since stacks kept
379
+ * across edits it never saw would undo the wrong text.
380
+ */
381
+ #claimUndo(owner, signal) {
382
+ if (this.#nested)
383
+ throw new Error('an inline expansion has no undo of its own');
384
+ if (this.#undoOwner)
385
+ throw new Error('undo is already owned by another extension');
386
+ this.#historyAc?.abort();
387
+ this.#history = null;
388
+ this.#undoOwner = owner;
389
+ signal.addEventListener('abort', () => {
390
+ this.#undoOwner = null;
391
+ this.#history = this.#makeHistory();
392
+ }, { once: true });
393
+ }
394
+ /**
395
+ * ArrowDown on a call site's line, or ArrowUp from the line below one, moves into the expansion
396
+ * between them, as it would into any line there: expansions take part in layout, so the
397
+ * keyboard goes where the eye does. A plain cursor only; a selection never spans two editors.
398
+ */
399
+ #enterExpansion(state, dir) {
400
+ if (!this.#expandEnabled() || this.#expansions.list.length === 0)
401
+ return null;
402
+ const sel = state.selection;
403
+ if (sel.ranges.length !== 1 || !isCursor(sel.primary))
404
+ return null;
405
+ const text = state.text;
406
+ const line = text.lineAt(sel.primary.head);
407
+ const from = dir > 0 ? line.number : nextVisibleLine(this.#folds.hidden, line.number, -1, text.lines);
408
+ if (from < 1 || this.#expansions.at(from).length === 0)
409
+ return null;
410
+ return this.#widgets.enterFrom(from, dir, sel.primary.head - line.from) ? { origin: 'select' } : null;
411
+ }
412
+ /** Focus this editor with a cursor at `pos` (an expansion handing focus back). */
413
+ #focusAt(pos) {
414
+ this.#core.apply({ selection: Selection.single(pos), origin: 'select', scrollIntoView: true });
415
+ this.#surface?.focusTarget.focus({ preventScroll: true });
416
+ }
417
+ /** Which regions are folded. Folds live as long as the element and map through every edit. */
418
+ get folds() {
419
+ return this.#folds;
420
+ }
421
+ get language() {
422
+ return this.getAttribute('language') ?? '';
423
+ }
424
+ set language(v) {
425
+ this.setAttribute('language', v);
426
+ }
427
+ /** Whether indent guides are drawn. Reflects `indent-guides`; without it, editorDefaults. */
428
+ get indentGuides() {
429
+ const v = this.getAttribute('indent-guides');
430
+ return v === null ? editorDefaults.indentGuides : v !== 'false';
431
+ }
432
+ set indentGuides(v) {
433
+ this.setAttribute('indent-guides', String(v));
434
+ }
435
+ /** Which whitespace is marked. Reflects `whitespace`; without a valid one, editorDefaults. */
436
+ get whitespace() {
437
+ const v = this.getAttribute('whitespace');
438
+ return isWhitespaceMode(v) ? v : editorDefaults.whitespace;
439
+ }
440
+ set whitespace(v) {
441
+ this.setAttribute('whitespace', v);
442
+ }
443
+ get theme() {
444
+ return this.#theme ?? editorDefaults.theme;
445
+ }
446
+ set theme(v) {
447
+ this.#theme = v;
448
+ this.#refreshRender();
449
+ }
450
+ /** A light and a dark theme, followed through the inherited `color-scheme` with no retokenize
451
+ * (see editorDefaults.themes). Wins over `theme`; either one set here wins over the defaults. */
452
+ get themes() {
453
+ return this.#themes ?? editorDefaults.themes;
454
+ }
455
+ set themes(v) {
456
+ this.#themes = v;
457
+ this.#refreshRender();
458
+ }
459
+ /** What the tokenizer and chrome resolve against: this element's pair, then its theme, then
460
+ * the defaults' pair, then theirs. */
461
+ #resolvedTheme() {
462
+ return this.#themes ?? this.#theme ?? editorDefaults.themes ?? editorDefaults.theme;
463
+ }
464
+ get grammars() {
465
+ return this.#grammars ?? editorDefaults.grammars;
466
+ }
467
+ set grammars(v) {
468
+ this.#grammars = v;
469
+ this.#refreshRender();
470
+ }
471
+ /** Runs a command (from `commands`) as its key binding would. False when it declined. */
472
+ run(command) {
473
+ return this.#run(command);
474
+ }
475
+ /** Scrolls `pos` into view without moving the selection, as following a collaborator does. */
476
+ revealPos(pos) {
477
+ this.#view?.revealPos(pos);
478
+ }
479
+ /** Undo, through whichever undo owns this editor (History, or an extension's). */
480
+ undo() {
481
+ return this.#run(this.#undo);
482
+ }
483
+ redo() {
484
+ return this.#run(this.#redo);
485
+ }
486
+ /** Programmatic edit. Origin defaults to 'host.apply' (its own undo step). */
487
+ apply(spec) {
488
+ return this.#core.apply({ ...spec, origin: spec.origin ?? 'host.apply' });
489
+ }
490
+ /** Install an extension. Resolves to its disposer once its setup has run. Extensions used
491
+ * before connect wait for it; disconnecting removes them. */
492
+ async use(extension) {
493
+ const lifetime = await this.#connected.promise;
494
+ const ac = new AbortController();
495
+ const signal = linked(ac.signal, lifetime);
496
+ try {
497
+ await extension(this.#contextFor(signal));
498
+ }
499
+ catch (err) {
500
+ ac.abort();
501
+ throw err;
502
+ }
503
+ return () => ac.abort();
504
+ }
505
+ connectedCallback() {
506
+ const lifetime = new AbortController();
507
+ this.#lifetime = lifetime;
508
+ const signal = lifetime.signal;
509
+ // The shadow root outlives a connection and delegatesFocus is fixed at attach, so the input
510
+ // path is chosen once.
511
+ this.#kind ??= surfaceKind(editorDefaults.input);
512
+ const root = this.shadowRoot ?? this.attachShadow({ mode: 'open', delegatesFocus: this.#kind === 'textarea' });
513
+ if (!this.#chrome || this.#chromeDoc !== root.ownerDocument) {
514
+ // Connected in another window (a tear-off): a sheet from the old one can't be adopted here,
515
+ // so start over. Everything else this root adopts is added again by this connection.
516
+ root.adoptedStyleSheets = [];
517
+ this.#chrome = sheetFor(root, this.#chromeCss);
518
+ this.#chromeDoc = root.ownerDocument;
519
+ }
520
+ if (!root.adoptedStyleSheets.includes(this.#chrome))
521
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, this.#chrome];
522
+ if (!this.hasAttribute('tabindex'))
523
+ this.setAttribute('tabindex', '0');
524
+ // In textarea mode the textarea is the one textbox assistive tech should see; giving the host
525
+ // role="textbox" too would nest a textbox inside a textbox. EditContext has no such child, so
526
+ // the host keeps the role.
527
+ if (this.#kind !== 'textarea')
528
+ for (const [k, v] of [['role', 'textbox'], ['aria-multiline', 'true']])
529
+ if (!this.hasAttribute(k))
530
+ this.setAttribute(k, v);
531
+ // An inline expansion reads its source's tokens and never needs a worker.
532
+ if (!this.#nested)
533
+ this.#spare ??= editorDefaults.worker();
534
+ this.#refreshRender();
535
+ followers.add(this.#onDefaults);
536
+ signal.addEventListener('abort', () => followers.delete(this.#onDefaults), { once: true });
537
+ this.#core.listen((u) => this.#onUpdate(u), signal);
538
+ this.addEventListener('mousedown', (e) => this.#onMouseDown(e), { signal });
539
+ // Built-in extensions, installed per connection. An inline expansion has none: Mod-f there
540
+ // searches nothing the source editor's bar would not.
541
+ if (!this.#nested)
542
+ void this.use(findReplace());
543
+ void createInputSurface(this, (e) => this.#onInput(e), this.#kind).then((surface) => {
544
+ if (signal.aborted)
545
+ return surface.dispose();
546
+ this.#surface = surface;
547
+ surface.setClipboardSource(() => this.#clipboardText());
548
+ this.#forwardLabel();
549
+ signal.addEventListener('abort', () => {
550
+ surface.dispose();
551
+ this.#surface = null;
552
+ this.#focused = false;
553
+ }, { once: true });
554
+ this.#syncSurface();
555
+ this.#connected.resolve(signal);
556
+ if (editorDefaults.autocomplete) {
557
+ void this.use(wordCompletions());
558
+ void this.use(autocomplete({ sources: () => this.#completionSources.map((r) => r.source) }));
559
+ }
560
+ });
561
+ }
562
+ disconnectedCallback() {
563
+ // Aborting tears down every follower, extension, worker, and highlight registration.
564
+ this.#lifetime?.abort();
565
+ this.#lifetime = null;
566
+ this.#holdUntil = null;
567
+ this.#spare?.terminate?.();
568
+ this.#spare = null;
569
+ this.#render = null;
570
+ this.#view = null;
571
+ this.#bridge = null;
572
+ this.#connected = deferred();
573
+ }
574
+ attributeChangedCallback(name) {
575
+ if (name === 'language')
576
+ this.#refreshRender();
577
+ else if (name === 'indent-guides' || name === 'whitespace')
578
+ this.#applyViewOptions();
579
+ else if (name === 'inline-expansion') {
580
+ if (!this.inlineExpansion)
581
+ this.#expansions.closeAll();
582
+ this.#refreshRender(true);
583
+ }
584
+ else
585
+ this.#forwardLabel();
586
+ }
587
+ #onDefaults = () => this.#refreshRender();
588
+ #applyViewOptions() {
589
+ this.#view?.setIndentGuides(this.indentGuides);
590
+ this.#view?.setWhitespace(this.whitespace);
591
+ }
592
+ /** Textarea mode: the textarea is the one textbox assistive tech sees, so the host's naming
593
+ * attributes have to reach it too. EditContext mode leaves the host untouched (focusTarget is
594
+ * the host itself). */
595
+ #forwardLabel() {
596
+ const target = this.#surface?.focusTarget;
597
+ if (!target || target === this)
598
+ return;
599
+ for (const k of ['aria-label', 'aria-labelledby', 'aria-describedby']) {
600
+ const v = this.getAttribute(k);
601
+ if (v === null)
602
+ target.removeAttribute(k);
603
+ else
604
+ target.setAttribute(k, v);
605
+ }
606
+ }
607
+ /** Builds or retargets the tokenizer and view to match language, grammars, and theme. `rebuild`
608
+ * builds the view again even when nothing it renders from changed (inline expansion on or off). */
609
+ #refreshRender(rebuild = false) {
610
+ const lifetime = this.#lifetime;
611
+ if (!lifetime)
612
+ return;
613
+ const grammars = this.grammars;
614
+ const theme = this.#resolvedTheme();
615
+ const language = this.language;
616
+ const config = { live: !!(grammars && theme && language), grammars, theme, language };
617
+ // Colors the knobs fall back to when the platform has no token (docs/design/theming.md).
618
+ this.#chromeCss = chromeCss(theme);
619
+ this.#chrome?.replaceSync(this.#chromeCss);
620
+ const cur = this.#render?.config;
621
+ // An expansion's tokens come from its source's bridge, whatever the theme or grammars do.
622
+ if (this.#nested && this.#render && !rebuild)
623
+ return;
624
+ if (!rebuild && cur && cur.live === config.live && (!config.live || cur.grammars === config.grammars)) {
625
+ if (config.live && !sameTheme(cur.theme, theme))
626
+ this.#bridge.setTheme(theme);
627
+ if (config.live && cur.language !== language)
628
+ this.#bridge.setLanguage(language, this.#core.state.version);
629
+ this.#render = { ac: this.#render.ac, config };
630
+ this.#applyViewOptions();
631
+ return;
632
+ }
633
+ this.#render?.ac.abort();
634
+ const ac = new AbortController();
635
+ this.#render = { ac, config };
636
+ const signal = linked(ac.signal, lifetime.signal);
637
+ let tokens;
638
+ let bridge = null;
639
+ const nested = this.#nested;
640
+ if (nested)
641
+ tokens = nested.tokens(signal);
642
+ else {
643
+ let worker = inertWorker();
644
+ if (config.live) {
645
+ worker = this.#spare ?? editorDefaults.worker();
646
+ this.#spare = null;
647
+ }
648
+ const b = new TokenBridge(worker, this.#core, { language, grammars: grammars ?? noGrammars, theme: theme ?? noTheme }, signal);
649
+ signal.addEventListener('abort', () => b.dispose(), { once: true });
650
+ tokens = bridge = b;
651
+ }
652
+ const rail = new FoldRail(this.#core, this.#folds, this.#foldRanges, signal);
653
+ const expand = this.inlineExpansion;
654
+ this.#expansions.resolver = expand ? (nested ? nested.resolver : sameDocumentResolver(this.#asSource)) : null;
655
+ const widgets = expand ? this.#makeWidgets(signal) : null;
656
+ const view = new EditorView(this.shadowRoot, this.#core, tokens, {
657
+ instance: this.#instance,
658
+ folding: rail,
659
+ indentGuides: this.indentGuides,
660
+ whitespace: this.whitespace,
661
+ ...(widgets ? { blocks: widgets } : {}),
662
+ ...(nested ? { lineNumbers: { offset: () => nested.gutter.offset(), digits: () => nested.gutter.digits() } } : {}),
663
+ }, signal);
664
+ if (nested) {
665
+ const off = nested.gutter.subscribe(() => view.invalidateGutter());
666
+ signal.addEventListener('abort', off, { once: true });
667
+ }
668
+ this.#widgets = widgets;
669
+ rail.mount(this.shadowRoot, signal);
670
+ new ScopeFocus(this.#core, this.#foldRanges, view).mount(this.shadowRoot, signal);
671
+ view.setFocused(this.#focused);
672
+ view.onFrame(() => this.#onFrame());
673
+ for (const r of this.#overlays)
674
+ view.addOverlaySource(r.source, linked(r.signal, signal));
675
+ for (const r of this.#lineClasses)
676
+ view.addLineClassSource(r.source, linked(r.signal, signal));
677
+ for (const r of this.#remoteCursors)
678
+ view.addRemoteCursorSource(r.source, linked(r.signal, signal));
679
+ this.#bridge = bridge;
680
+ this.#view = view;
681
+ this.#hold(false);
682
+ }
683
+ #makeWidgets(signal) {
684
+ return new ExpansionWidgets({
685
+ core: this.#core,
686
+ expansions: this.#expansions,
687
+ folds: this.#folds,
688
+ root: this.shadowRoot,
689
+ resolverIn: (doc) => sameDocumentResolver(doc),
690
+ createEditor: (config) => {
691
+ const el = createNestedEditor(this.ownerDocument, config);
692
+ el.language = this.language;
693
+ const theme = this.#resolvedTheme();
694
+ if (theme && isThemePair(theme))
695
+ el.themes = theme;
696
+ else
697
+ el.theme = theme;
698
+ el.grammars = this.grammars;
699
+ el.inlineExpansion = this.inlineExpansion;
700
+ el.indentGuides = this.indentGuides;
701
+ el.whitespace = this.whitespace;
702
+ el.setAttribute('aria-label', 'Inline definition');
703
+ return el;
704
+ },
705
+ focusAt: (pos) => this.#focusAt(pos),
706
+ digits: () => Math.max(String(this.#core.state.text.lines).length, this.#nested?.gutter.digits() ?? 0),
707
+ }, signal);
708
+ }
709
+ /** An inline expansion is as tall as its content, up to its line cap. */
710
+ #fitHeight(view) {
711
+ const cap = this.#nested.maxLines * view.lineHeight;
712
+ const h = `${Math.ceil(Math.min(view.contentHeight, cap) + view.scrollbarHeight)}px`;
713
+ if (this.style.height === h)
714
+ return;
715
+ // Inside a ResizeObserver callback (a nested expansion grew), resizing this host would be
716
+ // observed by the outer view in the same pass: the browser reports a loop. One frame later.
717
+ if (view.inResizeObserver)
718
+ requestAnimationFrame(() => (this.style.height = h));
719
+ else
720
+ this.style.height = h;
721
+ }
722
+ #onFrame() {
723
+ const view = this.#view;
724
+ if (this.#nested)
725
+ this.#fitHeight(view);
726
+ this.#geometry = {
727
+ control: this.getBoundingClientRect(),
728
+ caret: view.coordsAtPos(this.#core.state.selection.primary.head),
729
+ coordsAt: (pos) => view.coordsAtPos(pos),
730
+ };
731
+ this.#syncSurface();
732
+ }
733
+ /** Runs after every Update as well as after frames, so the platform's text and selection are
734
+ * current before the next keystroke even when no frame ran in between. Geometry is the last
735
+ * frame's. */
736
+ #syncSurface() {
737
+ const view = this.#view;
738
+ if (!this.#surface || !view)
739
+ return;
740
+ this.#geometry ??= { control: new DOMRect(), caret: null, coordsAt: (pos) => view.coordsAtPos(pos) };
741
+ this.#surface.sync(this.#core.state, this.#geometry);
742
+ }
743
+ #onUpdate(u) {
744
+ const c = this.#composition;
745
+ if (c && u.docChanged)
746
+ this.#composition = { from: u.changes.mapPos(c.from, 1), to: Math.max(u.changes.mapPos(c.from, 1), u.changes.mapPos(c.to, -1)) };
747
+ this.#syncSurface();
748
+ if (u.docChanged)
749
+ this.#queueEvent('change', u);
750
+ if (!u.before.selection.eq(u.after.selection))
751
+ this.#queueEvent('selectionchange', u);
752
+ }
753
+ #queueEvent(type, detail) {
754
+ this.#pendingEvents.push(new CustomEvent(type, { detail, bubbles: true }));
755
+ if (this.#pendingEvents.length === 1)
756
+ queueMicrotask(() => this.#flushEvents());
757
+ }
758
+ /** A listener (e.g. `change`) may call `apply()`, which queues more events; the loop picks
759
+ * those up too, so order stays FIFO across both the original batch and any reentrant ones. */
760
+ #flushEvents() {
761
+ while (this.#pendingEvents.length > 0)
762
+ this.dispatchEvent(this.#pendingEvents.shift());
763
+ }
764
+ /**
765
+ * The routing table from SurfaceEvent to commands. Exhaustive over SurfaceEvent.kind.
766
+ * - replace, composing or not: if [from, to) equals the primary range, run insertText at every
767
+ * range (multicursor typing and composition); otherwise one change at [from, to)
768
+ * (autocorrect, preedit updates), leaving the primary at its end when it was inside.
769
+ * Origin 'input.compose' while composing, else 'input.type'.
770
+ * - select: the platform moved its own caret; the selection follows as one range.
771
+ * - key: candidates from #keymap for normalizeKey(e); run each until one returns a spec; apply
772
+ * it; preventDefault. No binding, or every binding declined: let the platform act.
773
+ * - paste: N lines into N cursors go one per cursor; otherwise the whole text at each.
774
+ * - cut: copy is the surface's job; here delete every range with origin 'command'.
775
+ * - composition-end, focus: view state only (composition overlay, caret blink).
776
+ */
777
+ #onInput(e) {
778
+ const core = this.#core;
779
+ const state = core.state;
780
+ switch (e.kind) {
781
+ case 'replace': {
782
+ const p = state.selection.primary;
783
+ if (e.composing)
784
+ this.#composeTime ??= performance.now();
785
+ const origin = e.composing ? 'input.compose' : 'input.type';
786
+ let spec;
787
+ if (e.from === rangeFrom(p) && e.to === rangeTo(p)) {
788
+ // Auto-close: a bracket or quote pairs, steps over, or wraps, per range; never during
789
+ // composition, so IME preedit is unaffected. closeBrackets declines (null) for any
790
+ // other text, falling back to a plain insertText.
791
+ const paired = e.composing ? null : closeBrackets(e.text)({ state });
792
+ spec = { ...(paired ?? insertText(e.text)({ state })), origin };
793
+ }
794
+ else {
795
+ const changes = ChangeSet.of([{ from: e.from, to: e.to, insert: e.text }], state.text.length);
796
+ let selection = state.selection.map(changes);
797
+ if (p.head >= e.from && p.head <= e.to)
798
+ selection = withPrimary(selection, cursor(changes.mapPos(e.to, 1)));
799
+ spec = { changes, selection, origin, scrollIntoView: true };
800
+ }
801
+ const u = core.apply(spec);
802
+ if (e.composing && u) {
803
+ const from = u.changes.mapPos(e.from, -1);
804
+ const to = u.changes.mapPos(e.to, 1);
805
+ const c = this.#composition;
806
+ this.#composition = c ? { from: Math.min(c.from, from), to: Math.max(c.to, to) } : { from, to };
807
+ for (const f of this.#invalidateComposition)
808
+ f();
809
+ }
810
+ return;
811
+ }
812
+ case 'select':
813
+ core.apply({ selection: Selection.single(e.anchor, e.head), origin: 'select' });
814
+ return;
815
+ case 'key': {
816
+ if (!this.#focused)
817
+ return;
818
+ const name = normalizeKey(e.key, apple);
819
+ if (!name)
820
+ return;
821
+ for (const command of this.#keymap.candidates(name)) {
822
+ if (this.#run(command)) {
823
+ e.preventDefault();
824
+ return;
825
+ }
826
+ }
827
+ return;
828
+ }
829
+ case 'paste': {
830
+ const text = e.text.replace(/\r\n?/g, '\n');
831
+ const lines = text.split('\n');
832
+ if (state.selection.ranges.length > 1 && lines.length === state.selection.ranges.length) {
833
+ let i = 0;
834
+ core.apply(perRange(state, 'input.paste', (r) => {
835
+ const line = lines[i++];
836
+ return { change: { from: rangeFrom(r), to: rangeTo(r), insert: line }, range: cursor(rangeFrom(r) + line.length) };
837
+ }));
838
+ }
839
+ else
840
+ this.#run(insertText(text, 'input.paste'));
841
+ return;
842
+ }
843
+ case 'cut':
844
+ core.apply(perRange(state, 'command', (r) => (isCursor(r) ? { range: r } : { change: { from: rangeFrom(r), to: rangeTo(r) }, range: cursor(rangeFrom(r)) })));
845
+ return;
846
+ case 'composition-end':
847
+ this.#composition = null;
848
+ this.#composeTime = null;
849
+ for (const f of this.#invalidateComposition)
850
+ f();
851
+ this.#syncSurface();
852
+ return;
853
+ case 'focus':
854
+ this.#focused = e.focused;
855
+ this.#view?.setFocused(e.focused);
856
+ return;
857
+ }
858
+ }
859
+ /** True when the command took the key, even if its spec turned out to change nothing (an arrow
860
+ * at the document's edge): the platform must not act on it either. */
861
+ #run(command) {
862
+ const spec = command({ state: this.#core.state, layout: this.#view?.layout });
863
+ if (!spec)
864
+ return false;
865
+ this.#core.apply(spec);
866
+ return true;
867
+ }
868
+ /** Alt-Shift-drag: one range per line between the start and the pointer, spanning the same two
869
+ * x positions. Lines shorter than the box get a cursor at their end. Only mounted lines join. */
870
+ #boxSelect(e, pos) {
871
+ const x0 = e.clientX;
872
+ const line0 = this.#core.state.text.lineAt(pos).number;
873
+ this.#core.apply({ selection: Selection.single(pos), origin: 'select' });
874
+ this.#drag?.abort();
875
+ const drag = (this.#drag = new AbortController());
876
+ const signal = linked(drag.signal, this.#lifetime?.signal);
877
+ const doc = this.ownerDocument;
878
+ doc.addEventListener('mousemove', (m) => {
879
+ if ((m.buttons & 1) === 0)
880
+ return drag.abort();
881
+ const view = this.#view;
882
+ const head = view?.pointerPos(m.clientX, m.clientY, true);
883
+ if (!view || head == null)
884
+ return;
885
+ const text = this.#core.state.text;
886
+ const line1 = text.lineAt(head).number;
887
+ const ranges = [];
888
+ const step = line1 >= line0 ? 1 : -1;
889
+ for (let n = line0;; n += step) {
890
+ const r = view.coordsAtPos(text.line(n).from);
891
+ if (r) {
892
+ const y = r.top + r.height / 2;
893
+ const a = view.pointerPos(x0, y, true);
894
+ const b = view.pointerPos(m.clientX, y, true);
895
+ if (a != null && b != null)
896
+ ranges.push({ anchor: a, head: b });
897
+ }
898
+ if (n === line1)
899
+ break;
900
+ }
901
+ if (ranges.length === 0)
902
+ return;
903
+ const selection = Selection.create(ranges, ranges.length - 1);
904
+ this.#core.apply({ selection, origin: 'select' });
905
+ }, { signal });
906
+ doc.addEventListener('mouseup', () => drag.abort(), { signal });
907
+ }
908
+ #clipboardText() {
909
+ const { text, selection } = this.#core.state;
910
+ return selection.ranges
911
+ .filter((r) => !isCursor(r))
912
+ .map((r) => text.slice(rangeFrom(r), rangeTo(r)))
913
+ .join('\n');
914
+ }
915
+ #drag = null;
916
+ /** Started on connect so the worker's module graph loads while the host is still fetching
917
+ * grammars and a theme; the tokenizer takes it once those arrive. */
918
+ #spare = null;
919
+ /** When hidden text must show even without colors (performance.now() ms), or null. */
920
+ #holdUntil = null;
921
+ /** Overrides editorDefaults.multiCursorModifier for this editor. */
922
+ multiCursorModifier;
923
+ /** Click places the cursor, drag extends the primary range, Shift extends it, and the
924
+ * multi-cursor modifier adds a cursor. */
925
+ #onMouseDown(e) {
926
+ const view = this.#view;
927
+ const surface = this.#surface;
928
+ if (e.button !== 0 || !view || !surface)
929
+ return;
930
+ const pos = view.pointerPos(e.clientX, e.clientY, false);
931
+ if (pos === null)
932
+ return;
933
+ e.preventDefault();
934
+ surface.focusTarget.focus({ preventScroll: true });
935
+ if (e.altKey && e.shiftKey)
936
+ return this.#boxSelect(e, pos);
937
+ const sel = this.#core.state.selection;
938
+ const modifier = this.multiCursorModifier ?? editorDefaults.multiCursorModifier;
939
+ // Alt-click expands the call under the pointer, unless Alt is the multi-cursor modifier.
940
+ if (e.altKey && modifier !== 'alt' && this.#expandEnabled() && this.#expansions.toggle(pos) !== 'none') {
941
+ this.#core.apply({ selection: Selection.single(pos), origin: 'select' });
942
+ return;
943
+ }
944
+ const adds = modifier === 'alt' ? e.altKey : apple ? e.metaKey : e.ctrlKey;
945
+ const next = adds ? sel.addCursor(pos) : e.shiftKey ? Selection.single(sel.primary.anchor, pos) : Selection.single(pos);
946
+ this.#core.apply({ selection: next, origin: 'select' });
947
+ const anchor = next.primary.anchor;
948
+ // One drag at a time. A mouseup the document never saw would otherwise leave the old drag
949
+ // rewriting the selection on later clicks.
950
+ this.#drag?.abort();
951
+ const drag = (this.#drag = new AbortController());
952
+ const signal = linked(drag.signal, this.#lifetime?.signal);
953
+ const doc = this.ownerDocument;
954
+ doc.addEventListener('mousemove', (m) => {
955
+ if ((m.buttons & 1) === 0)
956
+ return drag.abort();
957
+ const head = this.#view?.pointerPos(m.clientX, m.clientY, true);
958
+ if (head == null)
959
+ return;
960
+ const s = this.#core.state.selection;
961
+ this.#core.apply({ selection: withPrimary(s, { anchor, head }), origin: 'select' });
962
+ }, { signal });
963
+ doc.addEventListener('mouseup', () => drag.abort(), { signal });
964
+ }
965
+ #addOverlays(source, signal) {
966
+ this.#overlays.push({ source, signal });
967
+ signal.addEventListener('abort', () => (this.#overlays = this.#overlays.filter((r) => r.source !== source)), { once: true });
968
+ if (this.#view && this.#render)
969
+ this.#view.addOverlaySource(source, linked(signal, this.#render.ac.signal));
970
+ }
971
+ #addLineClasses(source, signal) {
972
+ this.#lineClasses.push({ source, signal });
973
+ signal.addEventListener('abort', () => (this.#lineClasses = this.#lineClasses.filter((r) => r.source !== source)), { once: true });
974
+ if (this.#view && this.#render)
975
+ this.#view.addLineClassSource(source, linked(signal, this.#render.ac.signal));
976
+ }
977
+ #addRemoteCursors(source, signal) {
978
+ this.#remoteCursors.push({ source, signal });
979
+ signal.addEventListener('abort', () => (this.#remoteCursors = this.#remoteCursors.filter((r) => r.source !== source)), { once: true });
980
+ if (this.#view && this.#render)
981
+ this.#view.addRemoteCursorSource(source, linked(signal, this.#render.ac.signal));
982
+ }
983
+ #addCompletions(source, signal) {
984
+ const r = { source, signal };
985
+ this.#completionSources.push(r);
986
+ signal.addEventListener('abort', () => (this.#completionSources = this.#completionSources.filter((x) => x !== r)), { once: true });
987
+ }
988
+ #contextFor(signal) {
989
+ return {
990
+ core: this.#core,
991
+ signal,
992
+ host: this,
993
+ root: this.shadowRoot,
994
+ focusTarget: this.#surface.focusTarget,
995
+ completions: (source) => this.#addCompletions(source, signal),
996
+ keymap: (bindings, priority, sooner) => this.#keymap.add(bindings, priority, linked(signal, sooner)),
997
+ overlays: (source) => this.#addOverlays(source, signal),
998
+ lineClasses: (source) => this.#addLineClasses(source, signal),
999
+ remoteCursors: (source) => this.#addRemoteCursors(source, signal),
1000
+ undo: (owner) => this.#claimUndo(owner, signal),
1001
+ onUpdate: (listener) => void this.#core.listen(listener, signal),
1002
+ coordsAtPos: (pos) => this.#view?.coordsAtPos(pos) ?? null,
1003
+ };
1004
+ }
1005
+ }
1006
+ /** Idempotent: defining twice is a no-op, so two bundles importing the entry do not throw. */
1007
+ export function defineEditor(tag = 'nib-editor') {
1008
+ if (!customElements.get(tag))
1009
+ customElements.define(tag, class extends NibEditor {
1010
+ });
1011
+ }