@dou-ui/code 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -2
  3. package/dist/_virtual/_rolldown/runtime.js +12 -0
  4. package/dist/assets/default-BZBMZKf_.js.map +1 -0
  5. package/dist/code-diff.js +6 -0
  6. package/dist/code-diff.js.map +1 -0
  7. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +792 -0
  8. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -0
  9. package/dist/code-editor.js +6 -0
  10. package/dist/code-editor.js.map +1 -0
  11. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +4917 -0
  12. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -0
  13. package/dist/code-input.js +6 -0
  14. package/dist/code-input.js.map +1 -0
  15. package/dist/code-input.vue_vue_type_script_setup_true_lang.js +237 -0
  16. package/dist/code-input.vue_vue_type_script_setup_true_lang.js.map +1 -0
  17. package/dist/code-keys.js +42 -0
  18. package/dist/code-keys.js.map +1 -0
  19. package/dist/code-keys.vue_vue_type_script_setup_true_lang.js +168 -0
  20. package/dist/code-keys.vue_vue_type_script_setup_true_lang.js.map +1 -0
  21. package/dist/code-keys2.js +6 -0
  22. package/dist/code-keys2.js.map +1 -0
  23. package/dist/collaboration/index.js +255 -0
  24. package/dist/collaboration/index.js.map +1 -0
  25. package/dist/completion/match.js +55 -0
  26. package/dist/completion/match.js.map +1 -0
  27. package/dist/completion/snippet.js +71 -0
  28. package/dist/completion/snippet.js.map +1 -0
  29. package/dist/core/brackets.js +55 -0
  30. package/dist/core/brackets.js.map +1 -0
  31. package/dist/core/changes.js +185 -0
  32. package/dist/core/changes.js.map +1 -0
  33. package/dist/core/chars.js +130 -0
  34. package/dist/core/chars.js.map +1 -0
  35. package/dist/core/commands.js +910 -0
  36. package/dist/core/commands.js.map +1 -0
  37. package/dist/core/diff.js +215 -0
  38. package/dist/core/diff.js.map +1 -0
  39. package/dist/core/folding.js +87 -0
  40. package/dist/core/folding.js.map +1 -0
  41. package/dist/core/history.js +74 -0
  42. package/dist/core/history.js.map +1 -0
  43. package/dist/core/keymap.js +326 -0
  44. package/dist/core/keymap.js.map +1 -0
  45. package/dist/core/search.js +91 -0
  46. package/dist/core/search.js.map +1 -0
  47. package/dist/core/selection.js +88 -0
  48. package/dist/core/selection.js.map +1 -0
  49. package/dist/core/text.js +320 -0
  50. package/dist/core/text.js.map +1 -0
  51. package/dist/core/transaction.js +98 -0
  52. package/dist/core/transaction.js.map +1 -0
  53. package/dist/extension.js +16 -0
  54. package/dist/extension.js.map +1 -0
  55. package/dist/index.js +38 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/language/highlighter.js +336 -0
  58. package/dist/language/highlighter.js.map +1 -0
  59. package/dist/language/language.js +138 -0
  60. package/dist/language/language.js.map +1 -0
  61. package/dist/language/stream.js +112 -0
  62. package/dist/language/stream.js.map +1 -0
  63. package/dist/language/to-html.js +36 -0
  64. package/dist/language/to-html.js.map +1 -0
  65. package/dist/language/worker-client.js +198 -0
  66. package/dist/language/worker-client.js.map +1 -0
  67. package/dist/language/worker-protocol.js +48 -0
  68. package/dist/language/worker-protocol.js.map +1 -0
  69. package/dist/languages/css.js +128 -0
  70. package/dist/languages/css.js.map +1 -0
  71. package/dist/languages/html.js +175 -0
  72. package/dist/languages/html.js.map +1 -0
  73. package/dist/languages/javascript.js +300 -0
  74. package/dist/languages/javascript.js.map +1 -0
  75. package/dist/languages/json.js +45 -0
  76. package/dist/languages/json.js.map +1 -0
  77. package/dist/languages/markdown.js +82 -0
  78. package/dist/languages/markdown.js.map +1 -0
  79. package/dist/languages/python.js +88 -0
  80. package/dist/languages/python.js.map +1 -0
  81. package/dist/languages/shell.js +153 -0
  82. package/dist/languages/shell.js.map +1 -0
  83. package/dist/languages/sql.js +91 -0
  84. package/dist/languages/sql.js.map +1 -0
  85. package/dist/languages/yaml.js +85 -0
  86. package/dist/languages/yaml.js.map +1 -0
  87. package/dist/locale.js +164 -0
  88. package/dist/locale.js.map +1 -0
  89. package/dist/lsp/index.js +715 -0
  90. package/dist/lsp/index.js.map +1 -0
  91. package/dist/lsp/markup.js +139 -0
  92. package/dist/lsp/markup.js.map +1 -0
  93. package/dist/render-part.js +14 -0
  94. package/dist/render-part.js.map +1 -0
  95. package/dist/shiki/index.js +140 -0
  96. package/dist/shiki/index.js.map +1 -0
  97. package/dist/style.css +1 -0
  98. package/dist/style.d.ts +1 -0
  99. package/dist/style.js +4 -0
  100. package/dist/types/code-diff.vue.d.ts +45 -0
  101. package/dist/types/code-editor.vue.d.ts +43 -0
  102. package/dist/types/code-input.vue.d.ts +32 -0
  103. package/dist/types/code-keys.d.ts +9 -0
  104. package/dist/types/code-keys.vue.d.ts +8 -0
  105. package/dist/types/collaboration/index.d.ts +36 -0
  106. package/dist/types/completion/match.d.ts +13 -0
  107. package/dist/types/completion/snippet.d.ts +17 -0
  108. package/dist/types/core/brackets.d.ts +15 -0
  109. package/dist/types/core/changes.d.ts +52 -0
  110. package/dist/types/core/chars.d.ts +24 -0
  111. package/dist/types/core/commands.d.ts +199 -0
  112. package/dist/types/core/diff.d.ts +52 -0
  113. package/dist/types/core/folding.d.ts +23 -0
  114. package/dist/types/core/history.d.ts +24 -0
  115. package/dist/types/core/keymap.d.ts +29 -0
  116. package/dist/types/core/search.d.ts +37 -0
  117. package/dist/types/core/selection.d.ts +28 -0
  118. package/dist/types/core/text.d.ts +79 -0
  119. package/dist/types/core/transaction.d.ts +65 -0
  120. package/dist/types/extension.d.ts +321 -0
  121. package/dist/types/index.d.ts +159 -0
  122. package/dist/types/language/highlighter.d.ts +99 -0
  123. package/dist/types/language/language.d.ts +100 -0
  124. package/dist/types/language/stream.d.ts +56 -0
  125. package/dist/types/language/to-html.d.ts +17 -0
  126. package/dist/types/language/worker-client.d.ts +52 -0
  127. package/dist/types/language/worker-protocol.d.ts +50 -0
  128. package/dist/types/languages/css.d.ts +17 -0
  129. package/dist/types/languages/html.d.ts +34 -0
  130. package/dist/types/languages/javascript.d.ts +29 -0
  131. package/dist/types/languages/json.d.ts +7 -0
  132. package/dist/types/languages/markdown.d.ts +17 -0
  133. package/dist/types/languages/python.d.ts +9 -0
  134. package/dist/types/languages/shell.d.ts +11 -0
  135. package/dist/types/languages/sql.d.ts +9 -0
  136. package/dist/types/languages/yaml.d.ts +14 -0
  137. package/dist/types/locale.d.ts +79 -0
  138. package/dist/types/lsp/index.d.ts +119 -0
  139. package/dist/types/lsp/markup.d.ts +14 -0
  140. package/dist/types/render-part.d.ts +14 -0
  141. package/dist/types/shiki/index.d.ts +63 -0
  142. package/dist/types/types.d.ts +267 -0
  143. package/dist/types/view/input.d.ts +12 -0
  144. package/dist/types/view/layout.d.ts +55 -0
  145. package/dist/types/view/measure.d.ts +22 -0
  146. package/dist/types/worker/default.d.ts +1 -0
  147. package/dist/types/worker/index.d.ts +34 -0
  148. package/dist/view/input.js +27 -0
  149. package/dist/view/input.js.map +1 -0
  150. package/dist/view/layout.js +194 -0
  151. package/dist/view/layout.js.map +1 -0
  152. package/dist/view/measure.js +104 -0
  153. package/dist/view/measure.js.map +1 -0
  154. package/dist/worker/default.js +20 -0
  155. package/dist/worker/default.js.map +1 -0
  156. package/dist/worker/index.js +139 -0
  157. package/dist/worker/index.js.map +1 -0
  158. package/package.json +88 -4
