@onereach/ui-components 6.4.2 → 6.5.0-beta.3403.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 (77) hide show
  1. package/dist/bundled/v2/components/OrCode/OrCode.js +2 -2
  2. package/dist/bundled/v2/components/OrCode/index.js +5 -3
  3. package/dist/bundled/v2/components/OrCode/lang.js +5 -3
  4. package/dist/bundled/v2/components/OrCode/libs.js +5 -3
  5. package/dist/bundled/v2/components/OrCode/theme.js +1 -1
  6. package/dist/bundled/v2/components/OrCodeV3/OrCode.js +52 -30
  7. package/dist/bundled/v2/components/OrCodeV3/OrCode.vue.d.ts +4 -3
  8. package/dist/bundled/v2/components/OrCodeV3/index.d.ts +1 -0
  9. package/dist/bundled/v2/components/OrCodeV3/index.js +5 -0
  10. package/dist/bundled/v2/components/OrCodeV3/libs.d.ts +6 -0
  11. package/dist/bundled/v2/components/OrCodeV3/libs.js +5 -0
  12. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.js +2 -2
  13. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.js +1 -1
  14. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/theme.js +1 -1
  15. package/dist/bundled/v2/components/index.js +6 -3
  16. package/dist/bundled/v2/index-317a90b7.js +361 -0
  17. package/dist/bundled/v2/index-5465a04e.js +825 -0
  18. package/dist/bundled/v2/index-5df3b1d8.js +94 -0
  19. package/dist/bundled/v2/index-5fa53f66.js +759 -0
  20. package/dist/bundled/{v3/index-ceea3e83.js → v2/index-7caa3ac5.js} +3 -3
  21. package/dist/bundled/v2/{index-eca317e0.js → index-bd08fe6f.js} +27 -465
  22. package/dist/bundled/v2/index-d017a622.js +1892 -0
  23. package/dist/bundled/v2/{index-62bb1bac.js → index-d4e4f8a8.js} +10 -831
  24. package/dist/bundled/v2/{index-3cae2d25.js → index-d5c13979.js} +1 -1
  25. package/dist/bundled/v2/index-f949d42c.js +1598 -0
  26. package/dist/bundled/v2/index.js +6 -3
  27. package/dist/bundled/v3/{OrCode.vue_vue_type_script_lang-e88b2b44.js → OrCode.vue_vue_type_script_lang-9be03ab0.js} +2 -2
  28. package/dist/bundled/v3/{OrCode.vue_vue_type_script_lang-c9522cd5.js → OrCode.vue_vue_type_script_lang-f6022ce5.js} +52 -30
  29. package/dist/bundled/v3/components/OrCode/OrCode.js +2 -2
  30. package/dist/bundled/v3/components/OrCode/index.js +6 -4
  31. package/dist/bundled/v3/components/OrCode/lang.js +5 -3
  32. package/dist/bundled/v3/components/OrCode/libs.js +5 -3
  33. package/dist/bundled/v3/components/OrCode/theme.js +1 -1
  34. package/dist/bundled/v3/components/OrCodeV3/OrCode.js +2 -2
  35. package/dist/bundled/v3/components/OrCodeV3/OrCode.vue.d.ts +3 -2
  36. package/dist/bundled/v3/components/OrCodeV3/index.d.ts +1 -0
  37. package/dist/bundled/v3/components/OrCodeV3/index.js +6 -1
  38. package/dist/bundled/v3/components/OrCodeV3/libs.d.ts +6 -0
  39. package/dist/bundled/v3/components/OrCodeV3/libs.js +5 -0
  40. package/dist/bundled/v3/components/OrRichTextEditorV3/OrRichTextEditor.js +2 -2
  41. package/dist/bundled/v3/components/OrRichTextEditorV3/index.js +1 -1
  42. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.js +2 -2
  43. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.js +1 -1
  44. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/theme.js +1 -1
  45. package/dist/bundled/v3/components/index.js +9 -6
  46. package/dist/bundled/v3/{index-62bb1bac.js → index-16f605c7.js} +10 -831
  47. package/dist/bundled/v3/index-1f2974f3.js +1892 -0
  48. package/dist/bundled/v3/index-1fc9d52b.js +759 -0
  49. package/dist/bundled/v3/index-210fd8da.js +825 -0
  50. package/dist/bundled/{v2/index-ceea3e83.js → v3/index-71514f0d.js} +3 -3
  51. package/dist/bundled/v3/{index-eca317e0.js → index-766903ad.js} +27 -465
  52. package/dist/bundled/v3/index-a4b02e4e.js +1598 -0
  53. package/dist/bundled/v3/index-a8d259c3.js +361 -0
  54. package/dist/bundled/v3/{index-3cae2d25.js → index-e81a9bf9.js} +1 -1
  55. package/dist/bundled/v3/index-f6290750.js +94 -0
  56. package/dist/bundled/v3/index.js +9 -6
  57. package/dist/esm/v2/{OrCode-f5c25b63.js → OrCode-e2222cf7.js} +54 -34
  58. package/dist/esm/v2/components/index.js +3 -3
  59. package/dist/esm/v2/components/or-code-v3/OrCode.vue.d.ts +4 -3
  60. package/dist/esm/v2/components/or-code-v3/index.d.ts +1 -0
  61. package/dist/esm/v2/components/or-code-v3/index.js +9 -10
  62. package/dist/esm/v2/components/or-code-v3/libs.d.ts +6 -0
  63. package/dist/esm/v2/index.js +3 -3
  64. package/dist/esm/v3/{OrCode-9662d0da.js → OrCode-f6a8e9f2.js} +54 -34
  65. package/dist/esm/v3/components/index.js +3 -3
  66. package/dist/esm/v3/components/or-code-v3/OrCode.vue.d.ts +3 -2
  67. package/dist/esm/v3/components/or-code-v3/index.d.ts +1 -0
  68. package/dist/esm/v3/components/or-code-v3/index.js +9 -10
  69. package/dist/esm/v3/components/or-code-v3/libs.d.ts +6 -0
  70. package/dist/esm/v3/index.js +3 -3
  71. package/package.json +2 -3
  72. package/src/components/or-code-v3/OrCode.vue +70 -50
  73. package/src/components/or-code-v3/index.ts +1 -0
  74. package/src/components/or-code-v3/libs.ts +10 -0
  75. package/dist/bundled/v2/index-60e4eacf.js +0 -4048
  76. package/dist/bundled/v3/index-60e4eacf.js +0 -4048
  77. /package/dist/bundled/v3/{OrRichTextEditor.vue_vue_type_script_lang-5a2318e5.js → OrRichTextEditor.vue_vue_type_script_lang-63edf53c.js} +0 -0
