@pyscript/core 0.6.7 → 0.6.9

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