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