@@ -0,0 +1,1892 @@
1
+ import { s as syntaxTree, E as EditorView, r as codePointSize, q as codePointAt, b as EditorSelection, u as CharCategory, P as Prec, k as keymap, F as Facet, c as combineConfig, D as Direction, ak as getTooltip, V as ViewPlugin, Z as logException, m as StateEffect, S as StateField, a0 as showTooltip, al as MapMode, am as RangeValue, $ as RangeSet, v as fromCodePoint, A as Annotation, f as Text, h as indentUnit, p as Decoration, a1 as WidgetType } from './index-e81a9bf9.js';
2
+
3
+ /**
4
+ An instance of this is passed to completion source functions.
5
+ */
6
+ class CompletionContext {
7
+ /**
8
+ Create a new completion context. (Mostly useful for testing
9
+ completion sources—in the editor, the extension will create
10
+ these for you.)
11
+ */
12
+ constructor(
13
+ /**
14
+ The editor state that the completion happens in.
15
+ */
16
+ state,
17
+ /**
18
+ The position at which the completion is happening.
19
+ */
20
+ pos,
21
+ /**
22
+ Indicates whether completion was activated explicitly, or
23
+ implicitly by typing. The usual way to respond to this is to
24
+ only return completions when either there is part of a
25
+ completable entity before the cursor, or `explicit` is true.
26
+ */
27
+ explicit) {
28
+ this.state = state;
29
+ this.pos = pos;
30
+ this.explicit = explicit;
31
+ /**
32
+ @internal
33
+ */
34
+ this.abortListeners = [];
35
+ }
36
+ /**
37
+ Get the extent, content, and (if there is a token) type of the
38
+ token before `this.pos`.
39
+ */
40
+ tokenBefore(types) {
41
+ let token = syntaxTree(this.state).resolveInner(this.pos, -1);
42
+ while (token && types.indexOf(token.name) < 0) token = token.parent;
43
+ return token ? {
44
+ from: token.from,
45
+ to: this.pos,
46
+ text: this.state.sliceDoc(token.from, this.pos),
47
+ type: token.type
48
+ } : null;
49
+ }
50
+ /**
51
+ Get the match of the given expression directly before the
52
+ cursor.
53
+ */
54
+ matchBefore(expr) {
55
+ let line = this.state.doc.lineAt(this.pos);
56
+ let start = Math.max(line.from, this.pos - 250);
57
+ let str = line.text.slice(start - line.from, this.pos - line.from);
58
+ let found = str.search(ensureAnchor(expr, false));
59
+ return found < 0 ? null : {
60
+ from: start + found,
61
+ to: this.pos,
62
+ text: str.slice(found)
63
+ };
64
+ }
65
+ /**
66
+ Yields true when the query has been aborted. Can be useful in
67
+ asynchronous queries to avoid doing work that will be ignored.
68
+ */
69
+ get aborted() {
70
+ return this.abortListeners == null;
71
+ }
72
+ /**
73
+ Allows you to register abort handlers, which will be called when
74
+ the query is
75
+ [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
76
+ */
77
+ addEventListener(type, listener) {
78
+ if (type == "abort" && this.abortListeners) this.abortListeners.push(listener);
79
+ }
80
+ }
81
+ function toSet(chars) {
82
+ let flat = Object.keys(chars).join("");
83
+ let words = /\w/.test(flat);
84
+ if (words) flat = flat.replace(/\w/g, "");
85
+ return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
86
+ }
87
+ function prefixMatch(options) {
88
+ let first = Object.create(null),
89
+ rest = Object.create(null);
90
+ for (let {
91
+ label
92
+ } of options) {
93
+ first[label[0]] = true;
94
+ for (let i = 1; i < label.length; i++) rest[label[i]] = true;
95
+ }
96
+ let source = toSet(first) + toSet(rest) + "*$";
97
+ return [new RegExp("^" + source), new RegExp(source)];
98
+ }
99
+ /**
100
+ Given a a fixed array of options, return an autocompleter that
101
+ completes them.
102
+ */
103
+ function completeFromList(list) {
104
+ let options = list.map(o => typeof o == "string" ? {
105
+ label: o
106
+ } : o);
107
+ let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
108
+ return context => {
109
+ let token = context.matchBefore(match);
110
+ return token || context.explicit ? {
111
+ from: token ? token.from : context.pos,
112
+ options,
113
+ validFor
114
+ } : null;
115
+ };
116
+ }
117
+ /**
118
+ Wrap the given completion source so that it will not fire when the
119
+ cursor is in a syntax node with one of the given names.
120
+ */
121
+ function ifNotIn(nodes, source) {
122
+ return context => {
123
+ for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
124
+ if (nodes.indexOf(pos.name) > -1) return null;
125
+ if (pos.type.isTop) break;
126
+ }
127
+ return source(context);
128
+ };
129
+ }
130
+ class Option {
131
+ constructor(completion, source, match, score) {
132
+ this.completion = completion;
133
+ this.source = source;
134
+ this.match = match;
135
+ this.score = score;
136
+ }
137
+ }
138
+ function cur(state) {
139
+ return state.selection.main.from;
140
+ }
141
+ // Make sure the given regexp has a $ at its end and, if `start` is
142
+ // true, a ^ at its start.
143
+ function ensureAnchor(expr, start) {
144
+ var _a;
145
+ let {
146
+ source
147
+ } = expr;
148
+ let addStart = start && source[0] != "^",
149
+ addEnd = source[source.length - 1] != "$";
150
+ if (!addStart && !addEnd) return expr;
151
+ return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : expr.ignoreCase ? "i" : "");
152
+ }
153
+ /**
154
+ This annotation is added to transactions that are produced by
155
+ picking a completion.
156
+ */
157
+ const pickedCompletion = /*@__PURE__*/Annotation.define();
158
+ /**
159
+ Helper function that returns a transaction spec which inserts a
160
+ completion's text in the main selection range, and any other
161
+ selection range that has the same text in front of it.
162
+ */
163
+ function insertCompletionText(state, text, from, to) {
164
+ let {
165
+ main
166
+ } = state.selection,
167
+ fromOff = from - main.from,
168
+ toOff = to - main.from;
169
+ return Object.assign(Object.assign({}, state.changeByRange(range => {
170
+ if (range != main && from != to && state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to)) return {
171
+ range
172
+ };
173
+ return {
174
+ changes: {
175
+ from: range.from + fromOff,
176
+ to: to == main.from ? range.to : range.from + toOff,
177
+ insert: text
178
+ },
179
+ range: EditorSelection.cursor(range.from + fromOff + text.length)
180
+ };
181
+ })), {
182
+ userEvent: "input.complete"
183
+ });
184
+ }
185
+ const SourceCache = /*@__PURE__*/new WeakMap();
186
+ function asSource(source) {
187
+ if (!Array.isArray(source)) return source;
188
+ let known = SourceCache.get(source);
189
+ if (!known) SourceCache.set(source, known = completeFromList(source));
190
+ return known;
191
+ }
192
+ const startCompletionEffect = /*@__PURE__*/StateEffect.define();
193
+ const closeCompletionEffect = /*@__PURE__*/StateEffect.define();
194
+
195
+ // A pattern matcher for fuzzy completion matching. Create an instance
196
+ // once for a pattern, and then use that to match any number of
197
+ // completions.
198
+ class FuzzyMatcher {
199
+ constructor(pattern) {
200
+ this.pattern = pattern;
201
+ this.chars = [];
202
+ this.folded = [];
203
+ // Buffers reused by calls to `match` to track matched character
204
+ // positions.
205
+ this.any = [];
206
+ this.precise = [];
207
+ this.byWord = [];
208
+ for (let p = 0; p < pattern.length;) {
209
+ let char = codePointAt(pattern, p),
210
+ size = codePointSize(char);
211
+ this.chars.push(char);
212
+ let part = pattern.slice(p, p + size),
213
+ upper = part.toUpperCase();
214
+ this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
215
+ p += size;
216
+ }
217
+ this.astral = pattern.length != this.chars.length;
218
+ }
219
+ // Matches a given word (completion) against the pattern (input).
220
+ // Will return null for no match, and otherwise an array that starts
221
+ // with the match score, followed by any number of `from, to` pairs
222
+ // indicating the matched parts of `word`.
223
+ //
224
+ // The score is a number that is more negative the worse the match
225
+ // is. See `Penalty` above.
226
+ match(word) {
227
+ if (this.pattern.length == 0) return [-100 /* Penalty.NotFull */];
228
+ if (word.length < this.pattern.length) return null;
229
+ let {
230
+ chars,
231
+ folded,
232
+ any,
233
+ precise,
234
+ byWord
235
+ } = this;
236
+ // For single-character queries, only match when they occur right
237
+ // at the start
238
+ if (chars.length == 1) {
239
+ let first = codePointAt(word, 0),
240
+ firstSize = codePointSize(first);
241
+ let score = firstSize == word.length ? 0 : -100 /* Penalty.NotFull */;
242
+ if (first == chars[0]) ;else if (first == folded[0]) score += -200 /* Penalty.CaseFold */;else return null;
243
+ return [score, 0, firstSize];
244
+ }
245
+ let direct = word.indexOf(this.pattern);
246
+ if (direct == 0) return [word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */, 0, this.pattern.length];
247
+ let len = chars.length,
248
+ anyTo = 0;
249
+ if (direct < 0) {
250
+ for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
251
+ let next = codePointAt(word, i);
252
+ if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i;
253
+ i += codePointSize(next);
254
+ }
255
+ // No match, exit immediately
256
+ if (anyTo < len) return null;
257
+ }
258
+ // This tracks the extent of the precise (non-folded, not
259
+ // necessarily adjacent) match
260
+ let preciseTo = 0;
261
+ // Tracks whether there is a match that hits only characters that
262
+ // appear to be starting words. `byWordFolded` is set to true when
263
+ // a case folded character is encountered in such a match
264
+ let byWordTo = 0,
265
+ byWordFolded = false;
266
+ // If we've found a partial adjacent match, these track its state
267
+ let adjacentTo = 0,
268
+ adjacentStart = -1,
269
+ adjacentEnd = -1;
270
+ let hasLower = /[a-z]/.test(word),
271
+ wordAdjacent = true;
272
+ // Go over the option's text, scanning for the various kinds of matches
273
+ for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) {
274
+ let next = codePointAt(word, i);
275
+ if (direct < 0) {
276
+ if (preciseTo < len && next == chars[preciseTo]) precise[preciseTo++] = i;
277
+ if (adjacentTo < len) {
278
+ if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
279
+ if (adjacentTo == 0) adjacentStart = i;
280
+ adjacentEnd = i + 1;
281
+ adjacentTo++;
282
+ } else {
283
+ adjacentTo = 0;
284
+ }
285
+ }
286
+ }
287
+ let ch,
288
+ type = next < 0xff ? next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */ : (ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */;
289
+ if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) {
290
+ if (chars[byWordTo] == next || folded[byWordTo] == next && (byWordFolded = true)) byWord[byWordTo++] = i;else if (byWord.length) wordAdjacent = false;
291
+ }
292
+ prevType = type;
293
+ i += codePointSize(next);
294
+ }
295
+ if (byWordTo == len && byWord[0] == 0 && wordAdjacent) return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word);
296
+ if (adjacentTo == len && adjacentStart == 0) return [-200 /* Penalty.CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* Penalty.NotFull */), 0, adjacentEnd];
297
+ if (direct > -1) return [-700 /* Penalty.NotStart */ - word.length, direct, direct + this.pattern.length];
298
+ if (adjacentTo == len) return [-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, adjacentStart, adjacentEnd];
299
+ if (byWordTo == len) return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ + (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word);
300
+ return chars.length == 2 ? null : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word);
301
+ }
302
+ result(score, positions, word) {
303
+ let result = [score - word.length],
304
+ i = 1;
305
+ for (let pos of positions) {
306
+ let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
307
+ if (i > 1 && result[i - 1] == pos) result[i - 1] = to;else {
308
+ result[i++] = pos;
309
+ result[i++] = to;
310
+ }
311
+ }
312
+ return result;
313
+ }
314
+ }
315
+ const completionConfig = /*@__PURE__*/Facet.define({
316
+ combine(configs) {
317
+ return combineConfig(configs, {
318
+ activateOnTyping: true,
319
+ selectOnOpen: true,
320
+ override: null,
321
+ closeOnBlur: true,
322
+ maxRenderedOptions: 100,
323
+ defaultKeymap: true,
324
+ tooltipClass: () => "",
325
+ optionClass: () => "",
326
+ aboveCursor: false,
327
+ icons: true,
328
+ addToOptions: [],
329
+ positionInfo: defaultPositionInfo,
330
+ compareCompletions: (a, b) => a.label.localeCompare(b.label),
331
+ interactionDelay: 75
332
+ }, {
333
+ defaultKeymap: (a, b) => a && b,
334
+ closeOnBlur: (a, b) => a && b,
335
+ icons: (a, b) => a && b,
336
+ tooltipClass: (a, b) => c => joinClass(a(c), b(c)),
337
+ optionClass: (a, b) => c => joinClass(a(c), b(c)),
338
+ addToOptions: (a, b) => a.concat(b)
339
+ });
340
+ }
341
+ });
342
+ function joinClass(a, b) {
343
+ return a ? b ? a + " " + b : a : b;
344
+ }
345
+ function defaultPositionInfo(view, list, option, info, space) {
346
+ let rtl = view.textDirection == Direction.RTL,
347
+ left = rtl,
348
+ narrow = false;
349
+ let side = "top",
350
+ offset,
351
+ maxWidth;
352
+ let spaceLeft = list.left - space.left,
353
+ spaceRight = space.right - list.right;
354
+ let infoWidth = info.right - info.left,
355
+ infoHeight = info.bottom - info.top;
356
+ if (left && spaceLeft < Math.min(infoWidth, spaceRight)) left = false;else if (!left && spaceRight < Math.min(infoWidth, spaceLeft)) left = true;
357
+ if (infoWidth <= (left ? spaceLeft : spaceRight)) {
358
+ offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
359
+ maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight);
360
+ } else {
361
+ narrow = true;
362
+ maxWidth = Math.min(400 /* Info.Width */, (rtl ? list.right : space.right - list.left) - 30 /* Info.Margin */);
363
+ let spaceBelow = space.bottom - list.bottom;
364
+ if (spaceBelow >= infoHeight || spaceBelow > list.top) {
365
+ // Below the completion
366
+ offset = option.bottom - list.top;
367
+ } else {
368
+ // Above it
369
+ side = "bottom";
370
+ offset = list.bottom - option.top;
371
+ }
372
+ }
373
+ return {
374
+ style: `${side}: ${offset}px; max-width: ${maxWidth}px`,
375
+ class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left ? "left" : "right")
376
+ };
377
+ }
378
+
379
+ /**
380
+ Returns a command that moves the completion selection forward or
381
+ backward by the given amount.
382
+ */
383
+ function moveCompletionSelection(forward) {
384
+ let by = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "option";
385
+ return view => {
386
+ let cState = view.state.field(completionState, false);
387
+ if (!cState || !cState.open || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) return false;
388
+ let step = 1,
389
+ tooltip;
390
+ if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / tooltip.dom.querySelector("li").offsetHeight) - 1);
391
+ let {
392
+ length
393
+ } = cState.open.options;
394
+ let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
395
+ if (selected < 0) selected = by == "page" ? 0 : length - 1;else if (selected >= length) selected = by == "page" ? length - 1 : 0;
396
+ view.dispatch({
397
+ effects: setSelectedEffect.of(selected)
398
+ });
399
+ return true;
400
+ };
401
+ }
402
+ /**
403
+ Accept the current completion.
404
+ */
405
+ const acceptCompletion = view => {
406
+ let cState = view.state.field(completionState, false);
407
+ if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) return false;
408
+ if (!cState.open.disabled) return applyCompletion(view, cState.open.options[cState.open.selected]);
409
+ return true;
410
+ };
411
+ /**
412
+ Explicitly start autocompletion.
413
+ */
414
+ const startCompletion = view => {
415
+ let cState = view.state.field(completionState, false);
416
+ if (!cState) return false;
417
+ view.dispatch({
418
+ effects: startCompletionEffect.of(true)
419
+ });
420
+ return true;
421
+ };
422
+ /**
423
+ Close the currently active completion.
424
+ */
425
+ const closeCompletion = view => {
426
+ let cState = view.state.field(completionState, false);
427
+ if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */)) return false;
428
+ view.dispatch({
429
+ effects: closeCompletionEffect.of(null)
430
+ });
431
+ return true;
432
+ };
433
+ class RunningQuery {
434
+ constructor(active, context) {
435
+ this.active = active;
436
+ this.context = context;
437
+ this.time = Date.now();
438
+ this.updates = [];
439
+ // Note that 'undefined' means 'not done yet', whereas 'null' means
440
+ // 'query returned null'.
441
+ this.done = undefined;
442
+ }
443
+ }
444
+ const DebounceTime = 50,
445
+ MaxUpdateCount = 50,
446
+ MinAbortTime = 1000;
447
+ const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
448
+ constructor(view) {
449
+ this.view = view;
450
+ this.debounceUpdate = -1;
451
+ this.running = [];
452
+ this.debounceAccept = -1;
453
+ this.composing = 0 /* CompositionState.None */;
454
+ for (let active of view.state.field(completionState).active) if (active.state == 1 /* State.Pending */) this.startQuery(active);
455
+ }
456
+ update(update) {
457
+ let cState = update.state.field(completionState);
458
+ if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) return;
459
+ let doesReset = update.transactions.some(tr => {
460
+ return (tr.selection || tr.docChanged) && !getUserEvent(tr);
461
+ });
462
+ for (let i = 0; i < this.running.length; i++) {
463
+ let query = this.running[i];
464
+ if (doesReset || query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
465
+ for (let handler of query.context.abortListeners) {
466
+ try {
467
+ handler();
468
+ } catch (e) {
469
+ logException(this.view.state, e);
470
+ }
471
+ }
472
+ query.context.abortListeners = null;
473
+ this.running.splice(i--, 1);
474
+ } else {
475
+ query.updates.push(...update.transactions);
476
+ }
477
+ }
478
+ if (this.debounceUpdate > -1) clearTimeout(this.debounceUpdate);
479
+ this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source)) ? setTimeout(() => this.startUpdate(), DebounceTime) : -1;
480
+ if (this.composing != 0 /* CompositionState.None */) for (let tr of update.transactions) {
481
+ if (getUserEvent(tr) == "input") this.composing = 2 /* CompositionState.Changed */;else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection) this.composing = 3 /* CompositionState.ChangedAndMoved */;
482
+ }
483
+ }
484
+
485
+ startUpdate() {
486
+ this.debounceUpdate = -1;
487
+ let {
488
+ state
489
+ } = this.view,
490
+ cState = state.field(completionState);
491
+ for (let active of cState.active) {
492
+ if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source)) this.startQuery(active);
493
+ }
494
+ }
495
+ startQuery(active) {
496
+ let {
497
+ state
498
+ } = this.view,
499
+ pos = cur(state);
500
+ let context = new CompletionContext(state, pos, active.explicitPos == pos);
501
+ let pending = new RunningQuery(active, context);
502
+ this.running.push(pending);
503
+ Promise.resolve(active.source(context)).then(result => {
504
+ if (!pending.context.aborted) {
505
+ pending.done = result || null;
506
+ this.scheduleAccept();
507
+ }
508
+ }, err => {
509
+ this.view.dispatch({
510
+ effects: closeCompletionEffect.of(null)
511
+ });
512
+ logException(this.view.state, err);
513
+ });
514
+ }
515
+ scheduleAccept() {
516
+ if (this.running.every(q => q.done !== undefined)) this.accept();else if (this.debounceAccept < 0) this.debounceAccept = setTimeout(() => this.accept(), DebounceTime);
517
+ }
518
+ // For each finished query in this.running, try to create a result
519
+ // or, if appropriate, restart the query.
520
+ accept() {
521
+ var _a;
522
+ if (this.debounceAccept > -1) clearTimeout(this.debounceAccept);
523
+ this.debounceAccept = -1;
524
+ let updated = [];
525
+ let conf = this.view.state.facet(completionConfig);
526
+ for (let i = 0; i < this.running.length; i++) {
527
+ let query = this.running[i];
528
+ if (query.done === undefined) continue;
529
+ this.running.splice(i--, 1);
530
+ if (query.done) {
531
+ let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state));
532
+ // Replay the transactions that happened since the start of
533
+ // the request and see if that preserves the result
534
+ for (let tr of query.updates) active = active.update(tr, conf);
535
+ if (active.hasResult()) {
536
+ updated.push(active);
537
+ continue;
538
+ }
539
+ }
540
+ let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source);
541
+ if (current && current.state == 1 /* State.Pending */) {
542
+ if (query.done == null) {
543
+ // Explicitly failed. Should clear the pending status if it
544
+ // hasn't been re-set in the meantime.
545
+ let active = new ActiveSource(query.active.source, 0 /* State.Inactive */);
546
+ for (let tr of query.updates) active = active.update(tr, conf);
547
+ if (active.state != 1 /* State.Pending */) updated.push(active);
548
+ } else {
549
+ // Cleared by subsequent transactions. Restart.
550
+ this.startQuery(current);
551
+ }
552
+ }
553
+ }
554
+ if (updated.length) this.view.dispatch({
555
+ effects: setActiveEffect.of(updated)
556
+ });
557
+ }
558
+ }, {
559
+ eventHandlers: {
560
+ blur(event) {
561
+ let state = this.view.state.field(completionState, false);
562
+ if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
563
+ let dialog = state.open && getTooltip(this.view, state.open.tooltip);
564
+ if (!dialog || !dialog.dom.contains(event.relatedTarget)) this.view.dispatch({
565
+ effects: closeCompletionEffect.of(null)
566
+ });
567
+ }
568
+ },
569
+ compositionstart() {
570
+ this.composing = 1 /* CompositionState.Started */;
571
+ },
572
+
573
+ compositionend() {
574
+ if (this.composing == 3 /* CompositionState.ChangedAndMoved */) {
575
+ // Safari fires compositionend events synchronously, possibly
576
+ // from inside an update, so dispatch asynchronously to avoid reentrancy
577
+ setTimeout(() => this.view.dispatch({
578
+ effects: startCompletionEffect.of(false)
579
+ }), 20);
580
+ }
581
+ this.composing = 0 /* CompositionState.None */;
582
+ }
583
+ }
584
+ });
585
+
586
+ function applyCompletion(view, option) {
587
+ const apply = option.completion.apply || option.completion.label;
588
+ let result = view.state.field(completionState).active.find(a => a.source == option.source);
589
+ if (!(result instanceof ActiveResult)) return false;
590
+ if (typeof apply == "string") view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), {
591
+ annotations: pickedCompletion.of(option.completion)
592
+ }));else apply(view, option.completion, result.from, result.to);
593
+ return true;
594
+ }
595
+ function optionContent(config) {
596
+ let content = config.addToOptions.slice();
597
+ if (config.icons) content.push({
598
+ render(completion) {
599
+ let icon = document.createElement("div");
600
+ icon.classList.add("cm-completionIcon");
601
+ if (completion.type) icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
602
+ icon.setAttribute("aria-hidden", "true");
603
+ return icon;
604
+ },
605
+ position: 20
606
+ });
607
+ content.push({
608
+ render(completion, _s, match) {
609
+ let labelElt = document.createElement("span");
610
+ labelElt.className = "cm-completionLabel";
611
+ let {
612
+ label
613
+ } = completion,
614
+ off = 0;
615
+ for (let j = 1; j < match.length;) {
616
+ let from = match[j++],
617
+ to = match[j++];
618
+ if (from > off) labelElt.appendChild(document.createTextNode(label.slice(off, from)));
619
+ let span = labelElt.appendChild(document.createElement("span"));
620
+ span.appendChild(document.createTextNode(label.slice(from, to)));
621
+ span.className = "cm-completionMatchedText";
622
+ off = to;
623
+ }
624
+ if (off < label.length) labelElt.appendChild(document.createTextNode(label.slice(off)));
625
+ return labelElt;
626
+ },
627
+ position: 50
628
+ }, {
629
+ render(completion) {
630
+ if (!completion.detail) return null;
631
+ let detailElt = document.createElement("span");
632
+ detailElt.className = "cm-completionDetail";
633
+ detailElt.textContent = completion.detail;
634
+ return detailElt;
635
+ },
636
+ position: 80
637
+ });
638
+ return content.sort((a, b) => a.position - b.position).map(a => a.render);
639
+ }
640
+ function rangeAroundSelected(total, selected, max) {
641
+ if (total <= max) return {
642
+ from: 0,
643
+ to: total
644
+ };
645
+ if (selected < 0) selected = 0;
646
+ if (selected <= total >> 1) {
647
+ let off = Math.floor(selected / max);
648
+ return {
649
+ from: off * max,
650
+ to: (off + 1) * max
651
+ };
652
+ }
653
+ let off = Math.floor((total - selected) / max);
654
+ return {
655
+ from: total - (off + 1) * max,
656
+ to: total - off * max
657
+ };
658
+ }
659
+ class CompletionTooltip {
660
+ constructor(view, stateField) {
661
+ this.view = view;
662
+ this.stateField = stateField;
663
+ this.info = null;
664
+ this.placeInfoReq = {
665
+ read: () => this.measureInfo(),
666
+ write: pos => this.placeInfo(pos),
667
+ key: this
668
+ };
669
+ this.space = null;
670
+ this.currentClass = "";
671
+ let cState = view.state.field(stateField);
672
+ let {
673
+ options,
674
+ selected
675
+ } = cState.open;
676
+ let config = view.state.facet(completionConfig);
677
+ this.optionContent = optionContent(config);
678
+ this.optionClass = config.optionClass;
679
+ this.tooltipClass = config.tooltipClass;
680
+ this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
681
+ this.dom = document.createElement("div");
682
+ this.dom.className = "cm-tooltip-autocomplete";
683
+ this.updateTooltipClass(view.state);
684
+ this.dom.addEventListener("mousedown", e => {
685
+ for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
686
+ if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
687
+ applyCompletion(view, options[+match[1]]);
688
+ e.preventDefault();
689
+ return;
690
+ }
691
+ }
692
+ });
693
+ this.dom.addEventListener("focusout", e => {
694
+ let state = view.state.field(this.stateField, false);
695
+ if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur && e.relatedTarget != view.contentDOM) view.dispatch({
696
+ effects: closeCompletionEffect.of(null)
697
+ });
698
+ });
699
+ this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range));
700
+ this.list.addEventListener("scroll", () => {
701
+ if (this.info) this.view.requestMeasure(this.placeInfoReq);
702
+ });
703
+ }
704
+ mount() {
705
+ this.updateSel();
706
+ }
707
+ update(update) {
708
+ var _a, _b, _c;
709
+ let cState = update.state.field(this.stateField);
710
+ let prevState = update.startState.field(this.stateField);
711
+ this.updateTooltipClass(update.state);
712
+ if (cState != prevState) {
713
+ this.updateSel();
714
+ if (((_a = cState.open) === null || _a === void 0 ? void 0 : _a.disabled) != ((_b = prevState.open) === null || _b === void 0 ? void 0 : _b.disabled)) this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!((_c = cState.open) === null || _c === void 0 ? void 0 : _c.disabled));
715
+ }
716
+ }
717
+ updateTooltipClass(state) {
718
+ let cls = this.tooltipClass(state);
719
+ if (cls != this.currentClass) {
720
+ for (let c of this.currentClass.split(" ")) if (c) this.dom.classList.remove(c);
721
+ for (let c of cls.split(" ")) if (c) this.dom.classList.add(c);
722
+ this.currentClass = cls;
723
+ }
724
+ }
725
+ positioned(space) {
726
+ this.space = space;
727
+ if (this.info) this.view.requestMeasure(this.placeInfoReq);
728
+ }
729
+ updateSel() {
730
+ let cState = this.view.state.field(this.stateField),
731
+ open = cState.open;
732
+ if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
733
+ this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
734
+ this.list.remove();
735
+ this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range));
736
+ this.list.addEventListener("scroll", () => {
737
+ if (this.info) this.view.requestMeasure(this.placeInfoReq);
738
+ });
739
+ }
740
+ if (this.updateSelectedOption(open.selected)) {
741
+ if (this.info) {
742
+ this.info.remove();
743
+ this.info = null;
744
+ }
745
+ let {
746
+ completion
747
+ } = open.options[open.selected];
748
+ let {
749
+ info
750
+ } = completion;
751
+ if (!info) return;
752
+ let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion);
753
+ if (!infoResult) return;
754
+ if ('then' in infoResult) {
755
+ infoResult.then(node => {
756
+ if (node && this.view.state.field(this.stateField, false) == cState) this.addInfoPane(node);
757
+ }).catch(e => logException(this.view.state, e, "completion info"));
758
+ } else {
759
+ this.addInfoPane(infoResult);
760
+ }
761
+ }
762
+ }
763
+ addInfoPane(content) {
764
+ let dom = this.info = document.createElement("div");
765
+ dom.className = "cm-tooltip cm-completionInfo";
766
+ dom.appendChild(content);
767
+ this.dom.appendChild(dom);
768
+ this.view.requestMeasure(this.placeInfoReq);
769
+ }
770
+ updateSelectedOption(selected) {
771
+ let set = null;
772
+ for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
773
+ if (opt.nodeName != "LI" || !opt.id) {
774
+ i--; // A section header
775
+ } else if (i == selected) {
776
+ if (!opt.hasAttribute("aria-selected")) {
777
+ opt.setAttribute("aria-selected", "true");
778
+ set = opt;
779
+ }
780
+ } else {
781
+ if (opt.hasAttribute("aria-selected")) opt.removeAttribute("aria-selected");
782
+ }
783
+ }
784
+ if (set) scrollIntoView(this.list, set);
785
+ return set;
786
+ }
787
+ measureInfo() {
788
+ let sel = this.dom.querySelector("[aria-selected]");
789
+ if (!sel || !this.info) return null;
790
+ let listRect = this.dom.getBoundingClientRect();
791
+ let infoRect = this.info.getBoundingClientRect();
792
+ let selRect = sel.getBoundingClientRect();
793
+ let space = this.space;
794
+ if (!space) {
795
+ let win = this.dom.ownerDocument.defaultView || window;
796
+ space = {
797
+ left: 0,
798
+ top: 0,
799
+ right: win.innerWidth,
800
+ bottom: win.innerHeight
801
+ };
802
+ }
803
+ if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 || selRect.bottom < Math.max(space.top, listRect.top) + 10) return null;
804
+ return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space);
805
+ }
806
+ placeInfo(pos) {
807
+ if (this.info) {
808
+ if (pos) {
809
+ if (pos.style) this.info.style.cssText = pos.style;
810
+ this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
811
+ } else {
812
+ this.info.style.cssText = "top: -1e6px";
813
+ }
814
+ }
815
+ }
816
+ createListBox(options, id, range) {
817
+ const ul = document.createElement("ul");
818
+ ul.id = id;
819
+ ul.setAttribute("role", "listbox");
820
+ ul.setAttribute("aria-expanded", "true");
821
+ ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
822
+ let curSection = null;
823
+ for (let i = range.from; i < range.to; i++) {
824
+ let {
825
+ completion,
826
+ match
827
+ } = options[i],
828
+ {
829
+ section
830
+ } = completion;
831
+ if (section) {
832
+ let name = typeof section == "string" ? section : section.name;
833
+ if (name != curSection && (i > range.from || range.from == 0)) {
834
+ curSection = name;
835
+ if (typeof section != "string" && section.header) {
836
+ ul.appendChild(section.header(section));
837
+ } else {
838
+ let header = ul.appendChild(document.createElement("completion-section"));
839
+ header.textContent = name;
840
+ }
841
+ }
842
+ }
843
+ const li = ul.appendChild(document.createElement("li"));
844
+ li.id = id + "-" + i;
845
+ li.setAttribute("role", "option");
846
+ let cls = this.optionClass(completion);
847
+ if (cls) li.className = cls;
848
+ for (let source of this.optionContent) {
849
+ let node = source(completion, this.view.state, match);
850
+ if (node) li.appendChild(node);
851
+ }
852
+ }
853
+ if (range.from) ul.classList.add("cm-completionListIncompleteTop");
854
+ if (range.to < options.length) ul.classList.add("cm-completionListIncompleteBottom");
855
+ return ul;
856
+ }
857
+ }
858
+ // We allocate a new function instance every time the completion
859
+ // changes to force redrawing/repositioning of the tooltip
860
+ function completionTooltip(stateField) {
861
+ return view => new CompletionTooltip(view, stateField);
862
+ }
863
+ function scrollIntoView(container, element) {
864
+ let parent = container.getBoundingClientRect();
865
+ let self = element.getBoundingClientRect();
866
+ if (self.top < parent.top) container.scrollTop -= parent.top - self.top;else if (self.bottom > parent.bottom) container.scrollTop += self.bottom - parent.bottom;
867
+ }
868
+
869
+ // Used to pick a preferred option when two options with the same
870
+ // label occur in the result.
871
+ function score(option) {
872
+ return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
873
+ }
874
+ function sortOptions(active, state) {
875
+ let options = [];
876
+ let sections = null;
877
+ let addOption = option => {
878
+ options.push(option);
879
+ let {
880
+ section
881
+ } = option.completion;
882
+ if (section) {
883
+ if (!sections) sections = [];
884
+ let name = typeof section == "string" ? section : section.name;
885
+ if (!sections.some(s => s.name == name)) sections.push(typeof section == "string" ? {
886
+ name
887
+ } : section);
888
+ }
889
+ };
890
+ for (let a of active) if (a.hasResult()) {
891
+ if (a.result.filter === false) {
892
+ let getMatch = a.result.getMatch;
893
+ for (let option of a.result.options) {
894
+ let match = [1e9 - options.length];
895
+ if (getMatch) for (let n of getMatch(option)) match.push(n);
896
+ addOption(new Option(option, a.source, match, match[0]));
897
+ }
898
+ } else {
899
+ let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)),
900
+ match;
901
+ for (let option of a.result.options) if (match = matcher.match(option.label)) {
902
+ addOption(new Option(option, a.source, match, match[0] + (option.boost || 0)));
903
+ }
904
+ }
905
+ }
906
+ if (sections) {
907
+ let sectionOrder = Object.create(null),
908
+ pos = 0;
909
+ let cmp = (a, b) => {
910
+ var _a, _b;
911
+ return ((_a = a.rank) !== null && _a !== void 0 ? _a : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1);
912
+ };
913
+ for (let s of sections.sort(cmp)) {
914
+ pos -= 1e5;
915
+ sectionOrder[s.name] = pos;
916
+ }
917
+ for (let option of options) {
918
+ let {
919
+ section
920
+ } = option.completion;
921
+ if (section) option.score += sectionOrder[typeof section == "string" ? section : section.name];
922
+ }
923
+ }
924
+ let result = [],
925
+ prev = null;
926
+ let compare = state.facet(completionConfig).compareCompletions;
927
+ for (let opt of options.sort((a, b) => b.score - a.score || compare(a.completion, b.completion))) {
928
+ if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail || prev.type != null && opt.completion.type != null && prev.type != opt.completion.type || prev.apply != opt.completion.apply) result.push(opt);else if (score(opt.completion) > score(prev)) result[result.length - 1] = opt;
929
+ prev = opt.completion;
930
+ }
931
+ return result;
932
+ }
933
+ class CompletionDialog {
934
+ constructor(options, attrs, tooltip, timestamp, selected, disabled) {
935
+ this.options = options;
936
+ this.attrs = attrs;
937
+ this.tooltip = tooltip;
938
+ this.timestamp = timestamp;
939
+ this.selected = selected;
940
+ this.disabled = disabled;
941
+ }
942
+ setSelected(selected, id) {
943
+ return selected == this.selected || selected >= this.options.length ? this : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
944
+ }
945
+ static build(active, state, id, prev, conf) {
946
+ let options = sortOptions(active, state);
947
+ if (!options.length) {
948
+ return prev && active.some(a => a.state == 1 /* State.Pending */) ? new CompletionDialog(prev.options, prev.attrs, prev.tooltip, prev.timestamp, prev.selected, true) : null;
949
+ }
950
+ let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
951
+ if (prev && prev.selected != selected && prev.selected != -1) {
952
+ let selectedValue = prev.options[prev.selected].completion;
953
+ for (let i = 0; i < options.length; i++) if (options[i].completion == selectedValue) {
954
+ selected = i;
955
+ break;
956
+ }
957
+ }
958
+ return new CompletionDialog(options, makeAttrs(id, selected), {
959
+ pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
960
+ create: completionTooltip(completionState),
961
+ above: conf.aboveCursor
962
+ }, prev ? prev.timestamp : Date.now(), selected, false);
963
+ }
964
+ map(changes) {
965
+ return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), {
966
+ pos: changes.mapPos(this.tooltip.pos)
967
+ }), this.timestamp, this.selected, this.disabled);
968
+ }
969
+ }
970
+ class CompletionState {
971
+ constructor(active, id, open) {
972
+ this.active = active;
973
+ this.id = id;
974
+ this.open = open;
975
+ }
976
+ static start() {
977
+ return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
978
+ }
979
+ update(tr) {
980
+ let {
981
+ state
982
+ } = tr,
983
+ conf = state.facet(completionConfig);
984
+ let sources = conf.override || state.languageDataAt("autocomplete", cur(state)).map(asSource);
985
+ let active = sources.map(source => {
986
+ let value = this.active.find(s => s.source == source) || new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */);
987
+ return value.update(tr, conf);
988
+ });
989
+ if (active.length == this.active.length && active.every((a, i) => a == this.active[i])) active = this.active;
990
+ let open = this.open;
991
+ if (open && tr.docChanged) open = open.map(tr.changes);
992
+ if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active)) open = CompletionDialog.build(active, state, this.id, open, conf);else if (open && open.disabled && !active.some(a => a.state == 1 /* State.Pending */)) open = null;
993
+ if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult())) active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a);
994
+ for (let effect of tr.effects) if (effect.is(setSelectedEffect)) open = open && open.setSelected(effect.value, this.id);
995
+ return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
996
+ }
997
+ get tooltip() {
998
+ return this.open ? this.open.tooltip : null;
999
+ }
1000
+ get attrs() {
1001
+ return this.open ? this.open.attrs : baseAttrs;
1002
+ }
1003
+ }
1004
+ function sameResults(a, b) {
1005
+ if (a == b) return true;
1006
+ for (let iA = 0, iB = 0;;) {
1007
+ while (iA < a.length && !a[iA].hasResult) iA++;
1008
+ while (iB < b.length && !b[iB].hasResult) iB++;
1009
+ let endA = iA == a.length,
1010
+ endB = iB == b.length;
1011
+ if (endA || endB) return endA == endB;
1012
+ if (a[iA++].result != b[iB++].result) return false;
1013
+ }
1014
+ }
1015
+ const baseAttrs = {
1016
+ "aria-autocomplete": "list"
1017
+ };
1018
+ function makeAttrs(id, selected) {
1019
+ let result = {
1020
+ "aria-autocomplete": "list",
1021
+ "aria-haspopup": "listbox",
1022
+ "aria-controls": id
1023
+ };
1024
+ if (selected > -1) result["aria-activedescendant"] = id + "-" + selected;
1025
+ return result;
1026
+ }
1027
+ const none = [];
1028
+ function getUserEvent(tr) {
1029
+ return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
1030
+ }
1031
+ class ActiveSource {
1032
+ constructor(source, state) {
1033
+ let explicitPos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
1034
+ this.source = source;
1035
+ this.state = state;
1036
+ this.explicitPos = explicitPos;
1037
+ }
1038
+ hasResult() {
1039
+ return false;
1040
+ }
1041
+ update(tr, conf) {
1042
+ let event = getUserEvent(tr),
1043
+ value = this;
1044
+ if (event) value = value.handleUserEvent(tr, event, conf);else if (tr.docChanged) value = value.handleChange(tr);else if (tr.selection && value.state != 0 /* State.Inactive */) value = new ActiveSource(value.source, 0 /* State.Inactive */);
1045
+ for (let effect of tr.effects) {
1046
+ if (effect.is(startCompletionEffect)) value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1);else if (effect.is(closeCompletionEffect)) value = new ActiveSource(value.source, 0 /* State.Inactive */);else if (effect.is(setActiveEffect)) for (let active of effect.value) if (active.source == value.source) value = active;
1047
+ }
1048
+ return value;
1049
+ }
1050
+ handleUserEvent(tr, type, conf) {
1051
+ return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */);
1052
+ }
1053
+
1054
+ handleChange(tr) {
1055
+ return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);
1056
+ }
1057
+ map(changes) {
1058
+ return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));
1059
+ }
1060
+ }
1061
+ class ActiveResult extends ActiveSource {
1062
+ constructor(source, explicitPos, result, from, to) {
1063
+ super(source, 2 /* State.Result */, explicitPos);
1064
+ this.result = result;
1065
+ this.from = from;
1066
+ this.to = to;
1067
+ }
1068
+ hasResult() {
1069
+ return true;
1070
+ }
1071
+ handleUserEvent(tr, type, conf) {
1072
+ var _a;
1073
+ let from = tr.changes.mapPos(this.from),
1074
+ to = tr.changes.mapPos(this.to, 1);
1075
+ let pos = cur(tr.state);
1076
+ if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || pos > to || type == "delete" && cur(tr.startState) == this.from) return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */);
1077
+ let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos),
1078
+ updated;
1079
+ if (checkValid(this.result.validFor, tr.state, from, to)) return new ActiveResult(this.source, explicitPos, this.result, from, to);
1080
+ if (this.result.update && (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0)))) return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state));
1081
+ return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos);
1082
+ }
1083
+ handleChange(tr) {
1084
+ return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);
1085
+ }
1086
+ map(mapping) {
1087
+ return mapping.empty ? this : new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
1088
+ }
1089
+ }
1090
+ function checkValid(validFor, state, from, to) {
1091
+ if (!validFor) return false;
1092
+ let text = state.sliceDoc(from, to);
1093
+ return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
1094
+ }
1095
+ const setActiveEffect = /*@__PURE__*/StateEffect.define({
1096
+ map(sources, mapping) {
1097
+ return sources.map(s => s.map(mapping));
1098
+ }
1099
+ });
1100
+ const setSelectedEffect = /*@__PURE__*/StateEffect.define();
1101
+ const completionState = /*@__PURE__*/StateField.define({
1102
+ create() {
1103
+ return CompletionState.start();
1104
+ },
1105
+ update(value, tr) {
1106
+ return value.update(tr);
1107
+ },
1108
+ provide: f => [showTooltip.from(f, val => val.tooltip), EditorView.contentAttributes.from(f, state => state.attrs)]
1109
+ });
1110
+ const baseTheme = /*@__PURE__*/EditorView.baseTheme({
1111
+ ".cm-tooltip.cm-tooltip-autocomplete": {
1112
+ "& > ul": {
1113
+ fontFamily: "monospace",
1114
+ whiteSpace: "nowrap",
1115
+ overflow: "hidden auto",
1116
+ maxWidth_fallback: "700px",
1117
+ maxWidth: "min(700px, 95vw)",
1118
+ minWidth: "250px",
1119
+ maxHeight: "10em",
1120
+ height: "100%",
1121
+ listStyle: "none",
1122
+ margin: 0,
1123
+ padding: 0,
1124
+ "& > li, & > completion-section": {
1125
+ padding: "1px 3px",
1126
+ lineHeight: 1.2
1127
+ },
1128
+ "& > li": {
1129
+ overflowX: "hidden",
1130
+ textOverflow: "ellipsis",
1131
+ cursor: "pointer"
1132
+ },
1133
+ "& > completion-section": {
1134
+ display: "list-item",
1135
+ borderBottom: "1px solid silver",
1136
+ paddingLeft: "0.5em",
1137
+ opacity: 0.7
1138
+ }
1139
+ }
1140
+ },
1141
+ "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
1142
+ background: "#17c",
1143
+ color: "white"
1144
+ },
1145
+ "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
1146
+ background: "#777"
1147
+ },
1148
+ "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
1149
+ background: "#347",
1150
+ color: "white"
1151
+ },
1152
+ "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
1153
+ background: "#444"
1154
+ },
1155
+ ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
1156
+ content: '"···"',
1157
+ opacity: 0.5,
1158
+ display: "block",
1159
+ textAlign: "center"
1160
+ },
1161
+ ".cm-tooltip.cm-completionInfo": {
1162
+ position: "absolute",
1163
+ padding: "3px 9px",
1164
+ width: "max-content",
1165
+ maxWidth: `${400 /* Info.Width */}px`,
1166
+ boxSizing: "border-box"
1167
+ },
1168
+ ".cm-completionInfo.cm-completionInfo-left": {
1169
+ right: "100%"
1170
+ },
1171
+ ".cm-completionInfo.cm-completionInfo-right": {
1172
+ left: "100%"
1173
+ },
1174
+ ".cm-completionInfo.cm-completionInfo-left-narrow": {
1175
+ right: `${30 /* Info.Margin */}px`
1176
+ },
1177
+ ".cm-completionInfo.cm-completionInfo-right-narrow": {
1178
+ left: `${30 /* Info.Margin */}px`
1179
+ },
1180
+ "&light .cm-snippetField": {
1181
+ backgroundColor: "#00000022"
1182
+ },
1183
+ "&dark .cm-snippetField": {
1184
+ backgroundColor: "#ffffff22"
1185
+ },
1186
+ ".cm-snippetFieldPosition": {
1187
+ verticalAlign: "text-top",
1188
+ width: 0,
1189
+ height: "1.15em",
1190
+ display: "inline-block",
1191
+ margin: "0 -0.7px -.7em",
1192
+ borderLeft: "1.4px dotted #888"
1193
+ },
1194
+ ".cm-completionMatchedText": {
1195
+ textDecoration: "underline"
1196
+ },
1197
+ ".cm-completionDetail": {
1198
+ marginLeft: "0.5em",
1199
+ fontStyle: "italic"
1200
+ },
1201
+ ".cm-completionIcon": {
1202
+ fontSize: "90%",
1203
+ width: ".8em",
1204
+ display: "inline-block",
1205
+ textAlign: "center",
1206
+ paddingRight: ".6em",
1207
+ opacity: "0.6",
1208
+ boxSizing: "content-box"
1209
+ },
1210
+ ".cm-completionIcon-function, .cm-completionIcon-method": {
1211
+ "&:after": {
1212
+ content: "'ƒ'"
1213
+ }
1214
+ },
1215
+ ".cm-completionIcon-class": {
1216
+ "&:after": {
1217
+ content: "'○'"
1218
+ }
1219
+ },
1220
+ ".cm-completionIcon-interface": {
1221
+ "&:after": {
1222
+ content: "'◌'"
1223
+ }
1224
+ },
1225
+ ".cm-completionIcon-variable": {
1226
+ "&:after": {
1227
+ content: "'𝑥'"
1228
+ }
1229
+ },
1230
+ ".cm-completionIcon-constant": {
1231
+ "&:after": {
1232
+ content: "'𝐶'"
1233
+ }
1234
+ },
1235
+ ".cm-completionIcon-type": {
1236
+ "&:after": {
1237
+ content: "'𝑡'"
1238
+ }
1239
+ },
1240
+ ".cm-completionIcon-enum": {
1241
+ "&:after": {
1242
+ content: "'∪'"
1243
+ }
1244
+ },
1245
+ ".cm-completionIcon-property": {
1246
+ "&:after": {
1247
+ content: "'□'"
1248
+ }
1249
+ },
1250
+ ".cm-completionIcon-keyword": {
1251
+ "&:after": {
1252
+ content: "'🔑\uFE0E'"
1253
+ } // Disable emoji rendering
1254
+ },
1255
+
1256
+ ".cm-completionIcon-namespace": {
1257
+ "&:after": {
1258
+ content: "'▢'"
1259
+ }
1260
+ },
1261
+ ".cm-completionIcon-text": {
1262
+ "&:after": {
1263
+ content: "'abc'",
1264
+ fontSize: "50%",
1265
+ verticalAlign: "middle"
1266
+ }
1267
+ }
1268
+ });
1269
+ class FieldPos {
1270
+ constructor(field, line, from, to) {
1271
+ this.field = field;
1272
+ this.line = line;
1273
+ this.from = from;
1274
+ this.to = to;
1275
+ }
1276
+ }
1277
+ class FieldRange {
1278
+ constructor(field, from, to) {
1279
+ this.field = field;
1280
+ this.from = from;
1281
+ this.to = to;
1282
+ }
1283
+ map(changes) {
1284
+ let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
1285
+ let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
1286
+ return from == null || to == null ? null : new FieldRange(this.field, from, to);
1287
+ }
1288
+ }
1289
+ class Snippet {
1290
+ constructor(lines, fieldPositions) {
1291
+ this.lines = lines;
1292
+ this.fieldPositions = fieldPositions;
1293
+ }
1294
+ instantiate(state, pos) {
1295
+ let text = [],
1296
+ lineStart = [pos];
1297
+ let lineObj = state.doc.lineAt(pos),
1298
+ baseIndent = /^\s*/.exec(lineObj.text)[0];
1299
+ for (let line of this.lines) {
1300
+ if (text.length) {
1301
+ let indent = baseIndent,
1302
+ tabs = /^\t*/.exec(line)[0].length;
1303
+ for (let i = 0; i < tabs; i++) indent += state.facet(indentUnit);
1304
+ lineStart.push(pos + indent.length - tabs);
1305
+ line = indent + line.slice(tabs);
1306
+ }
1307
+ text.push(line);
1308
+ pos += line.length + 1;
1309
+ }
1310
+ let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
1311
+ return {
1312
+ text,
1313
+ ranges
1314
+ };
1315
+ }
1316
+ static parse(template) {
1317
+ let fields = [];
1318
+ let lines = [],
1319
+ positions = [],
1320
+ m;
1321
+ for (let line of template.split(/\r\n?|\n/)) {
1322
+ while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
1323
+ let seq = m[1] ? +m[1] : null,
1324
+ name = m[2] || m[3] || "",
1325
+ found = -1;
1326
+ for (let i = 0; i < fields.length; i++) {
1327
+ if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false) found = i;
1328
+ }
1329
+ if (found < 0) {
1330
+ let i = 0;
1331
+ while (i < fields.length && (seq == null || fields[i].seq != null && fields[i].seq < seq)) i++;
1332
+ fields.splice(i, 0, {
1333
+ seq,
1334
+ name
1335
+ });
1336
+ found = i;
1337
+ for (let pos of positions) if (pos.field >= found) pos.field++;
1338
+ }
1339
+ positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
1340
+ line = line.slice(0, m.index) + name + line.slice(m.index + m[0].length);
1341
+ }
1342
+ for (let esc; esc = /\\([{}])/.exec(line);) {
1343
+ line = line.slice(0, esc.index) + esc[1] + line.slice(esc.index + esc[0].length);
1344
+ for (let pos of positions) if (pos.line == lines.length && pos.from > esc.index) {
1345
+ pos.from--;
1346
+ pos.to--;
1347
+ }
1348
+ }
1349
+ lines.push(line);
1350
+ }
1351
+ return new Snippet(lines, positions);
1352
+ }
1353
+ }
1354
+ let fieldMarker = /*@__PURE__*/Decoration.widget({
1355
+ widget: /*@__PURE__*/new class extends WidgetType {
1356
+ toDOM() {
1357
+ let span = document.createElement("span");
1358
+ span.className = "cm-snippetFieldPosition";
1359
+ return span;
1360
+ }
1361
+ ignoreEvent() {
1362
+ return false;
1363
+ }
1364
+ }()
1365
+ });
1366
+ let fieldRange = /*@__PURE__*/Decoration.mark({
1367
+ class: "cm-snippetField"
1368
+ });
1369
+ class ActiveSnippet {
1370
+ constructor(ranges, active) {
1371
+ this.ranges = ranges;
1372
+ this.active = active;
1373
+ this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
1374
+ }
1375
+ map(changes) {
1376
+ let ranges = [];
1377
+ for (let r of this.ranges) {
1378
+ let mapped = r.map(changes);
1379
+ if (!mapped) return null;
1380
+ ranges.push(mapped);
1381
+ }
1382
+ return new ActiveSnippet(ranges, this.active);
1383
+ }
1384
+ selectionInsideField(sel) {
1385
+ return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
1386
+ }
1387
+ }
1388
+ const setActive = /*@__PURE__*/StateEffect.define({
1389
+ map(value, changes) {
1390
+ return value && value.map(changes);
1391
+ }
1392
+ });
1393
+ const moveToField = /*@__PURE__*/StateEffect.define();
1394
+ const snippetState = /*@__PURE__*/StateField.define({
1395
+ create() {
1396
+ return null;
1397
+ },
1398
+ update(value, tr) {
1399
+ for (let effect of tr.effects) {
1400
+ if (effect.is(setActive)) return effect.value;
1401
+ if (effect.is(moveToField) && value) return new ActiveSnippet(value.ranges, effect.value);
1402
+ }
1403
+ if (value && tr.docChanged) value = value.map(tr.changes);
1404
+ if (value && tr.selection && !value.selectionInsideField(tr.selection)) value = null;
1405
+ return value;
1406
+ },
1407
+ provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)
1408
+ });
1409
+ function fieldSelection(ranges, field) {
1410
+ return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
1411
+ }
1412
+ /**
1413
+ Convert a snippet template to a function that can
1414
+ [apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
1415
+ using syntax like this:
1416
+
1417
+ "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
1418
+
1419
+ Each `${}` placeholder (you may also use `#{}`) indicates a field
1420
+ that the user can fill in. Its name, if any, will be the default
1421
+ content for the field.
1422
+
1423
+ When the snippet is activated by calling the returned function,
1424
+ the code is inserted at the given position. Newlines in the
1425
+ template are indented by the indentation of the start line, plus
1426
+ one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
1427
+ the newline.
1428
+
1429
+ On activation, (all instances of) the first field are selected.
1430
+ The user can move between fields with Tab and Shift-Tab as long as
1431
+ the fields are active. Moving to the last field or moving the
1432
+ cursor out of the current field deactivates the fields.
1433
+
1434
+ The order of fields defaults to textual order, but you can add
1435
+ numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
1436
+ a custom order.
1437
+
1438
+ To include a literal `{` or `}` in your template, put a backslash
1439
+ in front of it. This will be removed and the brace will not be
1440
+ interpreted as indicating a placeholder.
1441
+ */
1442
+ function snippet(template) {
1443
+ let snippet = Snippet.parse(template);
1444
+ return (editor, completion, from, to) => {
1445
+ let {
1446
+ text,
1447
+ ranges
1448
+ } = snippet.instantiate(editor.state, from);
1449
+ let spec = {
1450
+ changes: {
1451
+ from,
1452
+ to,
1453
+ insert: Text.of(text)
1454
+ },
1455
+ scrollIntoView: true,
1456
+ annotations: completion ? pickedCompletion.of(completion) : undefined
1457
+ };
1458
+ if (ranges.length) spec.selection = fieldSelection(ranges, 0);
1459
+ if (ranges.length > 1) {
1460
+ let active = new ActiveSnippet(ranges, 0);
1461
+ let effects = spec.effects = [setActive.of(active)];
1462
+ if (editor.state.field(snippetState, false) === undefined) effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
1463
+ }
1464
+ editor.dispatch(editor.state.update(spec));
1465
+ };
1466
+ }
1467
+ function moveField(dir) {
1468
+ return _ref => {
1469
+ let {
1470
+ state,
1471
+ dispatch
1472
+ } = _ref;
1473
+ let active = state.field(snippetState, false);
1474
+ if (!active || dir < 0 && active.active == 0) return false;
1475
+ let next = active.active + dir,
1476
+ last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
1477
+ dispatch(state.update({
1478
+ selection: fieldSelection(active.ranges, next),
1479
+ effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next))
1480
+ }));
1481
+ return true;
1482
+ };
1483
+ }
1484
+ /**
1485
+ A command that clears the active snippet, if any.
1486
+ */
1487
+ const clearSnippet = _ref2 => {
1488
+ let {
1489
+ state,
1490
+ dispatch
1491
+ } = _ref2;
1492
+ let active = state.field(snippetState, false);
1493
+ if (!active) return false;
1494
+ dispatch(state.update({
1495
+ effects: setActive.of(null)
1496
+ }));
1497
+ return true;
1498
+ };
1499
+ /**
1500
+ Move to the next snippet field, if available.
1501
+ */
1502
+ const nextSnippetField = /*@__PURE__*/moveField(1);
1503
+ /**
1504
+ Move to the previous snippet field, if available.
1505
+ */
1506
+ const prevSnippetField = /*@__PURE__*/moveField(-1);
1507
+ const defaultSnippetKeymap = [{
1508
+ key: "Tab",
1509
+ run: nextSnippetField,
1510
+ shift: prevSnippetField
1511
+ }, {
1512
+ key: "Escape",
1513
+ run: clearSnippet
1514
+ }];
1515
+ /**
1516
+ A facet that can be used to configure the key bindings used by
1517
+ snippets. The default binds Tab to
1518
+ [`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
1519
+ [`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
1520
+ to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
1521
+ */
1522
+ const snippetKeymap = /*@__PURE__*/Facet.define({
1523
+ combine(maps) {
1524
+ return maps.length ? maps[0] : defaultSnippetKeymap;
1525
+ }
1526
+ });
1527
+ const addSnippetKeymap = /*@__PURE__*/Prec.highest( /*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
1528
+ /**
1529
+ Create a completion from a snippet. Returns an object with the
1530
+ properties from `completion`, plus an `apply` function that
1531
+ applies the snippet.
1532
+ */
1533
+ function snippetCompletion(template, completion) {
1534
+ return Object.assign(Object.assign({}, completion), {
1535
+ apply: snippet(template)
1536
+ });
1537
+ }
1538
+ const snippetPointerHandler = /*@__PURE__*/EditorView.domEventHandlers({
1539
+ mousedown(event, view) {
1540
+ let active = view.state.field(snippetState, false),
1541
+ pos;
1542
+ if (!active || (pos = view.posAtCoords({
1543
+ x: event.clientX,
1544
+ y: event.clientY
1545
+ })) == null) return false;
1546
+ let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
1547
+ if (!match || match.field == active.active) return false;
1548
+ view.dispatch({
1549
+ selection: fieldSelection(active.ranges, match.field),
1550
+ effects: setActive.of(active.ranges.some(r => r.field > match.field) ? new ActiveSnippet(active.ranges, match.field) : null)
1551
+ });
1552
+ return true;
1553
+ }
1554
+ });
1555
+ const defaults = {
1556
+ brackets: ["(", "[", "{", "'", '"'],
1557
+ before: ")]}:;>",
1558
+ stringPrefixes: []
1559
+ };
1560
+ const closeBracketEffect = /*@__PURE__*/StateEffect.define({
1561
+ map(value, mapping) {
1562
+ let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
1563
+ return mapped == null ? undefined : mapped;
1564
+ }
1565
+ });
1566
+ const closedBracket = /*@__PURE__*/new class extends RangeValue {}();
1567
+ closedBracket.startSide = 1;
1568
+ closedBracket.endSide = -1;
1569
+ const bracketState = /*@__PURE__*/StateField.define({
1570
+ create() {
1571
+ return RangeSet.empty;
1572
+ },
1573
+ update(value, tr) {
1574
+ if (tr.selection) {
1575
+ let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from;
1576
+ let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from;
1577
+ if (lineStart != tr.changes.mapPos(prevLineStart, -1)) value = RangeSet.empty;
1578
+ }
1579
+ value = value.map(tr.changes);
1580
+ for (let effect of tr.effects) if (effect.is(closeBracketEffect)) value = value.update({
1581
+ add: [closedBracket.range(effect.value, effect.value + 1)]
1582
+ });
1583
+ return value;
1584
+ }
1585
+ });
1586
+ /**
1587
+ Extension to enable bracket-closing behavior. When a closeable
1588
+ bracket is typed, its closing bracket is immediately inserted
1589
+ after the cursor. When closing a bracket directly in front of a
1590
+ closing bracket inserted by the extension, the cursor moves over
1591
+ that bracket.
1592
+ */
1593
+ function closeBrackets() {
1594
+ return [inputHandler, bracketState];
1595
+ }
1596
+ const definedClosing = "()[]{}<>";
1597
+ function closing(ch) {
1598
+ for (let i = 0; i < definedClosing.length; i += 2) if (definedClosing.charCodeAt(i) == ch) return definedClosing.charAt(i + 1);
1599
+ return fromCodePoint(ch < 128 ? ch : ch + 1);
1600
+ }
1601
+ function config(state, pos) {
1602
+ return state.languageDataAt("closeBrackets", pos)[0] || defaults;
1603
+ }
1604
+ const android = typeof navigator == "object" && /*@__PURE__*/ /Android\b/.test(navigator.userAgent);
1605
+ const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => {
1606
+ if ((android ? view.composing : view.compositionStarted) || view.state.readOnly) return false;
1607
+ let sel = view.state.selection.main;
1608
+ if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 || from != sel.from || to != sel.to) return false;
1609
+ let tr = insertBracket(view.state, insert);
1610
+ if (!tr) return false;
1611
+ view.dispatch(tr);
1612
+ return true;
1613
+ });
1614
+ /**
1615
+ Command that implements deleting a pair of matching brackets when
1616
+ the cursor is between them.
1617
+ */
1618
+ const deleteBracketPair = _ref3 => {
1619
+ let {
1620
+ state,
1621
+ dispatch
1622
+ } = _ref3;
1623
+ if (state.readOnly) return false;
1624
+ let conf = config(state, state.selection.main.head);
1625
+ let tokens = conf.brackets || defaults.brackets;
1626
+ let dont = null,
1627
+ changes = state.changeByRange(range => {
1628
+ if (range.empty) {
1629
+ let before = prevChar(state.doc, range.head);
1630
+ for (let token of tokens) {
1631
+ if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) return {
1632
+ changes: {
1633
+ from: range.head - token.length,
1634
+ to: range.head + token.length
1635
+ },
1636
+ range: EditorSelection.cursor(range.head - token.length)
1637
+ };
1638
+ }
1639
+ }
1640
+ return {
1641
+ range: dont = range
1642
+ };
1643
+ });
1644
+ if (!dont) dispatch(state.update(changes, {
1645
+ scrollIntoView: true,
1646
+ userEvent: "delete.backward"
1647
+ }));
1648
+ return !dont;
1649
+ };
1650
+ /**
1651
+ Close-brackets related key bindings. Binds Backspace to
1652
+ [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
1653
+ */
1654
+ const closeBracketsKeymap = [{
1655
+ key: "Backspace",
1656
+ run: deleteBracketPair
1657
+ }];
1658
+ /**
1659
+ Implements the extension's behavior on text insertion. If the
1660
+ given string counts as a bracket in the language around the
1661
+ selection, and replacing the selection with it requires custom
1662
+ behavior (inserting a closing version or skipping past a
1663
+ previously-closed bracket), this function returns a transaction
1664
+ representing that custom behavior. (You only need this if you want
1665
+ to programmatically insert brackets—the
1666
+ [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
1667
+ take care of running this for user input.)
1668
+ */
1669
+ function insertBracket(state, bracket) {
1670
+ let conf = config(state, state.selection.main.head);
1671
+ let tokens = conf.brackets || defaults.brackets;
1672
+ for (let tok of tokens) {
1673
+ let closed = closing(codePointAt(tok, 0));
1674
+ if (bracket == tok) return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state, tok, closed, conf.before || defaults.before);
1675
+ if (bracket == closed && closedBracketAt(state, state.selection.main.from)) return handleClose(state, tok, closed);
1676
+ }
1677
+ return null;
1678
+ }
1679
+ function closedBracketAt(state, pos) {
1680
+ let found = false;
1681
+ state.field(bracketState).between(0, state.doc.length, from => {
1682
+ if (from == pos) found = true;
1683
+ });
1684
+ return found;
1685
+ }
1686
+ function nextChar(doc, pos) {
1687
+ let next = doc.sliceString(pos, pos + 2);
1688
+ return next.slice(0, codePointSize(codePointAt(next, 0)));
1689
+ }
1690
+ function prevChar(doc, pos) {
1691
+ let prev = doc.sliceString(pos - 2, pos);
1692
+ return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
1693
+ }
1694
+ function handleOpen(state, open, close, closeBefore) {
1695
+ let dont = null,
1696
+ changes = state.changeByRange(range => {
1697
+ if (!range.empty) return {
1698
+ changes: [{
1699
+ insert: open,
1700
+ from: range.from
1701
+ }, {
1702
+ insert: close,
1703
+ from: range.to
1704
+ }],
1705
+ effects: closeBracketEffect.of(range.to + open.length),
1706
+ range: EditorSelection.range(range.anchor + open.length, range.head + open.length)
1707
+ };
1708
+ let next = nextChar(state.doc, range.head);
1709
+ if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) return {
1710
+ changes: {
1711
+ insert: open + close,
1712
+ from: range.head
1713
+ },
1714
+ effects: closeBracketEffect.of(range.head + open.length),
1715
+ range: EditorSelection.cursor(range.head + open.length)
1716
+ };
1717
+ return {
1718
+ range: dont = range
1719
+ };
1720
+ });
1721
+ return dont ? null : state.update(changes, {
1722
+ scrollIntoView: true,
1723
+ userEvent: "input.type"
1724
+ });
1725
+ }
1726
+ function handleClose(state, _open, close) {
1727
+ let dont = null,
1728
+ changes = state.changeByRange(range => {
1729
+ if (range.empty && nextChar(state.doc, range.head) == close) return {
1730
+ changes: {
1731
+ from: range.head,
1732
+ to: range.head + close.length,
1733
+ insert: close
1734
+ },
1735
+ range: EditorSelection.cursor(range.head + close.length)
1736
+ };
1737
+ return dont = {
1738
+ range
1739
+ };
1740
+ });
1741
+ return dont ? null : state.update(changes, {
1742
+ scrollIntoView: true,
1743
+ userEvent: "input.type"
1744
+ });
1745
+ }
1746
+ // Handles cases where the open and close token are the same, and
1747
+ // possibly triple quotes (as in `"""abc"""`-style quoting).
1748
+ function handleSame(state, token, allowTriple, config) {
1749
+ let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
1750
+ let dont = null,
1751
+ changes = state.changeByRange(range => {
1752
+ if (!range.empty) return {
1753
+ changes: [{
1754
+ insert: token,
1755
+ from: range.from
1756
+ }, {
1757
+ insert: token,
1758
+ from: range.to
1759
+ }],
1760
+ effects: closeBracketEffect.of(range.to + token.length),
1761
+ range: EditorSelection.range(range.anchor + token.length, range.head + token.length)
1762
+ };
1763
+ let pos = range.head,
1764
+ next = nextChar(state.doc, pos),
1765
+ start;
1766
+ if (next == token) {
1767
+ if (nodeStart(state, pos)) {
1768
+ return {
1769
+ changes: {
1770
+ insert: token + token,
1771
+ from: pos
1772
+ },
1773
+ effects: closeBracketEffect.of(pos + token.length),
1774
+ range: EditorSelection.cursor(pos + token.length)
1775
+ };
1776
+ } else if (closedBracketAt(state, pos)) {
1777
+ let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
1778
+ let content = isTriple ? token + token + token : token;
1779
+ return {
1780
+ changes: {
1781
+ from: pos,
1782
+ to: pos + content.length,
1783
+ insert: content
1784
+ },
1785
+ range: EditorSelection.cursor(pos + content.length)
1786
+ };
1787
+ }
1788
+ } else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state, start)) {
1789
+ return {
1790
+ changes: {
1791
+ insert: token + token + token + token,
1792
+ from: pos
1793
+ },
1794
+ effects: closeBracketEffect.of(pos + token.length),
1795
+ range: EditorSelection.cursor(pos + token.length)
1796
+ };
1797
+ } else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
1798
+ if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) return {
1799
+ changes: {
1800
+ insert: token + token,
1801
+ from: pos
1802
+ },
1803
+ effects: closeBracketEffect.of(pos + token.length),
1804
+ range: EditorSelection.cursor(pos + token.length)
1805
+ };
1806
+ }
1807
+ return {
1808
+ range: dont = range
1809
+ };
1810
+ });
1811
+ return dont ? null : state.update(changes, {
1812
+ scrollIntoView: true,
1813
+ userEvent: "input.type"
1814
+ });
1815
+ }
1816
+ function nodeStart(state, pos) {
1817
+ let tree = syntaxTree(state).resolveInner(pos + 1);
1818
+ return tree.parent && tree.from == pos;
1819
+ }
1820
+ function probablyInString(state, pos, quoteToken, prefixes) {
1821
+ let node = syntaxTree(state).resolveInner(pos, -1);
1822
+ let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);
1823
+ for (let i = 0; i < 5; i++) {
1824
+ let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
1825
+ let quotePos = start.indexOf(quoteToken);
1826
+ if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
1827
+ let first = node.firstChild;
1828
+ while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
1829
+ if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken) return false;
1830
+ first = first.firstChild;
1831
+ }
1832
+ return true;
1833
+ }
1834
+ let parent = node.to == pos && node.parent;
1835
+ if (!parent) break;
1836
+ node = parent;
1837
+ }
1838
+ return false;
1839
+ }
1840
+ function canStartStringAt(state, pos, prefixes) {
1841
+ let charCat = state.charCategorizer(pos);
1842
+ if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word) return pos;
1843
+ for (let prefix of prefixes) {
1844
+ let start = pos - prefix.length;
1845
+ if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word) return start;
1846
+ }
1847
+ return -1;
1848
+ }
1849
+
1850
+ /**
1851
+ Returns an extension that enables autocompletion.
1852
+ */
1853
+ function autocompletion() {
1854
+ let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1855
+ return [completionState, completionConfig.of(config), completionPlugin, completionKeymapExt, baseTheme];
1856
+ }
1857
+ /**
1858
+ Basic keybindings for autocompletion.
1859
+
1860
+ - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
1861
+ - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
1862
+ - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
1863
+ - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
1864
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
1865
+ - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
1866
+ - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
1867
+ */
1868
+ const completionKeymap = [{
1869
+ key: "Ctrl-Space",
1870
+ run: startCompletion
1871
+ }, {
1872
+ key: "Escape",
1873
+ run: closeCompletion
1874
+ }, {
1875
+ key: "ArrowDown",
1876
+ run: /*@__PURE__*/moveCompletionSelection(true)
1877
+ }, {
1878
+ key: "ArrowUp",
1879
+ run: /*@__PURE__*/moveCompletionSelection(false)
1880
+ }, {
1881
+ key: "PageDown",
1882
+ run: /*@__PURE__*/moveCompletionSelection(true, "page")
1883
+ }, {
1884
+ key: "PageUp",
1885
+ run: /*@__PURE__*/moveCompletionSelection(false, "page")
1886
+ }, {
1887
+ key: "Enter",
1888
+ run: acceptCompletion
1889
+ }];
1890
+ const completionKeymapExt = /*@__PURE__*/Prec.highest( /*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
1891
+
1892
+ export { autocompletion as a, closeBracketsKeymap as b, closeBrackets as c, completionKeymap as d, completeFromList as e, ifNotIn as i, snippetCompletion as s };