@@ -0,0 +1,4917 @@
1
+ import { matchBracket } from "./core/brackets.js";
2
+ import { ChangeSet } from "./core/changes.js";
3
+ import { indentOf, moveCluster, snapCluster, wordAt } from "./core/chars.js";
4
+ import { isEmptyRange, mainRange, normalizeSelection, rangeFrom, rangeTo, sameSelection, selectionOf } from "./core/selection.js";
5
+ import { deleteCharBackward, deleteCharForward, insertNewline, insertTab, insertText, selectAll } from "./core/commands.js";
6
+ import { foldEndAt, hiddenLines, mergeRanges } from "./core/folding.js";
7
+ import { CodeHistory } from "./core/history.js";
8
+ import { buildKeymap, defaultKeymap, eventKey, keymapBindings } from "./core/keymap.js";
9
+ import { CodeText, splitLines } from "./core/text.js";
10
+ import { CodeTransaction } from "./core/transaction.js";
11
+ import { matchAfter, replacementFor, searchText } from "./core/search.js";
12
+ import { lineParts, tokenTypes } from "./language/language.js";
13
+ import { CodeHighlighter } from "./language/highlighter.js";
14
+ import { SyntaxWorkerClient, holdWorker, ownWorker } from "./language/worker-client.js";
15
+ import { format, useCodeMessages } from "./locale.js";
16
+ import code_keys_default from "./code-keys2.js";
17
+ import { CODE_EDITOR_KEY } from "./extension.js";
18
+ import render_part_default from "./render-part.js";
19
+ import { matchCompletion } from "./completion/match.js";
20
+ import { parseSnippet } from "./completion/snippet.js";
21
+ import { diffText } from "./view/input.js";
22
+ import { LineLayout, UNWRAPPED, rowOfCol, updateRows, wrapLine } from "./view/layout.js";
23
+ import { Measure } from "./view/measure.js";
24
+ import { DouFindReplace, DouToggle, DouTooltip, holdPointer, isApplePlatform, isComposing, scrollPositionOf, useLocale, useNamespace, useTeleport, useZIndex } from "dou-ui";
25
+ import { Fragment, Teleport, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, getCurrentInstance, isMemoSame, markRaw, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, provide, reactive, ref, renderList, resolveDynamicComponent, shallowReactive, shallowRef, toDisplayString, toRaw, unref, watch, withCtx, withModifiers } from "vue";
26
+ import { AlertTriangleIcon, ChevronDownIcon, ChevronRightIcon, FunctionIcon, InfoIcon, LetterCaseIcon, LightbulbIcon, PackageIcon, RegexIcon, SquareCodeIcon, SymbolClassIcon, SymbolConstantIcon, SymbolKeywordIcon, SymbolTypeAliasIcon, TypeIcon, VariableIcon, WholeWordIcon, WrenchIcon, XCircleIcon } from "@dou-ui/icons";
27
+ // src/code-editor.vue?vue&type=script&setup=true&lang.ts
28
+ var _hoisted_1 = [
29
+ "title",
30
+ "data-gutter-cell",
31
+ "data-line"
32
+ ];
33
+ var _hoisted_2 = ["data-fold"];
34
+ var _hoisted_3 = ["title"];
35
+ var _hoisted_4 = ["data-unfold", "title"];
36
+ var _hoisted_5 = ["title"];
37
+ var _hoisted_6 = ["data-unfold", "title"];
38
+ var _hoisted_7 = ["aria-label"];
39
+ var _hoisted_8 = ["aria-current", "onClick"];
40
+ var _hoisted_9 = ["aria-label"];
41
+ var _hoisted_10 = [
42
+ "id",
43
+ "aria-selected",
44
+ "onClick"
45
+ ];
46
+ var _hoisted_11 = ["aria-label"];
47
+ var _hoisted_12 = ["onPointerdown"];
48
+ var _hoisted_13 = ["title"];
49
+ var _hoisted_14 = ["aria-label"];
50
+ var _hoisted_15 = ["onClick"];
51
+ var _hoisted_16 = [
52
+ "aria-label",
53
+ "aria-placeholder",
54
+ "aria-autocomplete",
55
+ "aria-controls",
56
+ "readonly",
57
+ "disabled"
58
+ ];
59
+ var _hoisted_17 = ["role", "aria-label"];
60
+ var MAX_HEIGHT = 8e6;
61
+ var OVERSCAN = 6;
62
+ /** The textarea mirrors at most this much text around the cursor. */
63
+ var WINDOW = 4e3;
64
+ var LINT_DELAY = 300;
65
+ var SYNTAX_REACH = 2e3;
66
+ /** Handles under the ends of the selection, or under a lone cursor right after a tap. */
67
+ var GAP = 8;
68
+ /** How high a handle reaches below its line, which the toolbar keeps clear of. */
69
+ var HANDLE = 24;
70
+ var KEYS_HEIGHT = 44;
71
+ var KEYS_GAP = 8;
72
+ var MINI_ROW = 2;
73
+ var MINI_CELL = 1;
74
+ /** The minimap's width, padding included. */
75
+ var MINI_WIDTH = 96;
76
+ var MINI_PAD = 6;
77
+ var code_editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
78
+ name: "DouCodeEditor",
79
+ __name: "code-editor",
80
+ props: {
81
+ modelValue: { default: void 0 },
82
+ modelModifiers: {},
83
+ doc: { default: void 0 },
84
+ selection: { default: void 0 },
85
+ readonly: { type: Boolean },
86
+ disabled: { type: Boolean },
87
+ lineNumbers: {
88
+ type: Boolean,
89
+ default: true
90
+ },
91
+ gutter: {
92
+ type: Boolean,
93
+ default: true
94
+ },
95
+ activeLine: {
96
+ type: Boolean,
97
+ default: true
98
+ },
99
+ tabSize: { default: 2 },
100
+ indentWithTabs: { type: Boolean },
101
+ placeholder: {},
102
+ language: { default: void 0 },
103
+ worker: {
104
+ type: [Boolean, Function],
105
+ default: false
106
+ },
107
+ closeBrackets: {
108
+ type: Boolean,
109
+ default: true
110
+ },
111
+ matchBrackets: {
112
+ type: Boolean,
113
+ default: true
114
+ },
115
+ searchable: {
116
+ type: Boolean,
117
+ default: true
118
+ },
119
+ wrap: {
120
+ type: Boolean,
121
+ default: false
122
+ },
123
+ minimap: {
124
+ type: Boolean,
125
+ default: false
126
+ },
127
+ foldable: {
128
+ type: Boolean,
129
+ default: true
130
+ },
131
+ messages: { default: void 0 },
132
+ keys: {
133
+ type: [Boolean, Array],
134
+ default: true
135
+ },
136
+ keymap: {},
137
+ tabIndents: {
138
+ type: Boolean,
139
+ default: true
140
+ },
141
+ extensions: {},
142
+ diagnostics: {},
143
+ teleport: {
144
+ type: [String, Boolean],
145
+ default: void 0
146
+ },
147
+ autofocus: { type: Boolean },
148
+ ariaLabel: {}
149
+ },
150
+ emits: [
151
+ "update:modelValue",
152
+ "update:doc",
153
+ "update:selection",
154
+ "transaction",
155
+ "focus",
156
+ "blur",
157
+ "foldChange"
158
+ ],
159
+ setup(__props, { expose: __expose, emit: __emit }) {
160
+ const props = __props;
161
+ const emit = __emit;
162
+ const ns = useNamespace("code-editor");
163
+ const instance = getCurrentInstance();
164
+ /** Space above the first line and below the last, and before and after each line; set from the styles once measured. */
165
+ const pad = reactive({
166
+ x: 12,
167
+ y: 8
168
+ });
169
+ /** Browsers stop growing an element somewhere past 16M px; taller texts scroll in scaled steps. */
170
+ const apple = isApplePlatform();
171
+ const initialDoc = () => (props.doc && toRaw(props.doc)) ?? (props.modelValue !== void 0 ? CodeText.of(props.modelValue) : CodeText.empty);
172
+ const startDoc = initialDoc();
173
+ const state = shallowRef(markRaw({
174
+ doc: startDoc,
175
+ selection: normalizeSelection(toRaw(props.selection) ?? selectionOf(0), startDoc.length)
176
+ }));
177
+ const doc = computed(() => state.value.doc);
178
+ const history = markRaw(new CodeHistory());
179
+ const historyTick = ref(0);
180
+ /** The last string handed out, for the text it was made from, so it is joined at most once. */
181
+ let joined = null;
182
+ const textOf = (text) => {
183
+ if (joined?.doc !== text) joined = {
184
+ doc: text,
185
+ text: text.toString()
186
+ };
187
+ return joined.text;
188
+ };
189
+ const listens = (event) => !!instance.vnode.props?.[event];
190
+ let lazyDirty = false;
191
+ /** Values this editor handed out; seeing one come back through a prop is only an echo. */
192
+ const handedOut = /* @__PURE__ */ new WeakSet();
193
+ function emitDoc(value) {
194
+ handedOut.add(value);
195
+ emit("update:doc", value);
196
+ }
197
+ function emitSelection(value) {
198
+ handedOut.add(value);
199
+ emit("update:selection", value);
200
+ }
201
+ function emitChange(result) {
202
+ const { state: next, before, changes } = result;
203
+ if (!changes.empty) {
204
+ emitDoc(next.doc);
205
+ if (props.modelModifiers?.lazy) lazyDirty = true;
206
+ else if (listens("onUpdate:modelValue")) emit("update:modelValue", textOf(next.doc));
207
+ }
208
+ if (!sameSelection(next.selection, before.selection)) emitSelection(next.selection);
209
+ emit("transaction", result);
210
+ }
211
+ /** Goal x of each cursor moved up or down, so it keeps its column across short lines. */
212
+ let goals = /* @__PURE__ */ new Map();
213
+ let pendingGoals = /* @__PURE__ */ new Map();
214
+ const blink = ref(0);
215
+ /** The last press was a finger: the selection gets handles, and a toolbar over it. */
216
+ const touchUi = ref(false);
217
+ /** A handle under a lone cursor, shown after a tap until the text changes. */
218
+ const caretHandle = ref(false);
219
+ /** The toolbar over the selection (cut, copy, paste, select all). */
220
+ const menuOpen = ref(false);
221
+ /** A finger drags a handle or a long-pressed selection: the magnifier shows. */
222
+ const touchDrag = ref(false);
223
+ /** Steps whose changes aren't this user's typing: extensions' `transaction` hooks don't see them. */
224
+ const UNHOOKED = /* @__PURE__ */ new Set([
225
+ "undo",
226
+ "redo",
227
+ "external",
228
+ "remote"
229
+ ]);
230
+ /** Runs every extension's `update` hook for a step that was applied. */
231
+ function notify(result) {
232
+ for (const extension of extensions.value) extension.update?.(result, context);
233
+ }
234
+ function dispatch(tr) {
235
+ const { action } = tr.meta;
236
+ if (!UNHOOKED.has(action ?? "")) for (const extension of extensions.value) extension.transaction?.(tr, context);
237
+ const result = tr.resolve();
238
+ const before = state.value;
239
+ if (!result.changed) {
240
+ pendingGoals = /* @__PURE__ */ new Map();
241
+ return result;
242
+ }
243
+ const remote = action === "remote";
244
+ if (!result.changes.empty && !historyHandler.value) {
245
+ history.record(result);
246
+ historyTick.value++;
247
+ }
248
+ if (!result.changes.empty) {
249
+ if (composing.value) mapComposition(result.changes);
250
+ syntaxChange(result.state.doc, result.changes);
251
+ mapMatches(result.changes);
252
+ updateWrap(before.doc, result.state.doc, result.changes);
253
+ mapFolds(result.changes, result.state.doc);
254
+ mapDiagnostics(result.changes, result.state.doc);
255
+ scheduleLint();
256
+ }
257
+ state.value = markRaw(result.state);
258
+ revealFolds();
259
+ if (!remote) {
260
+ problemBox.value = null;
261
+ menuOpen.value = false;
262
+ if (!result.changes.empty) caretHandle.value = false;
263
+ goals = pendingGoals;
264
+ blink.value++;
265
+ }
266
+ pendingGoals = /* @__PURE__ */ new Map();
267
+ if (!composing.value) syncInput();
268
+ updateAssist(result);
269
+ emitChange(result);
270
+ notify(result);
271
+ if (result.meta.scroll ?? !result.changes.empty) nextTick(() => {
272
+ scrollIntoView();
273
+ if (touchUi.value) followViewport();
274
+ });
275
+ return result;
276
+ }
277
+ const transaction = () => new CodeTransaction(state.value);
278
+ /** The extensions, highest priority first. */
279
+ const extensions = computed(() => (props.extensions ?? []).slice().sort((a, b) => (b.priority ?? 100) - (a.priority ?? 100)));
280
+ /** What extensions see; the same object as the instance, made once the instance is. */
281
+ let context;
282
+ /** Problems by who found them (`prop` for the prop, else the extension's name), moved with every edit. */
283
+ const diagnosticSets = shallowRef(/* @__PURE__ */ new Map());
284
+ const SEVERITY_RANK = {
285
+ error: 0,
286
+ warning: 1,
287
+ info: 2,
288
+ hint: 3
289
+ };
290
+ const diagnostics = computed(() => {
291
+ const all = [];
292
+ for (const list of diagnosticSets.value.values()) all.push(...list);
293
+ return all.sort((a, b) => a.from - b.from || SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
294
+ });
295
+ function setDiagnostics(key, list) {
296
+ const length = doc.value.length;
297
+ const next = new Map(diagnosticSets.value);
298
+ const clean = (list ?? []).map((d) => {
299
+ const from = Math.max(0, Math.min(length, Math.min(d.from, d.to)));
300
+ return {
301
+ ...d,
302
+ from,
303
+ to: Math.max(from, Math.min(length, Math.max(d.from, d.to)))
304
+ };
305
+ });
306
+ if (clean.length) next.set(key, clean);
307
+ else if (!next.has(key)) return;
308
+ else next.delete(key);
309
+ diagnosticSets.value = next;
310
+ }
311
+ /** Moves the problems along with an edit; one whose text was all deleted shrinks to where it was. */
312
+ function mapDiagnostics(changes, after) {
313
+ if (!diagnosticSets.value.size) return;
314
+ const next = /* @__PURE__ */ new Map();
315
+ for (const [key, list] of diagnosticSets.value) next.set(key, list.map((d) => {
316
+ const from = Math.min(after.length, changes.mapPos(d.from, 1));
317
+ return {
318
+ ...d,
319
+ from,
320
+ to: Math.max(from, Math.min(after.length, changes.mapPos(d.to, -1)))
321
+ };
322
+ }));
323
+ diagnosticSets.value = next;
324
+ }
325
+ watch(() => props.diagnostics, (list) => setDiagnostics("prop", list), { immediate: true });
326
+ /** Runs the linters a moment after the text stops changing. */
327
+ let lintTimer = 0;
328
+ const linting = computed(() => extensions.value.some((extension) => extension.lint));
329
+ function runLint(name) {
330
+ if (name === void 0) clearTimeout(lintTimer);
331
+ const text = doc.value;
332
+ for (const extension of extensions.value) {
333
+ if (!extension.lint || name !== void 0 && extension.name !== name) continue;
334
+ let found;
335
+ try {
336
+ found = extension.lint(context);
337
+ } catch (error) {
338
+ console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error);
339
+ continue;
340
+ }
341
+ if (!found || !("then" in found)) {
342
+ setDiagnostics(extension.name, found);
343
+ continue;
344
+ }
345
+ Promise.resolve(found).then((list) => {
346
+ if (doc.value === text) setDiagnostics(extension.name, list);
347
+ }).catch((error) => console.error(`[@dou-ui/code] ${extension.name}: lint failed`, error));
348
+ }
349
+ }
350
+ function scheduleLint() {
351
+ if (!linting.value || !mounted.value) return;
352
+ clearTimeout(lintTimer);
353
+ lintTimer = window.setTimeout(runLint, LINT_DELAY);
354
+ }
355
+ watch(extensions, (next, before) => {
356
+ if (before && before.length === next.length && next.every((extension, i) => extension === before[i])) return;
357
+ for (const gone of before ?? []) if (!next.includes(gone)) setDiagnostics(gone.name, []);
358
+ if (mounted.value) runLint();
359
+ });
360
+ function transact(build, meta) {
361
+ const tr = transaction();
362
+ if (meta) tr.setMeta(meta);
363
+ build(tr);
364
+ return dispatch(tr);
365
+ }
366
+ function applySteps(step, action) {
367
+ if (!step) return false;
368
+ const tr = transaction().setMeta({
369
+ action,
370
+ history: false,
371
+ scroll: true
372
+ });
373
+ for (const change of step.changes.changes) tr.replace(change.from, change.to, change.insert);
374
+ tr.select(step.selection);
375
+ dispatch(tr);
376
+ return true;
377
+ }
378
+ /** The undo history an extension brings in place of the editor's own; the first one wins. */
379
+ const historyHandler = computed(() => {
380
+ for (const extension of extensions.value) if (extension.history) return markRaw(extension.history(context));
381
+ return null;
382
+ });
383
+ const undo = () => !props.readonly && (historyHandler.value ? historyHandler.value.undo() : applySteps(history.undo(), "undo"));
384
+ const redo = () => !props.readonly && (historyHandler.value ? historyHandler.value.redo() : applySteps(history.redo(), "redo"));
385
+ const closeHistory = () => historyHandler.value ? historyHandler.value.close?.() : history.close();
386
+ /**
387
+ * Takes in a new text from outside as the smallest change, so the cursor
388
+ * and undo survive. `given` is the text as a `CodeText` when it came in as
389
+ * one; it is kept as it is, so it compares equal when it comes back.
390
+ */
391
+ function receive(next, given) {
392
+ if (joined && joined.text === next && joined.doc === doc.value) return;
393
+ const old = textOf(doc.value);
394
+ const normalized = next.includes("\r") ? next.replace(/\r\n?/g, "\n") : next;
395
+ const diff = diffText(old, normalized, mainRange(state.value.selection).head);
396
+ if (!diff) {
397
+ if (given) {
398
+ highlighter?.update(given, ChangeSet.of([], given.length));
399
+ state.value = markRaw({
400
+ ...state.value,
401
+ doc: given
402
+ });
403
+ if (wrapRows) rebuildWrap();
404
+ }
405
+ return;
406
+ }
407
+ const tr = transaction().setMeta({
408
+ action: "external",
409
+ scroll: false
410
+ });
411
+ tr.replace(diff.from, diff.to, diff.insert);
412
+ const resolved = tr.resolve();
413
+ const result = given ? {
414
+ ...resolved,
415
+ state: markRaw({
416
+ ...resolved.state,
417
+ doc: given
418
+ })
419
+ } : resolved;
420
+ if (!historyHandler.value) {
421
+ history.record(result);
422
+ historyTick.value++;
423
+ }
424
+ if (composing.value) mapComposition(result.changes);
425
+ syntaxChange(result.state.doc, result.changes);
426
+ updateWrap(result.before.doc, result.state.doc, result.changes);
427
+ mapFolds(result.changes, result.state.doc);
428
+ mapDiagnostics(result.changes, result.state.doc);
429
+ problemBox.value = null;
430
+ scheduleLint();
431
+ state.value = markRaw(result.state);
432
+ mapMatches(result.changes);
433
+ menuOpen.value = false;
434
+ caretHandle.value = false;
435
+ joined = {
436
+ doc: result.state.doc,
437
+ text: normalized
438
+ };
439
+ if (!composing.value) syncInput();
440
+ if (!sameSelection(result.state.selection, result.before.selection)) emitSelection(result.state.selection);
441
+ if (!given) emitDoc(result.state.doc);
442
+ else if (listens("onUpdate:modelValue")) emit("update:modelValue", normalized);
443
+ emit("transaction", result);
444
+ notify(result);
445
+ }
446
+ watch(() => props.modelValue, (value) => value !== void 0 && receive(value));
447
+ watch(() => props.doc && toRaw(props.doc), (value) => {
448
+ if (!value || value === doc.value || handedOut.has(value)) return;
449
+ receive(value.toString(), value);
450
+ });
451
+ watch(() => props.selection && toRaw(props.selection), (value) => {
452
+ if (!value || handedOut.has(value)) return;
453
+ const next = normalizeSelection(value, doc.value.length);
454
+ if (sameSelection(next, state.value.selection)) return;
455
+ dispatch(transaction().select(next).setMeta({ scroll: true }));
456
+ });
457
+ const root = ref();
458
+ const scroller = ref();
459
+ const content = ref();
460
+ const probe = ref();
461
+ const input = ref();
462
+ const measure = markRaw(new Measure(() => probe.value));
463
+ /** Bumped when the font metrics change, so everything drawn from them is worked out again. */
464
+ const metrics = ref(0);
465
+ const mounted = ref(false);
466
+ const scrollTop = ref(0);
467
+ const scrollLeft = ref(0);
468
+ const viewHeight = ref(0);
469
+ const viewWidth = ref(0);
470
+ /** The part of the scroller that is inside the window, for an editor taller than the page. */
471
+ const clip = ref(null);
472
+ const lineHeight = computed(() => {
473
+ metrics.value;
474
+ return measure.lineHeight;
475
+ });
476
+ /** The width a row of text may take when wrapping; 0 when lines don't wrap. */
477
+ const wrapWidth = computed(() => {
478
+ if (!props.wrap || !mounted.value) return 0;
479
+ metrics.value;
480
+ const width = viewWidth.value - gutterWidth.value - pad.x * 2 - measure.cell;
481
+ return Math.max(measure.cell * 8, width);
482
+ });
483
+ /** How each line text is cut at the current width; texts repeat (blank lines, braces), so this is by text. */
484
+ let wrapCache = /* @__PURE__ */ new Map();
485
+ /** Rows of each line while wrapping (index `n - 1`), kept in step with edits. */
486
+ let wrapRows = null;
487
+ /** Bumped when `wrapRows` changes without the text changing. */
488
+ const layoutTick = ref(0);
489
+ function wrapOf(text) {
490
+ const width = wrapWidth.value;
491
+ if (!width || text.length * measure.cell <= width / 2) return UNWRAPPED;
492
+ let wrapped = wrapCache.get(text);
493
+ if (!wrapped) {
494
+ if (wrapCache.size > 2e4) wrapCache = /* @__PURE__ */ new Map();
495
+ wrapped = wrapLine(text, width, measure);
496
+ wrapCache.set(text, wrapped);
497
+ }
498
+ return wrapped;
499
+ }
500
+ const rowsOfText = (text) => wrapOf(text).breaks.length + 1;
501
+ function rebuildWrap() {
502
+ wrapCache = /* @__PURE__ */ new Map();
503
+ wrapRows = wrapWidth.value ? doc.value.lineTexts(1, doc.value.lines).map(rowsOfText) : null;
504
+ layoutTick.value++;
505
+ }
506
+ /** Moves the wrapped rows along with an edit, cutting again only the lines it touched. */
507
+ function updateWrap(before, after, changes) {
508
+ if (!wrapRows) return;
509
+ if (!updateRows(wrapRows, before, after, changes, rowsOfText)) rebuildWrap();
510
+ }
511
+ const folds = shallowRef([]);
512
+ const NOTHING_HIDDEN = [];
513
+ const foldHidden = computed(() => folds.value.length ? hiddenLines(doc.value, folds.value) : NOTHING_HIDDEN);
514
+ /** The lines extensions hide, as sorted ranges that don't overlap. */
515
+ const extensionHidden = computed(() => {
516
+ const lines = doc.value.lines;
517
+ const ranges = [];
518
+ for (const extension of extensions.value) {
519
+ if (!extension.hide) continue;
520
+ for (const { from, to } of extension.hide(context)) {
521
+ const a = Math.max(1, Math.floor(from));
522
+ const b = Math.min(lines, Math.floor(to));
523
+ if (b >= a) ranges.push([a, b]);
524
+ }
525
+ }
526
+ return ranges.length ? mergeRanges(ranges) : NOTHING_HIDDEN;
527
+ });
528
+ /** The lines not drawn: folded, or hidden by an extension. */
529
+ const hidden = computed(() => {
530
+ const own = foldHidden.value;
531
+ const other = extensionHidden.value;
532
+ if (!other.length) return own;
533
+ if (!own.length) return other;
534
+ return mergeRanges([...own, ...other]);
535
+ });
536
+ const layout = computed((previous) => {
537
+ layoutTick.value;
538
+ const lines = doc.value.lines;
539
+ const rows = wrapRows && wrapRows.length === lines ? wrapRows : null;
540
+ if (!rows && !hidden.value.length && previous?.uniform && previous.lines === lines) return previous;
541
+ return markRaw(new LineLayout(lines, rows, hidden.value));
542
+ });
543
+ /** The widgets' heights as last measured, by key. */
544
+ const widgetHeights = shallowReactive(/* @__PURE__ */ new Map());
545
+ const widgets = computed(() => {
546
+ const drawn = layout.value;
547
+ const lh = lineHeight.value;
548
+ const out = [];
549
+ for (const extension of extensions.value) {
550
+ if (!extension.widgets) continue;
551
+ for (const widget of extension.widgets(context)) {
552
+ const n = widget.pos !== void 0 ? doc.value.lineAt(Math.max(0, Math.min(doc.value.length, widget.pos))).number : widget.line ?? 0;
553
+ if (n < 1 || n > drawn.lines || !drawn.shown(n)) continue;
554
+ const above = widget.position === "above";
555
+ const key = `${extension.name}/${widget.id}`;
556
+ out.push({
557
+ key,
558
+ line: n,
559
+ above,
560
+ render: widget.render,
561
+ label: widget.label,
562
+ row: drawn.rowOf(n) + (above ? 0 : drawn.rowsOf(n)),
563
+ height: widgetHeights.get(key) ?? widget.height ?? lh,
564
+ before: 0
565
+ });
566
+ }
567
+ }
568
+ if (!out.length) return out;
569
+ out.sort((a, b) => a.row - b.row || Number(a.above) - Number(b.above) || a.line - b.line);
570
+ let sum = 0;
571
+ for (const widget of out) {
572
+ widget.before = sum;
573
+ sum += widget.height;
574
+ }
575
+ return out;
576
+ });
577
+ /** How much of the widgets' height comes before row `row`. */
578
+ function widgetsBefore(row) {
579
+ const list = widgets.value;
580
+ let lo = 0;
581
+ let hi = list.length;
582
+ while (lo < hi) {
583
+ const mid = lo + hi >> 1;
584
+ if (list[mid].row <= row) lo = mid + 1;
585
+ else hi = mid;
586
+ }
587
+ if (!lo) return 0;
588
+ const last = list[lo - 1];
589
+ return last.before + last.height;
590
+ }
591
+ /** The y of row `row` from the text's top, below the widgets before it. */
592
+ const rowTop = (row) => row * lineHeight.value + widgetsBefore(row);
593
+ /** The row at a y from the text's top; a y over a widget gives the row right after it. */
594
+ function rowAtTextY(y) {
595
+ const list = widgets.value;
596
+ const lh = lineHeight.value;
597
+ if (!list.length) return Math.floor(y / lh);
598
+ let lo = 0;
599
+ let hi = list.length;
600
+ while (lo < hi) {
601
+ const mid = lo + hi >> 1;
602
+ if (list[mid].row * lh + list[mid].before <= y) lo = mid + 1;
603
+ else hi = mid;
604
+ }
605
+ if (!lo) return Math.floor(y / lh);
606
+ const widget = list[lo - 1];
607
+ const end = widget.row * lh + widget.before + widget.height;
608
+ if (y < end) return widget.row;
609
+ return widget.row + Math.floor((y - end) / lh);
610
+ }
611
+ const widgetsHeight = computed(() => {
612
+ const list = widgets.value;
613
+ const last = list[list.length - 1];
614
+ return last ? last.before + last.height : 0;
615
+ });
616
+ const total = computed(() => layout.value.total * lineHeight.value + widgetsHeight.value);
617
+ const sizerHeight = computed(() => Math.min(total.value, MAX_HEIGHT) + pad.y * 2);
618
+ /** How much faster than the scrollbar the text moves, above `MAX_HEIGHT`. */
619
+ const ratio = computed(() => {
620
+ if (total.value <= MAX_HEIGHT) return 1;
621
+ const view = viewHeight.value || 1;
622
+ return Math.max(1, (total.value - view) / Math.max(1, MAX_HEIGHT - view));
623
+ });
624
+ /** Offset between the text's own y and where it is drawn in the scaled scroller. */
625
+ const shift = computed(() => scrollTop.value - scrollTop.value * ratio.value);
626
+ /** The y line `n` is drawn at. */
627
+ const yOf = (line) => pad.y + rowTop(layout.value.rowOf(line)) + shift.value;
628
+ /** The row under a y in the content, from the text's top. */
629
+ const rowAtY = (y) => rowAtTextY(y - pad.y - shift.value);
630
+ const visibleFrom = computed(() => {
631
+ const top = scrollTop.value * ratio.value + (clip.value?.top ?? 0);
632
+ const row = rowAtTextY(Math.max(0, top - pad.y)) - OVERSCAN;
633
+ return layout.value.lineAtRow(Math.max(0, row)).n;
634
+ });
635
+ const visibleTo = computed(() => {
636
+ const bottom = scrollTop.value * ratio.value + (clip.value?.bottom ?? viewHeight.value);
637
+ const row = rowAtTextY(Math.max(0, bottom - pad.y)) + 1 + OVERSCAN;
638
+ return layout.value.lineAtRow(row).n;
639
+ });
640
+ /** The widgets in view, where they are drawn. */
641
+ const shownWidgets = computed(() => {
642
+ const list = widgets.value;
643
+ if (!list.length) return [];
644
+ const from = layout.value.rowOf(visibleFrom.value);
645
+ const to = layout.value.rowOf(visibleTo.value) + layout.value.rowsOf(visibleTo.value);
646
+ const lh = lineHeight.value;
647
+ return list.filter((widget) => widget.row >= from && widget.row <= to).map((widget) => ({
648
+ ...widget,
649
+ top: pad.y + widget.row * lh + widget.before + shift.value
650
+ }));
651
+ });
652
+ /** Room left in the column of lines (and of numbers) before line `n` for the widgets there; none before the first line drawn, which is placed past them. */
653
+ function gapBefore(n) {
654
+ if (n === visibleFrom.value || !widgets.value.length) return 0;
655
+ const row = layout.value.rowOf(n);
656
+ return widgetsBefore(row) - widgetsBefore(row - 1);
657
+ }
658
+ let widgetObserver;
659
+ const observedWidgets = /* @__PURE__ */ new Map();
660
+ /** Measures a widget as drawn, keeping its height so the lines after it are placed below it. */
661
+ function observeWidget(el, key) {
662
+ if (!el || observedWidgets.get(el) === key) return;
663
+ observedWidgets.set(el, key);
664
+ const measureNow = (target) => {
665
+ const id = observedWidgets.get(target);
666
+ if (!id || !target.isConnected) return;
667
+ const height = target.offsetHeight;
668
+ if (height && widgetHeights.get(id) !== height) widgetHeights.set(id, height);
669
+ };
670
+ measureNow(el);
671
+ if (typeof ResizeObserver === "undefined") return;
672
+ widgetObserver ??= new ResizeObserver((entries) => {
673
+ for (const entry of entries) measureNow(entry.target);
674
+ for (const [target] of observedWidgets) if (!target.isConnected) {
675
+ widgetObserver.unobserve(target);
676
+ observedWidgets.delete(target);
677
+ }
678
+ });
679
+ widgetObserver.observe(el);
680
+ }
681
+ /** The lines in view that are drawn (folded ones left out), with their text; read in runs, once per frame. */
682
+ const shownLines = computed(() => {
683
+ const from = visibleFrom.value;
684
+ const to = visibleTo.value;
685
+ const text = doc.value;
686
+ const numbers = [];
687
+ const texts = [];
688
+ let n = from;
689
+ for (const [a, b] of hidden.value) {
690
+ if (b < n) continue;
691
+ if (a > to) break;
692
+ if (a > n) {
693
+ const chunk = text.lineTexts(n, a - 1);
694
+ for (let i = 0; i < chunk.length; i++) numbers.push(n + i);
695
+ texts.push(...chunk);
696
+ }
697
+ n = Math.max(n, b + 1);
698
+ }
699
+ if (n <= to) {
700
+ const chunk = text.lineTexts(n, to);
701
+ for (let i = 0; i < chunk.length; i++) numbers.push(n + i);
702
+ texts.push(...chunk);
703
+ }
704
+ return {
705
+ numbers,
706
+ texts
707
+ };
708
+ });
709
+ const lines = computed(() => shownLines.value.texts);
710
+ /** A line's text, from the lines in view when it is one of them. */
711
+ function lineText(n) {
712
+ const { numbers, texts } = shownLines.value;
713
+ let lo = 0;
714
+ let hi = numbers.length - 1;
715
+ while (lo <= hi) {
716
+ const mid = lo + hi >> 1;
717
+ if (numbers[mid] === n) return texts[mid];
718
+ if (numbers[mid] < n) lo = mid + 1;
719
+ else hi = mid - 1;
720
+ }
721
+ return doc.value.line(n).text;
722
+ }
723
+ const isShown = (n) => n >= visibleFrom.value && n <= visibleTo.value && layout.value.shown(n);
724
+ /** Where column `col` of line `n` is drawn: the row's top, the x from the text's left edge, and which row of the line. */
725
+ function place(n, text, col) {
726
+ const wrapped = wrapOf(text);
727
+ const sub = rowOfCol(wrapped, col);
728
+ const top = yOf(n) + sub * lineHeight.value;
729
+ if (!sub) return {
730
+ top,
731
+ x: measure.x(text, col) + inlineWidth(n, 0, col),
732
+ sub
733
+ };
734
+ const start = wrapped.breaks[sub - 1];
735
+ return {
736
+ top,
737
+ x: wrapped.indent + measure.x(text, col) - measure.x(text, start) + inlineWidth(n, start, col),
738
+ sub
739
+ };
740
+ }
741
+ /** The column nearest to `x` on row `sub` of line `n`. */
742
+ function colAt(n, text, sub, x) {
743
+ const wrapped = wrapOf(text);
744
+ const { breaks } = wrapped;
745
+ if (!breaks.length) return colInRow(n, text, 0, text.length, x);
746
+ const start = sub ? breaks[sub - 1] : 0;
747
+ const end = sub < breaks.length ? breaks[sub] : text.length;
748
+ const col = colInRow(n, text, start, end, Math.max(0, x - (sub ? wrapped.indent : 0)));
749
+ if (sub < breaks.length && col >= end) return Math.max(start, moveCluster(text, end, -1));
750
+ return Math.max(start, col);
751
+ }
752
+ /** Boxes over columns `from` to `to` of line `n`, one per row; `tail` adds width past the line's end. */
753
+ function spans(n, text, from, to, tail = 0) {
754
+ const wrapped = wrapOf(text);
755
+ const out = [];
756
+ const rows = wrapped.breaks.length + 1;
757
+ const top = yOf(n);
758
+ for (let sub = 0; sub < rows; sub++) {
759
+ const start = sub ? wrapped.breaks[sub - 1] : 0;
760
+ const end = sub < rows - 1 ? wrapped.breaks[sub] : text.length;
761
+ if (to < start || from > end || from === end && sub < rows - 1) continue;
762
+ const a = Math.max(from, start);
763
+ const b = Math.min(to, end);
764
+ const base = sub ? wrapped.indent - measure.x(text, start) : 0;
765
+ const left = base + measure.x(text, a) + inlineWidth(n, start, a);
766
+ const right = base + measure.x(text, b) + inlineWidth(n, start, b - 1) + (sub === rows - 1 ? tail : 0);
767
+ if (right > left) out.push({
768
+ top: top + sub * lineHeight.value,
769
+ left,
770
+ width: right - left
771
+ });
772
+ }
773
+ return out;
774
+ }
775
+ const SEVERITY_ICON = {
776
+ error: XCircleIcon,
777
+ warning: AlertTriangleIcon,
778
+ info: InfoIcon,
779
+ hint: LightbulbIcon
780
+ };
781
+ /** Columns left of the line numbers: the problems' column, then the extensions' own. */
782
+ const gutterColumns = computed(() => {
783
+ const columns = [];
784
+ if (!props.gutter) return columns;
785
+ if (props.diagnostics !== void 0 || linting.value || diagnostics.value.length) columns.push({
786
+ name: "problems",
787
+ width: 16,
788
+ markers: problemMarkers
789
+ });
790
+ for (const extension of extensions.value) for (const gutter of extension.gutters ?? []) columns.push({
791
+ name: gutter.name,
792
+ width: gutter.width ?? 16,
793
+ markers: () => gutter.markers(context),
794
+ onPress: gutter.onPress && ((line, event) => gutter.onPress(line, event, context))
795
+ });
796
+ return columns;
797
+ });
798
+ const gutterCells = computed(() => gutterColumns.value.reduce((sum, column) => sum + column.width, 0));
799
+ /** The worst problem on each line in view, as a marker. */
800
+ function problemMarkers() {
801
+ const text = doc.value;
802
+ const first = visibleFrom.value;
803
+ const last = visibleTo.value;
804
+ const end = text.line(last).to;
805
+ const worst = /* @__PURE__ */ new Map();
806
+ for (const problem of diagnostics.value) {
807
+ if (problem.from > end) break;
808
+ const n = text.lineAt(problem.from).number;
809
+ if (n < first) continue;
810
+ const had = worst.get(n);
811
+ if (!had || SEVERITY_RANK[problem.severity] < SEVERITY_RANK[had.severity]) worst.set(n, problem);
812
+ }
813
+ const m = messages.value;
814
+ return [...worst].map(([line, problem]) => ({
815
+ line,
816
+ icon: SEVERITY_ICON[problem.severity],
817
+ class: `dou-code-editor__problem-icon is-${problem.severity}`,
818
+ title: `${m[problem.severity]}:${problem.message}`
819
+ }));
820
+ }
821
+ /** The markers of each column, by line, for the lines in view. */
822
+ const gutterMarkers = computed(() => gutterColumns.value.map((column) => {
823
+ const byLine = /* @__PURE__ */ new Map();
824
+ for (const marker of column.markers()) byLine.set(marker.line, marker);
825
+ return byLine;
826
+ }));
827
+ const gutterWidth = computed(() => {
828
+ const cells = gutterCells.value;
829
+ if (!props.gutter || !props.lineNumbers && !props.foldable && !cells) return 0;
830
+ metrics.value;
831
+ const digits = Math.max(2, String(doc.value.lines).length);
832
+ return cells + (props.lineNumbers ? Math.ceil(digits * measure.cell) + 28 : 12) + (props.foldable ? 14 : 0);
833
+ });
834
+ const contentWidth = computed(() => {
835
+ if (props.wrap) return 0;
836
+ metrics.value;
837
+ let widest = doc.value.widest * measure.cell;
838
+ for (const text of lines.value) {
839
+ if (text.length * measure.cell * 2 < widest) continue;
840
+ widest = Math.max(widest, measure.x(text, text.length));
841
+ }
842
+ for (const [n, own] of lineDecorations.value.inlines) {
843
+ const text = lineText(n);
844
+ widest = Math.max(widest, measure.x(text, text.length) + own.reduce((w, i) => w + widthOf(i), 0));
845
+ }
846
+ return Math.ceil(widest + pad.x * 2 + measure.cell);
847
+ });
848
+ watch(wrapWidth, rebuildWrap, { immediate: true });
849
+ /**
850
+ * Where a fold starting at line `n` would end, or `null`; by brackets with a
851
+ * language, else by indentation. Brackets in strings and comments count
852
+ * only where the text has been read already, so folding a whole long text
853
+ * doesn't read all of it first.
854
+ */
855
+ const inStringOrComment = (pos) => {
856
+ const kind = syntaxAt(pos);
857
+ return kind === "string" || kind === "comment";
858
+ };
859
+ function foldEnd(n) {
860
+ return foldEnds()(n);
861
+ }
862
+ /**
863
+ * A function giving where folds end in the text as it is now, set up once
864
+ * for asking about many lines; `lines` holds the lines' texts when the
865
+ * caller has them.
866
+ */
867
+ function foldEnds(texts) {
868
+ const text = doc.value;
869
+ const hl = highlighter;
870
+ const outer = props.language;
871
+ const tabSize = props.tabSize;
872
+ const lineOf = texts ? (k) => texts[k - 1] : void 0;
873
+ return (n) => {
874
+ const read = !!hl?.ready(n);
875
+ const language = outer ? (read ? hl.languageAt(n) : null) ?? outer : null;
876
+ return foldEndAt(text, n, {
877
+ brackets: language?.brackets,
878
+ tabSize,
879
+ skip: read ? inStringOrComment : void 0,
880
+ lineText: lineOf
881
+ });
882
+ };
883
+ }
884
+ /** The lines that start a fold, from 1. */
885
+ const foldStarts = computed(() => folds.value.map((fold) => doc.value.lineAt(fold.from).number));
886
+ watch(foldStarts, (next, prev) => {
887
+ if (next.length !== prev.length || next.some((n, i) => n !== prev[i])) emit("foldChange", next);
888
+ });
889
+ function setFolds(next) {
890
+ folds.value = next.slice().sort((a, b) => a.from - b.from);
891
+ }
892
+ /** Moves the folds along with an edit; a fold whose lines were joined goes away. */
893
+ function mapFolds(changes, after) {
894
+ if (!folds.value.length) return;
895
+ setFolds(folds.value.map((fold) => ({
896
+ from: changes.mapPos(fold.from, 1),
897
+ to: changes.mapPos(fold.to, -1)
898
+ })).filter((fold) => after.lineAt(fold.to).number > after.lineAt(fold.from).number));
899
+ }
900
+ /** Unfolds whatever hides a cursor, so the cursor is never out of sight. */
901
+ function revealFolds() {
902
+ if (!folds.value.length) return;
903
+ const heads = state.value.selection.ranges.map((range) => range.head);
904
+ const keep = folds.value.filter((fold) => !heads.some((h) => h > fold.from && h <= fold.to));
905
+ if (keep.length !== folds.value.length) folds.value = keep;
906
+ }
907
+ /** Folds the block starting at line `n`; cursors inside move to its first line. */
908
+ function foldLine(n) {
909
+ const end = foldEnd(n);
910
+ if (end === null) return false;
911
+ const text = doc.value;
912
+ const fold = {
913
+ from: text.line(n).to,
914
+ to: text.line(end).to
915
+ };
916
+ if (folds.value.some((f) => f.from === fold.from)) return false;
917
+ const { selection } = state.value;
918
+ if (selection.ranges.some((range) => range.head > fold.from && range.head <= fold.to)) {
919
+ const ranges = selection.ranges.map((range) => range.head > fold.from && range.head <= fold.to ? {
920
+ anchor: fold.from,
921
+ head: fold.from
922
+ } : range);
923
+ dispatch(transaction().select(normalizeSelection({
924
+ ranges,
925
+ main: selection.main
926
+ }, text.length)));
927
+ }
928
+ setFolds([...folds.value, fold]);
929
+ announce(format(messages.value.folded, {
930
+ from: n + 1,
931
+ to: end
932
+ }));
933
+ return true;
934
+ }
935
+ /** Reads a fold out; the same words twice in a row are read again. */
936
+ function announce(text) {
937
+ announcement.value = announcement.value === text ? `${text}\u200b` : text;
938
+ }
939
+ const folding = {
940
+ fold(line) {
941
+ if (!props.foldable) return false;
942
+ const text = doc.value;
943
+ const n = line ?? text.lineAt(mainRange(state.value.selection).head).number;
944
+ if (line !== void 0) return foldLine(n);
945
+ for (let k = n; k >= Math.max(1, n - 2e3); k--) {
946
+ const end = foldEnd(k);
947
+ if (end !== null && (k === n || end >= n) && foldLine(k)) return true;
948
+ }
949
+ return false;
950
+ },
951
+ unfold(line) {
952
+ const text = doc.value;
953
+ const n = line ?? text.lineAt(mainRange(state.value.selection).head).number;
954
+ const keep = folds.value.filter((fold) => {
955
+ const from = text.lineAt(fold.from).number;
956
+ return n < from || n > text.lineAt(fold.to).number;
957
+ });
958
+ if (keep.length === folds.value.length) return false;
959
+ folds.value = keep;
960
+ announce(messages.value.unfolded);
961
+ return true;
962
+ },
963
+ foldAll() {
964
+ if (!props.foldable) return false;
965
+ const text = doc.value;
966
+ const next = [];
967
+ const endOf = foldEnds(text.lineTexts(1, text.lines));
968
+ for (let n = 1; n < text.lines; n++) {
969
+ const end = endOf(n);
970
+ if (end === null) continue;
971
+ next.push({
972
+ from: text.line(n).to,
973
+ to: text.line(end).to
974
+ });
975
+ n = end;
976
+ }
977
+ if (!next.length) return false;
978
+ setFolds(next);
979
+ announce(messages.value.foldedAll);
980
+ const { selection } = state.value;
981
+ const ranges = selection.ranges.map((range) => {
982
+ const fold = next.find((f) => range.head > f.from && range.head <= f.to);
983
+ return fold ? {
984
+ anchor: fold.from,
985
+ head: fold.from
986
+ } : range;
987
+ });
988
+ dispatch(transaction().select(normalizeSelection({
989
+ ranges,
990
+ main: selection.main
991
+ }, text.length)));
992
+ return true;
993
+ },
994
+ unfoldAll() {
995
+ if (!folds.value.length) return false;
996
+ folds.value = [];
997
+ announce(messages.value.unfoldedAll);
998
+ return true;
999
+ }
1000
+ };
1001
+ /** Whether lines in view start a block, worked out only while the gutter is pointed at (or on touch screens). */
1002
+ const gutterHover = ref(false);
1003
+ /**
1004
+ * A touch screen. Read once mounted, never while rendering on the server:
1005
+ * the first render must match the server's markup, then touch-only parts show.
1006
+ */
1007
+ const coarse = ref(false);
1008
+ onMounted(() => {
1009
+ coarse.value = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
1010
+ });
1011
+ let foldCache = {
1012
+ doc: null,
1013
+ ends: /* @__PURE__ */ new Map()
1014
+ };
1015
+ const foldableLines = computed(() => {
1016
+ const out = /* @__PURE__ */ new Set();
1017
+ if (!props.foldable || !(gutterHover.value || coarse.value)) return out;
1018
+ syntaxTick.value;
1019
+ if (foldCache.doc !== doc.value) foldCache = {
1020
+ doc: doc.value,
1021
+ ends: /* @__PURE__ */ new Map()
1022
+ };
1023
+ for (const n of shownLines.value.numbers) {
1024
+ let end = foldCache.ends.get(n);
1025
+ if (end === void 0) {
1026
+ end = foldEnd(n);
1027
+ foldCache.ends.set(n, end);
1028
+ }
1029
+ if (end !== null) out.add(n);
1030
+ }
1031
+ return out;
1032
+ });
1033
+ function toggleFold(n, folded) {
1034
+ if (folded) folding.unfold(n);
1035
+ else folding.fold(n);
1036
+ }
1037
+ const composing = ref(false);
1038
+ /** What the input method shows while composing: a replacement of the text, drawn but not applied yet. */
1039
+ const preview = shallowRef(null);
1040
+ /**
1041
+ * Changes that came in while composing (someone else's, or a new
1042
+ * `v-model`): the textarea still holds the text from before them, so what
1043
+ * it gives back is moved through these.
1044
+ */
1045
+ let composeMap = null;
1046
+ /** A position in the text the textarea was filled from, in the text now. */
1047
+ const composedPos = (pos, assoc) => composeMap ? composeMap.mapPos(pos, assoc) : pos;
1048
+ function mapComposition(changes) {
1049
+ composeMap = composeMap ? composeMap.compose(changes) : changes;
1050
+ const shown = preview.value;
1051
+ if (shown) preview.value = {
1052
+ ...shown,
1053
+ from: changes.mapPos(shown.from, -1),
1054
+ to: Math.max(changes.mapPos(shown.from, -1), changes.mapPos(shown.to, 1))
1055
+ };
1056
+ }
1057
+ /** A class over part of a line, `from`–`to` in the line, with a title shown on hover. */
1058
+ const rows = computed(() => {
1059
+ const { numbers, texts } = shownLines.value;
1060
+ const p = preview.value;
1061
+ const line = p ? doc.value.lineAt(p.from) : null;
1062
+ const tokensOf = syntaxLines(visibleFrom.value, visibleTo.value);
1063
+ const starts = new Set(foldHidden.value.map(([from]) => from - 1));
1064
+ const { marks, lineClasses, inlines } = lineDecorations.value;
1065
+ return texts.map((text, i) => {
1066
+ const n = numbers[i];
1067
+ const tokens = tokensOf(n);
1068
+ const wrapped = wrapOf(text);
1069
+ const folded = starts.has(n);
1070
+ if (!p || n !== line.number) {
1071
+ const own = marks.get(n);
1072
+ return {
1073
+ n,
1074
+ text,
1075
+ tokens,
1076
+ wrapped,
1077
+ folded,
1078
+ marks: own,
1079
+ marksKey: own?.map((m) => m.join(",")).join(";"),
1080
+ lineClass: lineClasses.get(n),
1081
+ inlines: inlines.get(n),
1082
+ inlinesKey: inlines.get(n)?.map((item) => `${item.col}:${item.key}`).join(";")
1083
+ };
1084
+ }
1085
+ const col = p.from - line.from;
1086
+ const end = p.to <= line.to ? p.to - line.from : col;
1087
+ return {
1088
+ n,
1089
+ text,
1090
+ tokens: null,
1091
+ wrapped,
1092
+ folded,
1093
+ compose: [
1094
+ text.slice(0, col),
1095
+ p.insert,
1096
+ text.slice(end)
1097
+ ]
1098
+ };
1099
+ });
1100
+ });
1101
+ /** What extensions decorate, asked for while drawing. */
1102
+ const decorations = computed(() => {
1103
+ const out = [];
1104
+ for (const extension of extensions.value) if (extension.decorations) out.push(...extension.decorations(context));
1105
+ return out;
1106
+ });
1107
+ /** Decorations and problems on the lines in view, cut to each line. */
1108
+ const lineDecorations = computed(() => {
1109
+ const marks = /* @__PURE__ */ new Map();
1110
+ const lineClasses = /* @__PURE__ */ new Map();
1111
+ const inlines = /* @__PURE__ */ new Map();
1112
+ const list = decorations.value;
1113
+ const problems = diagnostics.value;
1114
+ const session = snippet.value;
1115
+ if (!list.length && !problems.length && !session) return {
1116
+ marks,
1117
+ lineClasses,
1118
+ inlines
1119
+ };
1120
+ const text = doc.value;
1121
+ const first = visibleFrom.value;
1122
+ const last = visibleTo.value;
1123
+ const start = text.line(first).from;
1124
+ const end = text.line(last).to;
1125
+ const mark = (from, to, cls, title, style) => {
1126
+ if (to < start || from > end || to <= from) return;
1127
+ const a = text.lineAt(Math.max(from, start));
1128
+ const b = text.lineAt(Math.min(to, end));
1129
+ for (let n = a.number; n <= b.number; n++) {
1130
+ const line = n === a.number ? a : n === b.number ? b : text.line(n);
1131
+ const x = Math.max(from, line.from) - line.from;
1132
+ const y = Math.min(to, line.to) - line.from;
1133
+ if (y <= x) continue;
1134
+ const own = marks.get(n);
1135
+ const item = style ? [
1136
+ x,
1137
+ y,
1138
+ cls,
1139
+ title,
1140
+ style
1141
+ ] : title ? [
1142
+ x,
1143
+ y,
1144
+ cls,
1145
+ title
1146
+ ] : [
1147
+ x,
1148
+ y,
1149
+ cls
1150
+ ];
1151
+ if (own) own.push(item);
1152
+ else marks.set(n, [item]);
1153
+ }
1154
+ };
1155
+ for (const item of list) if (item.type === "line") {
1156
+ if (item.line < first || item.line > last) continue;
1157
+ const had = lineClasses.get(item.line);
1158
+ lineClasses.set(item.line, had ? `${had} ${item.class}` : item.class);
1159
+ } else if (item.type === "inline") {
1160
+ if (item.pos < start || item.pos > end) continue;
1161
+ const line = text.lineAt(item.pos);
1162
+ const own = inlines.get(line.number) ?? [];
1163
+ own.push({
1164
+ col: item.pos - line.from,
1165
+ key: item.id ?? `@${item.pos}`,
1166
+ render: item.render,
1167
+ width: item.width
1168
+ });
1169
+ inlines.set(line.number, own);
1170
+ } else mark(item.from, item.to, item.class, item.title, item.style);
1171
+ for (const own of inlines.values()) if (own.length > 1) {
1172
+ const order = new Map(own.map((item, i) => [item, i]));
1173
+ own.sort((a, b) => a.col - b.col || order.get(a) - order.get(b));
1174
+ }
1175
+ for (const problem of problems) {
1176
+ if (problem.from > end) break;
1177
+ let { from, to } = problem;
1178
+ if (from === to) {
1179
+ const line = text.lineAt(from);
1180
+ if (from < line.to) to = line.from + moveCluster(line.text, from - line.from, 1);
1181
+ else if (from > line.from) from = line.from + moveCluster(line.text, from - line.from, -1);
1182
+ else continue;
1183
+ }
1184
+ mark(from, to, `dou-code-editor__problem is-${problem.severity}`);
1185
+ }
1186
+ if (session) {
1187
+ for (let i = session.at + 1; i < session.groups.length; i++) for (const range of session.groups[i].ranges) if (range.to > range.from && range.from <= end) mark(range.from, range.to, "dou-code-editor__field");
1188
+ }
1189
+ return {
1190
+ marks,
1191
+ lineClasses,
1192
+ inlines
1193
+ };
1194
+ });
1195
+ /** The widths of inline widgets as last measured, by key. */
1196
+ const inlineWidths = shallowReactive(/* @__PURE__ */ new Map());
1197
+ const widthOf = (item) => item.width ?? inlineWidths.get(item.key) ?? 0;
1198
+ /** Width of the inline widgets on line `n` at columns `from` to `to`, both included. */
1199
+ function inlineWidth(n, from, to) {
1200
+ const own = lineDecorations.value.inlines.get(n);
1201
+ if (!own) return 0;
1202
+ let sum = 0;
1203
+ for (const item of own) if (item.col >= from && item.col <= to) sum += widthOf(item);
1204
+ return sum;
1205
+ }
1206
+ /**
1207
+ * The column nearest to `x` (from the row's left, past its indent) on the
1208
+ * part `start`–`end` of line `n`, stepping over the inline widgets there.
1209
+ */
1210
+ function colInRow(n, text, start, end, x) {
1211
+ const own = lineDecorations.value.inlines.get(n);
1212
+ const x0 = measure.x(text, start);
1213
+ const clamp = (col, low) => Math.max(low, Math.min(end, col));
1214
+ if (!own) return clamp(measure.col(text, x0 + x), start);
1215
+ let offset = 0;
1216
+ let low = start;
1217
+ for (const item of own) {
1218
+ if (item.col < start || item.col > end) continue;
1219
+ const at = measure.x(text, item.col) - x0 + offset;
1220
+ if (x < at) return Math.min(item.col, clamp(measure.col(text, x0 + x - offset), low));
1221
+ const width = widthOf(item);
1222
+ if (x < at + width) return item.col;
1223
+ offset += width;
1224
+ low = item.col;
1225
+ }
1226
+ return clamp(measure.col(text, x0 + x - offset), low);
1227
+ }
1228
+ let inlineObserver;
1229
+ const observedInlines = /* @__PURE__ */ new Map();
1230
+ /** Measures an inline widget as drawn, keeping its width so the text after it is placed past it. */
1231
+ function observeInline(el, key, given) {
1232
+ if (!el || given !== void 0 || observedInlines.get(el) === key) return;
1233
+ observedInlines.set(el, key);
1234
+ const measureNow = (target) => {
1235
+ const width = target.offsetWidth;
1236
+ const id = observedInlines.get(target);
1237
+ if (id && target.isConnected && width && inlineWidths.get(id) !== width) inlineWidths.set(id, width);
1238
+ };
1239
+ measureNow(el);
1240
+ if (typeof ResizeObserver === "undefined") return;
1241
+ inlineObserver ??= new ResizeObserver((entries) => {
1242
+ for (const entry of entries) measureNow(entry.target);
1243
+ for (const [target] of observedInlines) if (!target.isConnected) {
1244
+ inlineObserver.unobserve(target);
1245
+ observedInlines.delete(target);
1246
+ }
1247
+ });
1248
+ inlineObserver.observe(el);
1249
+ }
1250
+ /** Lines read ahead of the last read one while drawing; further away, idle time catches up first. */
1251
+ let highlighter = null;
1252
+ /** Bumped when lines in view got their tokens in idle time. */
1253
+ const syntaxTick = ref(0);
1254
+ watch(() => props.language, (language) => {
1255
+ highlighter = language ? markRaw(new CodeHighlighter(language, doc.value, props.tabSize)) : null;
1256
+ syntaxTick.value++;
1257
+ }, { immediate: true });
1258
+ /** The worker reading ahead, with `worker`, and how to let go of it. */
1259
+ let syntaxWorker = null;
1260
+ let releaseWorker = null;
1261
+ let workerJob = 0;
1262
+ function stopSyntaxWorker() {
1263
+ syntaxWorker?.dispose();
1264
+ syntaxWorker = null;
1265
+ releaseWorker?.();
1266
+ releaseWorker = null;
1267
+ }
1268
+ /** Reading goes back to the page, saying why while developing. */
1269
+ function workerFallback(message, error) {
1270
+ stopSyntaxWorker();
1271
+ syntaxTick.value++;
1272
+ if (process.env.NODE_ENV !== "production") console.warn(`[@dou-ui/code] ${message}: colors are read on the page instead.`, ...error ? [error] : []);
1273
+ }
1274
+ function attachWorker(worker, release) {
1275
+ const language = props.language;
1276
+ releaseWorker = release;
1277
+ syntaxWorker = new SyntaxWorkerClient(worker, language, () => doc.value, props.tabSize, {
1278
+ states(points) {
1279
+ const hl = highlighter;
1280
+ if (!hl || hl.language !== language) return;
1281
+ hl.adopt(points);
1282
+ syntaxTick.value++;
1283
+ },
1284
+ unsupported(missing) {
1285
+ workerFallback(missing ? `the worker has no language named "${missing}" (for "${language.name}"); pass it to serveCodeHighlighting in the worker` : `the states of "${language.name}" can't be sent from the worker; keep them to plain data`);
1286
+ },
1287
+ failed(error) {
1288
+ workerFallback("the highlighting worker failed", error);
1289
+ }
1290
+ });
1291
+ syntaxTick.value++;
1292
+ }
1293
+ watch([
1294
+ () => props.language,
1295
+ () => props.worker,
1296
+ mounted
1297
+ ], ([language, option, isMounted]) => {
1298
+ stopSyntaxWorker();
1299
+ const job = ++workerJob;
1300
+ if (!language || !option || !isMounted || typeof Worker === "undefined") return;
1301
+ if (option === true) {
1302
+ ownWorker().then(({ worker, release }) => {
1303
+ if (job === workerJob) attachWorker(worker, release);
1304
+ else release();
1305
+ }, (error) => job === workerJob && workerFallback("the built-in worker could not start", error));
1306
+ return;
1307
+ }
1308
+ let worker;
1309
+ try {
1310
+ worker = option();
1311
+ } catch (error) {
1312
+ workerFallback("the worker could not start", error);
1313
+ return;
1314
+ }
1315
+ attachWorker(worker, holdWorker(worker));
1316
+ }, { immediate: true });
1317
+ onBeforeUnmount(() => {
1318
+ workerJob++;
1319
+ stopSyntaxWorker();
1320
+ });
1321
+ /** Brings the colors along with a change of the text. */
1322
+ function syntaxChange(next, changes) {
1323
+ highlighter?.update(next, changes);
1324
+ syntaxWorker?.change(changes);
1325
+ }
1326
+ /** Gets the tokens of the lines in view, asking idle time for the ones too far ahead. */
1327
+ function syntaxLines(from, to) {
1328
+ syntaxTick.value;
1329
+ const hl = highlighter;
1330
+ if (!hl) return () => null;
1331
+ if (!hl.ready(to) && to - hl.frontier > SYNTAX_REACH) {
1332
+ if (syntaxWorker) syntaxWorker.want(hl.frontier, to);
1333
+ else scheduleSyntax(to);
1334
+ return (n) => hl.ready(n) ? hl.line(n) : null;
1335
+ }
1336
+ return (n) => hl.line(n);
1337
+ }
1338
+ let syntaxJob = 0;
1339
+ let syntaxUntil = 0;
1340
+ /** Runs `task` when the page is idle, with how long it may take (ms). */
1341
+ const idle = typeof requestIdleCallback === "function" ? (task) => requestIdleCallback((deadline) => task(deadline.timeRemaining()), { timeout: 100 }) : (task) => window.setTimeout(() => task(8), 16);
1342
+ const cancelIdle = (id) => typeof cancelIdleCallback === "function" ? cancelIdleCallback(id) : clearTimeout(id);
1343
+ function scheduleSyntax(until) {
1344
+ syntaxUntil = Math.max(syntaxUntil, until);
1345
+ if (syntaxJob) return;
1346
+ syntaxJob = idle((budget) => {
1347
+ syntaxJob = 0;
1348
+ const hl = highlighter;
1349
+ if (!hl) return;
1350
+ hl.work(performance.now() + Math.min(20, Math.max(4, budget - 1)), syntaxUntil);
1351
+ if (hl.ready(syntaxUntil)) {
1352
+ syntaxUntil = 0;
1353
+ syntaxTick.value++;
1354
+ } else scheduleSyntax(syntaxUntil);
1355
+ });
1356
+ }
1357
+ /** The kind of token the character at `pos` is part of, when its line has been read. */
1358
+ function syntaxAt(pos) {
1359
+ const hl = highlighter;
1360
+ if (!hl || pos < 0 || pos >= doc.value.length) return null;
1361
+ const line = doc.value.lineAt(pos);
1362
+ const tokens = hl.line(line.number, SYNTAX_REACH);
1363
+ if (!tokens) return null;
1364
+ const col = pos - line.from;
1365
+ for (let i = 0; i < tokens.length; i += 2) if (col < tokens[i]) {
1366
+ const type = tokens[i + 1];
1367
+ return type < 0 ? null : tokenTypes[type];
1368
+ }
1369
+ return null;
1370
+ }
1371
+ function languageAt(pos) {
1372
+ const hl = highlighter;
1373
+ if (!hl) return null;
1374
+ const line = doc.value.lineAt(Math.min(Math.max(pos, 0), doc.value.length));
1375
+ if (line.number - hl.frontier > SYNTAX_REACH) return hl.language;
1376
+ return hl.languageAt(line.number);
1377
+ }
1378
+ /**
1379
+ * A piece of a line, with the classes it is drawn with and the title of a
1380
+ * mark over it; or, with `inline`, the line's inline widget of that index
1381
+ * (its text empty).
1382
+ */
1383
+ function partsOf(row) {
1384
+ const parts = textParts(row);
1385
+ const own = row.inlines;
1386
+ if (!own?.length) return parts;
1387
+ const out = [];
1388
+ let at = 0;
1389
+ let next = 0;
1390
+ for (const part of parts) {
1391
+ while (next < own.length && own[next].col <= at) out.push([
1392
+ "",
1393
+ null,
1394
+ void 0,
1395
+ next++
1396
+ ]);
1397
+ let piece = part;
1398
+ while (next < own.length && own[next].col < at + piece[0].length) {
1399
+ const cut = own[next].col - at;
1400
+ out.push([
1401
+ piece[0].slice(0, cut),
1402
+ piece[1],
1403
+ piece[2],
1404
+ void 0,
1405
+ piece[4]
1406
+ ]);
1407
+ piece = [
1408
+ piece[0].slice(cut),
1409
+ piece[1],
1410
+ piece[2],
1411
+ void 0,
1412
+ piece[4]
1413
+ ];
1414
+ at += cut;
1415
+ while (next < own.length && own[next].col <= at) out.push([
1416
+ "",
1417
+ null,
1418
+ void 0,
1419
+ next++
1420
+ ]);
1421
+ }
1422
+ out.push(piece);
1423
+ at += piece[0].length;
1424
+ }
1425
+ while (next < own.length) out.push([
1426
+ "",
1427
+ null,
1428
+ void 0,
1429
+ next++
1430
+ ]);
1431
+ return out;
1432
+ }
1433
+ function textParts(row) {
1434
+ const base = lineParts(row.text, row.tokens);
1435
+ const marks = row.marks;
1436
+ if (!marks?.length) return base.map(([text, type]) => [text, type && `dou-syntax-${type}`]);
1437
+ const cuts = /* @__PURE__ */ new Set([0, row.text.length]);
1438
+ for (const [from, to] of marks) {
1439
+ cuts.add(from);
1440
+ cuts.add(to);
1441
+ }
1442
+ let at = 0;
1443
+ for (const [text] of base) {
1444
+ cuts.add(at);
1445
+ at += text.length;
1446
+ }
1447
+ const points = [...cuts].sort((a, b) => a - b);
1448
+ const out = [];
1449
+ let index = 0;
1450
+ let partStart = 0;
1451
+ for (let i = 0; i + 1 < points.length; i++) {
1452
+ const from = points[i];
1453
+ const to = points[i + 1];
1454
+ if (to <= from || from >= row.text.length) continue;
1455
+ while (partStart + base[index][0].length <= from) partStart += base[index++][0].length;
1456
+ const type = base[index][1];
1457
+ let cls = type ? `dou-syntax-${type}` : "";
1458
+ let title;
1459
+ let style;
1460
+ for (const [a, b, name, label, css] of marks) if (a <= from && b >= to) {
1461
+ cls = cls ? `${cls} ${name}` : name;
1462
+ title = label ?? title;
1463
+ if (css) style = style ? {
1464
+ ...style,
1465
+ ...css
1466
+ } : css;
1467
+ }
1468
+ const piece = row.text.slice(from, to);
1469
+ out.push(style ? [
1470
+ piece,
1471
+ cls || null,
1472
+ title,
1473
+ void 0,
1474
+ style
1475
+ ] : title ? [
1476
+ piece,
1477
+ cls || null,
1478
+ title
1479
+ ] : [piece, cls || null]);
1480
+ }
1481
+ return out;
1482
+ }
1483
+ /** The parts of one row of a wrapped line. */
1484
+ function rowParts(row, sub) {
1485
+ const { breaks } = row.wrapped;
1486
+ const start = sub ? breaks[sub - 1] : 0;
1487
+ const end = sub < breaks.length ? breaks[sub] : row.text.length;
1488
+ const out = [];
1489
+ let at = 0;
1490
+ const last = sub === breaks.length;
1491
+ for (const part of partsOf(row)) {
1492
+ const [text, type, title, inline, style] = part;
1493
+ if (inline !== void 0) {
1494
+ if (at >= start && (at < end || last && at === end)) out.push(part);
1495
+ continue;
1496
+ }
1497
+ const from = Math.max(at, start);
1498
+ const to = Math.min(at + text.length, end);
1499
+ if (to > from) out.push([
1500
+ text.slice(from - at, to - at),
1501
+ type,
1502
+ title,
1503
+ void 0,
1504
+ style
1505
+ ]);
1506
+ at += text.length;
1507
+ }
1508
+ return out;
1509
+ }
1510
+ const focused = ref(false);
1511
+ const cursors = computed(() => {
1512
+ metrics.value;
1513
+ const out = [];
1514
+ const { doc: text, selection } = state.value;
1515
+ const p = preview.value;
1516
+ selection.ranges.forEach((range, i) => {
1517
+ const pos = range.head;
1518
+ const line = text.lineAt(pos);
1519
+ if (!isShown(line.number)) return;
1520
+ let lineStr = lineText(line.number);
1521
+ if (p && i === selection.main) {
1522
+ const at = text.lineAt(p.from);
1523
+ lineStr = rows.value.find((row) => row.n === at.number)?.compose?.slice(0, 2).join("") ?? lineStr;
1524
+ out.push({
1525
+ key: `c${i}`,
1526
+ left: pad.x + measure.x(lineStr, lineStr.length),
1527
+ top: yOf(at.number),
1528
+ width: 2
1529
+ });
1530
+ return;
1531
+ }
1532
+ const at = place(line.number, lineStr, pos - line.from);
1533
+ out.push({
1534
+ key: `c${i}`,
1535
+ left: pad.x + at.x,
1536
+ top: at.top,
1537
+ width: 2
1538
+ });
1539
+ });
1540
+ return out;
1541
+ });
1542
+ const selectionBoxes = computed(() => {
1543
+ metrics.value;
1544
+ if (preview.value) return [];
1545
+ const out = [];
1546
+ const { doc: text, selection } = state.value;
1547
+ const first = visibleFrom.value;
1548
+ const last = visibleTo.value;
1549
+ selection.ranges.forEach((range, i) => {
1550
+ if (isEmptyRange(range)) return;
1551
+ const from = text.lineAt(rangeFrom(range));
1552
+ const to = text.lineAt(rangeTo(range));
1553
+ for (let n = Math.max(from.number, first); n <= Math.min(to.number, last); n++) {
1554
+ if (!layout.value.shown(n)) continue;
1555
+ const str = lineText(n);
1556
+ const a = n === from.number ? rangeFrom(range) - from.from : 0;
1557
+ const b = n === to.number ? rangeTo(range) - to.from : str.length;
1558
+ spans(n, str, a, b, n === to.number ? 0 : measure.cell / 2).forEach((box, k) => out.push({
1559
+ key: `s${i}-${n}-${k}`,
1560
+ ...box,
1561
+ left: pad.x + box.left
1562
+ }));
1563
+ }
1564
+ });
1565
+ return out;
1566
+ });
1567
+ const activeLineTop = computed(() => {
1568
+ const n = doc.value.lineAt(mainRange(state.value.selection).head).number;
1569
+ return isShown(n) ? yOf(n) : null;
1570
+ });
1571
+ const activeLineRows = computed(() => layout.value.rowsOf(activeLineNumber.value) || 1);
1572
+ const activeLineNumber = computed(() => doc.value.lineAt(mainRange(state.value.selection).head).number);
1573
+ watch(activeLineNumber, (n) => {
1574
+ if (!focused.value || !widgets.value.length) return;
1575
+ const labels = widgets.value.filter((widget) => widget.line === n && widget.label).map((widget) => widget.label);
1576
+ if (labels.length) announce(labels.join(" · "));
1577
+ });
1578
+ /** The bracket at the main cursor and its partner, outlined; a bracket without one is marked. */
1579
+ const bracketBoxes = computed(() => {
1580
+ metrics.value;
1581
+ syntaxTick.value;
1582
+ if (!props.matchBrackets || !props.language || !focused.value || preview.value) return [];
1583
+ const main = mainRange(state.value.selection);
1584
+ if (!isEmptyRange(main)) return [];
1585
+ const text = doc.value;
1586
+ const brackets = languageAt(main.head)?.brackets ?? props.language.brackets;
1587
+ const found = matchBracket(text, main.head, brackets, (pos) => {
1588
+ const kind = syntaxAt(pos);
1589
+ return kind === "string" || kind === "comment";
1590
+ });
1591
+ if (!found) return [];
1592
+ const out = [];
1593
+ for (const pos of found.match === null ? [found.from] : [found.from, found.match]) {
1594
+ const line = text.lineAt(pos);
1595
+ if (!isShown(line.number)) continue;
1596
+ const str = lineText(line.number);
1597
+ const [box] = spans(line.number, str, pos - line.from, pos - line.from + 1);
1598
+ if (box) out.push({
1599
+ key: `b${pos}`,
1600
+ ...box,
1601
+ left: pad.x + box.left,
1602
+ matched: found.match !== null
1603
+ });
1604
+ }
1605
+ return out;
1606
+ });
1607
+ const messages = useCodeMessages(() => props.messages);
1608
+ const searchOpen = ref(false);
1609
+ const showReplace = ref(false);
1610
+ const query = ref({ search: "" });
1611
+ const panel = ref();
1612
+ const { t: common } = useLocale();
1613
+ /** The toggles in the find box. */
1614
+ const searchOptions = [
1615
+ {
1616
+ key: "caseSensitive",
1617
+ icon: LetterCaseIcon
1618
+ },
1619
+ {
1620
+ key: "wholeWord",
1621
+ icon: WholeWordIcon
1622
+ },
1623
+ {
1624
+ key: "regexp",
1625
+ icon: RegexIcon
1626
+ }
1627
+ ];
1628
+ /** The matches, kept in step with edits between searches. */
1629
+ const matches = shallowRef([]);
1630
+ const capped = ref(false);
1631
+ const searchError = ref();
1632
+ /** Read out after a replacement. */
1633
+ const announcement = ref("");
1634
+ let searchTimer = 0;
1635
+ function runSearch() {
1636
+ clearTimeout(searchTimer);
1637
+ searchTimer = 0;
1638
+ if (!searchOpen.value || !query.value.search) {
1639
+ matches.value = [];
1640
+ capped.value = false;
1641
+ searchError.value = void 0;
1642
+ return;
1643
+ }
1644
+ const result = searchText(doc.value, query.value);
1645
+ matches.value = result.matches;
1646
+ capped.value = result.capped;
1647
+ searchError.value = result.error;
1648
+ }
1649
+ /** Searches again a little later, so typing in a long text doesn't search on every key. */
1650
+ function scheduleSearch(delay = 120) {
1651
+ clearTimeout(searchTimer);
1652
+ searchTimer = window.setTimeout(runSearch, delay);
1653
+ }
1654
+ watch(query, () => {
1655
+ runSearch();
1656
+ revealMatch(matchAfter(matches.value, rangeFrom(mainRange(state.value.selection))));
1657
+ });
1658
+ /** Moves the matches along with an edit, and searches again soon. */
1659
+ function mapMatches(changes) {
1660
+ if (!searchOpen.value || !matches.value.length) return;
1661
+ matches.value = matches.value.map((m) => ({
1662
+ from: changes.mapPos(m.from, 1),
1663
+ to: changes.mapPos(m.to, -1)
1664
+ })).filter((m) => m.to > m.from);
1665
+ scheduleSearch(doc.value.length > 2e5 ? 300 : 120);
1666
+ }
1667
+ /** Which match the main selection is exactly on, or `-1`. */
1668
+ const currentMatch = computed(() => {
1669
+ const main = mainRange(state.value.selection);
1670
+ const i = matchAfter(matches.value, rangeFrom(main));
1671
+ const m = matches.value[i];
1672
+ return m && m.from === rangeFrom(main) && m.to === rangeTo(main) ? i : -1;
1673
+ });
1674
+ function revealMatch(index) {
1675
+ const m = matches.value[index];
1676
+ if (!m) return false;
1677
+ dispatch(transaction().select(m.from, m.to).setMeta({ scroll: true }));
1678
+ return true;
1679
+ }
1680
+ function nextMatch() {
1681
+ if (!matches.value.length) return false;
1682
+ const main = mainRange(state.value.selection);
1683
+ const at = currentMatch.value >= 0 ? rangeTo(main) : rangeFrom(main);
1684
+ let i = matchAfter(matches.value, at);
1685
+ if (currentMatch.value >= 0 && i === currentMatch.value) i = (i + 1) % matches.value.length;
1686
+ return revealMatch(i);
1687
+ }
1688
+ function previousMatch() {
1689
+ if (!matches.value.length) return false;
1690
+ const list = matches.value;
1691
+ const from = rangeFrom(mainRange(state.value.selection));
1692
+ const after = matchAfter(list, from);
1693
+ return revealMatch(list[after].from < from ? list.length - 1 : (after - 1 + list.length) % list.length);
1694
+ }
1695
+ function openSearch(replace = false, given) {
1696
+ if (!props.searchable) return false;
1697
+ menuOpen.value = false;
1698
+ closeProblems();
1699
+ const main = mainRange(state.value.selection);
1700
+ const patch = { ...given };
1701
+ if (given?.search === void 0) {
1702
+ const selected = doc.value.slice(rangeFrom(main), rangeTo(main));
1703
+ if (selected && !selected.includes("\n")) patch.search = selected;
1704
+ else if (!selected) {
1705
+ const line = doc.value.lineAt(main.head);
1706
+ const col = main.head - line.from;
1707
+ const text = lineText(line.number);
1708
+ for (const at of [col, col - 1]) {
1709
+ if (at < 0 || at >= text.length || !/[\p{L}\p{N}_$]/u.test(text[at])) continue;
1710
+ const word = wordAt(text, at);
1711
+ patch.search = text.slice(word.from, word.to);
1712
+ dispatch(transaction().select(line.from + word.from, line.from + word.to));
1713
+ break;
1714
+ }
1715
+ }
1716
+ }
1717
+ if (Object.keys(patch).length) query.value = {
1718
+ ...query.value,
1719
+ ...patch
1720
+ };
1721
+ if ((replace || given?.replace !== void 0) && !target.readonly) showReplace.value = true;
1722
+ searchOpen.value = true;
1723
+ runSearch();
1724
+ panel.value?.focus(replace ? "replace" : "find");
1725
+ nextTick(() => panel.value?.focus(replace ? "replace" : "find"));
1726
+ return true;
1727
+ }
1728
+ function closeSearch() {
1729
+ if (!searchOpen.value) return false;
1730
+ searchOpen.value = false;
1731
+ matches.value = [];
1732
+ focusInput();
1733
+ return true;
1734
+ }
1735
+ function replaceOne() {
1736
+ if (target.readonly) return;
1737
+ if (currentMatch.value < 0) {
1738
+ nextMatch();
1739
+ return;
1740
+ }
1741
+ const m = matches.value[currentMatch.value];
1742
+ const insert = replacementFor(doc.value, m, query.value);
1743
+ const tr = transaction().setMeta({
1744
+ action: "replace",
1745
+ scroll: true
1746
+ });
1747
+ tr.replace(m.from, m.to, insert);
1748
+ dispatch(tr);
1749
+ runSearch();
1750
+ const i = matchAfter(matches.value, m.from + insert.length);
1751
+ if (i >= 0 && (matches.value[i].from >= m.from + insert.length || i === 0)) revealMatch(i);
1752
+ }
1753
+ function replaceAll() {
1754
+ if (target.readonly) return;
1755
+ const all = capped.value ? searchText(doc.value, query.value, Infinity).matches : matches.value;
1756
+ if (!all.length) return;
1757
+ const text = doc.value;
1758
+ const tr = transaction().setMeta({
1759
+ action: "replace",
1760
+ scroll: true
1761
+ });
1762
+ for (const m of all) tr.replace(m.from, m.to, replacementFor(text, m, query.value));
1763
+ dispatch(tr);
1764
+ const head = mainRange(state.value.selection).head;
1765
+ dispatch(transaction().select(head));
1766
+ announcement.value = common("findReplace.replaced", { count: all.length });
1767
+ runSearch();
1768
+ }
1769
+ /** The matches on the lines in view, as boxes; the one selected stands out. */
1770
+ const matchBoxes = computed(() => {
1771
+ metrics.value;
1772
+ if (!searchOpen.value || !matches.value.length) return [];
1773
+ const text = doc.value;
1774
+ const first = text.line(visibleFrom.value).from;
1775
+ const last = text.line(visibleTo.value).to;
1776
+ const out = [];
1777
+ for (let i = matchAfter(matches.value, first); i >= 0 && i < matches.value.length; i++) {
1778
+ const m = matches.value[i];
1779
+ if (m.from > last || m.to < first) break;
1780
+ const from = text.lineAt(m.from);
1781
+ const to = text.lineAt(m.to);
1782
+ for (let n = Math.max(from.number, visibleFrom.value); n <= Math.min(to.number, visibleTo.value); n++) {
1783
+ if (!layout.value.shown(n)) continue;
1784
+ const str = lineText(n);
1785
+ const a = n === from.number ? m.from - from.from : 0;
1786
+ const b = n === to.number ? m.to - to.from : str.length;
1787
+ spans(n, str, a, b).forEach((box, k) => out.push({
1788
+ key: `m${m.from}-${n}-${k}`,
1789
+ ...box,
1790
+ left: pad.x + box.left,
1791
+ current: i === currentMatch.value
1792
+ }));
1793
+ }
1794
+ if (out.length > 2e3) break;
1795
+ }
1796
+ return out;
1797
+ });
1798
+ /** Marks beside the scrollbar for where the matches are in the whole text, one per pixel row. */
1799
+ const searchMarks = computed(() => {
1800
+ if (!searchOpen.value || !matches.value.length) return [];
1801
+ const text = doc.value;
1802
+ const drawn = layout.value;
1803
+ /** Where a line sits in the whole text, from 0 to 1, as drawn (wrapped rows and folds counted). */
1804
+ const lh = lineHeight.value;
1805
+ const all = total.value;
1806
+ const share = (pos) => (rowTop(drawn.rowOf(text.lineAt(pos).number)) + lh / 2) / all;
1807
+ const taken = /* @__PURE__ */ new Set();
1808
+ const out = [];
1809
+ const current = matches.value[currentMatch.value];
1810
+ const step = Math.max(1, Math.floor(matches.value.length / 1e3));
1811
+ for (let i = 0; i < matches.value.length; i += step) {
1812
+ const top = Math.round(share(matches.value[i].from) * 1e3) / 10;
1813
+ if (taken.has(top)) continue;
1814
+ taken.add(top);
1815
+ out.push({
1816
+ top,
1817
+ current: false
1818
+ });
1819
+ }
1820
+ if (current) out.push({
1821
+ top: share(current.from) * 100,
1822
+ current: true
1823
+ });
1824
+ return out;
1825
+ });
1826
+ /** The box over a place in the text with the problems there and their fixes; `keyboard` when opened by a key, so arrows pick a fix. */
1827
+ const problemBox = shallowRef(null);
1828
+ const problemEl = ref();
1829
+ const problemSize = ref({
1830
+ width: 0,
1831
+ height: 0
1832
+ });
1833
+ let problemTimer = 0;
1834
+ /** The problems that cover a position; an empty one covers the character it marks. */
1835
+ function problemsAt(pos) {
1836
+ const out = [];
1837
+ for (const problem of diagnostics.value) {
1838
+ if (problem.from > pos) break;
1839
+ if (pos <= Math.max(problem.to, problem.from + 1)) out.push(problem);
1840
+ }
1841
+ return out;
1842
+ }
1843
+ const fixes = computed(() => (problemBox.value?.problems ?? []).flatMap((problem) => (problem.actions ?? []).map((action) => ({
1844
+ problem,
1845
+ action
1846
+ }))));
1847
+ function showProblems(pos, keyboard) {
1848
+ clearTimeout(problemTimer);
1849
+ const problems = problemsAt(pos);
1850
+ if (!problems.length) {
1851
+ problemBox.value = null;
1852
+ return false;
1853
+ }
1854
+ const hasFixes = problems.some((problem) => problem.actions?.length);
1855
+ problemBox.value = {
1856
+ pos,
1857
+ problems,
1858
+ info: [],
1859
+ ...problemsSpan(problems, pos),
1860
+ index: keyboard && hasFixes ? 0 : -1,
1861
+ keyboard
1862
+ };
1863
+ return true;
1864
+ }
1865
+ function problemsSpan(problems, pos) {
1866
+ let from = pos;
1867
+ let to = pos;
1868
+ for (const problem of problems) {
1869
+ from = Math.min(from, problem.from);
1870
+ to = Math.max(to, problem.to);
1871
+ }
1872
+ return {
1873
+ from,
1874
+ to
1875
+ };
1876
+ }
1877
+ /** Counts requests for hover text, so an answer to an older one is dropped. */
1878
+ let hoverRequest = 0;
1879
+ let hoverAbort = null;
1880
+ /**
1881
+ * Shows what is known about a place: the extensions' hover text and the
1882
+ * problems there. Slow sources fill in when they answer. `false` when
1883
+ * there is nothing and nothing is coming.
1884
+ */
1885
+ function showInfo(pos, keyboard) {
1886
+ clearTimeout(problemTimer);
1887
+ const id = ++hoverRequest;
1888
+ hoverAbort?.abort();
1889
+ const abort = new AbortController();
1890
+ hoverAbort = abort;
1891
+ const text = doc.value;
1892
+ const problems = problemsAt(pos);
1893
+ const info = [];
1894
+ let { from, to } = problemsSpan(problems, pos);
1895
+ const line = text.lineAt(pos);
1896
+ const word = wordAt(line.text, pos - line.from);
1897
+ const add = (result) => {
1898
+ if (!result) return;
1899
+ info.push(result.content);
1900
+ from = Math.min(from, result.from ?? line.from + word.from);
1901
+ to = Math.max(to, result.to ?? line.from + word.to);
1902
+ };
1903
+ const apply = () => {
1904
+ if (id !== hoverRequest || doc.value !== text) return;
1905
+ if (!problems.length && !info.length) {
1906
+ problemBox.value = null;
1907
+ return;
1908
+ }
1909
+ const hasFixes = problems.some((problem) => problem.actions?.length);
1910
+ problemBox.value = {
1911
+ pos,
1912
+ problems,
1913
+ info: info.slice(),
1914
+ from,
1915
+ to,
1916
+ index: keyboard && hasFixes ? 0 : -1,
1917
+ keyboard
1918
+ };
1919
+ if (keyboard) {
1920
+ const said = info.filter((item) => typeof item === "string");
1921
+ if (said.length) announce(said.join("\n"));
1922
+ }
1923
+ };
1924
+ let waiting = 0;
1925
+ for (const extension of extensions.value) {
1926
+ if (!extension.hover) continue;
1927
+ let answer;
1928
+ try {
1929
+ answer = extension.hover({
1930
+ pos,
1931
+ signal: abort.signal
1932
+ }, context);
1933
+ } catch (error) {
1934
+ console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error);
1935
+ continue;
1936
+ }
1937
+ if (answer && "then" in answer) {
1938
+ waiting++;
1939
+ Promise.resolve(answer).then((result) => {
1940
+ add(result);
1941
+ apply();
1942
+ }).catch((error) => {
1943
+ if (!abort.signal.aborted) console.error(`[@dou-ui/code] ${extension.name}: hover failed`, error);
1944
+ });
1945
+ } else add(answer);
1946
+ }
1947
+ apply();
1948
+ return problems.length > 0 || info.length > 0 || waiting > 0;
1949
+ }
1950
+ /** Reads out the fix picked from the keyboard, and where it is in the list. */
1951
+ function announceFix() {
1952
+ const index = problemBox.value?.index ?? -1;
1953
+ const fix = fixes.value[index];
1954
+ if (!fix) return;
1955
+ announce(format(messages.value.itemAt, {
1956
+ label: fix.action.label,
1957
+ index: index + 1,
1958
+ count: fixes.value.length
1959
+ }));
1960
+ }
1961
+ function closeProblems() {
1962
+ clearTimeout(problemTimer);
1963
+ hoverRequest++;
1964
+ hoverAbort?.abort();
1965
+ hoverAbort = null;
1966
+ problemBox.value = null;
1967
+ }
1968
+ watch(menuOpen, (open) => open && closeProblems());
1969
+ function onPressAway(event) {
1970
+ const at = event.target;
1971
+ if (at && (root.value?.contains(at) || problemEl.value?.contains(at))) return;
1972
+ closeProblems();
1973
+ }
1974
+ watch(() => !!problemBox.value, (open, _old, onCleanup) => {
1975
+ if (!open || typeof window === "undefined") return;
1976
+ window.addEventListener("pointerdown", onPressAway, true);
1977
+ onCleanup(() => window.removeEventListener("pointerdown", onPressAway, true));
1978
+ });
1979
+ /** The line whose problem icon in the gutter is under a pointer. */
1980
+ function problemIconLine(event) {
1981
+ const line = (event.target?.closest?.(`.${ns.e("problem-icon")}`))?.getAttribute("data-line");
1982
+ return line ? Number(line) : null;
1983
+ }
1984
+ /** Shows the problems on a line, as a press on its icon in the gutter asks. */
1985
+ function showLineProblems(n) {
1986
+ const line = doc.value.line(n);
1987
+ const first = diagnostics.value.find((problem) => problem.from >= line.from);
1988
+ if (!first || first.from > line.to) return;
1989
+ menuOpen.value = false;
1990
+ showInfo(first.from, false);
1991
+ }
1992
+ function runFix(index) {
1993
+ const fix = fixes.value[index];
1994
+ if (!fix) return;
1995
+ closeProblems();
1996
+ fix.action.run(context, fix.problem);
1997
+ focusInput();
1998
+ }
1999
+ /** Moves the cursor to the next problem after it (`1`) or before it (`-1`), going round, and shows it. */
2000
+ function goToProblem(direction) {
2001
+ const list = diagnostics.value;
2002
+ if (!list.length) return false;
2003
+ const head = mainRange(state.value.selection).head;
2004
+ let found;
2005
+ if (direction > 0) found = list.find((problem) => problem.from > head) ?? list[0];
2006
+ else {
2007
+ for (let i = list.length - 1; i >= 0 && !found; i--) if (list[i].from < head) found = list[i];
2008
+ found ??= list[list.length - 1];
2009
+ }
2010
+ const problem = found;
2011
+ dispatch(transaction().select(problem.from).setMeta({ scroll: true }));
2012
+ showProblems(problem.from, true);
2013
+ const m = messages.value;
2014
+ announce(format(m.problemAt, {
2015
+ line: doc.value.lineAt(problem.from).number,
2016
+ severity: m[problem.severity],
2017
+ message: problem.message
2018
+ }));
2019
+ return true;
2020
+ }
2021
+ const diagnosticControl = {
2022
+ next: () => goToProblem(1),
2023
+ previous: () => goToProblem(-1),
2024
+ showFixes: () => {
2025
+ if (!showProblems(mainRange(state.value.selection).head, true)) return false;
2026
+ announceFix();
2027
+ return true;
2028
+ }
2029
+ };
2030
+ /** Keys while the box is open from the keyboard: arrows pick a fix, Enter makes it, Escape closes the box. */
2031
+ function problemKey(name) {
2032
+ const box = problemBox.value;
2033
+ if (!box) return false;
2034
+ if (name === "escape") {
2035
+ closeProblems();
2036
+ return true;
2037
+ }
2038
+ const count = fixes.value.length;
2039
+ if (!box.keyboard || !count) return false;
2040
+ if (name === "arrowdown" || name === "arrowup") {
2041
+ const step = name === "arrowdown" ? 1 : -1;
2042
+ problemBox.value = {
2043
+ ...box,
2044
+ index: (box.index + step + count) % count
2045
+ };
2046
+ announceFix();
2047
+ return true;
2048
+ }
2049
+ if (name === "enter" || name === "tab") {
2050
+ runFix(Math.max(0, box.index));
2051
+ return true;
2052
+ }
2053
+ return false;
2054
+ }
2055
+ /**
2056
+ * Shows the problems under the mouse after a moment; leaving them hides the
2057
+ * box a moment later. Fingers are left out: a tap shows the box itself, and
2058
+ * the mouse events a browser makes up after it would only close it again.
2059
+ */
2060
+ function onContentHover(event) {
2061
+ if (event.pointerType !== "mouse" || drag || problemBox.value?.keyboard) return;
2062
+ if (!content.value?.getBoundingClientRect()) return;
2063
+ const point = {
2064
+ x: event.clientX,
2065
+ y: event.clientY
2066
+ };
2067
+ const pos = posAtCoords(point);
2068
+ const at = coordsAtPos(pos);
2069
+ const over = !!at && Math.abs(point.x - at.left) <= measure.cell * 2;
2070
+ const box = problemBox.value;
2071
+ if (box && over && pos >= box.from && pos <= box.to) {
2072
+ clearTimeout(problemTimer);
2073
+ return;
2074
+ }
2075
+ clearTimeout(problemTimer);
2076
+ const asks = over && (problemsAt(pos).length > 0 || extensions.value.some((e) => e.hover));
2077
+ problemTimer = window.setTimeout(() => asks ? showInfo(pos, false) || closeProblems() : closeProblems(), asks ? 350 : 250);
2078
+ }
2079
+ /** The mouse came onto the box: it stays. */
2080
+ function keepProblems() {
2081
+ clearTimeout(problemTimer);
2082
+ }
2083
+ function onContentLeave(event) {
2084
+ if (event.pointerType !== "mouse" || problemBox.value?.keyboard) return;
2085
+ clearTimeout(problemTimer);
2086
+ problemTimer = window.setTimeout(closeProblems, 250);
2087
+ }
2088
+ const problemStyle = computed(() => {
2089
+ const box = problemBox.value;
2090
+ return box ? floatingStyle(box.pos, problemSize.value) : null;
2091
+ });
2092
+ /**
2093
+ * Where a box about position `pos` goes: below its line, or above it when
2094
+ * there is no room (first, with `above`), always in view; too tall for
2095
+ * either side, it scrolls inside on the roomier one.
2096
+ */
2097
+ function floatingStyle(pos, size, above = false) {
2098
+ const inside = pointOf(pos);
2099
+ if (!inside) return null;
2100
+ let at = inside;
2101
+ let view = visibleBox();
2102
+ if (floatingTarget.value) {
2103
+ const page = toPage(inside);
2104
+ if (!page) return null;
2105
+ at = page;
2106
+ view = pageBox();
2107
+ }
2108
+ const { width, height } = size;
2109
+ const lh = lineHeight.value;
2110
+ const maxWidth = `${Math.max(0, Math.floor(Math.min(440, view.right - view.left - 8)))}px`;
2111
+ if (above && at.top - 4 - height >= view.top) {
2112
+ const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4));
2113
+ return {
2114
+ transform: `translate(${Math.round(left)}px, ${Math.round(at.top - 4 - height)}px)`,
2115
+ maxHeight: void 0,
2116
+ maxWidth
2117
+ };
2118
+ }
2119
+ const below = at.top + lh + 4;
2120
+ const roomBelow = view.bottom - 4 - below;
2121
+ const roomAbove = at.top - 4 - view.top;
2122
+ const handle = touchUi.value && caretHandle.value ? HANDLE : 0;
2123
+ let top;
2124
+ let room;
2125
+ if (roomBelow - handle >= height) [top, room] = [below + handle, roomBelow - handle];
2126
+ else if (roomAbove >= height) [top, room] = [at.top - 4 - height, roomAbove];
2127
+ else if (roomBelow >= height || roomBelow >= roomAbove) [top, room] = [below, roomBelow];
2128
+ else [top, room] = [view.top + 4, roomAbove];
2129
+ const left = Math.max(view.left + 4, Math.min(at.x - 12, view.right - width - 4));
2130
+ return {
2131
+ transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,
2132
+ maxHeight: height > room ? `${Math.max(0, Math.floor(room))}px` : void 0,
2133
+ maxWidth
2134
+ };
2135
+ }
2136
+ /** Keeps a floating box's whole size, even while it is cut short and scrolls. */
2137
+ function measureFloating(el, size) {
2138
+ if (el) size.value = {
2139
+ width: el.offsetWidth,
2140
+ height: el.scrollHeight + el.offsetHeight - el.clientHeight
2141
+ };
2142
+ }
2143
+ watch([problemEl, problemBox], () => measureFloating(problemEl.value, problemSize), { flush: "post" });
2144
+ const KIND_ICON = {
2145
+ keyword: SymbolKeywordIcon,
2146
+ function: FunctionIcon,
2147
+ method: FunctionIcon,
2148
+ variable: VariableIcon,
2149
+ property: WrenchIcon,
2150
+ constant: SymbolConstantIcon,
2151
+ class: SymbolClassIcon,
2152
+ type: SymbolTypeAliasIcon,
2153
+ module: PackageIcon,
2154
+ snippet: SquareCodeIcon,
2155
+ text: TypeIcon
2156
+ };
2157
+ const completion = shallowRef(null);
2158
+ const completionEl = ref();
2159
+ const completionList = ref();
2160
+ const completionSize = ref({
2161
+ width: 0,
2162
+ height: 0
2163
+ });
2164
+ const completionId = `dou-code-completion-${instance.uid}`;
2165
+ const hasCompletion = computed(() => extensions.value.some((extension) => extension.completion));
2166
+ let completionRequest = 0;
2167
+ let completionAbort = null;
2168
+ const WORD_BEFORE = /[\p{L}\p{N}_$]+$/u;
2169
+ const WORD_CHAR = /[\p{L}\p{N}_$]/u;
2170
+ /** The word right before `pos`. */
2171
+ function wordBefore(pos) {
2172
+ const line = doc.value.lineAt(pos);
2173
+ const found = WORD_BEFORE.exec(line.text.slice(0, pos - line.from));
2174
+ const text = found ? found[0] : "";
2175
+ return {
2176
+ from: pos - text.length,
2177
+ to: pos,
2178
+ text
2179
+ };
2180
+ }
2181
+ /** The answers' entries that match what is typed since each answer's `from`, best first. */
2182
+ function rankCompletions(results, pos) {
2183
+ const out = [];
2184
+ const text = doc.value;
2185
+ for (const result of results) {
2186
+ if (result.from > pos || result.from < 0) continue;
2187
+ const typed = text.slice(result.from, pos);
2188
+ for (const option of result.options) {
2189
+ const match = matchCompletion(option.label, typed);
2190
+ if (match) out.push({
2191
+ option,
2192
+ from: result.from,
2193
+ ranges: match.ranges,
2194
+ score: match.score + (option.boost ?? 0)
2195
+ });
2196
+ }
2197
+ }
2198
+ out.sort((a, b) => b.score - a.score || a.option.label.localeCompare(b.option.label));
2199
+ return out.length > 200 ? out.slice(0, 200) : out;
2200
+ }
2201
+ /** Asks the extensions for completions at the cursor and opens the list with what matches. */
2202
+ function startCompletion(explicit) {
2203
+ const main = mainRange(state.value.selection);
2204
+ const sources = extensions.value.filter((extension) => extension.completion);
2205
+ if (!sources.length || !isEmptyRange(main) || props.readonly || props.disabled) {
2206
+ closeCompletion();
2207
+ return false;
2208
+ }
2209
+ const pos = main.head;
2210
+ const id = ++completionRequest;
2211
+ completionAbort?.abort();
2212
+ const abort = new AbortController();
2213
+ completionAbort = abort;
2214
+ const text = doc.value;
2215
+ const request = {
2216
+ pos,
2217
+ word: wordBefore(pos),
2218
+ explicit,
2219
+ signal: abort.signal
2220
+ };
2221
+ const previous = completion.value?.results ?? [];
2222
+ const results = [];
2223
+ let waiting = 0;
2224
+ const apply = () => {
2225
+ if (id !== completionRequest || doc.value !== text) return;
2226
+ if (mainRange(state.value.selection).head !== pos) return;
2227
+ const source = results.length || !waiting ? results : previous;
2228
+ const items = rankCompletions(source, pos);
2229
+ const done = !explicit && items.length === 1 && text.slice(items[0].from, pos) === items[0].option.label;
2230
+ if (!items.length || done) {
2231
+ if (!waiting) completion.value = null;
2232
+ return;
2233
+ }
2234
+ const before = completion.value;
2235
+ const picked = before?.items[before.index]?.option;
2236
+ const kept = picked ? items.findIndex((item) => item.option === picked) : -1;
2237
+ completion.value = {
2238
+ pos,
2239
+ results: source,
2240
+ items,
2241
+ index: Math.max(0, kept),
2242
+ explicit,
2243
+ moved: kept > 0 && !!before?.moved
2244
+ };
2245
+ if (!before) announceCompletion();
2246
+ };
2247
+ for (const extension of sources) {
2248
+ let answer;
2249
+ try {
2250
+ answer = extension.completion(request, context);
2251
+ } catch (error) {
2252
+ console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error);
2253
+ continue;
2254
+ }
2255
+ if (answer && "then" in answer) {
2256
+ waiting++;
2257
+ Promise.resolve(answer).then((result) => {
2258
+ waiting--;
2259
+ if (result) results.push(result);
2260
+ apply();
2261
+ }).catch((error) => {
2262
+ waiting--;
2263
+ if (!abort.signal.aborted) console.error(`[@dou-ui/code] ${extension.name}: completion failed`, error);
2264
+ apply();
2265
+ });
2266
+ } else if (answer) results.push(answer);
2267
+ }
2268
+ apply();
2269
+ return true;
2270
+ }
2271
+ function closeCompletion() {
2272
+ completionRequest++;
2273
+ completionAbort?.abort();
2274
+ completionAbort = null;
2275
+ completion.value = null;
2276
+ }
2277
+ function moveCompletion(step) {
2278
+ const list = completion.value;
2279
+ if (!list) return;
2280
+ const count = list.items.length;
2281
+ const index = Math.abs(step) === 1 ? (list.index + step + count) % count : Math.max(0, Math.min(count - 1, list.index + step));
2282
+ completion.value = {
2283
+ ...list,
2284
+ index,
2285
+ moved: true
2286
+ };
2287
+ announceCompletion();
2288
+ nextTick(() => completionList.value?.querySelector(`#${completionId}-${index}`)?.scrollIntoView?.({ block: "nearest" }));
2289
+ }
2290
+ /** Reads out the picked entry, and where it is in the list. */
2291
+ function announceCompletion() {
2292
+ const list = completion.value;
2293
+ const item = list?.items[list.index];
2294
+ if (!item) return;
2295
+ announce(format(messages.value.itemAt, {
2296
+ label: item.option.detail ? `${item.option.label} ${item.option.detail}` : item.option.label,
2297
+ index: list.index + 1,
2298
+ count: list.items.length
2299
+ }));
2300
+ }
2301
+ /** Puts the entry's text in place of what was typed for it. */
2302
+ function acceptCompletion(index) {
2303
+ const item = completion.value?.items[index];
2304
+ if (!item) return;
2305
+ closeCompletion();
2306
+ const pos = mainRange(state.value.selection).head;
2307
+ const { option } = item;
2308
+ if (option.snippet !== void 0) insertSnippet(item.from, pos, option.snippet);
2309
+ else {
2310
+ const insert = option.insert ?? option.label;
2311
+ dispatch(transaction().replace(item.from, pos, insert).select(item.from + insert.length).setMeta({
2312
+ action: "complete",
2313
+ scroll: true
2314
+ }));
2315
+ }
2316
+ focusInput();
2317
+ }
2318
+ /** Keys while the list is open: arrows and pages pick, Enter or Tab puts the entry in, Escape closes it. */
2319
+ function completionKey(name) {
2320
+ if (!completion.value) return false;
2321
+ if (name === "arrowdown" || name === "arrowup") moveCompletion(name === "arrowdown" ? 1 : -1);
2322
+ else if (name === "pagedown" || name === "pageup") moveCompletion(name === "pagedown" ? 8 : -8);
2323
+ else if (name === "tab" && snippet.value && !completion.value.moved && !completion.value.explicit) {
2324
+ closeCompletion();
2325
+ return false;
2326
+ } else if (name === "enter" || name === "tab") acceptCompletion(completion.value.index);
2327
+ else if (name === "escape") closeCompletion();
2328
+ else return false;
2329
+ return true;
2330
+ }
2331
+ /** A label cut where the typed characters start and end. */
2332
+ function labelParts(item) {
2333
+ const { label } = item.option;
2334
+ const out = [];
2335
+ let at = 0;
2336
+ for (const [from, to] of item.ranges) {
2337
+ if (from > at) out.push([label.slice(at, from), false]);
2338
+ out.push([label.slice(from, to), true]);
2339
+ at = to;
2340
+ }
2341
+ if (at < label.length) out.push([label.slice(at), false]);
2342
+ return out;
2343
+ }
2344
+ const completionStyle = computed(() => {
2345
+ const list = completion.value;
2346
+ if (!list) return null;
2347
+ return floatingStyle(list.items[list.index]?.from ?? list.pos, completionSize.value);
2348
+ });
2349
+ watch([completionEl, completion], () => {
2350
+ const el = completionEl.value;
2351
+ const list = completionList.value;
2352
+ if (el && list) completionSize.value = {
2353
+ width: el.offsetWidth,
2354
+ height: el.offsetHeight + list.scrollHeight - list.clientHeight
2355
+ };
2356
+ }, { flush: "post" });
2357
+ /** The snippet being filled in: its places, grouped by number in Tab order, and which one is selected. */
2358
+ const snippet = shallowRef(null);
2359
+ /** Inserts a snippet in place of `from`–`to`, its later lines indented like the first, and selects its first place. */
2360
+ function insertSnippet(from, to, source) {
2361
+ const line = doc.value.lineAt(from);
2362
+ const indent = indentOf(line.text);
2363
+ const unit = props.indentWithTabs ? " " : " ".repeat(props.tabSize);
2364
+ const own = source.replace(/\t/g, unit);
2365
+ const { text, fields } = parseSnippet(indent ? own.replace(/\n/g, `\n${indent}`) : own);
2366
+ const groups = [];
2367
+ for (const field of fields) {
2368
+ const range = {
2369
+ from: from + field.from,
2370
+ to: from + field.to
2371
+ };
2372
+ const group = groups.find((g) => g.index === field.index);
2373
+ if (group) group.ranges.push(range);
2374
+ else groups.push({
2375
+ index: field.index,
2376
+ ranges: [range]
2377
+ });
2378
+ }
2379
+ const tr = transaction().replace(from, to, text).setMeta({
2380
+ action: "complete",
2381
+ scroll: true
2382
+ });
2383
+ if (!groups.length) {
2384
+ snippet.value = null;
2385
+ dispatch(tr.select(from + text.length));
2386
+ return;
2387
+ }
2388
+ const first = groups[0];
2389
+ tr.select({
2390
+ ranges: first.ranges.map((r) => ({
2391
+ anchor: r.from,
2392
+ head: r.to
2393
+ })),
2394
+ main: 0
2395
+ });
2396
+ dispatch(tr);
2397
+ snippet.value = groups.length > 1 || first.index !== 0 ? {
2398
+ groups,
2399
+ at: 0,
2400
+ end: from + text.length
2401
+ } : null;
2402
+ }
2403
+ /** Selects the next or previous place of the snippet; past the last, the snippet is done. */
2404
+ function snippetField(dir) {
2405
+ const session = snippet.value;
2406
+ if (!session) return false;
2407
+ const next = Math.max(0, session.at + dir);
2408
+ const group = session.groups[next];
2409
+ if (!group) {
2410
+ snippet.value = null;
2411
+ dispatch(transaction().select(session.end).setMeta({
2412
+ action: "snippet",
2413
+ scroll: true
2414
+ }));
2415
+ return true;
2416
+ }
2417
+ snippet.value = group.index === 0 ? null : {
2418
+ ...session,
2419
+ at: next
2420
+ };
2421
+ dispatch(transaction().select({
2422
+ ranges: group.ranges.map((r) => ({
2423
+ anchor: r.from,
2424
+ head: r.to
2425
+ })),
2426
+ main: 0
2427
+ }).setMeta({
2428
+ action: "snippet",
2429
+ scroll: true
2430
+ }));
2431
+ return true;
2432
+ }
2433
+ const signature = shallowRef(null);
2434
+ const signatureEl = ref();
2435
+ const signatureSize = ref({
2436
+ width: 0,
2437
+ height: 0
2438
+ });
2439
+ let signatureRequest = 0;
2440
+ let signatureAbort = null;
2441
+ /** Asks the extensions about the call around the cursor; the first answer, by priority, is shown. */
2442
+ function updateSignature() {
2443
+ const id = ++signatureRequest;
2444
+ signatureAbort?.abort();
2445
+ const abort = new AbortController();
2446
+ signatureAbort = abort;
2447
+ const pos = mainRange(state.value.selection).head;
2448
+ const text = doc.value;
2449
+ const answers = [];
2450
+ for (const extension of extensions.value) {
2451
+ if (!extension.signature) continue;
2452
+ try {
2453
+ const answer = extension.signature({
2454
+ pos,
2455
+ signal: abort.signal
2456
+ }, context);
2457
+ if (answer && "then" in answer) answers.push(Promise.resolve(answer).catch((error) => {
2458
+ if (!abort.signal.aborted) console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error);
2459
+ return null;
2460
+ }));
2461
+ else answers.push(answer);
2462
+ } catch (error) {
2463
+ console.error(`[@dou-ui/code] ${extension.name}: signature failed`, error);
2464
+ }
2465
+ }
2466
+ const show = (result) => {
2467
+ if (id !== signatureRequest || doc.value !== text) return;
2468
+ if (mainRange(state.value.selection).head !== pos) return;
2469
+ if (!result) {
2470
+ signature.value = null;
2471
+ return;
2472
+ }
2473
+ const before = signature.value?.result;
2474
+ signature.value = {
2475
+ pos,
2476
+ result
2477
+ };
2478
+ if (!before || before.label !== result.label || before.active !== result.active) {
2479
+ const param = result.params[result.active];
2480
+ announce(param ? result.label.slice(param[0], param[1]) : result.label);
2481
+ }
2482
+ };
2483
+ let i = 0;
2484
+ const next = () => {
2485
+ for (; i < answers.length; i++) {
2486
+ const answer = answers[i];
2487
+ if (answer && "then" in answer) {
2488
+ const at = i;
2489
+ answer.then((result) => {
2490
+ answers[at] = result;
2491
+ next();
2492
+ });
2493
+ return;
2494
+ }
2495
+ if (answer) return show(answer);
2496
+ }
2497
+ show(null);
2498
+ };
2499
+ next();
2500
+ }
2501
+ function closeSignature() {
2502
+ signatureRequest++;
2503
+ signatureAbort?.abort();
2504
+ signatureAbort = null;
2505
+ signature.value = null;
2506
+ }
2507
+ const signatureParts = computed(() => {
2508
+ const result = signature.value?.result;
2509
+ if (!result) return [];
2510
+ const param = result.params[result.active];
2511
+ if (!param) return [[result.label, false]];
2512
+ return [
2513
+ [result.label.slice(0, param[0]), false],
2514
+ [result.label.slice(param[0], param[1]), true],
2515
+ [result.label.slice(param[1]), false]
2516
+ ];
2517
+ });
2518
+ const signatureStyle = computed(() => {
2519
+ const box = signature.value;
2520
+ return box ? floatingStyle(box.pos, signatureSize.value, true) : null;
2521
+ });
2522
+ watch([signatureEl, signature], () => measureFloating(signatureEl.value, signatureSize), { flush: "post" });
2523
+ const teleport = useTeleport(() => props.teleport);
2524
+ /**
2525
+ * Where the boxes about the text and the touch handles render: above the
2526
+ * page by default, so a short editor never cuts them off; inside the frame
2527
+ * (`null`) when `teleport` is `false`, and until the editor is mounted.
2528
+ */
2529
+ const floatingTarget = computed(() => teleport.value.disabled || !mounted.value ? null : teleport.value.to);
2530
+ const floatingZ = ref(0);
2531
+ const floatingEl = ref();
2532
+ /**
2533
+ * The layer above the page sits in the page, not fixed to the window, so it
2534
+ * scrolls with the page on its own and never lags behind a finger's scroll.
2535
+ * Its boxes are placed in the window's coordinates; this moves the layer so
2536
+ * those land where the window has them, as of the last scroll.
2537
+ */
2538
+ const layerShift = ref({
2539
+ x: 0,
2540
+ y: 0
2541
+ });
2542
+ function readLayerShift() {
2543
+ const el = floatingEl.value;
2544
+ if (!el || !floatingTarget.value) return;
2545
+ const rect = el.getBoundingClientRect();
2546
+ const { x, y } = layerShift.value;
2547
+ layerShift.value = {
2548
+ x: x - rect.left,
2549
+ y: y - rect.top
2550
+ };
2551
+ }
2552
+ /** Bumped when the page scrolls or resizes, for boxes placed in the window's coordinates. */
2553
+ const viewportTick = ref(0);
2554
+ const bumpViewport = () => {
2555
+ readLayerShift();
2556
+ viewportTick.value++;
2557
+ };
2558
+ /**
2559
+ * A box the editor sits in scrolling (a drawer, a side panel, an app's main
2560
+ * area): the layer above the page scrolls with the page only, so it hides
2561
+ * until that box stops, rather than trail behind the text.
2562
+ */
2563
+ const boxScrolling = ref(false);
2564
+ let boxScrollTimer = 0;
2565
+ /**
2566
+ * How the editor moves when the page scrolls, read as the layer opens: with
2567
+ * the page; not at all, inside a `fixed` box (a bar pinned to the bottom, a
2568
+ * panel), where the layer stays fixed too; or partly, inside a `sticky` box,
2569
+ * where the layer hides while the page scrolls.
2570
+ */
2571
+ const anchorMode = ref("page");
2572
+ function readAnchorMode() {
2573
+ let mode = "page";
2574
+ for (let el = root.value?.parentElement; el && el !== document.body; el = el.parentElement) {
2575
+ const { position } = getComputedStyle(el);
2576
+ if (position === "fixed") {
2577
+ mode = "fixed";
2578
+ break;
2579
+ }
2580
+ if (position === "sticky") mode = "sticky";
2581
+ }
2582
+ anchorMode.value = mode;
2583
+ }
2584
+ function onAnyScroll(event) {
2585
+ const box = event.target;
2586
+ if (!(box instanceof Element) ? anchorMode.value === "sticky" : box !== scroller.value && !!root.value && box.contains(root.value)) {
2587
+ boxScrolling.value = true;
2588
+ clearTimeout(boxScrollTimer);
2589
+ boxScrollTimer = window.setTimeout(() => boxScrolling.value = false, 160);
2590
+ }
2591
+ bumpViewport();
2592
+ }
2593
+ const floatingOpen = computed(() => !!(problemBox.value || completion.value || signature.value) || touchUi.value && focused.value);
2594
+ watch(floatingOpen, (open, _old, onCleanup) => {
2595
+ if (!open || !floatingTarget.value || typeof window === "undefined") return;
2596
+ floatingZ.value = nextZIndex();
2597
+ readFrameFont();
2598
+ readAnchorMode();
2599
+ readLayerShift();
2600
+ nextTick(bumpViewport);
2601
+ const vv = window.visualViewport;
2602
+ window.addEventListener("scroll", onAnyScroll, {
2603
+ capture: true,
2604
+ passive: true
2605
+ });
2606
+ window.addEventListener("resize", bumpViewport, { passive: true });
2607
+ vv?.addEventListener("resize", bumpViewport, { passive: true });
2608
+ vv?.addEventListener("scroll", bumpViewport, { passive: true });
2609
+ onCleanup(() => {
2610
+ window.removeEventListener("scroll", onAnyScroll, { capture: true });
2611
+ clearTimeout(boxScrollTimer);
2612
+ boxScrolling.value = false;
2613
+ window.removeEventListener("resize", bumpViewport);
2614
+ vv?.removeEventListener("resize", bumpViewport);
2615
+ vv?.removeEventListener("scroll", bumpViewport);
2616
+ });
2617
+ });
2618
+ /** Where a point of the content is in the window; `null` while it is out of the editor's view. */
2619
+ function toPage(inside) {
2620
+ viewportTick.value;
2621
+ const view = visibleBox();
2622
+ if (inside.top + lineHeight.value <= view.top || inside.top >= view.bottom) return null;
2623
+ if (inside.x < view.left - 1 || inside.x > view.right + 1) return null;
2624
+ const rect = content.value?.getBoundingClientRect();
2625
+ if (!rect) return null;
2626
+ return {
2627
+ x: rect.left + inside.x,
2628
+ top: rect.top + inside.top
2629
+ };
2630
+ }
2631
+ /** The editor's text in view, in the window's coordinates. */
2632
+ function frameInPage() {
2633
+ viewportTick.value;
2634
+ const view = visibleBox();
2635
+ const rect = content.value?.getBoundingClientRect();
2636
+ const x = rect?.left ?? 0;
2637
+ const y = rect?.top ?? 0;
2638
+ return {
2639
+ left: x + view.left,
2640
+ top: y + view.top,
2641
+ right: x + view.right,
2642
+ bottom: y + view.bottom
2643
+ };
2644
+ }
2645
+ /**
2646
+ * The part of the page in view, in the window's coordinates: on a phone,
2647
+ * above the keyboard and the bar of keys over it.
2648
+ */
2649
+ function pageBox() {
2650
+ viewportTick.value;
2651
+ const vv = window.visualViewport;
2652
+ const left = vv ? vv.offsetLeft : 0;
2653
+ const top = vv ? vv.offsetTop : 0;
2654
+ const width = vv ? vv.width : document.documentElement.clientWidth;
2655
+ const height = vv ? vv.height : document.documentElement.clientHeight;
2656
+ return {
2657
+ left,
2658
+ top,
2659
+ right: left + width,
2660
+ bottom: top + height - (showKeys.value ? KEYS_SPACE : 0)
2661
+ };
2662
+ }
2663
+ /** After each change: opens, updates or closes the completion list and the parameter hints, and moves the snippet's places. */
2664
+ function updateAssist(result) {
2665
+ const { action } = result.meta;
2666
+ const { changes } = result;
2667
+ const main = mainRange(result.state.selection);
2668
+ const session = snippet.value;
2669
+ if (session) {
2670
+ const groups = changes.empty ? session.groups : session.groups.map((group) => ({
2671
+ index: group.index,
2672
+ ranges: group.ranges.map((range) => ({
2673
+ from: changes.mapPos(range.from, -1),
2674
+ to: changes.mapPos(range.to, 1)
2675
+ }))
2676
+ }));
2677
+ const inside = groups[session.at]?.ranges.some((range) => main.head >= range.from && main.head <= range.to);
2678
+ const end = changes.empty ? session.end : changes.mapPos(session.end, 1);
2679
+ snippet.value = action === "snippet" || action === "complete" || inside ? {
2680
+ ...session,
2681
+ groups,
2682
+ end
2683
+ } : null;
2684
+ }
2685
+ if (action === "remote") {
2686
+ if (changes.empty) return;
2687
+ const head = mainRange(result.before.selection).head;
2688
+ const map = (pos) => changes.mapPos(pos, -1);
2689
+ const list = completion.value;
2690
+ if (list) {
2691
+ const start = Math.min(list.pos, ...list.results.map((answer) => answer.from));
2692
+ if (changes.touches(Math.min(start, head), Math.max(list.pos, head))) closeCompletion();
2693
+ else completion.value = {
2694
+ ...list,
2695
+ pos: map(list.pos),
2696
+ results: list.results.map((answer) => ({
2697
+ ...answer,
2698
+ from: map(answer.from)
2699
+ })),
2700
+ items: list.items.map((item) => ({
2701
+ ...item,
2702
+ from: map(item.from)
2703
+ }))
2704
+ };
2705
+ }
2706
+ const hints = signature.value;
2707
+ if (hints) if (changes.touches(Math.min(hints.pos, head), Math.max(hints.pos, head))) updateSignature();
2708
+ else signature.value = {
2709
+ ...hints,
2710
+ pos: map(hints.pos)
2711
+ };
2712
+ return;
2713
+ }
2714
+ if (action === "complete" || action === "snippet") {
2715
+ updateSignature();
2716
+ return;
2717
+ }
2718
+ if (action === "input" && !changes.empty && result.state.selection.ranges.length === 1) {
2719
+ const ch = changes.changes[changes.changes.length - 1].insert ? result.state.doc.slice(main.head - 1, main.head) : "";
2720
+ const trigger = extensions.value.some((extension) => extension.completionTriggers?.includes(ch));
2721
+ if (ch && (WORD_CHAR.test(ch) || trigger)) startCompletion(false);
2722
+ else closeCompletion();
2723
+ if (signature.value || ch === "(" || ch === ",") updateSignature();
2724
+ return;
2725
+ }
2726
+ if (action === "delete" && completion.value && wordBefore(main.head).text) startCompletion(completion.value.explicit);
2727
+ else closeCompletion();
2728
+ if (signature.value) updateSignature();
2729
+ }
2730
+ /** Where the problems sit along the scrollbar, by severity. */
2731
+ const problemMarks = computed(() => {
2732
+ const list = diagnostics.value;
2733
+ if (!list.length) return [];
2734
+ const text = doc.value;
2735
+ const drawn = layout.value;
2736
+ const lh = lineHeight.value;
2737
+ const all = total.value;
2738
+ const taken = /* @__PURE__ */ new Set();
2739
+ const out = [];
2740
+ for (const problem of list) {
2741
+ const y = rowTop(drawn.rowOf(text.lineAt(problem.from).number)) + lh / 2;
2742
+ const top = Math.round(y / all * 1e3) / 10;
2743
+ const key = `${top}${problem.severity}`;
2744
+ if (taken.has(key)) continue;
2745
+ taken.add(key);
2746
+ out.push({
2747
+ top,
2748
+ severity: problem.severity
2749
+ });
2750
+ if (out.length >= 1e3) break;
2751
+ }
2752
+ return out;
2753
+ });
2754
+ const panels = computed(() => {
2755
+ const top = [];
2756
+ const bottom = [];
2757
+ for (const extension of extensions.value) for (const bar of extension.panels?.(context) ?? []) (bar.position === "top" ? top : bottom).push({
2758
+ key: `${extension.name}/${bar.name}`,
2759
+ render: bar.render
2760
+ });
2761
+ return {
2762
+ top,
2763
+ bottom
2764
+ };
2765
+ });
2766
+ const searchControl = {
2767
+ open: (replace) => openSearch(replace),
2768
+ close: closeSearch,
2769
+ next: () => nextMatch(),
2770
+ previous: () => previousMatch()
2771
+ };
2772
+ /**
2773
+ * What the textarea holds: the text from `from` to `to`, and the caret
2774
+ * inside it. `selected` is the selection its caret stands for, on a touch
2775
+ * screen: whatever the textarea is given there replaces it.
2776
+ */
2777
+ let mirror = {
2778
+ from: 0,
2779
+ to: 0,
2780
+ value: "",
2781
+ start: 0,
2782
+ end: 0,
2783
+ selected: null
2784
+ };
2785
+ const inputBox = ref({
2786
+ top: pad.y,
2787
+ left: pad.x,
2788
+ height: 20
2789
+ });
2790
+ function syncInput() {
2791
+ const { doc: text, selection } = state.value;
2792
+ const main = mainRange(selection);
2793
+ const first = text.lineAt(rangeFrom(main));
2794
+ const last = text.lineAt(rangeTo(main));
2795
+ let from = first.from;
2796
+ let to = last.to;
2797
+ if (to - from > WINDOW || last.number - first.number > 50) {
2798
+ const line = text.lineAt(main.head);
2799
+ from = Math.max(line.from, main.head - WINDOW / 2);
2800
+ to = Math.min(line.to, main.head + WINDOW / 2);
2801
+ from = line.from + snapCluster(line.text, from - line.from);
2802
+ }
2803
+ const value = text.slice(from, to);
2804
+ let start = Math.max(0, Math.min(rangeFrom(main), to) - from);
2805
+ const end = Math.max(0, Math.min(rangeTo(main), to) - from);
2806
+ const selected = coarse.value && !isEmptyRange(main) ? {
2807
+ from: rangeFrom(main),
2808
+ to: rangeTo(main)
2809
+ } : null;
2810
+ if (selected) start = end;
2811
+ mirror = {
2812
+ from,
2813
+ to,
2814
+ value,
2815
+ start,
2816
+ end,
2817
+ selected
2818
+ };
2819
+ composeMap = null;
2820
+ const startLine = text.lineAt(from);
2821
+ const headLine = text.lineAt(main.head);
2822
+ const headText = headLine.number === startLine.number ? startLine.text : headLine.text;
2823
+ const caret = place(headLine.number, headText, main.head - headLine.from);
2824
+ const lineStart = headLine.number === startLine.number ? from - startLine.from : 0;
2825
+ inputBox.value = {
2826
+ top: caret.top - (headLine.number - startLine.number) * lineHeight.value,
2827
+ left: pad.x + caret.x - (measure.x(headText, main.head - headLine.from) - measure.x(headText, lineStart)),
2828
+ height: (text.lineAt(to).number - startLine.number + 1) * lineHeight.value
2829
+ };
2830
+ const el = input.value;
2831
+ if (!el) return;
2832
+ if (el.value !== value) el.value = value;
2833
+ if (document.activeElement === el && (el.selectionStart !== start || el.selectionEnd !== end)) el.setSelectionRange(start, end, main.head < main.anchor ? "backward" : "forward");
2834
+ }
2835
+ /** The text a change in the textarea replaces: the part it changed, or the selection its caret stands for. */
2836
+ function inputRange(diff) {
2837
+ const { selected } = mirror;
2838
+ const from = composedPos(selected ? selected.from : mirror.from + diff.from, -1);
2839
+ return {
2840
+ from,
2841
+ to: Math.max(from, composedPos(selected ? selected.to : mirror.from + diff.to, 1))
2842
+ };
2843
+ }
2844
+ /** Turns what the textarea now holds into a change of the text. */
2845
+ function readInput() {
2846
+ const el = input.value;
2847
+ if (!el || props.readonly) return;
2848
+ const diff = diffText(mirror.value, el.value, mirror.start);
2849
+ if (!diff) return;
2850
+ const { from, to } = inputRange(diff);
2851
+ let { insert } = diff;
2852
+ if (insert.endsWith("\n") && performance.now() - confirmEnter < 200) {
2853
+ insert = insert.slice(0, -1);
2854
+ confirmEnter = -Infinity;
2855
+ }
2856
+ if (!insert && from === to) return syncInput();
2857
+ const { doc: text, selection } = state.value;
2858
+ const main = mainRange(selection);
2859
+ if (from === rangeFrom(main) && to === rangeTo(main) && insert) {
2860
+ if (insert === "\n") return run(insertNewline);
2861
+ if (insertText(target, insert)) return;
2862
+ dispatch(transaction().replaceSelection(insert).setMeta({ action: "input" }));
2863
+ return;
2864
+ }
2865
+ if (mirror.selected && !insert && from === rangeFrom(main) && to === rangeTo(main)) return run(deleteCharBackward);
2866
+ if (!insert && isEmptyRange(main)) {
2867
+ const line = text.lineAt(main.head);
2868
+ const col = main.head - line.from;
2869
+ const back = col ? line.from + moveCluster(line.text, col, -1) : main.head - 1;
2870
+ const forward = col < line.text.length ? line.from + moveCluster(line.text, col, 1) : main.head + 1;
2871
+ if (from === back && to === main.head) return run(deleteCharBackward);
2872
+ if (from === main.head && to === forward) return run(deleteCharForward);
2873
+ }
2874
+ const tr = transaction().setMeta({ action: insert ? "input" : "delete" });
2875
+ tr.replace(from, to, insert);
2876
+ if (mirror.selected) {
2877
+ dispatch(tr.select(from + insert.length));
2878
+ return;
2879
+ }
2880
+ const result = tr.resolve();
2881
+ const base = composedPos(mirror.from, 1);
2882
+ const caret = (offset) => base + offset;
2883
+ const ranges = result.state.selection.ranges.slice();
2884
+ const backward = el.selectionDirection === "backward";
2885
+ const head = caret(backward ? el.selectionStart : el.selectionEnd);
2886
+ const anchor = caret(backward ? el.selectionEnd : el.selectionStart);
2887
+ ranges[result.state.selection.main] = {
2888
+ anchor,
2889
+ head
2890
+ };
2891
+ tr.select({
2892
+ ranges,
2893
+ main: result.state.selection.main
2894
+ });
2895
+ dispatch(tr);
2896
+ }
2897
+ function onInput() {
2898
+ if (composing.value) {
2899
+ const el = input.value;
2900
+ const diff = diffText(mirror.value, el.value, mirror.start);
2901
+ if (!diff) {
2902
+ preview.value = null;
2903
+ return;
2904
+ }
2905
+ preview.value = {
2906
+ ...inputRange(diff),
2907
+ insert: diff.insert
2908
+ };
2909
+ return;
2910
+ }
2911
+ readInput();
2912
+ }
2913
+ function onCompositionStart() {
2914
+ composing.value = true;
2915
+ }
2916
+ function onCompositionEnd() {
2917
+ composing.value = false;
2918
+ preview.value = null;
2919
+ readInput();
2920
+ syncInput();
2921
+ }
2922
+ function onSelectionChange() {
2923
+ const el = input.value;
2924
+ if (!el || document.activeElement !== el || composing.value) return;
2925
+ if (el.selectionStart === mirror.start && el.selectionEnd === mirror.end) return;
2926
+ if (el.value !== mirror.value) return;
2927
+ const backward = el.selectionDirection === "backward";
2928
+ const start = mirror.from + el.selectionStart;
2929
+ const end = mirror.from + el.selectionEnd;
2930
+ const selection = state.value.selection;
2931
+ const ranges = selection.ranges.slice();
2932
+ ranges[selection.main] = backward ? {
2933
+ anchor: end,
2934
+ head: start
2935
+ } : {
2936
+ anchor: start,
2937
+ head: end
2938
+ };
2939
+ mirror.start = el.selectionStart;
2940
+ mirror.end = el.selectionEnd;
2941
+ dispatch(transaction().select({
2942
+ ranges,
2943
+ main: selection.main
2944
+ }).setMeta({ scroll: true }));
2945
+ }
2946
+ const target = {
2947
+ get state() {
2948
+ return state.value;
2949
+ },
2950
+ get readonly() {
2951
+ return !!props.readonly || !!props.disabled;
2952
+ },
2953
+ get tabSize() {
2954
+ return props.tabSize;
2955
+ },
2956
+ get indentWithTabs() {
2957
+ return !!props.indentWithTabs;
2958
+ },
2959
+ get pageLines() {
2960
+ return Math.max(1, Math.floor((viewHeight.value || 400) / lineHeight.value) - 1);
2961
+ },
2962
+ get language() {
2963
+ return props.language ?? null;
2964
+ },
2965
+ get closeBrackets() {
2966
+ return props.closeBrackets;
2967
+ },
2968
+ transaction,
2969
+ dispatch,
2970
+ moveVertically,
2971
+ undo,
2972
+ redo,
2973
+ languageAt,
2974
+ syntaxAt,
2975
+ get search() {
2976
+ return props.searchable ? searchControl : void 0;
2977
+ },
2978
+ get folding() {
2979
+ return props.foldable ? folding : void 0;
2980
+ },
2981
+ get diagnostics() {
2982
+ return diagnosticControl;
2983
+ },
2984
+ assist: {
2985
+ complete: () => startCompletion(true),
2986
+ hover: () => showInfo(mainRange(state.value.selection).head, true),
2987
+ field: (dir) => snippetField(dir)
2988
+ }
2989
+ };
2990
+ function run(command) {
2991
+ return command(target);
2992
+ }
2993
+ /** Moves by rows as drawn: a wrapped line's rows one by one, over folded lines. */
2994
+ function moveVertically(range, count) {
2995
+ const { doc: text } = state.value;
2996
+ const line = text.lineAt(range.head);
2997
+ const at = place(line.number, line.text, range.head - line.from);
2998
+ const goal = goals.get(range.head) ?? at.x;
2999
+ const row = layout.value.rowOf(line.number) + at.sub + count;
3000
+ let head;
3001
+ if (row < 0) head = 0;
3002
+ else if (row >= layout.value.total) head = text.length;
3003
+ else {
3004
+ const { n, sub } = layout.value.lineAtRow(row);
3005
+ const next = text.line(n);
3006
+ head = next.from + colAt(next.number, next.text, sub, goal);
3007
+ }
3008
+ pendingGoals.set(head, goal);
3009
+ return head;
3010
+ }
3011
+ /** The extensions' keys, lowest priority first, since later bindings are tried first. */
3012
+ function extensionKeys() {
3013
+ const list = extensions.value;
3014
+ const out = [];
3015
+ for (let i = list.length - 1; i >= 0; i--) out.push(...keymapBindings(list[i].keymap?.(context)));
3016
+ return out;
3017
+ }
3018
+ const keymap = computed(() => buildKeymap([
3019
+ ...props.tabIndents ? defaultKeymap : defaultKeymap.filter((b) => b.run !== insertTab),
3020
+ ...extensionKeys(),
3021
+ ...keymapBindings(props.keymap)
3022
+ ], apple));
3023
+ /** After Escape, Tab leaves the editor instead of indenting, so keyboard users are never stuck. */
3024
+ let tabLeaves = false;
3025
+ /** When Enter last confirmed a composition; some browsers also put a line break into the textarea for it, right after. */
3026
+ let confirmEnter = -Infinity;
3027
+ function onKeydown(event) {
3028
+ if (isComposing(event) || composing.value) {
3029
+ if (event.key === "Enter") confirmEnter = performance.now();
3030
+ return;
3031
+ }
3032
+ confirmEnter = -Infinity;
3033
+ const name = eventKey(event, apple);
3034
+ if (completionKey(name) || problemKey(name)) {
3035
+ event.preventDefault();
3036
+ event.stopPropagation();
3037
+ return;
3038
+ }
3039
+ if (name === "escape" && menuOpen.value) {
3040
+ menuOpen.value = false;
3041
+ event.preventDefault();
3042
+ event.stopPropagation();
3043
+ return;
3044
+ }
3045
+ if (name === "escape" && snippet.value) {
3046
+ snippet.value = null;
3047
+ event.preventDefault();
3048
+ event.stopPropagation();
3049
+ return;
3050
+ }
3051
+ const leaving = tabLeaves && (name === "tab" || name === "shift+tab");
3052
+ tabLeaves = name === "escape";
3053
+ if (leaving) return;
3054
+ for (const command of keymap.value.get(name) ?? []) if (command(target)) {
3055
+ event.preventDefault();
3056
+ event.stopPropagation();
3057
+ return;
3058
+ }
3059
+ }
3060
+ function onBeforeInput(event) {
3061
+ if (event.inputType === "historyUndo" || event.inputType === "historyRedo") {
3062
+ event.preventDefault();
3063
+ if (event.inputType === "historyUndo") undo();
3064
+ else redo();
3065
+ }
3066
+ }
3067
+ function selectedText() {
3068
+ const { doc: text, selection } = state.value;
3069
+ return selection.ranges.filter((range) => !isEmptyRange(range)).map((range) => text.slice(rangeFrom(range), rangeTo(range))).join("\n");
3070
+ }
3071
+ function onCopy(event) {
3072
+ const text = selectedText();
3073
+ if (!text) return;
3074
+ event.preventDefault();
3075
+ event.clipboardData?.setData("text/plain", text);
3076
+ }
3077
+ function onCut(event) {
3078
+ onCopy(event);
3079
+ if (!event.defaultPrevented || target.readonly) return;
3080
+ dispatch(transaction().replaceSelection("").setMeta({ action: "cut" }));
3081
+ }
3082
+ function onPaste(event) {
3083
+ event.preventDefault();
3084
+ pasteText(event.clipboardData?.getData("text/plain"));
3085
+ }
3086
+ function pasteText(text) {
3087
+ if (!text || target.readonly) return;
3088
+ const { ranges } = state.value.selection;
3089
+ const parts = splitLines(text);
3090
+ const spread = ranges.length > 1 && parts.length === ranges.length;
3091
+ dispatch(transaction().replaceSelection(spread ? (_, i) => parts[i] : text).setMeta({ action: "paste" }));
3092
+ }
3093
+ /** The text position under a point in the page, clamped to the text. */
3094
+ function posAtCoords(point) {
3095
+ const rect = content.value?.getBoundingClientRect();
3096
+ if (!rect) return 0;
3097
+ const { n, sub } = layout.value.lineAtRow(rowAtY(point.y - rect.top));
3098
+ const line = state.value.doc.line(n);
3099
+ return line.from + colAt(n, line.text, sub, point.x - rect.left - pad.x);
3100
+ }
3101
+ function coordsAtPos(pos) {
3102
+ const rect = content.value?.getBoundingClientRect();
3103
+ if (!rect) return null;
3104
+ const line = doc.value.lineAt(pos);
3105
+ if (!isShown(line.number)) return null;
3106
+ const at = place(line.number, line.text, pos - line.from);
3107
+ const top = rect.top + at.top;
3108
+ return {
3109
+ left: rect.left + pad.x + at.x,
3110
+ top,
3111
+ bottom: top + lineHeight.value
3112
+ };
3113
+ }
3114
+ function unitAt(pos, unit) {
3115
+ if (unit === "char") return {
3116
+ from: pos,
3117
+ to: pos
3118
+ };
3119
+ const line = doc.value.lineAt(pos);
3120
+ if (unit === "line") return {
3121
+ from: line.from,
3122
+ to: Math.min(doc.value.length, line.to + 1)
3123
+ };
3124
+ const word = wordAt(line.text, pos - line.from);
3125
+ return {
3126
+ from: line.from + word.from,
3127
+ to: line.from + word.to
3128
+ };
3129
+ }
3130
+ let drag = null;
3131
+ /** The line and the x inside the text (from the line's start) under a point in the page. */
3132
+ function lineAtCoords(point) {
3133
+ const rect = content.value.getBoundingClientRect();
3134
+ const { n } = layout.value.lineAtRow(rowAtY(point.y - rect.top));
3135
+ return {
3136
+ n,
3137
+ x: Math.max(0, point.x - rect.left - pad.x)
3138
+ };
3139
+ }
3140
+ /** A rectangle of text from the drag's start to `point`: one range per line, cut at the same x. */
3141
+ function extendColumns(point) {
3142
+ const start = drag.column;
3143
+ const end = lineAtCoords(point);
3144
+ const ranges = [];
3145
+ const step = end.n >= start.n ? 1 : -1;
3146
+ for (let n = start.n;; n += step) {
3147
+ if (!layout.value.shown(n) && n !== end.n) continue;
3148
+ const line = doc.value.line(n);
3149
+ const anchor = line.from + measure.col(line.text, start.x);
3150
+ const head = line.from + measure.col(line.text, end.x);
3151
+ if (anchor !== head || start.x === end.x || measure.x(line.text, line.text.length) >= start.x) ranges.push({
3152
+ anchor,
3153
+ head
3154
+ });
3155
+ if (n === end.n) break;
3156
+ }
3157
+ if (!ranges.length) return;
3158
+ dispatch(transaction().select(normalizeSelection({
3159
+ ranges,
3160
+ main: ranges.length - 1
3161
+ }, doc.value.length)).setMeta({ scroll: false }));
3162
+ }
3163
+ function extendTo(point) {
3164
+ if (!drag) return;
3165
+ if (drag.column) return extendColumns(point);
3166
+ const { offset } = drag;
3167
+ const pos = posAtCoords(offset ? {
3168
+ x: point.x - offset.x,
3169
+ y: point.y - offset.y
3170
+ } : point);
3171
+ if (drag.caret) {
3172
+ dispatch(transaction().select(pos).setMeta({ scroll: false }));
3173
+ caretHandle.value = true;
3174
+ return;
3175
+ }
3176
+ if (offset && pos === drag.start.from) return;
3177
+ const at = unitAt(pos, drag.unit);
3178
+ const { start } = drag;
3179
+ const range = at.from < start.from ? {
3180
+ anchor: start.to,
3181
+ head: at.from
3182
+ } : {
3183
+ anchor: start.from,
3184
+ head: Math.max(at.to, start.to)
3185
+ };
3186
+ if (drag.unit === "char") {
3187
+ range.anchor = start.from;
3188
+ range.head = pos;
3189
+ }
3190
+ const selection = state.value.selection;
3191
+ const ranges = selection.ranges.slice();
3192
+ ranges[selection.main] = range;
3193
+ dispatch(transaction().select({
3194
+ ranges,
3195
+ main: selection.main
3196
+ }).setMeta({ scroll: false }));
3197
+ }
3198
+ /** Scrolls while a drag is held past the top or bottom edge. */
3199
+ function autoScroll() {
3200
+ if (!drag || !scroller.value) return;
3201
+ const rect = scroller.value.getBoundingClientRect();
3202
+ const dy = drag.y < rect.top ? drag.y - rect.top : drag.y > rect.bottom ? drag.y - rect.bottom : 0;
3203
+ const dx = drag.x < rect.left + gutterWidth.value ? drag.x - rect.left - gutterWidth.value : drag.x > rect.right ? drag.x - rect.right : 0;
3204
+ if (dy || dx) {
3205
+ scroller.value.scrollTop += dy / 2;
3206
+ scroller.value.scrollLeft += dx / 2;
3207
+ onScroll();
3208
+ extendTo(drag);
3209
+ }
3210
+ drag.frame = requestAnimationFrame(autoScroll);
3211
+ }
3212
+ function startDrag(event, unit, start, hold = holdPointer(event, root.value), touch) {
3213
+ drag = {
3214
+ unit,
3215
+ start,
3216
+ x: event.clientX,
3217
+ y: event.clientY,
3218
+ frame: 0,
3219
+ hold,
3220
+ touch: !!touch,
3221
+ ...touch
3222
+ };
3223
+ touchDrag.value = !!touch;
3224
+ drag.hold.grab();
3225
+ drag.frame = requestAnimationFrame(autoScroll);
3226
+ window.addEventListener("pointermove", onDragMove);
3227
+ window.addEventListener("pointerup", endDrag);
3228
+ window.addEventListener("pointercancel", endDrag);
3229
+ }
3230
+ function onDragMove(event) {
3231
+ if (!drag) return;
3232
+ drag.x = event.clientX;
3233
+ drag.y = event.clientY;
3234
+ extendTo(drag);
3235
+ }
3236
+ function endDrag() {
3237
+ if (!drag) return;
3238
+ cancelAnimationFrame(drag.frame);
3239
+ drag.hold.release();
3240
+ const { touch, caret } = drag;
3241
+ drag = null;
3242
+ touchDrag.value = false;
3243
+ if (touch && !caret && !isEmptyRange(mainRange(state.value.selection))) menuOpen.value = true;
3244
+ window.removeEventListener("pointermove", onDragMove);
3245
+ window.removeEventListener("pointerup", endDrag);
3246
+ window.removeEventListener("pointercancel", endDrag);
3247
+ }
3248
+ function focusInput() {
3249
+ if (props.disabled) return;
3250
+ input.value?.focus({ preventScroll: true });
3251
+ }
3252
+ /** Selects the unit at `pos`: alone, extending the main range (`extend`), or as one more range (`add`). */
3253
+ function select(unit, pos, extend, add = false) {
3254
+ const at = unitAt(pos, unit);
3255
+ const { selection } = state.value;
3256
+ const main = mainRange(selection);
3257
+ const range = extend ? {
3258
+ anchor: main.anchor,
3259
+ head: pos < main.anchor ? at.from : at.to
3260
+ } : {
3261
+ anchor: at.from,
3262
+ head: at.to
3263
+ };
3264
+ const next = add ? {
3265
+ ranges: [...selection.ranges, range],
3266
+ main: selection.ranges.length
3267
+ } : {
3268
+ ranges: [range],
3269
+ main: 0
3270
+ };
3271
+ dispatch(transaction().select(normalizeSelection(next, doc.value.length)).setMeta({ scroll: false }));
3272
+ return extend ? {
3273
+ from: main.anchor,
3274
+ to: main.anchor
3275
+ } : at;
3276
+ }
3277
+ /** A tap that may turn into a scroll or a long press; touches only act once they end in place. */
3278
+ let touch = null;
3279
+ /** The fold toggle or folded marker under a pointer, as the line it belongs to. */
3280
+ function foldTarget(event) {
3281
+ const el = event.target?.closest?.("[data-fold], [data-unfold]");
3282
+ if (!el) return null;
3283
+ const unfold = el.getAttribute("data-unfold");
3284
+ return unfold ? {
3285
+ n: Number(unfold),
3286
+ folded: true
3287
+ } : {
3288
+ n: Number(el.getAttribute("data-fold")),
3289
+ folded: el.classList.contains("is-folded")
3290
+ };
3291
+ }
3292
+ function onPointerDown(event, area) {
3293
+ if (event.button !== 0 || props.disabled) return;
3294
+ const cell = event.target?.closest?.("[data-gutter-cell]");
3295
+ const column = cell && gutterColumns.value[Number(cell.getAttribute("data-gutter-cell"))];
3296
+ if (column?.onPress) {
3297
+ event.preventDefault();
3298
+ event.stopPropagation();
3299
+ column.onPress(Number(cell.getAttribute("data-line")), event);
3300
+ return;
3301
+ }
3302
+ const fold = foldTarget(event);
3303
+ if (fold) {
3304
+ event.preventDefault();
3305
+ event.stopPropagation();
3306
+ toggleFold(fold.n, fold.folded);
3307
+ return;
3308
+ }
3309
+ const pos = posAtCoords({
3310
+ x: event.clientX,
3311
+ y: event.clientY
3312
+ });
3313
+ const iconLine = area === "gutter" ? problemIconLine(event) : null;
3314
+ if (iconLine !== null && event.pointerType === "mouse") {
3315
+ event.preventDefault();
3316
+ showLineProblems(iconLine);
3317
+ return;
3318
+ }
3319
+ if (event.pointerType !== "mouse") {
3320
+ onPointerCancel();
3321
+ const x = event.clientX;
3322
+ const y = event.clientY;
3323
+ touch = {
3324
+ x,
3325
+ y,
3326
+ pointer: event.pointerId,
3327
+ hold: holdPointer(event, root.value, () => {
3328
+ onPointerCancel();
3329
+ endDrag();
3330
+ }),
3331
+ timer: window.setTimeout(() => {
3332
+ if (!touch) return;
3333
+ const { hold } = touch;
3334
+ touch = null;
3335
+ touchUi.value = true;
3336
+ const unit = area === "gutter" ? "line" : "word";
3337
+ const at = select(unit, pos, false);
3338
+ focusInput();
3339
+ startDrag({
3340
+ clientX: x,
3341
+ clientY: y
3342
+ }, unit, at, hold, {});
3343
+ }, 450)
3344
+ };
3345
+ return;
3346
+ }
3347
+ touchUi.value = false;
3348
+ menuOpen.value = false;
3349
+ closeProblems();
3350
+ event.preventDefault();
3351
+ focusInput();
3352
+ if (event.altKey && event.shiftKey && area === "text") {
3353
+ startDrag(event, "char", {
3354
+ from: pos,
3355
+ to: pos
3356
+ });
3357
+ drag.column = lineAtCoords({
3358
+ x: event.clientX,
3359
+ y: event.clientY
3360
+ });
3361
+ extendColumns({
3362
+ x: event.clientX,
3363
+ y: event.clientY
3364
+ });
3365
+ return;
3366
+ }
3367
+ const count = countClick(event);
3368
+ const unit = area === "gutter" || count === 3 ? "line" : count === 2 ? "word" : "char";
3369
+ startDrag(event, unit, select(unit, pos, event.shiftKey, event.altKey && !event.shiftKey));
3370
+ }
3371
+ /**
3372
+ * Counts quick clicks in one spot ourselves: a `pointerdown`'s `detail` is
3373
+ * 0 in some browsers, and the `mousedown` that has it is held back here.
3374
+ */
3375
+ let lastClick = {
3376
+ time: 0,
3377
+ x: 0,
3378
+ y: 0,
3379
+ count: 0
3380
+ };
3381
+ function countClick(event) {
3382
+ const count = Math.abs(event.clientX - lastClick.x) < 4 && Math.abs(event.clientY - lastClick.y) < 4 && event.timeStamp - lastClick.time < 500 ? lastClick.count % 3 + 1 : 1;
3383
+ lastClick = {
3384
+ time: event.timeStamp,
3385
+ x: event.clientX,
3386
+ y: event.clientY,
3387
+ count
3388
+ };
3389
+ return count;
3390
+ }
3391
+ function onPointerMove(event) {
3392
+ if (!touch || event.pointerId !== touch.pointer) return;
3393
+ if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) onPointerCancel();
3394
+ }
3395
+ function onPointerUp(event, area) {
3396
+ if (!touch || event.pointerId !== touch.pointer) return;
3397
+ onPointerCancel();
3398
+ const iconLine = area === "gutter" ? problemIconLine(event) : null;
3399
+ if (iconLine !== null) return showLineProblems(iconLine);
3400
+ const pos = posAtCoords({
3401
+ x: event.clientX,
3402
+ y: event.clientY
3403
+ });
3404
+ const main = mainRange(state.value.selection);
3405
+ const onCursor = area === "text" && focused.value && isEmptyRange(main) && main.head === pos && caretHandle.value;
3406
+ const wasOpen = menuOpen.value;
3407
+ const showsProblem = area === "text" && problemsAt(pos).length > 0 && !problemBox.value;
3408
+ touchUi.value = true;
3409
+ select(area === "gutter" ? "line" : "char", pos, false);
3410
+ caretHandle.value = area === "text";
3411
+ menuOpen.value = area === "gutter" || onCursor && !wasOpen && !showsProblem;
3412
+ if (area === "text" && !menuOpen.value) showInfo(pos, false);
3413
+ focusInput();
3414
+ }
3415
+ function onPointerCancel() {
3416
+ if (touch) {
3417
+ clearTimeout(touch.timer);
3418
+ touch.hold.release();
3419
+ }
3420
+ touch = null;
3421
+ }
3422
+ /** The part of the content in view, in its own px. */
3423
+ function visibleBox() {
3424
+ const top = scrollTop.value + (clip.value?.top ?? 0);
3425
+ const bottom = scrollTop.value + (clip.value?.bottom ?? viewHeight.value);
3426
+ const left = scrollLeft.value;
3427
+ return {
3428
+ top,
3429
+ bottom,
3430
+ left,
3431
+ right: left + Math.max(0, viewWidth.value - gutterWidth.value)
3432
+ };
3433
+ }
3434
+ /** Where a position is drawn in the content, when its line is in view. */
3435
+ function pointOf(pos) {
3436
+ const line = doc.value.lineAt(pos);
3437
+ if (!isShown(line.number)) return null;
3438
+ const at = place(line.number, lineText(line.number), pos - line.from);
3439
+ return {
3440
+ x: pad.x + at.x,
3441
+ top: at.top,
3442
+ sub: at.sub,
3443
+ n: line.number
3444
+ };
3445
+ }
3446
+ const handles = computed(() => {
3447
+ metrics.value;
3448
+ if (!touchUi.value || !focused.value || preview.value || props.disabled) return [];
3449
+ const main = mainRange(state.value.selection);
3450
+ const ends = isEmptyRange(main) ? caretHandle.value && !props.readonly ? [["caret", main.head]] : [] : [["start", rangeFrom(main)], ["end", rangeTo(main)]];
3451
+ const out = [];
3452
+ for (const [kind, pos] of ends) {
3453
+ const inside = pointOf(pos);
3454
+ const at = inside && floatingTarget.value ? toPage(inside) : inside;
3455
+ if (at) out.push({
3456
+ kind,
3457
+ left: Math.round(at.x),
3458
+ top: Math.round(at.top + lineHeight.value)
3459
+ });
3460
+ }
3461
+ return out;
3462
+ });
3463
+ /** A handle pressed but not moved yet: a press that stays put is a tap or a long press on the text below. */
3464
+ let handlePress = null;
3465
+ function onHandleDown(event, kind) {
3466
+ if (event.button !== 0) return;
3467
+ event.preventDefault();
3468
+ event.stopPropagation();
3469
+ onPointerCancel();
3470
+ endHandlePress();
3471
+ const hold = holdPointer(event, root.value, () => {
3472
+ clearHandlePress();
3473
+ endDrag();
3474
+ });
3475
+ hold.grab();
3476
+ handlePress = {
3477
+ kind,
3478
+ x: event.clientX,
3479
+ y: event.clientY,
3480
+ pointer: event.pointerId,
3481
+ hold,
3482
+ timer: kind === "caret" ? window.setTimeout(() => {
3483
+ if (!handlePress) return;
3484
+ const { x, y } = handlePress;
3485
+ const taken = handlePress.hold;
3486
+ clearHandlePress();
3487
+ const at = select("word", posAtCoords({
3488
+ x,
3489
+ y
3490
+ }), false);
3491
+ startDrag({
3492
+ clientX: x,
3493
+ clientY: y
3494
+ }, "word", at, taken, {});
3495
+ }, 450) : 0
3496
+ };
3497
+ window.addEventListener("pointermove", onHandleMove);
3498
+ window.addEventListener("pointerup", onHandleUp);
3499
+ window.addEventListener("pointercancel", endHandlePress);
3500
+ }
3501
+ function clearHandlePress() {
3502
+ if (handlePress) clearTimeout(handlePress.timer);
3503
+ handlePress = null;
3504
+ window.removeEventListener("pointermove", onHandleMove);
3505
+ window.removeEventListener("pointerup", onHandleUp);
3506
+ window.removeEventListener("pointercancel", endHandlePress);
3507
+ }
3508
+ function endHandlePress() {
3509
+ handlePress?.hold.release();
3510
+ clearHandlePress();
3511
+ }
3512
+ function onHandleMove(event) {
3513
+ const press = handlePress;
3514
+ if (!press || event.pointerId !== press.pointer) return;
3515
+ if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < 4) return;
3516
+ const { kind, hold, x, y } = press;
3517
+ clearHandlePress();
3518
+ const main = mainRange(state.value.selection);
3519
+ const pos = kind === "start" ? rangeFrom(main) : kind === "end" ? rangeTo(main) : main.head;
3520
+ const fixed = kind === "start" ? rangeTo(main) : kind === "end" ? rangeFrom(main) : pos;
3521
+ const at = coordsAtPos(pos);
3522
+ if (!at) return hold.release();
3523
+ if (kind !== "caret") dispatch(transaction().select(fixed, pos).setMeta({ scroll: false }));
3524
+ menuOpen.value = false;
3525
+ const offset = {
3526
+ x: x - at.left,
3527
+ y: y - (at.top + lineHeight.value / 2)
3528
+ };
3529
+ startDrag(event, "char", {
3530
+ from: fixed,
3531
+ to: fixed
3532
+ }, hold, {
3533
+ caret: kind === "caret",
3534
+ offset
3535
+ });
3536
+ onDragMove(event);
3537
+ }
3538
+ function onHandleUp(event) {
3539
+ const press = handlePress;
3540
+ if (!press || event.pointerId !== press.pointer) return;
3541
+ endHandlePress();
3542
+ if (press.kind !== "caret") return;
3543
+ const pos = posAtCoords({
3544
+ x: event.clientX,
3545
+ y: event.clientY
3546
+ });
3547
+ if (doc.value.lineAt(pos).number !== doc.value.lineAt(mainRange(state.value.selection).head).number) {
3548
+ select("char", pos, false);
3549
+ menuOpen.value = false;
3550
+ showInfo(pos, false);
3551
+ return focusInput();
3552
+ }
3553
+ menuOpen.value = !menuOpen.value;
3554
+ }
3555
+ /** Room between the toolbar or magnifier and what they point at. */
3556
+ const menuEl = ref();
3557
+ const menuSize = ref({
3558
+ width: 0,
3559
+ height: 0
3560
+ });
3561
+ const canPaste = typeof navigator !== "undefined" && !!navigator.clipboard?.readText;
3562
+ /** The toolbar's buttons for the selection now. */
3563
+ const menuItems = computed(() => {
3564
+ if (!menuOpen.value || !focused.value || props.disabled) return [];
3565
+ const m = messages.value;
3566
+ const main = mainRange(state.value.selection);
3567
+ const empty = isEmptyRange(main);
3568
+ const editable = !target.readonly;
3569
+ const items = [];
3570
+ if (!empty && editable) items.push({
3571
+ key: "cut",
3572
+ label: m.cut,
3573
+ run: () => copySelection(true)
3574
+ });
3575
+ if (!empty) items.push({
3576
+ key: "copy",
3577
+ label: m.copy,
3578
+ run: () => copySelection(false)
3579
+ });
3580
+ if (editable && canPaste) items.push({
3581
+ key: "paste",
3582
+ label: m.paste,
3583
+ run: pasteFromClipboard
3584
+ });
3585
+ if (rangeFrom(main) > 0 || rangeTo(main) < doc.value.length) items.push({
3586
+ key: "all",
3587
+ label: m.selectAll,
3588
+ run: () => {
3589
+ run(selectAll);
3590
+ menuOpen.value = true;
3591
+ }
3592
+ });
3593
+ for (const extension of extensions.value) {
3594
+ if (!extension.menu) continue;
3595
+ extension.menu(context).forEach((item, i) => items.push({
3596
+ key: `${extension.name}/${i}`,
3597
+ label: item.label,
3598
+ run: () => {
3599
+ menuOpen.value = false;
3600
+ item.run(context);
3601
+ }
3602
+ }));
3603
+ }
3604
+ return items;
3605
+ });
3606
+ const menuStyle = computed(() => {
3607
+ if (!menuItems.value.length) return null;
3608
+ const main = mainRange(state.value.selection);
3609
+ let start = pointOf(rangeFrom(main));
3610
+ let end = pointOf(rangeTo(main));
3611
+ let view = visibleBox();
3612
+ let frame = view;
3613
+ if (floatingTarget.value) {
3614
+ start = start && toPage(start) && {
3615
+ ...start,
3616
+ ...toPage(start)
3617
+ };
3618
+ end = end && toPage(end) && {
3619
+ ...end,
3620
+ ...toPage(end)
3621
+ };
3622
+ view = pageBox();
3623
+ frame = frameInPage();
3624
+ }
3625
+ if (!start && !end) return null;
3626
+ const { width, height } = menuSize.value;
3627
+ const lh = lineHeight.value;
3628
+ const x = start && end && start.top === end.top ? (start.x + end.x) / 2 : (frame.left + frame.right) / 2;
3629
+ const above = start ? start.top - GAP - height : -Infinity;
3630
+ const below = (end ?? start).top + lh + HANDLE + GAP;
3631
+ let top = above >= view.top + GAP ? above : below;
3632
+ top = Math.max(view.top + GAP, Math.min(top, view.bottom - height - GAP));
3633
+ const left = Math.max(view.left + GAP, Math.min(x - width / 2, view.right - width - GAP));
3634
+ return { transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)` };
3635
+ });
3636
+ watch([menuEl, menuItems], () => {
3637
+ const el = menuEl.value;
3638
+ if (el) menuSize.value = {
3639
+ width: el.offsetWidth,
3640
+ height: el.offsetHeight
3641
+ };
3642
+ }, { flush: "post" });
3643
+ /** Copies through the textarea, which hands the selection to the copy event. */
3644
+ function copyFromInput() {
3645
+ focusInput();
3646
+ document.execCommand("copy");
3647
+ }
3648
+ function writeClipboard(text) {
3649
+ const fallback = copyFromInput;
3650
+ if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).catch(fallback);
3651
+ else fallback();
3652
+ }
3653
+ function copySelection(cut) {
3654
+ const text = selectedText();
3655
+ if (!text) return;
3656
+ writeClipboard(text);
3657
+ if (cut && !target.readonly) dispatch(transaction().replaceSelection("").setMeta({ action: "cut" }));
3658
+ menuOpen.value = false;
3659
+ }
3660
+ function pasteFromClipboard() {
3661
+ menuOpen.value = false;
3662
+ navigator.clipboard.readText().then((text) => pasteText(text)).catch(() => {});
3663
+ }
3664
+ /** The editor's variables the boxes use, carried to them when they are drawn above the page. */
3665
+ const FRAME_VARS = [
3666
+ "--dou-code-editor-font-size",
3667
+ "--dou-code-editor-line-height",
3668
+ "--dou-code-editor-bg",
3669
+ "--dou-code-editor-error",
3670
+ "--dou-code-editor-warning",
3671
+ "--dou-code-editor-info",
3672
+ "--dou-code-editor-selection"
3673
+ ];
3674
+ const frameVars = shallowRef({});
3675
+ /** The editor's font, for the magnifier when it is drawn above the page. */
3676
+ const frameFont = shallowRef({});
3677
+ function readFrameFont() {
3678
+ const el = root.value;
3679
+ if (!el) return;
3680
+ const style = getComputedStyle(el);
3681
+ const vars = {};
3682
+ for (const name of FRAME_VARS) {
3683
+ const value = style.getPropertyValue(name).trim();
3684
+ if (value) vars[name] = value;
3685
+ }
3686
+ frameVars.value = vars;
3687
+ frameFont.value = {
3688
+ fontFamily: style.fontFamily,
3689
+ fontSize: style.fontSize,
3690
+ "--dou-code-editor-line-height": `${lineHeight.value}px`,
3691
+ "--dou-code-editor-tab-size": String(props.tabSize)
3692
+ };
3693
+ }
3694
+ /** The magnifier over a finger dragging the selection: the row at the moving end, larger. */
3695
+ const MAGNIFIER = {
3696
+ width: 128,
3697
+ scale: 1.5
3698
+ };
3699
+ const magnifier = computed(() => {
3700
+ if (!touchDrag.value) return null;
3701
+ metrics.value;
3702
+ const head = mainRange(state.value.selection).head;
3703
+ const inside = pointOf(head);
3704
+ if (!inside) return null;
3705
+ const row = rows.value.find((r) => r.n === inside.n);
3706
+ if (!row) return null;
3707
+ const outside = !!floatingTarget.value;
3708
+ const page = outside ? toPage(inside) : inside;
3709
+ if (!page) return null;
3710
+ const at = {
3711
+ ...inside,
3712
+ x: page.x,
3713
+ top: page.top
3714
+ };
3715
+ const lh = lineHeight.value;
3716
+ const height = Math.round(lh * MAGNIFIER.scale) + 8;
3717
+ const view = outside ? pageBox() : visibleBox();
3718
+ const { width } = MAGNIFIER;
3719
+ const above = at.top - GAP - height;
3720
+ const top = above >= view.top + 4 ? above : at.top + lh + HANDLE + GAP;
3721
+ const left = Math.max(view.left + 4, Math.min(at.x - width / 2, view.right - width - 4));
3722
+ const parts = row.wrapped.breaks.length ? rowParts(row, at.sub) : row.tokens || row.marks || row.inlines ? partsOf(row) : [[row.text, null]];
3723
+ const x = inside.x - pad.x;
3724
+ const caret = Math.max(4, Math.min(width - 4, at.x - left));
3725
+ return {
3726
+ parts,
3727
+ inlines: row.inlines ?? [],
3728
+ indent: at.sub ? row.wrapped.indent : 0,
3729
+ style: {
3730
+ transform: `translate(${Math.round(left)}px, ${Math.round(top)}px)`,
3731
+ height: `${height}px`,
3732
+ ...outside ? frameFont.value : null
3733
+ },
3734
+ textStyle: { transform: `translateX(${caret - x * MAGNIFIER.scale}px) scale(${MAGNIFIER.scale})` },
3735
+ caret
3736
+ };
3737
+ });
3738
+ const showKeys = computed(() => !!props.keys && coarse.value && focused.value && !props.readonly && !props.disabled);
3739
+ const keysList = computed(() => Array.isArray(props.keys) ? props.keys : void 0);
3740
+ const keysEditor = { run };
3741
+ const { next: nextZIndex } = useZIndex();
3742
+ const keysZIndex = ref();
3743
+ watch(showKeys, (shown) => {
3744
+ if (shown) keysZIndex.value = nextZIndex();
3745
+ });
3746
+ /**
3747
+ * The bar of keys floats over the keyboard, a gap apart, the way the
3748
+ * phone's own bars do: its height, the gap, and the room it takes from the
3749
+ * view, which the cursor keeps clear of.
3750
+ */
3751
+ const KEYS_SPACE = 60;
3752
+ const viewport = ref({
3753
+ top: 0,
3754
+ left: 0,
3755
+ width: 0,
3756
+ height: 0
3757
+ });
3758
+ function readViewport() {
3759
+ const vv = window.visualViewport;
3760
+ viewport.value = vv ? {
3761
+ top: vv.offsetTop,
3762
+ left: vv.offsetLeft,
3763
+ width: vv.width,
3764
+ height: vv.height
3765
+ } : {
3766
+ top: 0,
3767
+ left: 0,
3768
+ width: window.innerWidth,
3769
+ height: window.innerHeight
3770
+ };
3771
+ }
3772
+ const keysStyle = computed(() => {
3773
+ const { top, left, width, height } = viewport.value;
3774
+ return {
3775
+ transform: `translate(${left}px, ${top + height - KEYS_HEIGHT - KEYS_GAP}px)`,
3776
+ width: `${width}px`,
3777
+ zIndex: keysZIndex.value
3778
+ };
3779
+ });
3780
+ /**
3781
+ * Keeps the main cursor clear of the phone's keyboard and the bar above it:
3782
+ * scrolls the editor when the cursor can move inside it, else the page.
3783
+ */
3784
+ function followViewport() {
3785
+ const vv = window.visualViewport;
3786
+ const el = scroller.value;
3787
+ if (!vv || !el || !focused.value) return;
3788
+ const at = coordsAtPos(mainRange(state.value.selection).head);
3789
+ if (!at) return;
3790
+ const lh = lineHeight.value;
3791
+ const room = lh / 2 + (handles.value.length ? HANDLE : 0);
3792
+ const rect = el.getBoundingClientRect();
3793
+ const visibleTop = Math.max(rect.top, vv.offsetTop);
3794
+ const visibleBottom = Math.min(rect.bottom, vv.offsetTop + vv.height - (showKeys.value ? KEYS_SPACE : 0));
3795
+ if (at.bottom + room > visibleBottom && visibleBottom - visibleTop >= lh * 3) {
3796
+ el.scrollTop += (at.bottom + room - visibleBottom) / ratio.value;
3797
+ onScroll();
3798
+ } else if (at.top - lh / 2 < visibleTop && visibleBottom - visibleTop >= lh * 3) {
3799
+ el.scrollTop -= (visibleTop - at.top + lh / 2) / ratio.value;
3800
+ onScroll();
3801
+ }
3802
+ const after = coordsAtPos(mainRange(state.value.selection).head);
3803
+ if (!after) return;
3804
+ const bottom = vv.offsetTop + vv.height - (showKeys.value ? KEYS_SPACE : 0);
3805
+ if (after.bottom + room > bottom) {
3806
+ ownScrollUntil = performance.now() + 200;
3807
+ window.scrollBy(0, after.bottom + room - bottom);
3808
+ }
3809
+ }
3810
+ /** How much of the window the keyboard took when last seen. */
3811
+ let keyboardHeight = 0;
3812
+ function readKeyboard() {
3813
+ const vv = window.visualViewport;
3814
+ return vv ? Math.max(0, window.innerHeight - vv.height * vv.scale) : 0;
3815
+ }
3816
+ /**
3817
+ * Follows the keyboard as it comes up or grows (a row of candidates, another
3818
+ * layout), and only then: the view also resizes while the page scrolls, as
3819
+ * the browser's own bars shrink and grow, and scrolling the page back to the
3820
+ * cursor then would fight the finger.
3821
+ */
3822
+ function onViewportChange() {
3823
+ readViewport();
3824
+ const now = readKeyboard();
3825
+ const grew = now > keyboardHeight + 1;
3826
+ keyboardHeight = now;
3827
+ if (grew && !fingerScrolling) followViewport();
3828
+ }
3829
+ /**
3830
+ * While the page scrolls, the bar of keys fades out: the browser moves the
3831
+ * page faster than the bar can follow the keyboard, and it would shake.
3832
+ */
3833
+ const pageScrolling = ref(false);
3834
+ /**
3835
+ * A finger scrolls the page, by dragging or by the glide after it: the view
3836
+ * resizing meanwhile is the browser's bars, never a reason to scroll back.
3837
+ * The browser scrolling to the cursor on its own, as a tap brings the
3838
+ * keyboard up, has no finger moving and leaves the editor free to follow.
3839
+ */
3840
+ let fingerScrolling = false;
3841
+ let pageScrollTimer = 0;
3842
+ /** Until when a page scroll is the editor's own, keeping the cursor in view, which leaves the bar be. */
3843
+ let ownScrollUntil = 0;
3844
+ function settleLater() {
3845
+ clearTimeout(pageScrollTimer);
3846
+ pageScrollTimer = window.setTimeout(() => {
3847
+ readViewport();
3848
+ pageScrolling.value = false;
3849
+ fingerScrolling = false;
3850
+ }, 160);
3851
+ }
3852
+ function onPageScroll() {
3853
+ if (performance.now() < ownScrollUntil) return;
3854
+ pageScrolling.value = true;
3855
+ settleLater();
3856
+ }
3857
+ function onFingerMove() {
3858
+ fingerScrolling = true;
3859
+ settleLater();
3860
+ }
3861
+ /** On a touch screen the keyboard comes and goes with focus; the view follows it meanwhile. */
3862
+ const following = computed(() => coarse.value && focused.value);
3863
+ function unfollow() {
3864
+ if (typeof window === "undefined") return;
3865
+ const vv = window.visualViewport;
3866
+ vv?.removeEventListener("resize", onViewportChange);
3867
+ vv?.removeEventListener("scroll", readViewport);
3868
+ vv?.removeEventListener("scroll", onPageScroll);
3869
+ window.removeEventListener("scroll", onPageScroll);
3870
+ window.removeEventListener("touchmove", onFingerMove);
3871
+ clearTimeout(pageScrollTimer);
3872
+ pageScrolling.value = false;
3873
+ fingerScrolling = false;
3874
+ }
3875
+ watch(following, (on) => {
3876
+ const vv = window.visualViewport;
3877
+ if (on) {
3878
+ readViewport();
3879
+ keyboardHeight = readKeyboard();
3880
+ vv?.addEventListener("resize", onViewportChange);
3881
+ vv?.addEventListener("scroll", readViewport);
3882
+ vv?.addEventListener("scroll", onPageScroll, { passive: true });
3883
+ window.addEventListener("scroll", onPageScroll, { passive: true });
3884
+ window.addEventListener("touchmove", onFingerMove, { passive: true });
3885
+ } else unfollow();
3886
+ });
3887
+ /** Height of a row in the minimap, and width of a character, in px. */
3888
+ const minimapCanvas = ref();
3889
+ /** The editor's own width, minimap included. */
3890
+ const rootWidth = ref(0);
3891
+ const minimapOn = computed(() => !!props.minimap && mounted.value && rootWidth.value >= 480);
3892
+ /** Where the minimap is: the row at its top (fractional), and the part in view as a box. */
3893
+ const minimap = computed(() => {
3894
+ if (!minimapOn.value) return null;
3895
+ const track = viewHeight.value;
3896
+ const lh = lineHeight.value || 1;
3897
+ const height = layout.value.total * MINI_ROW;
3898
+ const textTop = scrollTop.value * ratio.value;
3899
+ const first = rowAtTextY(Math.max(0, textTop - pad.y));
3900
+ const last = rowAtTextY(Math.max(0, textTop + track - pad.y));
3901
+ const range = Math.max(1, total.value + pad.y * 2 - track);
3902
+ const progress = Math.min(1, Math.max(0, textTop / range));
3903
+ const top = height > track ? progress * (height - track) : 0;
3904
+ const firstFraction = first + ((textTop - pad.y - rowTop(first)) / lh || 0);
3905
+ return {
3906
+ top,
3907
+ track,
3908
+ height,
3909
+ slider: {
3910
+ top: Math.max(0, firstFraction) * MINI_ROW - top,
3911
+ height: Math.max(8, (last - first + 1) * MINI_ROW)
3912
+ }
3913
+ };
3914
+ });
3915
+ /** Whether a character is drawn two cells wide: CJK, Hangul, full-width forms. */
3916
+ const isWideCode = (code) => code >= 4352 && code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65103 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510;
3917
+ /** The token colors, read from the theme when it changes. */
3918
+ let miniColors = null;
3919
+ function minimapColors(canvas) {
3920
+ const style = getComputedStyle(canvas);
3921
+ const key = `${style.color}|${style.getPropertyValue("--dou-color-syntax-keyword")}`;
3922
+ if (miniColors?.key === key) return miniColors;
3923
+ const swatch = document.createElement("span");
3924
+ swatch.style.display = "none";
3925
+ canvas.parentElement.append(swatch);
3926
+ const types = tokenTypes.map((type) => {
3927
+ swatch.style.color = `var(--dou-color-syntax-${type}, currentColor)`;
3928
+ return getComputedStyle(swatch).color;
3929
+ });
3930
+ swatch.remove();
3931
+ miniColors = {
3932
+ key,
3933
+ text: style.color,
3934
+ types
3935
+ };
3936
+ return miniColors;
3937
+ }
3938
+ let miniFrame = 0;
3939
+ function drawMinimap() {
3940
+ miniFrame = 0;
3941
+ const canvas = minimapCanvas.value;
3942
+ const map = minimap.value;
3943
+ if (!canvas || !map) return;
3944
+ const dpr = window.devicePixelRatio || 1;
3945
+ const width = MINI_WIDTH;
3946
+ const height = map.track;
3947
+ if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {
3948
+ canvas.width = Math.round(width * dpr);
3949
+ canvas.height = Math.round(height * dpr);
3950
+ }
3951
+ const ctx = canvas.getContext("2d");
3952
+ if (!ctx) return;
3953
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
3954
+ ctx.clearRect(0, 0, width, height);
3955
+ const colors = minimapColors(canvas);
3956
+ const text = doc.value;
3957
+ const lay = layout.value;
3958
+ const hl = highlighter;
3959
+ const cols = Math.floor(84 / MINI_CELL);
3960
+ const tab = props.tabSize;
3961
+ const firstRow = Math.max(0, Math.floor(map.top / MINI_ROW));
3962
+ const lastRow = Math.min(lay.total - 1, Math.ceil((map.top + height) / MINI_ROW));
3963
+ const mark = MINI_ROW * .75;
3964
+ ctx.globalAlpha = .7;
3965
+ let row = firstRow;
3966
+ while (row <= lastRow) {
3967
+ const { n, sub } = lay.lineAtRow(row);
3968
+ const rowText = text.lineText(n);
3969
+ const breaks = wrapRows ? wrapOf(rowText).breaks : [];
3970
+ const tokens = hl && (hl.ready(n) || n - hl.frontier <= SYNTAX_REACH) ? hl.line(n) : null;
3971
+ const rowsHere = lay.rowsOf(n);
3972
+ for (let k = sub; k < rowsHere && row <= lastRow; k++, row++) {
3973
+ const start = k ? breaks[k - 1] : 0;
3974
+ const end = k < breaks.length ? breaks[k] : rowText.length;
3975
+ const y = row * MINI_ROW - map.top;
3976
+ let col = 0;
3977
+ let runFrom = -1;
3978
+ let runColor = "";
3979
+ let t = 0;
3980
+ const flush = () => {
3981
+ if (runFrom < 0) return;
3982
+ ctx.fillStyle = runColor;
3983
+ ctx.fillRect(MINI_PAD + runFrom * MINI_CELL, y, (col - runFrom) * MINI_CELL, mark);
3984
+ runFrom = -1;
3985
+ };
3986
+ for (let i = start; i < end && col < cols; i++) {
3987
+ const code = rowText.charCodeAt(i);
3988
+ if (code === 32 || code === 9) {
3989
+ flush();
3990
+ col += code === 9 ? tab - col % tab : 1;
3991
+ continue;
3992
+ }
3993
+ let color = colors.text;
3994
+ if (tokens) {
3995
+ while (t < tokens.length && tokens[t] <= i) t += 2;
3996
+ const type = t < tokens.length ? tokens[t + 1] : -1;
3997
+ if (type >= 0) color = colors.types[type];
3998
+ }
3999
+ if (runFrom >= 0 && color !== runColor) flush();
4000
+ if (runFrom < 0) {
4001
+ runFrom = col;
4002
+ runColor = color;
4003
+ }
4004
+ col += code >= 4352 && isWideCode(code) ? 2 : 1;
4005
+ }
4006
+ flush();
4007
+ }
4008
+ }
4009
+ }
4010
+ function scheduleMinimap() {
4011
+ if (!miniFrame && minimapOn.value) miniFrame = requestAnimationFrame(drawMinimap);
4012
+ }
4013
+ watch([
4014
+ minimap,
4015
+ doc,
4016
+ layout,
4017
+ syntaxTick,
4018
+ () => props.tabSize
4019
+ ], () => scheduleMinimap(), { flush: "post" });
4020
+ let themeWatch = null;
4021
+ watch(minimapOn, (on) => {
4022
+ themeWatch?.();
4023
+ themeWatch = null;
4024
+ if (!on || typeof MutationObserver === "undefined") return;
4025
+ const observer = new MutationObserver(scheduleMinimap);
4026
+ observer.observe(document.documentElement, {
4027
+ attributes: true,
4028
+ attributeFilter: [
4029
+ "class",
4030
+ "style",
4031
+ "data-dou-theme"
4032
+ ]
4033
+ });
4034
+ const dark = matchMedia?.("(prefers-color-scheme: dark)");
4035
+ dark?.addEventListener?.("change", scheduleMinimap);
4036
+ themeWatch = () => {
4037
+ observer.disconnect();
4038
+ dark?.removeEventListener?.("change", scheduleMinimap);
4039
+ };
4040
+ });
4041
+ onBeforeUnmount(() => {
4042
+ if (miniFrame) cancelAnimationFrame(miniFrame);
4043
+ themeWatch?.();
4044
+ });
4045
+ /** Scrolls so that minimap row `row` is in the middle of the view. */
4046
+ function scrollToMiniRow(row) {
4047
+ const el = scroller.value;
4048
+ if (!el) return;
4049
+ const lay = layout.value;
4050
+ const at = Math.max(0, Math.min(lay.total - 1, Math.floor(row)));
4051
+ const y = pad.y + rowTop(at) - el.clientHeight / 2;
4052
+ el.scrollTop = Math.max(0, y / ratio.value);
4053
+ onScroll();
4054
+ }
4055
+ let miniDrag = null;
4056
+ function onMinimapDown(event) {
4057
+ const map = minimap.value;
4058
+ const canvas = event.currentTarget;
4059
+ if (!map || event.button !== 0) return;
4060
+ event.preventDefault();
4061
+ const box = canvas.getBoundingClientRect();
4062
+ const y = event.clientY - box.top;
4063
+ if (y < map.slider.top || y > map.slider.top + map.slider.height) scrollToMiniRow((map.top + y) / MINI_ROW);
4064
+ miniDrag = {
4065
+ y: event.clientY,
4066
+ scroll: scroller.value?.scrollTop ?? 0,
4067
+ pointer: event.pointerId
4068
+ };
4069
+ canvas.setPointerCapture?.(event.pointerId);
4070
+ }
4071
+ function onMinimapMove(event) {
4072
+ const map = minimap.value;
4073
+ const el = scroller.value;
4074
+ if (!miniDrag || !map || !el || event.pointerId !== miniDrag.pointer) return;
4075
+ const dy = event.clientY - miniDrag.y;
4076
+ const max = el.scrollHeight - el.clientHeight;
4077
+ const room = map.height > map.track ? map.track - map.slider.height : map.height - map.slider.height;
4078
+ el.scrollTop = Math.max(0, Math.min(max, miniDrag.scroll + dy * max / Math.max(1, room)));
4079
+ onScroll();
4080
+ }
4081
+ function onMinimapUp(event) {
4082
+ if (miniDrag?.pointer === event.pointerId) miniDrag = null;
4083
+ }
4084
+ function onScroll() {
4085
+ const el = scroller.value;
4086
+ if (!el) return;
4087
+ const { top, left } = scrollPositionOf(el);
4088
+ scrollTop.value = top;
4089
+ scrollLeft.value = left;
4090
+ updateClip();
4091
+ }
4092
+ /** Keeps a position in view, with a line of room around it. */
4093
+ function scrollIntoView(pos = mainRange(state.value.selection).head) {
4094
+ const el = scroller.value;
4095
+ if (!el) return;
4096
+ const line = doc.value.lineAt(pos);
4097
+ const lh = lineHeight.value;
4098
+ const view = el.clientHeight;
4099
+ if (view < lh * 3) return;
4100
+ const at = place(line.number, line.text, pos - line.from);
4101
+ const y = at.top - shift.value;
4102
+ const top = el.scrollTop * ratio.value;
4103
+ const margin = Math.min(lh, view / 4);
4104
+ if (y - margin < top) el.scrollTop = Math.max(0, (y - margin) / ratio.value);
4105
+ else if (y + lh + margin > top + view) el.scrollTop = (y + lh + margin - view) / ratio.value;
4106
+ const x = pad.x + at.x;
4107
+ const width = el.clientWidth - gutterWidth.value;
4108
+ if (x - measure.cell * 2 < el.scrollLeft) el.scrollLeft = Math.max(0, x - measure.cell * 4);
4109
+ else if (x + measure.cell * 2 > el.scrollLeft + width) el.scrollLeft = x + measure.cell * 4 - width;
4110
+ onScroll();
4111
+ }
4112
+ let clipFrame = 0;
4113
+ /** For an editor taller than the window, draws only the lines inside the window. */
4114
+ function updateClip() {
4115
+ const el = scroller.value;
4116
+ if (!el) return;
4117
+ if (el.clientHeight <= window.innerHeight) {
4118
+ if (clip.value) clip.value = null;
4119
+ return;
4120
+ }
4121
+ const rect = el.getBoundingClientRect();
4122
+ const top = Math.max(0, -rect.top);
4123
+ const bottom = Math.max(top, Math.min(el.clientHeight, window.innerHeight - rect.top));
4124
+ if (clip.value?.top !== top || clip.value?.bottom !== bottom) clip.value = {
4125
+ top,
4126
+ bottom
4127
+ };
4128
+ }
4129
+ function onWindowScroll(event) {
4130
+ if (event.target === scroller.value || clipFrame) return;
4131
+ clipFrame = requestAnimationFrame(() => {
4132
+ clipFrame = 0;
4133
+ updateClip();
4134
+ });
4135
+ }
4136
+ let resize;
4137
+ function refreshMetrics() {
4138
+ measure.refresh(props.tabSize);
4139
+ pad.y = measure.padY;
4140
+ pad.x = measure.padX;
4141
+ readFrameFont();
4142
+ metrics.value++;
4143
+ syncInput();
4144
+ }
4145
+ watch(() => props.tabSize, () => refreshMetrics());
4146
+ onMounted(() => {
4147
+ refreshMetrics();
4148
+ const el = scroller.value;
4149
+ viewHeight.value = el.clientHeight;
4150
+ viewWidth.value = el.clientWidth;
4151
+ rootWidth.value = root.value?.clientWidth ?? 0;
4152
+ if (typeof ResizeObserver !== "undefined") {
4153
+ resize = new ResizeObserver(() => {
4154
+ viewHeight.value = el.clientHeight;
4155
+ viewWidth.value = el.clientWidth;
4156
+ rootWidth.value = root.value?.clientWidth ?? 0;
4157
+ updateClip();
4158
+ });
4159
+ resize.observe(el);
4160
+ if (root.value) resize.observe(root.value);
4161
+ }
4162
+ updateClip();
4163
+ mounted.value = true;
4164
+ window.addEventListener("scroll", onWindowScroll, {
4165
+ capture: true,
4166
+ passive: true
4167
+ });
4168
+ window.addEventListener("resize", onWindowScroll, { passive: true });
4169
+ document.addEventListener("selectionchange", onSelectionChange);
4170
+ document.fonts?.ready.then(() => root.value && refreshMetrics());
4171
+ document.fonts?.addEventListener?.("loadingdone", refreshMetrics);
4172
+ if (props.autofocus) focusInput();
4173
+ for (const extension of extensions.value) startExtension(extension);
4174
+ runLint();
4175
+ });
4176
+ /** What each extension's `setup` returned, to run when it goes. */
4177
+ const cleanups = /* @__PURE__ */ new Map();
4178
+ function startExtension(extension) {
4179
+ if (cleanups.has(extension)) return;
4180
+ const cleanup = extension.setup?.(context);
4181
+ cleanups.set(extension, typeof cleanup === "function" ? cleanup : () => {});
4182
+ }
4183
+ let restarts = [];
4184
+ let restartWarned = false;
4185
+ /** An extension made in the template is new on every render, and set up again each time. */
4186
+ function warnRestarts() {
4187
+ if (process.env.NODE_ENV === "production" || restartWarned) return;
4188
+ const now = Date.now();
4189
+ restarts = [...restarts.filter((time) => now - time < 1e3), now];
4190
+ if (restarts.length < 4) return;
4191
+ restartWarned = true;
4192
+ console.warn("[@dou-ui/code] the extensions keep being set up again, which also starts their state over (such as a shared undo history). Create them once in <script setup> instead of in the template.");
4193
+ }
4194
+ watch(extensions, (next) => {
4195
+ if (!mounted.value) return;
4196
+ let restarted = false;
4197
+ for (const [extension, cleanup] of cleanups) if (!next.includes(extension)) {
4198
+ cleanup();
4199
+ cleanups.delete(extension);
4200
+ restarted = true;
4201
+ }
4202
+ for (const extension of next) startExtension(extension);
4203
+ if (restarted) warnRestarts();
4204
+ });
4205
+ onBeforeUnmount(() => {
4206
+ if (syntaxJob) cancelIdle(syntaxJob);
4207
+ clearTimeout(searchTimer);
4208
+ resize?.disconnect();
4209
+ widgetObserver?.disconnect();
4210
+ inlineObserver?.disconnect();
4211
+ endDrag();
4212
+ onPointerCancel();
4213
+ endHandlePress();
4214
+ unfollow();
4215
+ clearTimeout(lintTimer);
4216
+ clearTimeout(problemTimer);
4217
+ for (const cleanup of cleanups.values()) cleanup();
4218
+ cleanups.clear();
4219
+ cancelAnimationFrame(clipFrame);
4220
+ window.removeEventListener("scroll", onWindowScroll, { capture: true });
4221
+ window.removeEventListener("resize", onWindowScroll);
4222
+ document.removeEventListener("selectionchange", onSelectionChange);
4223
+ document.fonts?.removeEventListener?.("loadingdone", refreshMetrics);
4224
+ });
4225
+ function onFocus(event) {
4226
+ focused.value = true;
4227
+ syncInput();
4228
+ emit("focus", event);
4229
+ }
4230
+ function onBlur(event) {
4231
+ onPointerCancel();
4232
+ endHandlePress();
4233
+ endDrag();
4234
+ focused.value = false;
4235
+ menuOpen.value = false;
4236
+ if (problemBox.value?.keyboard || touchUi.value) closeProblems();
4237
+ closeCompletion();
4238
+ closeSignature();
4239
+ closeHistory();
4240
+ if (lazyDirty) {
4241
+ lazyDirty = false;
4242
+ emit("update:modelValue", textOf(doc.value));
4243
+ }
4244
+ emit("blur", event);
4245
+ }
4246
+ const api = {
4247
+ get state() {
4248
+ return state.value;
4249
+ },
4250
+ get doc() {
4251
+ return state.value.doc;
4252
+ },
4253
+ get selection() {
4254
+ return state.value.selection;
4255
+ },
4256
+ transact,
4257
+ run,
4258
+ undo,
4259
+ redo,
4260
+ get canUndo() {
4261
+ if (historyHandler.value) return historyHandler.value.canUndo();
4262
+ historyTick.value;
4263
+ return history.canUndo;
4264
+ },
4265
+ get canRedo() {
4266
+ if (historyHandler.value) return historyHandler.value.canRedo();
4267
+ historyTick.value;
4268
+ return history.canRedo;
4269
+ },
4270
+ select(anchor, head) {
4271
+ const selection = typeof anchor === "number" ? selectionOf(anchor, head) : anchor;
4272
+ dispatch(transaction().select(normalizeSelection(selection, doc.value.length)).setMeta({ scroll: true }));
4273
+ },
4274
+ scrollIntoView,
4275
+ coordsAtPos,
4276
+ posAtCoords,
4277
+ focus: focusInput,
4278
+ blur: () => input.value?.blur(),
4279
+ openSearch: (given) => openSearch(false, given),
4280
+ closeSearch,
4281
+ fold: (line) => folding.fold(line),
4282
+ unfold: (line) => folding.unfold(line),
4283
+ foldAll: () => folding.foldAll(),
4284
+ unfoldAll: () => folding.unfoldAll(),
4285
+ get folds() {
4286
+ return foldStarts.value;
4287
+ },
4288
+ get diagnostics() {
4289
+ return diagnostics.value;
4290
+ },
4291
+ get visible() {
4292
+ return {
4293
+ from: visibleFrom.value,
4294
+ to: visibleTo.value
4295
+ };
4296
+ },
4297
+ get focused() {
4298
+ return focused.value;
4299
+ },
4300
+ get messages() {
4301
+ return messages.value;
4302
+ },
4303
+ announce,
4304
+ relint: (name) => {
4305
+ if (mounted.value) runLint(name);
4306
+ }
4307
+ };
4308
+ context = api;
4309
+ provide(CODE_EDITOR_KEY, api);
4310
+ __expose(api);
4311
+ return (_ctx, _cache) => {
4312
+ return openBlock(), createElementBlock("div", {
4313
+ ref_key: "root",
4314
+ ref: root,
4315
+ class: normalizeClass([
4316
+ unref(ns).b(),
4317
+ unref(ns).is("focused", focused.value),
4318
+ unref(ns).is("readonly", !!__props.readonly),
4319
+ unref(ns).is("disabled", !!__props.disabled),
4320
+ unref(ns).is("foldable", __props.foldable),
4321
+ unref(ns).is("wrap", __props.wrap)
4322
+ ]),
4323
+ style: normalizeStyle({
4324
+ "--dou-code-editor-gutter": `${gutterWidth.value}px`,
4325
+ "--dou-code-editor-gutter-cells": `${gutterCells.value}px`,
4326
+ "--dou-code-editor-tab-size": __props.tabSize
4327
+ })
4328
+ }, [
4329
+ searchOpen.value ? (openBlock(), createElementBlock("div", {
4330
+ key: 0,
4331
+ class: normalizeClass(unref(ns).e("search"))
4332
+ }, [createVNode(unref(DouFindReplace), {
4333
+ ref_key: "panel",
4334
+ ref: panel,
4335
+ search: query.value.search,
4336
+ replace: query.value.replace ?? "",
4337
+ replacing: showReplace.value,
4338
+ "onUpdate:replacing": _cache[0] || (_cache[0] = ($event) => showReplace.value = $event),
4339
+ count: matches.value.length,
4340
+ current: currentMatch.value,
4341
+ capped: capped.value,
4342
+ error: searchError.value && unref(common)("findReplace.invalidRegexp"),
4343
+ readonly: __props.readonly || __props.disabled,
4344
+ "onUpdate:search": _cache[1] || (_cache[1] = ($event) => query.value = {
4345
+ ...query.value,
4346
+ search: $event
4347
+ }),
4348
+ "onUpdate:replace": _cache[2] || (_cache[2] = ($event) => query.value = {
4349
+ ...query.value,
4350
+ replace: $event
4351
+ }),
4352
+ onNext: _cache[3] || (_cache[3] = ($event) => nextMatch()),
4353
+ onPrevious: _cache[4] || (_cache[4] = ($event) => previousMatch()),
4354
+ onReplaceOne: replaceOne,
4355
+ onReplaceAll: replaceAll,
4356
+ onClose: closeSearch
4357
+ }, {
4358
+ options: withCtx(() => [(openBlock(), createElementBlock(Fragment, null, renderList(searchOptions, (option) => {
4359
+ return createVNode(unref(DouTooltip), {
4360
+ key: option.key,
4361
+ content: unref(common)(`findReplace.${option.key}`)
4362
+ }, {
4363
+ default: withCtx(() => [createVNode(unref(DouToggle), {
4364
+ pressed: !!query.value[option.key],
4365
+ size: "sm",
4366
+ "aria-label": unref(common)(`findReplace.${option.key}`),
4367
+ "onUpdate:pressed": ($event) => query.value = {
4368
+ ...query.value,
4369
+ [option.key]: $event
4370
+ }
4371
+ }, {
4372
+ default: withCtx(() => [(openBlock(), createBlock(resolveDynamicComponent(option.icon)))]),
4373
+ _: 2
4374
+ }, 1032, [
4375
+ "pressed",
4376
+ "aria-label",
4377
+ "onUpdate:pressed"
4378
+ ])]),
4379
+ _: 2
4380
+ }, 1032, ["content"]);
4381
+ }), 64))]),
4382
+ _: 1
4383
+ }, 8, [
4384
+ "search",
4385
+ "replace",
4386
+ "replacing",
4387
+ "count",
4388
+ "current",
4389
+ "capped",
4390
+ "error",
4391
+ "readonly"
4392
+ ])], 2)) : createCommentVNode("", true),
4393
+ problemMarks.value.length ? (openBlock(), createElementBlock("div", {
4394
+ key: 1,
4395
+ class: normalizeClass(unref(ns).e("marks")),
4396
+ "aria-hidden": "true"
4397
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(problemMarks.value, (mark) => {
4398
+ return openBlock(), createElementBlock("div", {
4399
+ key: `${mark.top}${mark.severity}`,
4400
+ class: normalizeClass([
4401
+ unref(ns).e("mark"),
4402
+ unref(ns).e("problem-mark"),
4403
+ unref(ns).is(mark.severity, true)
4404
+ ]),
4405
+ style: normalizeStyle({ top: `${mark.top}%` })
4406
+ }, null, 6);
4407
+ }), 128))], 2)) : createCommentVNode("", true),
4408
+ searchMarks.value.length ? (openBlock(), createElementBlock("div", {
4409
+ key: 2,
4410
+ class: normalizeClass(unref(ns).e("marks")),
4411
+ "aria-hidden": "true"
4412
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(searchMarks.value, (mark) => {
4413
+ return openBlock(), createElementBlock("div", {
4414
+ key: `${mark.top}${mark.current ? "c" : ""}`,
4415
+ class: normalizeClass([unref(ns).e("mark"), unref(ns).is("current", mark.current)]),
4416
+ style: normalizeStyle({ top: `${mark.top}%` })
4417
+ }, null, 6);
4418
+ }), 128))], 2)) : createCommentVNode("", true),
4419
+ createElementVNode("div", {
4420
+ class: normalizeClass(unref(ns).e("live")),
4421
+ "aria-live": "polite"
4422
+ }, toDisplayString(announcement.value), 3),
4423
+ panels.value.top.length ? (openBlock(), createElementBlock("div", {
4424
+ key: 3,
4425
+ class: normalizeClass([unref(ns).e("panels"), unref(ns).is("top", true)])
4426
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(panels.value.top, (panel) => {
4427
+ return openBlock(), createBlock(unref(render_part_default), {
4428
+ key: panel.key,
4429
+ render: panel.render
4430
+ }, null, 8, ["render"]);
4431
+ }), 128))], 2)) : createCommentVNode("", true),
4432
+ createElementVNode("div", { class: normalizeClass(unref(ns).e("body")) }, [createElementVNode("div", {
4433
+ ref_key: "scroller",
4434
+ ref: scroller,
4435
+ class: normalizeClass(unref(ns).e("scroller")),
4436
+ onScrollPassive: onScroll
4437
+ }, [createElementVNode("div", {
4438
+ class: normalizeClass(unref(ns).e("sizer")),
4439
+ style: normalizeStyle({
4440
+ height: `${sizerHeight.value}px`,
4441
+ minWidth: `max(100%, ${contentWidth.value + gutterWidth.value}px)`
4442
+ })
4443
+ }, [__props.gutter && (__props.lineNumbers || __props.foldable || gutterCells.value) ? (openBlock(), createElementBlock("div", {
4444
+ key: 0,
4445
+ class: normalizeClass(unref(ns).e("gutter")),
4446
+ "aria-hidden": "true",
4447
+ onPointerdown: _cache[5] || (_cache[5] = ($event) => onPointerDown($event, "gutter")),
4448
+ onPointermove: onPointerMove,
4449
+ onPointerup: _cache[6] || (_cache[6] = ($event) => onPointerUp($event, "gutter")),
4450
+ onPointercancel: onPointerCancel,
4451
+ onPointerenter: _cache[7] || (_cache[7] = ($event) => gutterHover.value = true),
4452
+ onPointerleave: _cache[8] || (_cache[8] = ($event) => gutterHover.value = false),
4453
+ onMousedown: _cache[9] || (_cache[9] = withModifiers(() => {}, ["prevent"]))
4454
+ }, [createElementVNode("div", {
4455
+ class: normalizeClass(unref(ns).e("numbers")),
4456
+ style: normalizeStyle({ transform: `translateY(${yOf(visibleFrom.value)}px)` })
4457
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(rows.value, (row) => {
4458
+ return openBlock(), createElementBlock("div", {
4459
+ key: row.n,
4460
+ class: normalizeClass([unref(ns).e("number"), unref(ns).is("active", row.n === activeLineNumber.value)]),
4461
+ style: normalizeStyle({
4462
+ height: row.wrapped.breaks.length ? `${(row.wrapped.breaks.length + 1) * lineHeight.value}px` : void 0,
4463
+ marginTop: gapBefore(row.n) ? `${gapBefore(row.n)}px` : void 0
4464
+ })
4465
+ }, [
4466
+ gutterCells.value ? (openBlock(), createElementBlock("span", {
4467
+ key: 0,
4468
+ class: normalizeClass(unref(ns).e("cells"))
4469
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(gutterColumns.value, (column, c) => {
4470
+ return openBlock(), createElementBlock("span", {
4471
+ key: column.name,
4472
+ class: normalizeClass([unref(ns).e("cell"), gutterMarkers.value[c]?.get(row.n)?.class]),
4473
+ style: normalizeStyle({ width: `${column.width}px` }),
4474
+ title: gutterMarkers.value[c]?.get(row.n)?.title,
4475
+ "data-gutter-cell": column.onPress ? c : void 0,
4476
+ "data-line": row.n
4477
+ }, [gutterMarkers.value[c]?.get(row.n) ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [gutterMarkers.value[c].get(row.n).icon ? (openBlock(), createBlock(resolveDynamicComponent(gutterMarkers.value[c].get(row.n).icon), { key: 0 })) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(gutterMarkers.value[c].get(row.n).text), 1)], 64))], 64)) : createCommentVNode("", true)], 14, _hoisted_1);
4478
+ }), 128))], 2)) : createCommentVNode("", true),
4479
+ __props.lineNumbers ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(row.n), 1)], 64)) : createCommentVNode("", true),
4480
+ __props.foldable && (row.folded || foldableLines.value.has(row.n)) ? (openBlock(), createElementBlock("span", {
4481
+ key: 2,
4482
+ class: normalizeClass([unref(ns).e("fold-toggle"), unref(ns).is("folded", row.folded)]),
4483
+ "data-fold": row.n
4484
+ }, [row.folded ? (openBlock(), createBlock(unref(ChevronRightIcon), { key: 0 })) : (openBlock(), createBlock(unref(ChevronDownIcon), { key: 1 }))], 10, _hoisted_2)) : createCommentVNode("", true)
4485
+ ], 6);
4486
+ }), 128))], 6)], 34)) : createCommentVNode("", true), createElementVNode("div", {
4487
+ ref_key: "content",
4488
+ ref: content,
4489
+ class: normalizeClass(unref(ns).e("content")),
4490
+ onPointerdown: _cache[21] || (_cache[21] = ($event) => onPointerDown($event, "text")),
4491
+ onPointermove: _cache[22] || (_cache[22] = ($event) => (onPointerMove($event), onContentHover($event))),
4492
+ onPointerup: _cache[23] || (_cache[23] = ($event) => onPointerUp($event, "text")),
4493
+ onPointercancel: onPointerCancel,
4494
+ onPointerleave: onContentLeave,
4495
+ onMousedown: _cache[24] || (_cache[24] = withModifiers(() => {}, ["prevent"]))
4496
+ }, [
4497
+ createElementVNode("div", {
4498
+ ref_key: "probe",
4499
+ ref: probe,
4500
+ class: normalizeClass(unref(ns).e("probe")),
4501
+ "aria-hidden": "true"
4502
+ }, null, 2),
4503
+ __props.activeLine && activeLineTop.value !== null && !__props.disabled ? (openBlock(), createElementBlock("div", {
4504
+ key: 0,
4505
+ class: normalizeClass(unref(ns).e("active-line")),
4506
+ style: normalizeStyle({
4507
+ transform: `translateY(${activeLineTop.value}px)`,
4508
+ height: activeLineRows.value > 1 ? `${activeLineRows.value * lineHeight.value}px` : void 0
4509
+ })
4510
+ }, null, 6)) : createCommentVNode("", true),
4511
+ createElementVNode("div", {
4512
+ class: normalizeClass(unref(ns).e("matches")),
4513
+ "aria-hidden": "true"
4514
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(matchBoxes.value, (box) => {
4515
+ return openBlock(), createElementBlock("div", {
4516
+ key: box.key,
4517
+ class: normalizeClass([unref(ns).e("match"), unref(ns).is("current", box.current)]),
4518
+ style: normalizeStyle({
4519
+ transform: `translate(${box.left}px, ${box.top}px)`,
4520
+ width: `${box.width}px`
4521
+ })
4522
+ }, null, 6);
4523
+ }), 128))], 2),
4524
+ createElementVNode("div", {
4525
+ class: normalizeClass(unref(ns).e("brackets")),
4526
+ "aria-hidden": "true"
4527
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(bracketBoxes.value, (box) => {
4528
+ return openBlock(), createElementBlock("div", {
4529
+ key: box.key,
4530
+ class: normalizeClass([unref(ns).e("bracket"), unref(ns).is("unmatched", !box.matched)]),
4531
+ style: normalizeStyle({
4532
+ transform: `translate(${box.left}px, ${box.top}px)`,
4533
+ width: `${box.width}px`
4534
+ })
4535
+ }, null, 6);
4536
+ }), 128))], 2),
4537
+ createElementVNode("div", {
4538
+ class: normalizeClass(unref(ns).e("selections")),
4539
+ "aria-hidden": "true"
4540
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(selectionBoxes.value, (box) => {
4541
+ return openBlock(), createElementBlock("div", {
4542
+ key: box.key,
4543
+ class: normalizeClass(unref(ns).e("selection")),
4544
+ style: normalizeStyle({
4545
+ transform: `translate(${box.left}px, ${box.top}px)`,
4546
+ width: `${box.width}px`
4547
+ })
4548
+ }, null, 6);
4549
+ }), 128))], 2),
4550
+ createElementVNode("div", {
4551
+ class: normalizeClass(unref(ns).e("lines")),
4552
+ "aria-hidden": "true",
4553
+ style: normalizeStyle({ transform: `translateY(${yOf(visibleFrom.value)}px)` })
4554
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(rows.value, (row, __, ___, _cached) => {
4555
+ const _memo = [
4556
+ row.text,
4557
+ row.tokens,
4558
+ row.compose?.join("\0"),
4559
+ row.wrapped,
4560
+ row.folded,
4561
+ row.marksKey,
4562
+ row.inlinesKey,
4563
+ row.lineClass,
4564
+ gapBefore(row.n)
4565
+ ];
4566
+ if (_cached && _cached.el && _cached.key === row.n && isMemoSame(_cached, _memo)) return _cached;
4567
+ const _item = (openBlock(), createElementBlock("div", {
4568
+ key: row.n,
4569
+ class: normalizeClass([
4570
+ unref(ns).e("line"),
4571
+ unref(ns).is("wrapped", !!row.wrapped.breaks.length),
4572
+ row.lineClass
4573
+ ]),
4574
+ style: normalizeStyle(gapBefore(row.n) ? { marginTop: `${gapBefore(row.n)}px` } : void 0)
4575
+ }, [row.compose ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
4576
+ createTextVNode(toDisplayString(row.compose[0]), 1),
4577
+ createElementVNode("span", { class: normalizeClass(unref(ns).e("compose")) }, toDisplayString(row.compose[1]), 3),
4578
+ createTextVNode(toDisplayString(row.compose[2]), 1)
4579
+ ], 64)) : row.wrapped.breaks.length ? (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(row.wrapped.breaks.length + 1, (_, sub) => {
4580
+ return openBlock(), createElementBlock("div", {
4581
+ key: sub,
4582
+ class: normalizeClass(unref(ns).e("row")),
4583
+ style: normalizeStyle(sub ? { paddingLeft: `${row.wrapped.indent}px` } : void 0)
4584
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(rowParts(row, sub), (part, i) => {
4585
+ return openBlock(), createElementBlock(Fragment, { key: i }, [part[3] !== void 0 ? (openBlock(), createElementBlock("span", {
4586
+ key: 0,
4587
+ ref_for: true,
4588
+ ref: (el) => observeInline(el, row.inlines[part[3]].key, row.inlines[part[3]].width),
4589
+ class: normalizeClass(unref(ns).e("inline")),
4590
+ style: normalizeStyle(row.inlines[part[3]].width !== void 0 ? { width: `${row.inlines[part[3]].width}px` } : void 0)
4591
+ }, [createVNode(unref(render_part_default), { render: row.inlines[part[3]].render }, null, 8, ["render"])], 6)) : part[1] ? (openBlock(), createElementBlock("span", {
4592
+ key: 1,
4593
+ class: normalizeClass(part[1]),
4594
+ title: part[2],
4595
+ style: normalizeStyle(part[4])
4596
+ }, toDisplayString(part[0]), 15, _hoisted_3)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(toDisplayString(part[0]), 1)], 64))], 64);
4597
+ }), 128)), row.folded && sub === row.wrapped.breaks.length ? (openBlock(), createElementBlock("span", {
4598
+ key: 0,
4599
+ class: normalizeClass(unref(ns).e("fold-marker")),
4600
+ "data-unfold": row.n,
4601
+ title: unref(messages).unfold
4602
+ }, "⋯", 10, _hoisted_4)) : createCommentVNode("", true)], 6);
4603
+ }), 128)) : row.tokens || row.marks || row.inlines ? (openBlock(true), createElementBlock(Fragment, { key: 2 }, renderList(partsOf(row), (part, i) => {
4604
+ return openBlock(), createElementBlock(Fragment, { key: i }, [part[3] !== void 0 ? (openBlock(), createElementBlock("span", {
4605
+ key: 0,
4606
+ ref_for: true,
4607
+ ref: (el) => observeInline(el, row.inlines[part[3]].key, row.inlines[part[3]].width),
4608
+ class: normalizeClass(unref(ns).e("inline")),
4609
+ style: normalizeStyle(row.inlines[part[3]].width !== void 0 ? { width: `${row.inlines[part[3]].width}px` } : void 0)
4610
+ }, [createVNode(unref(render_part_default), { render: row.inlines[part[3]].render }, null, 8, ["render"])], 6)) : part[1] ? (openBlock(), createElementBlock("span", {
4611
+ key: 1,
4612
+ class: normalizeClass(part[1]),
4613
+ title: part[2],
4614
+ style: normalizeStyle(part[4])
4615
+ }, toDisplayString(part[0]), 15, _hoisted_5)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(toDisplayString(part[0]), 1)], 64))], 64);
4616
+ }), 128)) : (openBlock(), createElementBlock(Fragment, { key: 3 }, [createTextVNode(toDisplayString(row.text), 1)], 64)), row.folded && !row.wrapped.breaks.length ? (openBlock(), createElementBlock("span", {
4617
+ key: 4,
4618
+ class: normalizeClass(unref(ns).e("fold-marker")),
4619
+ "data-unfold": row.n,
4620
+ title: unref(messages).unfold
4621
+ }, "⋯", 10, _hoisted_6)) : createCommentVNode("", true)], 6));
4622
+ _item.memo = _memo;
4623
+ return _item;
4624
+ }, _cache, 10), 128))], 6),
4625
+ __props.placeholder && !doc.value.length && !composing.value ? (openBlock(), createElementBlock("div", {
4626
+ key: 1,
4627
+ class: normalizeClass(unref(ns).e("placeholder")),
4628
+ "aria-hidden": "true"
4629
+ }, toDisplayString(__props.placeholder), 3)) : createCommentVNode("", true),
4630
+ focused.value ? (openBlock(), createElementBlock("div", {
4631
+ key: blink.value,
4632
+ class: normalizeClass(unref(ns).e("cursors")),
4633
+ "aria-hidden": "true"
4634
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(cursors.value, (cursor) => {
4635
+ return openBlock(), createElementBlock("div", {
4636
+ key: cursor.key,
4637
+ class: normalizeClass(unref(ns).e("cursor")),
4638
+ style: normalizeStyle({ transform: `translate(${cursor.left - 1}px, ${cursor.top}px)` })
4639
+ }, null, 6);
4640
+ }), 128))], 2)) : createCommentVNode("", true),
4641
+ (openBlock(), createBlock(Teleport, {
4642
+ to: floatingTarget.value || "body",
4643
+ disabled: !floatingTarget.value
4644
+ }, [createElementVNode("div", {
4645
+ ref_key: "floatingEl",
4646
+ ref: floatingEl,
4647
+ class: normalizeClass([
4648
+ unref(ns).e("floating"),
4649
+ unref(ns).is("outside", !!floatingTarget.value),
4650
+ unref(ns).is("fixed", !!floatingTarget.value && anchorMode.value === "fixed"),
4651
+ unref(ns).is("scrolling", !!floatingTarget.value && boxScrolling.value)
4652
+ ]),
4653
+ style: normalizeStyle(floatingTarget.value ? {
4654
+ ...frameVars.value,
4655
+ zIndex: floatingZ.value,
4656
+ transform: `translate(${layerShift.value.x}px, ${layerShift.value.y}px)`
4657
+ } : void 0)
4658
+ }, [
4659
+ problemStyle.value ? (openBlock(), createElementBlock("div", {
4660
+ key: 0,
4661
+ ref_key: "problemEl",
4662
+ ref: problemEl,
4663
+ class: normalizeClass(unref(ns).e("problems")),
4664
+ role: "group",
4665
+ "aria-label": problemBox.value.problems.length ? unref(messages).problems : unref(messages).details,
4666
+ style: normalizeStyle(problemStyle.value),
4667
+ onPointerdown: _cache[12] || (_cache[12] = withModifiers(() => {}, ["stop", "prevent"])),
4668
+ onPointermove: _cache[13] || (_cache[13] = withModifiers(() => {}, ["stop"])),
4669
+ onPointerenter: keepProblems,
4670
+ onPointerleave: onContentLeave
4671
+ }, [
4672
+ (openBlock(true), createElementBlock(Fragment, null, renderList(problemBox.value.info, (item, i) => {
4673
+ return openBlock(), createElementBlock("div", {
4674
+ key: `info-${i}`,
4675
+ class: normalizeClass(unref(ns).e("hover"))
4676
+ }, [typeof item === "string" ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(toDisplayString(item), 1)], 64)) : (openBlock(), createBlock(unref(render_part_default), {
4677
+ key: 1,
4678
+ render: item
4679
+ }, null, 8, ["render"]))], 2);
4680
+ }), 128)),
4681
+ (openBlock(true), createElementBlock(Fragment, null, renderList(problemBox.value.problems, (problem, i) => {
4682
+ return openBlock(), createElementBlock("div", {
4683
+ key: i,
4684
+ class: normalizeClass([unref(ns).e("problem-item"), unref(ns).is(problem.severity, true)])
4685
+ }, [(openBlock(), createBlock(resolveDynamicComponent(SEVERITY_ICON[problem.severity]), { class: normalizeClass(unref(ns).e("problem-severity")) }, null, 8, ["class"])), createElementVNode("span", { class: normalizeClass(unref(ns).e("problem-message")) }, [createTextVNode(toDisplayString(problem.message), 1), problem.source ? (openBlock(), createElementBlock("span", {
4686
+ key: 0,
4687
+ class: normalizeClass(unref(ns).e("problem-source"))
4688
+ }, toDisplayString(problem.source), 3)) : createCommentVNode("", true)], 2)], 2);
4689
+ }), 128)),
4690
+ fixes.value.length ? (openBlock(), createElementBlock("div", {
4691
+ key: 0,
4692
+ class: normalizeClass(unref(ns).e("fixes"))
4693
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(fixes.value, (fix, i) => {
4694
+ return openBlock(), createElementBlock("button", {
4695
+ key: i,
4696
+ type: "button",
4697
+ tabindex: "-1",
4698
+ class: normalizeClass([unref(ns).e("fix"), unref(ns).is("active", i === problemBox.value.index)]),
4699
+ "aria-current": i === problemBox.value.index || void 0,
4700
+ onClick: ($event) => runFix(i)
4701
+ }, toDisplayString(fix.action.label), 11, _hoisted_8);
4702
+ }), 128))], 2)) : createCommentVNode("", true)
4703
+ ], 46, _hoisted_7)) : createCommentVNode("", true),
4704
+ completionStyle.value ? (openBlock(), createElementBlock("div", {
4705
+ key: 1,
4706
+ ref_key: "completionEl",
4707
+ ref: completionEl,
4708
+ class: normalizeClass(unref(ns).e("completions")),
4709
+ style: normalizeStyle(completionStyle.value),
4710
+ onPointerdown: _cache[14] || (_cache[14] = withModifiers(() => {}, ["stop", "prevent"])),
4711
+ onPointermove: _cache[15] || (_cache[15] = withModifiers(() => {}, ["stop"]))
4712
+ }, [createElementVNode("div", {
4713
+ id: completionId,
4714
+ ref_key: "completionList",
4715
+ ref: completionList,
4716
+ class: normalizeClass(unref(ns).e("completion-list")),
4717
+ role: "listbox",
4718
+ "aria-label": unref(messages).completions
4719
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(completion.value.items, (item, i) => {
4720
+ return openBlock(), createElementBlock("div", {
4721
+ id: `${completionId}-${i}`,
4722
+ key: i,
4723
+ role: "option",
4724
+ "aria-selected": i === completion.value.index,
4725
+ class: normalizeClass([unref(ns).e("completion"), unref(ns).is("active", i === completion.value.index)]),
4726
+ onClick: ($event) => acceptCompletion(i)
4727
+ }, [
4728
+ (openBlock(), createBlock(resolveDynamicComponent(KIND_ICON[item.option.kind ?? "text"]), {
4729
+ class: normalizeClass([unref(ns).e("completion-kind"), unref(ns).is(item.option.kind ?? "text", true)]),
4730
+ "aria-hidden": "true"
4731
+ }, null, 8, ["class"])),
4732
+ createElementVNode("span", { class: normalizeClass(unref(ns).e("completion-label")) }, [(openBlock(true), createElementBlock(Fragment, null, renderList(labelParts(item), (part, j) => {
4733
+ return openBlock(), createElementBlock(Fragment, { key: j }, [part[1] ? (openBlock(), createElementBlock("mark", {
4734
+ key: 0,
4735
+ class: normalizeClass(unref(ns).e("completion-match"))
4736
+ }, toDisplayString(part[0]), 3)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(part[0]), 1)], 64))], 64);
4737
+ }), 128))], 2),
4738
+ item.option.detail ? (openBlock(), createElementBlock("span", {
4739
+ key: 0,
4740
+ class: normalizeClass(unref(ns).e("completion-detail"))
4741
+ }, toDisplayString(item.option.detail), 3)) : createCommentVNode("", true)
4742
+ ], 10, _hoisted_10);
4743
+ }), 128))], 10, _hoisted_9), completion.value.items[completion.value.index]?.option.info ? (openBlock(), createElementBlock("div", {
4744
+ key: 0,
4745
+ class: normalizeClass(unref(ns).e("completion-info"))
4746
+ }, [typeof completion.value.items[completion.value.index].option.info === "string" ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(toDisplayString(completion.value.items[completion.value.index].option.info), 1)], 64)) : (openBlock(), createBlock(unref(render_part_default), {
4747
+ key: 1,
4748
+ render: completion.value.items[completion.value.index].option.info
4749
+ }, null, 8, ["render"]))], 2)) : createCommentVNode("", true)], 38)) : createCommentVNode("", true),
4750
+ signatureStyle.value ? (openBlock(), createElementBlock("div", {
4751
+ key: 2,
4752
+ ref_key: "signatureEl",
4753
+ ref: signatureEl,
4754
+ class: normalizeClass(unref(ns).e("signature")),
4755
+ role: "note",
4756
+ "aria-label": unref(messages).signature,
4757
+ style: normalizeStyle(signatureStyle.value),
4758
+ onPointerdown: _cache[16] || (_cache[16] = withModifiers(() => {}, ["stop", "prevent"]))
4759
+ }, [createElementVNode("div", { class: normalizeClass(unref(ns).e("signature-label")) }, [(openBlock(true), createElementBlock(Fragment, null, renderList(signatureParts.value, (part, i) => {
4760
+ return openBlock(), createElementBlock(Fragment, { key: i }, [part[1] ? (openBlock(), createElementBlock("span", {
4761
+ key: 0,
4762
+ class: normalizeClass(unref(ns).e("signature-active"))
4763
+ }, toDisplayString(part[0]), 3)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(part[0]), 1)], 64))], 64);
4764
+ }), 128))], 2), signature.value.result.info ? (openBlock(), createElementBlock("div", {
4765
+ key: 0,
4766
+ class: normalizeClass(unref(ns).e("signature-info"))
4767
+ }, [typeof signature.value.result.info === "string" ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(toDisplayString(signature.value.result.info), 1)], 64)) : (openBlock(), createBlock(unref(render_part_default), {
4768
+ key: 1,
4769
+ render: signature.value.result.info
4770
+ }, null, 8, ["render"]))], 2)) : createCommentVNode("", true)], 46, _hoisted_11)) : createCommentVNode("", true),
4771
+ (openBlock(true), createElementBlock(Fragment, null, renderList(handles.value, (handle) => {
4772
+ return openBlock(), createElementBlock("div", {
4773
+ key: handle.kind,
4774
+ class: normalizeClass([unref(ns).e("handle"), unref(ns).is(handle.kind, true)]),
4775
+ style: normalizeStyle({ transform: `translate(${handle.left}px, ${handle.top}px)` }),
4776
+ "aria-hidden": "true",
4777
+ onPointerdown: ($event) => onHandleDown($event, handle.kind)
4778
+ }, null, 46, _hoisted_12);
4779
+ }), 128)),
4780
+ magnifier.value ? (openBlock(), createElementBlock("div", {
4781
+ key: 3,
4782
+ class: normalizeClass(unref(ns).e("magnifier")),
4783
+ style: normalizeStyle(magnifier.value.style),
4784
+ "aria-hidden": "true"
4785
+ }, [createElementVNode("div", {
4786
+ class: normalizeClass(unref(ns).e("magnifier-text")),
4787
+ style: normalizeStyle([magnifier.value.textStyle, { paddingLeft: `${magnifier.value.indent}px` }])
4788
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(magnifier.value.parts, (part, i) => {
4789
+ return openBlock(), createElementBlock(Fragment, { key: i }, [part[3] !== void 0 ? (openBlock(), createElementBlock("span", {
4790
+ key: 0,
4791
+ class: normalizeClass(unref(ns).e("inline")),
4792
+ style: normalizeStyle({ width: `${widthOf(magnifier.value.inlines[part[3]])}px` })
4793
+ }, [createVNode(unref(render_part_default), { render: magnifier.value.inlines[part[3]].render }, null, 8, ["render"])], 6)) : part[1] ? (openBlock(), createElementBlock("span", {
4794
+ key: 1,
4795
+ class: normalizeClass(part[1]),
4796
+ title: part[2],
4797
+ style: normalizeStyle(part[4])
4798
+ }, toDisplayString(part[0]), 15, _hoisted_13)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(toDisplayString(part[0]), 1)], 64))], 64);
4799
+ }), 128))], 6), createElementVNode("div", {
4800
+ class: normalizeClass(unref(ns).e("magnifier-caret")),
4801
+ style: normalizeStyle({ left: `${magnifier.value.caret - 1}px` })
4802
+ }, null, 6)], 6)) : createCommentVNode("", true),
4803
+ menuStyle.value ? (openBlock(), createElementBlock("div", {
4804
+ key: 4,
4805
+ ref_key: "menuEl",
4806
+ ref: menuEl,
4807
+ class: normalizeClass(unref(ns).e("menu")),
4808
+ role: "toolbar",
4809
+ "aria-label": unref(messages).editMenu,
4810
+ style: normalizeStyle(menuStyle.value),
4811
+ onPointerdown: _cache[17] || (_cache[17] = withModifiers(() => {}, ["stop", "prevent"]))
4812
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(menuItems.value, (item) => {
4813
+ return openBlock(), createElementBlock("button", {
4814
+ key: item.key,
4815
+ type: "button",
4816
+ tabindex: "-1",
4817
+ class: normalizeClass(unref(ns).e("menu-button")),
4818
+ onClick: ($event) => item.run()
4819
+ }, toDisplayString(item.label), 11, _hoisted_15);
4820
+ }), 128))], 46, _hoisted_14)) : createCommentVNode("", true)
4821
+ ], 6)], 8, ["to", "disabled"])),
4822
+ createElementVNode("textarea", {
4823
+ ref_key: "input",
4824
+ ref: input,
4825
+ class: normalizeClass(unref(ns).e("input")),
4826
+ style: normalizeStyle({
4827
+ top: `${inputBox.value.top}px`,
4828
+ left: `${inputBox.value.left}px`,
4829
+ height: `${inputBox.value.height}px`
4830
+ }),
4831
+ "aria-label": __props.ariaLabel,
4832
+ "aria-placeholder": __props.placeholder || void 0,
4833
+ "aria-autocomplete": hasCompletion.value ? "list" : void 0,
4834
+ "aria-controls": completion.value ? completionId : void 0,
4835
+ readonly: __props.readonly,
4836
+ disabled: __props.disabled,
4837
+ wrap: "off",
4838
+ autocomplete: "off",
4839
+ autocorrect: "off",
4840
+ autocapitalize: "off",
4841
+ spellcheck: "false",
4842
+ enterkeyhint: "enter",
4843
+ onKeydown,
4844
+ onBeforeinput: onBeforeInput,
4845
+ onInput,
4846
+ onCompositionstart: onCompositionStart,
4847
+ onCompositionend: onCompositionEnd,
4848
+ onCopy,
4849
+ onCut,
4850
+ onPaste,
4851
+ onFocus,
4852
+ onBlur
4853
+ }, null, 46, _hoisted_16),
4854
+ shownWidgets.value.length ? (openBlock(), createElementBlock("div", {
4855
+ key: 3,
4856
+ class: normalizeClass(unref(ns).e("widgets")),
4857
+ onPointerdown: _cache[18] || (_cache[18] = withModifiers(() => {}, ["stop"])),
4858
+ onPointermove: _cache[19] || (_cache[19] = withModifiers(() => {}, ["stop"])),
4859
+ onMousedown: _cache[20] || (_cache[20] = withModifiers(() => {}, ["stop"]))
4860
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(shownWidgets.value, (widget) => {
4861
+ return openBlock(), createElementBlock("div", {
4862
+ key: widget.key,
4863
+ ref_for: true,
4864
+ ref: (el) => observeWidget(el, widget.key),
4865
+ class: normalizeClass(unref(ns).e("widget")),
4866
+ role: widget.label ? "group" : void 0,
4867
+ "aria-label": widget.label,
4868
+ style: normalizeStyle({
4869
+ transform: `translate(${scrollLeft.value}px, ${widget.top}px)`,
4870
+ width: `${Math.max(0, viewWidth.value - gutterWidth.value)}px`
4871
+ })
4872
+ }, [createVNode(unref(render_part_default), { render: widget.render }, null, 8, ["render"])], 14, _hoisted_17);
4873
+ }), 128))], 34)) : createCommentVNode("", true)
4874
+ ], 34)], 6)], 34), minimapOn.value && minimap.value ? (openBlock(), createElementBlock("div", {
4875
+ key: 0,
4876
+ class: normalizeClass(unref(ns).e("minimap")),
4877
+ "aria-hidden": "true",
4878
+ onPointerdown: onMinimapDown,
4879
+ onPointermove: onMinimapMove,
4880
+ onPointerup: onMinimapUp,
4881
+ onPointercancel: onMinimapUp
4882
+ }, [createElementVNode("canvas", {
4883
+ ref_key: "minimapCanvas",
4884
+ ref: minimapCanvas,
4885
+ class: normalizeClass(unref(ns).e("minimap-canvas"))
4886
+ }, null, 2), createElementVNode("div", {
4887
+ class: normalizeClass(unref(ns).e("minimap-view")),
4888
+ style: normalizeStyle({
4889
+ transform: `translateY(${minimap.value.slider.top}px)`,
4890
+ height: `${minimap.value.slider.height}px`
4891
+ })
4892
+ }, null, 6)], 34)) : createCommentVNode("", true)], 2),
4893
+ panels.value.bottom.length ? (openBlock(), createElementBlock("div", {
4894
+ key: 4,
4895
+ class: normalizeClass([unref(ns).e("panels"), unref(ns).is("bottom", true)])
4896
+ }, [(openBlock(true), createElementBlock(Fragment, null, renderList(panels.value.bottom, (panel) => {
4897
+ return openBlock(), createBlock(unref(render_part_default), {
4898
+ key: panel.key,
4899
+ render: panel.render
4900
+ }, null, 8, ["render"]);
4901
+ }), 128))], 2)) : createCommentVNode("", true),
4902
+ (openBlock(), createBlock(Teleport, { to: "body" }, [showKeys.value ? (openBlock(), createElementBlock("div", {
4903
+ key: 0,
4904
+ class: normalizeClass([unref(ns).e("keys"), unref(ns).is("scrolling", pageScrolling.value)]),
4905
+ style: normalizeStyle(keysStyle.value)
4906
+ }, [createVNode(code_keys_default, {
4907
+ editor: keysEditor,
4908
+ keys: keysList.value,
4909
+ messages: unref(messages)
4910
+ }, null, 8, ["keys", "messages"])], 6)) : createCommentVNode("", true)]))
4911
+ ], 6);
4912
+ };
4913
+ }
4914
+ });
4915
+ export { code_editor_vue_vue_type_script_setup_true_lang_default as default };
4916
+
4917
+ //# sourceMappingURL=code-editor.vue_vue_type_script_setup_true_lang.js.map