~repos /gromer

#golang#htmx#ssr

git clone https://pyrossh.dev/repos/gromer.git

gromer is a framework and cli to build multipage web apps in golang using htmx and alpinejs.


f8ffbbb6 Peter John

3 years ago
add hyperscript
assets/js/codemirror-javascript@5.63.1.js DELETED
@@ -1,1079 +0,0 @@
1
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
- // Distributed under an MIT license: https://codemirror.net/LICENSE
3
-
4
- (function (mod) {
5
- if (typeof exports == 'object' && typeof module == 'object')
6
- // CommonJS
7
- mod(require('../../lib/codemirror'));
8
- else if (typeof define == 'function' && define.amd)
9
- // AMD
10
- define(['../../lib/codemirror'], mod);
11
- // Plain browser env
12
- else mod(CodeMirror);
13
- })(function (CodeMirror) {
14
- 'use strict';
15
-
16
- CodeMirror.defineMode('javascript', function (config, parserConfig) {
17
- var indentUnit = config.indentUnit;
18
- var statementIndent = parserConfig.statementIndent;
19
- var jsonldMode = parserConfig.jsonld;
20
- var jsonMode = parserConfig.json || jsonldMode;
21
- var trackScope = parserConfig.trackScope !== false;
22
- var isTS = parserConfig.typescript;
23
- var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
24
-
25
- // Tokenizer
26
-
27
- var keywords = (function () {
28
- function kw(type) {
29
- return { type: type, style: 'keyword' };
30
- }
31
- var A = kw('keyword a'),
32
- B = kw('keyword b'),
33
- C = kw('keyword c'),
34
- D = kw('keyword d');
35
- var operator = kw('operator'),
36
- atom = { type: 'atom', style: 'atom' };
37
-
38
- return {
39
- if: kw('if'),
40
- while: A,
41
- with: A,
42
- else: B,
43
- do: B,
44
- try: B,
45
- finally: B,
46
- return: D,
47
- break: D,
48
- continue: D,
49
- new: kw('new'),
50
- delete: C,
51
- void: C,
52
- throw: C,
53
- debugger: kw('debugger'),
54
- var: kw('var'),
55
- const: kw('var'),
56
- let: kw('var'),
57
- function: kw('function'),
58
- catch: kw('catch'),
59
- for: kw('for'),
60
- switch: kw('switch'),
61
- case: kw('case'),
62
- default: kw('default'),
63
- in: operator,
64
- typeof: operator,
65
- instanceof: operator,
66
- true: atom,
67
- false: atom,
68
- null: atom,
69
- undefined: atom,
70
- NaN: atom,
71
- Infinity: atom,
72
- this: kw('this'),
73
- class: kw('class'),
74
- super: kw('atom'),
75
- yield: C,
76
- export: kw('export'),
77
- import: kw('import'),
78
- extends: C,
79
- await: C,
80
- };
81
- })();
82
-
83
- var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
84
- var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
85
-
86
- function readRegexp(stream) {
87
- var escaped = false,
88
- next,
89
- inSet = false;
90
- while ((next = stream.next()) != null) {
91
- if (!escaped) {
92
- if (next == '/' && !inSet) return;
93
- if (next == '[') inSet = true;
94
- else if (inSet && next == ']') inSet = false;
95
- }
96
- escaped = !escaped && next == '\\';
97
- }
98
- }
99
-
100
- // Used as scratch variables to communicate multiple values without
101
- // consing up tons of objects.
102
- var type, content;
103
- function ret(tp, style, cont) {
104
- type = tp;
105
- content = cont;
106
- return style;
107
- }
108
- function tokenBase(stream, state) {
109
- var ch = stream.next();
110
- if (ch == '"' || ch == "'") {
111
- state.tokenize = tokenString(ch);
112
- return state.tokenize(stream, state);
113
- } else if (ch == '.' && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
114
- return ret('number', 'number');
115
- } else if (ch == '.' && stream.match('..')) {
116
- return ret('spread', 'meta');
117
- } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
118
- return ret(ch);
119
- } else if (ch == '=' && stream.eat('>')) {
120
- return ret('=>', 'operator');
121
- } else if (ch == '0' && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
122
- return ret('number', 'number');
123
- } else if (/\d/.test(ch)) {
124
- stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
125
- return ret('number', 'number');
126
- } else if (ch == '/') {
127
- if (stream.eat('*')) {
128
- state.tokenize = tokenComment;
129
- return tokenComment(stream, state);
130
- } else if (stream.eat('/')) {
131
- stream.skipToEnd();
132
- return ret('comment', 'comment');
133
- } else if (expressionAllowed(stream, state, 1)) {
134
- readRegexp(stream);
135
- stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
136
- return ret('regexp', 'string-2');
137
- } else {
138
- stream.eat('=');
139
- return ret('operator', 'operator', stream.current());
140
- }
141
- } else if (ch == '`') {
142
- state.tokenize = tokenQuasi;
143
- return tokenQuasi(stream, state);
144
- } else if (ch == '#' && stream.peek() == '!') {
145
- stream.skipToEnd();
146
- return ret('meta', 'meta');
147
- } else if (ch == '#' && stream.eatWhile(wordRE)) {
148
- return ret('variable', 'property');
149
- } else if ((ch == '<' && stream.match('!--')) || (ch == '-' && stream.match('->') && !/\S/.test(stream.string.slice(0, stream.start)))) {
150
- stream.skipToEnd();
151
- return ret('comment', 'comment');
152
- } else if (isOperatorChar.test(ch)) {
153
- if (ch != '>' || !state.lexical || state.lexical.type != '>') {
154
- if (stream.eat('=')) {
155
- if (ch == '!' || ch == '=') stream.eat('=');
156
- } else if (/[<>*+\-|&?]/.test(ch)) {
157
- stream.eat(ch);
158
- if (ch == '>') stream.eat(ch);
159
- }
160
- }
161
- if (ch == '?' && stream.eat('.')) return ret('.');
162
- return ret('operator', 'operator', stream.current());
163
- } else if (wordRE.test(ch)) {
164
- stream.eatWhile(wordRE);
165
- var word = stream.current();
166
- if (state.lastType != '.') {
167
- if (keywords.propertyIsEnumerable(word)) {
168
- var kw = keywords[word];
169
- return ret(kw.type, kw.style, word);
170
- }
171
- if (word == 'async' && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret('async', 'keyword', word);
172
- }
173
- return ret('variable', 'variable', word);
174
- }
175
- }
176
-
177
- function tokenString(quote) {
178
- return function (stream, state) {
179
- var escaped = false,
180
- next;
181
- if (jsonldMode && stream.peek() == '@' && stream.match(isJsonldKeyword)) {
182
- state.tokenize = tokenBase;
183
- return ret('jsonld-keyword', 'meta');
184
- }
185
- while ((next = stream.next()) != null) {
186
- if (next == quote && !escaped) break;
187
- escaped = !escaped && next == '\\';
188
- }
189
- if (!escaped) state.tokenize = tokenBase;
190
- return ret('string', 'string');
191
- };
192
- }
193
-
194
- function tokenComment(stream, state) {
195
- var maybeEnd = false,
196
- ch;
197
- while ((ch = stream.next())) {
198
- if (ch == '/' && maybeEnd) {
199
- state.tokenize = tokenBase;
200
- break;
201
- }
202
- maybeEnd = ch == '*';
203
- }
204
- return ret('comment', 'comment');
205
- }
206
-
207
- function tokenQuasi(stream, state) {
208
- var escaped = false,
209
- next;
210
- while ((next = stream.next()) != null) {
211
- if (!escaped && (next == '`' || (next == '$' && stream.eat('{')))) {
212
- state.tokenize = tokenBase;
213
- break;
214
- }
215
- escaped = !escaped && next == '\\';
216
- }
217
- return ret('quasi', 'string-2', stream.current());
218
- }
219
-
220
- var brackets = '([{}])';
221
- // This is a crude lookahead trick to try and notice that we're
222
- // parsing the argument patterns for a fat-arrow function before we
223
- // actually hit the arrow token. It only works if the arrow is on
224
- // the same line as the arguments and there's no strange noise
225
- // (comments) in between. Fallback is to only notice when we hit the
226
- // arrow, and not declare the arguments as locals for the arrow
227
- // body.
228
- function findFatArrow(stream, state) {
229
- if (state.fatArrowAt) state.fatArrowAt = null;
230
- var arrow = stream.string.indexOf('=>', stream.start);
231
- if (arrow < 0) return;
232
-
233
- if (isTS) {
234
- // Try to skip TypeScript return type declarations after the arguments
235
- var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow));
236
- if (m) arrow = m.index;
237
- }
238
-
239
- var depth = 0,
240
- sawSomething = false;
241
- for (var pos = arrow - 1; pos >= 0; --pos) {
242
- var ch = stream.string.charAt(pos);
243
- var bracket = brackets.indexOf(ch);
244
- if (bracket >= 0 && bracket < 3) {
245
- if (!depth) {
246
- ++pos;
247
- break;
248
- }
249
- if (--depth == 0) {
250
- if (ch == '(') sawSomething = true;
251
- break;
252
- }
253
- } else if (bracket >= 3 && bracket < 6) {
254
- ++depth;
255
- } else if (wordRE.test(ch)) {
256
- sawSomething = true;
257
- } else if (/["'\/`]/.test(ch)) {
258
- for (; ; --pos) {
259
- if (pos == 0) return;
260
- var next = stream.string.charAt(pos - 1);
261
- if (next == ch && stream.string.charAt(pos - 2) != '\\') {
262
- pos--;
263
- break;
264
- }
265
- }
266
- } else if (sawSomething && !depth) {
267
- ++pos;
268
- break;
269
- }
270
- }
271
- if (sawSomething && !depth) state.fatArrowAt = pos;
272
- }
273
-
274
- // Parser
275
-
276
- var atomicTypes = { atom: true, number: true, variable: true, string: true, regexp: true, this: true, import: true, 'jsonld-keyword': true };
277
-
278
- function JSLexical(indented, column, type, align, prev, info) {
279
- this.indented = indented;
280
- this.column = column;
281
- this.type = type;
282
- this.prev = prev;
283
- this.info = info;
284
- if (align != null) this.align = align;
285
- }
286
-
287
- function inScope(state, varname) {
288
- if (!trackScope) return false;
289
- for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true;
290
- for (var cx = state.context; cx; cx = cx.prev) {
291
- for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true;
292
- }
293
- }
294
-
295
- function parseJS(state, style, type, content, stream) {
296
- var cc = state.cc;
297
- // Communicate our context to the combinators.
298
- // (Less wasteful than consing up a hundred closures on every call.)
299
- cx.state = state;
300
- cx.stream = stream;
301
- (cx.marked = null), (cx.cc = cc);
302
- cx.style = style;
303
-
304
- if (!state.lexical.hasOwnProperty('align')) state.lexical.align = true;
305
-
306
- while (true) {
307
- var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
308
- if (combinator(type, content)) {
309
- while (cc.length && cc[cc.length - 1].lex) cc.pop()();
310
- if (cx.marked) return cx.marked;
311
- if (type == 'variable' && inScope(state, content)) return 'variable-2';
312
- return style;
313
- }
314
- }
315
- }
316
-
317
- // Combinator utils
318
-
319
- var cx = { state: null, column: null, marked: null, cc: null };
320
- function pass() {
321
- for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
322
- }
323
- function cont() {
324
- pass.apply(null, arguments);
325
- return true;
326
- }
327
- function inList(name, list) {
328
- for (var v = list; v; v = v.next) if (v.name == name) return true;
329
- return false;
330
- }
331
- function register(varname) {
332
- var state = cx.state;
333
- cx.marked = 'def';
334
- if (!trackScope) return;
335
- if (state.context) {
336
- if (state.lexical.info == 'var' && state.context && state.context.block) {
337
- // FIXME function decls are also not block scoped
338
- var newContext = registerVarScoped(varname, state.context);
339
- if (newContext != null) {
340
- state.context = newContext;
341
- return;
342
- }
343
- } else if (!inList(varname, state.localVars)) {
344
- state.localVars = new Var(varname, state.localVars);
345
- return;
346
- }
347
- }
348
- // Fall through means this is global
349
- if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars);
350
- }
351
- function registerVarScoped(varname, context) {
352
- if (!context) {
353
- return null;
354
- } else if (context.block) {
355
- var inner = registerVarScoped(varname, context.prev);
356
- if (!inner) return null;
357
- if (inner == context.prev) return context;
358
- return new Context(inner, context.vars, true);
359
- } else if (inList(varname, context.vars)) {
360
- return context;
361
- } else {
362
- return new Context(context.prev, new Var(varname, context.vars), false);
363
- }
364
- }
365
-
366
- function isModifier(name) {
367
- return name == 'public' || name == 'private' || name == 'protected' || name == 'abstract' || name == 'readonly';
368
- }
369
-
370
- // Combinators
371
-
372
- function Context(prev, vars, block) {
373
- this.prev = prev;
374
- this.vars = vars;
375
- this.block = block;
376
- }
377
- function Var(name, next) {
378
- this.name = name;
379
- this.next = next;
380
- }
381
-
382
- var defaultVars = new Var('this', new Var('arguments', null));
383
- function pushcontext() {
384
- cx.state.context = new Context(cx.state.context, cx.state.localVars, false);
385
- cx.state.localVars = defaultVars;
386
- }
387
- function pushblockcontext() {
388
- cx.state.context = new Context(cx.state.context, cx.state.localVars, true);
389
- cx.state.localVars = null;
390
- }
391
- function popcontext() {
392
- cx.state.localVars = cx.state.context.vars;
393
- cx.state.context = cx.state.context.prev;
394
- }
395
- popcontext.lex = true;
396
- function pushlex(type, info) {
397
- var result = function () {
398
- var state = cx.state,
399
- indent = state.indented;
400
- if (state.lexical.type == 'stat') indent = state.lexical.indented;
401
- else for (var outer = state.lexical; outer && outer.type == ')' && outer.align; outer = outer.prev) indent = outer.indented;
402
- state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
403
- };
404
- result.lex = true;
405
- return result;
406
- }
407
- function poplex() {
408
- var state = cx.state;
409
- if (state.lexical.prev) {
410
- if (state.lexical.type == ')') state.indented = state.lexical.indented;
411
- state.lexical = state.lexical.prev;
412
- }
413
- }
414
- poplex.lex = true;
415
-
416
- function expect(wanted) {
417
- function exp(type) {
418
- if (type == wanted) return cont();
419
- else if (wanted == ';' || type == '}' || type == ')' || type == ']') return pass();
420
- else return cont(exp);
421
- }
422
- return exp;
423
- }
424
-
425
- function statement(type, value) {
426
- if (type == 'var') return cont(pushlex('vardef', value), vardef, expect(';'), poplex);
427
- if (type == 'keyword a') return cont(pushlex('form'), parenExpr, statement, poplex);
428
- if (type == 'keyword b') return cont(pushlex('form'), statement, poplex);
429
- if (type == 'keyword d') return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex('stat'), maybeexpression, expect(';'), poplex);
430
- if (type == 'debugger') return cont(expect(';'));
431
- if (type == '{') return cont(pushlex('}'), pushblockcontext, block, poplex, popcontext);
432
- if (type == ';') return cont();
433
- if (type == 'if') {
434
- if (cx.state.lexical.info == 'else' && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()();
435
- return cont(pushlex('form'), parenExpr, statement, poplex, maybeelse);
436
- }
437
- if (type == 'function') return cont(functiondef);
438
- if (type == 'for') return cont(pushlex('form'), pushblockcontext, forspec, statement, popcontext, poplex);
439
- if (type == 'class' || (isTS && value == 'interface')) {
440
- cx.marked = 'keyword';
441
- return cont(pushlex('form', type == 'class' ? type : value), className, poplex);
442
- }
443
- if (type == 'variable') {
444
- if (isTS && value == 'declare') {
445
- cx.marked = 'keyword';
446
- return cont(statement);
447
- } else if (isTS && (value == 'module' || value == 'enum' || value == 'type') && cx.stream.match(/^\s*\w/, false)) {
448
- cx.marked = 'keyword';
449
- if (value == 'enum') return cont(enumdef);
450
- else if (value == 'type') return cont(typename, expect('operator'), typeexpr, expect(';'));
451
- else return cont(pushlex('form'), pattern, expect('{'), pushlex('}'), block, poplex, poplex);
452
- } else if (isTS && value == 'namespace') {
453
- cx.marked = 'keyword';
454
- return cont(pushlex('form'), expression, statement, poplex);
455
- } else if (isTS && value == 'abstract') {
456
- cx.marked = 'keyword';
457
- return cont(statement);
458
- } else {
459
- return cont(pushlex('stat'), maybelabel);
460
- }
461
- }
462
- if (type == 'switch') return cont(pushlex('form'), parenExpr, expect('{'), pushlex('}', 'switch'), pushblockcontext, block, poplex, poplex, popcontext);
463
- if (type == 'case') return cont(expression, expect(':'));
464
- if (type == 'default') return cont(expect(':'));
465
- if (type == 'catch') return cont(pushlex('form'), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
466
- if (type == 'export') return cont(pushlex('stat'), afterExport, poplex);
467
- if (type == 'import') return cont(pushlex('stat'), afterImport, poplex);
468
- if (type == 'async') return cont(statement);
469
- if (value == '@') return cont(expression, statement);
470
- return pass(pushlex('stat'), expression, expect(';'), poplex);
471
- }
472
- function maybeCatchBinding(type) {
473
- if (type == '(') return cont(funarg, expect(')'));
474
- }
475
- function expression(type, value) {
476
- return expressionInner(type, value, false);
477
- }
478
- function expressionNoComma(type, value) {
479
- return expressionInner(type, value, true);
480
- }
481
- function parenExpr(type) {
482
- if (type != '(') return pass();
483
- return cont(pushlex(')'), maybeexpression, expect(')'), poplex);
484
- }
485
- function expressionInner(type, value, noComma) {
486
- if (cx.state.fatArrowAt == cx.stream.start) {
487
- var body = noComma ? arrowBodyNoComma : arrowBody;
488
- if (type == '(') return cont(pushcontext, pushlex(')'), commasep(funarg, ')'), poplex, expect('=>'), body, popcontext);
489
- else if (type == 'variable') return pass(pushcontext, pattern, expect('=>'), body, popcontext);
490
- }
491
-
492
- var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
493
- if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
494
- if (type == 'function') return cont(functiondef, maybeop);
495
- if (type == 'class' || (isTS && value == 'interface')) {
496
- cx.marked = 'keyword';
497
- return cont(pushlex('form'), classExpression, poplex);
498
- }
499
- if (type == 'keyword c' || type == 'async') return cont(noComma ? expressionNoComma : expression);
500
- if (type == '(') return cont(pushlex(')'), maybeexpression, expect(')'), poplex, maybeop);
501
- if (type == 'operator' || type == 'spread') return cont(noComma ? expressionNoComma : expression);
502
- if (type == '[') return cont(pushlex(']'), arrayLiteral, poplex, maybeop);
503
- if (type == '{') return contCommasep(objprop, '}', null, maybeop);
504
- if (type == 'quasi') return pass(quasi, maybeop);
505
- if (type == 'new') return cont(maybeTarget(noComma));
506
- return cont();
507
- }
508
- function maybeexpression(type) {
509
- if (type.match(/[;\}\)\],]/)) return pass();
510
- return pass(expression);
511
- }
512
-
513
- function maybeoperatorComma(type, value) {
514
- if (type == ',') return cont(maybeexpression);
515
- return maybeoperatorNoComma(type, value, false);
516
- }
517
- function maybeoperatorNoComma(type, value, noComma) {
518
- var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
519
- var expr = noComma == false ? expression : expressionNoComma;
520
- if (type == '=>') return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
521
- if (type == 'operator') {
522
- if (/\+\+|--/.test(value) || (isTS && value == '!')) return cont(me);
523
- if (isTS && value == '<' && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex('>'), commasep(typeexpr, '>'), poplex, me);
524
- if (value == '?') return cont(expression, expect(':'), expr);
525
- return cont(expr);
526
- }
527
- if (type == 'quasi') {
528
- return pass(quasi, me);
529
- }
530
- if (type == ';') return;
531
- if (type == '(') return contCommasep(expressionNoComma, ')', 'call', me);
532
- if (type == '.') return cont(property, me);
533
- if (type == '[') return cont(pushlex(']'), maybeexpression, expect(']'), poplex, me);
534
- if (isTS && value == 'as') {
535
- cx.marked = 'keyword';
536
- return cont(typeexpr, me);
537
- }
538
- if (type == 'regexp') {
539
- cx.state.lastType = cx.marked = 'operator';
540
- cx.stream.backUp(cx.stream.pos - cx.stream.start - 1);
541
- return cont(expr);
542
- }
543
- }
544
- function quasi(type, value) {
545
- if (type != 'quasi') return pass();
546
- if (value.slice(value.length - 2) != '${') return cont(quasi);
547
- return cont(maybeexpression, continueQuasi);
548
- }
549
- function continueQuasi(type) {
550
- if (type == '}') {
551
- cx.marked = 'string-2';
552
- cx.state.tokenize = tokenQuasi;
553
- return cont(quasi);
554
- }
555
- }
556
- function arrowBody(type) {
557
- findFatArrow(cx.stream, cx.state);
558
- return pass(type == '{' ? statement : expression);
559
- }
560
- function arrowBodyNoComma(type) {
561
- findFatArrow(cx.stream, cx.state);
562
- return pass(type == '{' ? statement : expressionNoComma);
563
- }
564
- function maybeTarget(noComma) {
565
- return function (type) {
566
- if (type == '.') return cont(noComma ? targetNoComma : target);
567
- else if (type == 'variable' && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);
568
- else return pass(noComma ? expressionNoComma : expression);
569
- };
570
- }
571
- function target(_, value) {
572
- if (value == 'target') {
573
- cx.marked = 'keyword';
574
- return cont(maybeoperatorComma);
575
- }
576
- }
577
- function targetNoComma(_, value) {
578
- if (value == 'target') {
579
- cx.marked = 'keyword';
580
- return cont(maybeoperatorNoComma);
581
- }
582
- }
583
- function maybelabel(type) {
584
- if (type == ':') return cont(poplex, statement);
585
- return pass(maybeoperatorComma, expect(';'), poplex);
586
- }
587
- function property(type) {
588
- if (type == 'variable') {
589
- cx.marked = 'property';
590
- return cont();
591
- }
592
- }
593
- function objprop(type, value) {
594
- if (type == 'async') {
595
- cx.marked = 'property';
596
- return cont(objprop);
597
- } else if (type == 'variable' || cx.style == 'keyword') {
598
- cx.marked = 'property';
599
- if (value == 'get' || value == 'set') return cont(getterSetter);
600
- var m; // Work around fat-arrow-detection complication for detecting typescript typed arrow params
601
- if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length;
602
- return cont(afterprop);
603
- } else if (type == 'number' || type == 'string') {
604
- cx.marked = jsonldMode ? 'property' : cx.style + ' property';
605
- return cont(afterprop);
606
- } else if (type == 'jsonld-keyword') {
607
- return cont(afterprop);
608
- } else if (isTS && isModifier(value)) {
609
- cx.marked = 'keyword';
610
- return cont(objprop);
611
- } else if (type == '[') {
612
- return cont(expression, maybetype, expect(']'), afterprop);
613
- } else if (type == 'spread') {
614
- return cont(expressionNoComma, afterprop);
615
- } else if (value == '*') {
616
- cx.marked = 'keyword';
617
- return cont(objprop);
618
- } else if (type == ':') {
619
- return pass(afterprop);
620
- }
621
- }
622
- function getterSetter(type) {
623
- if (type != 'variable') return pass(afterprop);
624
- cx.marked = 'property';
625
- return cont(functiondef);
626
- }
627
- function afterprop(type) {
628
- if (type == ':') return cont(expressionNoComma);
629
- if (type == '(') return pass(functiondef);
630
- }
631
- function commasep(what, end, sep) {
632
- function proceed(type, value) {
633
- if (sep ? sep.indexOf(type) > -1 : type == ',') {
634
- var lex = cx.state.lexical;
635
- if (lex.info == 'call') lex.pos = (lex.pos || 0) + 1;
636
- return cont(function (type, value) {
637
- if (type == end || value == end) return pass();
638
- return pass(what);
639
- }, proceed);
640
- }
641
- if (type == end || value == end) return cont();
642
- if (sep && sep.indexOf(';') > -1) return pass(what);
643
- return cont(expect(end));
644
- }
645
- return function (type, value) {
646
- if (type == end || value == end) return cont();
647
- return pass(what, proceed);
648
- };
649
- }
650
- function contCommasep(what, end, info) {
651
- for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]);
652
- return cont(pushlex(end, info), commasep(what, end), poplex);
653
- }
654
- function block(type) {
655
- if (type == '}') return cont();
656
- return pass(statement, block);
657
- }
658
- function maybetype(type, value) {
659
- if (isTS) {
660
- if (type == ':') return cont(typeexpr);
661
- if (value == '?') return cont(maybetype);
662
- }
663
- }
664
- function maybetypeOrIn(type, value) {
665
- if (isTS && (type == ':' || value == 'in')) return cont(typeexpr);
666
- }
667
- function mayberettype(type) {
668
- if (isTS && type == ':') {
669
- if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);
670
- else return cont(typeexpr);
671
- }
672
- }
673
- function isKW(_, value) {
674
- if (value == 'is') {
675
- cx.marked = 'keyword';
676
- return cont();
677
- }
678
- }
679
- function typeexpr(type, value) {
680
- if (value == 'keyof' || value == 'typeof' || value == 'infer' || value == 'readonly') {
681
- cx.marked = 'keyword';
682
- return cont(value == 'typeof' ? expressionNoComma : typeexpr);
683
- }
684
- if (type == 'variable' || value == 'void') {
685
- cx.marked = 'type';
686
- return cont(afterType);
687
- }
688
- if (value == '|' || value == '&') return cont(typeexpr);
689
- if (type == 'string' || type == 'number' || type == 'atom') return cont(afterType);
690
- if (type == '[') return cont(pushlex(']'), commasep(typeexpr, ']', ','), poplex, afterType);
691
- if (type == '{') return cont(pushlex('}'), typeprops, poplex, afterType);
692
- if (type == '(') return cont(commasep(typearg, ')'), maybeReturnType, afterType);
693
- if (type == '<') return cont(commasep(typeexpr, '>'), typeexpr);
694
- if (type == 'quasi') {
695
- return pass(quasiType, afterType);
696
- }
697
- }
698
- function maybeReturnType(type) {
699
- if (type == '=>') return cont(typeexpr);
700
- }
701
- function typeprops(type) {
702
- if (type.match(/[\}\)\]]/)) return cont();
703
- if (type == ',' || type == ';') return cont(typeprops);
704
- return pass(typeprop, typeprops);
705
- }
706
- function typeprop(type, value) {
707
- if (type == 'variable' || cx.style == 'keyword') {
708
- cx.marked = 'property';
709
- return cont(typeprop);
710
- } else if (value == '?' || type == 'number' || type == 'string') {
711
- return cont(typeprop);
712
- } else if (type == ':') {
713
- return cont(typeexpr);
714
- } else if (type == '[') {
715
- return cont(expect('variable'), maybetypeOrIn, expect(']'), typeprop);
716
- } else if (type == '(') {
717
- return pass(functiondecl, typeprop);
718
- } else if (!type.match(/[;\}\)\],]/)) {
719
- return cont();
720
- }
721
- }
722
- function quasiType(type, value) {
723
- if (type != 'quasi') return pass();
724
- if (value.slice(value.length - 2) != '${') return cont(quasiType);
725
- return cont(typeexpr, continueQuasiType);
726
- }
727
- function continueQuasiType(type) {
728
- if (type == '}') {
729
- cx.marked = 'string-2';
730
- cx.state.tokenize = tokenQuasi;
731
- return cont(quasiType);
732
- }
733
- }
734
- function typearg(type, value) {
735
- if ((type == 'variable' && cx.stream.match(/^\s*[?:]/, false)) || value == '?') return cont(typearg);
736
- if (type == ':') return cont(typeexpr);
737
- if (type == 'spread') return cont(typearg);
738
- return pass(typeexpr);
739
- }
740
- function afterType(type, value) {
741
- if (value == '<') return cont(pushlex('>'), commasep(typeexpr, '>'), poplex, afterType);
742
- if (value == '|' || type == '.' || value == '&') return cont(typeexpr);
743
- if (type == '[') return cont(typeexpr, expect(']'), afterType);
744
- if (value == 'extends' || value == 'implements') {
745
- cx.marked = 'keyword';
746
- return cont(typeexpr);
747
- }
748
- if (value == '?') return cont(typeexpr, expect(':'), typeexpr);
749
- }
750
- function maybeTypeArgs(_, value) {
751
- if (value == '<') return cont(pushlex('>'), commasep(typeexpr, '>'), poplex, afterType);
752
- }
753
- function typeparam() {
754
- return pass(typeexpr, maybeTypeDefault);
755
- }
756
- function maybeTypeDefault(_, value) {
757
- if (value == '=') return cont(typeexpr);
758
- }
759
- function vardef(_, value) {
760
- if (value == 'enum') {
761
- cx.marked = 'keyword';
762
- return cont(enumdef);
763
- }
764
- return pass(pattern, maybetype, maybeAssign, vardefCont);
765
- }
766
- function pattern(type, value) {
767
- if (isTS && isModifier(value)) {
768
- cx.marked = 'keyword';
769
- return cont(pattern);
770
- }
771
- if (type == 'variable') {
772
- register(value);
773
- return cont();
774
- }
775
- if (type == 'spread') return cont(pattern);
776
- if (type == '[') return contCommasep(eltpattern, ']');
777
- if (type == '{') return contCommasep(proppattern, '}');
778
- }
779
- function proppattern(type, value) {
780
- if (type == 'variable' && !cx.stream.match(/^\s*:/, false)) {
781
- register(value);
782
- return cont(maybeAssign);
783
- }
784
- if (type == 'variable') cx.marked = 'property';
785
- if (type == 'spread') return cont(pattern);
786
- if (type == '}') return pass();
787
- if (type == '[') return cont(expression, expect(']'), expect(':'), proppattern);
788
- return cont(expect(':'), pattern, maybeAssign);
789
- }
790
- function eltpattern() {
791
- return pass(pattern, maybeAssign);
792
- }
793
- function maybeAssign(_type, value) {
794
- if (value == '=') return cont(expressionNoComma);
795
- }
796
- function vardefCont(type) {
797
- if (type == ',') return cont(vardef);
798
- }
799
- function maybeelse(type, value) {
800
- if (type == 'keyword b' && value == 'else') return cont(pushlex('form', 'else'), statement, poplex);
801
- }
802
- function forspec(type, value) {
803
- if (value == 'await') return cont(forspec);
804
- if (type == '(') return cont(pushlex(')'), forspec1, poplex);
805
- }
806
- function forspec1(type) {
807
- if (type == 'var') return cont(vardef, forspec2);
808
- if (type == 'variable') return cont(forspec2);
809
- return pass(forspec2);
810
- }
811
- function forspec2(type, value) {
812
- if (type == ')') return cont();
813
- if (type == ';') return cont(forspec2);
814
- if (value == 'in' || value == 'of') {
815
- cx.marked = 'keyword';
816
- return cont(expression, forspec2);
817
- }
818
- return pass(expression, forspec2);
819
- }
820
- function functiondef(type, value) {
821
- if (value == '*') {
822
- cx.marked = 'keyword';
823
- return cont(functiondef);
824
- }
825
- if (type == 'variable') {
826
- register(value);
827
- return cont(functiondef);
828
- }
829
- if (type == '(') return cont(pushcontext, pushlex(')'), commasep(funarg, ')'), poplex, mayberettype, statement, popcontext);
830
- if (isTS && value == '<') return cont(pushlex('>'), commasep(typeparam, '>'), poplex, functiondef);
831
- }
832
- function functiondecl(type, value) {
833
- if (value == '*') {
834
- cx.marked = 'keyword';
835
- return cont(functiondecl);
836
- }
837
- if (type == 'variable') {
838
- register(value);
839
- return cont(functiondecl);
840
- }
841
- if (type == '(') return cont(pushcontext, pushlex(')'), commasep(funarg, ')'), poplex, mayberettype, popcontext);
842
- if (isTS && value == '<') return cont(pushlex('>'), commasep(typeparam, '>'), poplex, functiondecl);
843
- }
844
- function typename(type, value) {
845
- if (type == 'keyword' || type == 'variable') {
846
- cx.marked = 'type';
847
- return cont(typename);
848
- } else if (value == '<') {
849
- return cont(pushlex('>'), commasep(typeparam, '>'), poplex);
850
- }
851
- }
852
- function funarg(type, value) {
853
- if (value == '@') cont(expression, funarg);
854
- if (type == 'spread') return cont(funarg);
855
- if (isTS && isModifier(value)) {
856
- cx.marked = 'keyword';
857
- return cont(funarg);
858
- }
859
- if (isTS && type == 'this') return cont(maybetype, maybeAssign);
860
- return pass(pattern, maybetype, maybeAssign);
861
- }
862
- function classExpression(type, value) {
863
- // Class expressions may have an optional name.
864
- if (type == 'variable') return className(type, value);
865
- return classNameAfter(type, value);
866
- }
867
- function className(type, value) {
868
- if (type == 'variable') {
869
- register(value);
870
- return cont(classNameAfter);
871
- }
872
- }
873
- function classNameAfter(type, value) {
874
- if (value == '<') return cont(pushlex('>'), commasep(typeparam, '>'), poplex, classNameAfter);
875
- if (value == 'extends' || value == 'implements' || (isTS && type == ',')) {
876
- if (value == 'implements') cx.marked = 'keyword';
877
- return cont(isTS ? typeexpr : expression, classNameAfter);
878
- }
879
- if (type == '{') return cont(pushlex('}'), classBody, poplex);
880
- }
881
- function classBody(type, value) {
882
- if (
883
- type == 'async' ||
884
- (type == 'variable' &&
885
- (value == 'static' || value == 'get' || value == 'set' || (isTS && isModifier(value))) &&
886
- cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))
887
- ) {
888
- cx.marked = 'keyword';
889
- return cont(classBody);
890
- }
891
- if (type == 'variable' || cx.style == 'keyword') {
892
- cx.marked = 'property';
893
- return cont(classfield, classBody);
894
- }
895
- if (type == 'number' || type == 'string') return cont(classfield, classBody);
896
- if (type == '[') return cont(expression, maybetype, expect(']'), classfield, classBody);
897
- if (value == '*') {
898
- cx.marked = 'keyword';
899
- return cont(classBody);
900
- }
901
- if (isTS && type == '(') return pass(functiondecl, classBody);
902
- if (type == ';' || type == ',') return cont(classBody);
903
- if (type == '}') return cont();
904
- if (value == '@') return cont(expression, classBody);
905
- }
906
- function classfield(type, value) {
907
- if (value == '!') return cont(classfield);
908
- if (value == '?') return cont(classfield);
909
- if (type == ':') return cont(typeexpr, maybeAssign);
910
- if (value == '=') return cont(expressionNoComma);
911
- var context = cx.state.lexical.prev,
912
- isInterface = context && context.info == 'interface';
913
- return pass(isInterface ? functiondecl : functiondef);
914
- }
915
- function afterExport(type, value) {
916
- if (value == '*') {
917
- cx.marked = 'keyword';
918
- return cont(maybeFrom, expect(';'));
919
- }
920
- if (value == 'default') {
921
- cx.marked = 'keyword';
922
- return cont(expression, expect(';'));
923
- }
924
- if (type == '{') return cont(commasep(exportField, '}'), maybeFrom, expect(';'));
925
- return pass(statement);
926
- }
927
- function exportField(type, value) {
928
- if (value == 'as') {
929
- cx.marked = 'keyword';
930
- return cont(expect('variable'));
931
- }
932
- if (type == 'variable') return pass(expressionNoComma, exportField);
933
- }
934
- function afterImport(type) {
935
- if (type == 'string') return cont();
936
- if (type == '(') return pass(expression);
937
- if (type == '.') return pass(maybeoperatorComma);
938
- return pass(importSpec, maybeMoreImports, maybeFrom);
939
- }
940
- function importSpec(type, value) {
941
- if (type == '{') return contCommasep(importSpec, '}');
942
- if (type == 'variable') register(value);
943
- if (value == '*') cx.marked = 'keyword';
944
- return cont(maybeAs);
945
- }
946
- function maybeMoreImports(type) {
947
- if (type == ',') return cont(importSpec, maybeMoreImports);
948
- }
949
- function maybeAs(_type, value) {
950
- if (value == 'as') {
951
- cx.marked = 'keyword';
952
- return cont(importSpec);
953
- }
954
- }
955
- function maybeFrom(_type, value) {
956
- if (value == 'from') {
957
- cx.marked = 'keyword';
958
- return cont(expression);
959
- }
960
- }
961
- function arrayLiteral(type) {
962
- if (type == ']') return cont();
963
- return pass(commasep(expressionNoComma, ']'));
964
- }
965
- function enumdef() {
966
- return pass(pushlex('form'), pattern, expect('{'), pushlex('}'), commasep(enummember, '}'), poplex, poplex);
967
- }
968
- function enummember() {
969
- return pass(pattern, maybeAssign);
970
- }
971
-
972
- function isContinuedStatement(state, textAfter) {
973
- return state.lastType == 'operator' || state.lastType == ',' || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0));
974
- }
975
-
976
- function expressionAllowed(stream, state, backUp) {
977
- return (
978
- (state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType)) ||
979
- (state.lastType == 'quasi' && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
980
- );
981
- }
982
-
983
- // Interface
984
-
985
- return {
986
- startState: function (basecolumn) {
987
- var state = {
988
- tokenize: tokenBase,
989
- lastType: 'sof',
990
- cc: [],
991
- lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, 'block', false),
992
- localVars: parserConfig.localVars,
993
- context: parserConfig.localVars && new Context(null, null, false),
994
- indented: basecolumn || 0,
995
- };
996
- if (parserConfig.globalVars && typeof parserConfig.globalVars == 'object') state.globalVars = parserConfig.globalVars;
997
- return state;
998
- },
999
-
1000
- token: function (stream, state) {
1001
- if (stream.sol()) {
1002
- if (!state.lexical.hasOwnProperty('align')) state.lexical.align = false;
1003
- state.indented = stream.indentation();
1004
- findFatArrow(stream, state);
1005
- }
1006
- if (state.tokenize != tokenComment && stream.eatSpace()) return null;
1007
- var style = state.tokenize(stream, state);
1008
- if (type == 'comment') return style;
1009
- state.lastType = type == 'operator' && (content == '++' || content == '--') ? 'incdec' : type;
1010
- return parseJS(state, style, type, content, stream);
1011
- },
1012
-
1013
- indent: function (state, textAfter) {
1014
- if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass;
1015
- if (state.tokenize != tokenBase) return 0;
1016
- var firstChar = textAfter && textAfter.charAt(0),
1017
- lexical = state.lexical,
1018
- top;
1019
- // Kludge to prevent 'maybelse' from blocking lexical scope pops
1020
- if (!/^\s*else\b/.test(textAfter))
1021
- for (var i = state.cc.length - 1; i >= 0; --i) {
1022
- var c = state.cc[i];
1023
- if (c == poplex) lexical = lexical.prev;
1024
- else if (c != maybeelse && c != popcontext) break;
1025
- }
1026
- while (
1027
- (lexical.type == 'stat' || lexical.type == 'form') &&
1028
- (firstChar == '}' ||
1029
- ((top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter)))
1030
- )
1031
- lexical = lexical.prev;
1032
- if (statementIndent && lexical.type == ')' && lexical.prev.type == 'stat') lexical = lexical.prev;
1033
- var type = lexical.type,
1034
- closing = firstChar == type;
1035
-
1036
- if (type == 'vardef') return lexical.indented + (state.lastType == 'operator' || state.lastType == ',' ? lexical.info.length + 1 : 0);
1037
- else if (type == 'form' && firstChar == '{') return lexical.indented;
1038
- else if (type == 'form') return lexical.indented + indentUnit;
1039
- else if (type == 'stat') return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
1040
- else if (lexical.info == 'switch' && !closing && parserConfig.doubleIndentSwitch != false)
1041
- return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
1042
- else if (lexical.align) return lexical.column + (closing ? 0 : 1);
1043
- else return lexical.indented + (closing ? 0 : indentUnit);
1044
- },
1045
-
1046
- electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
1047
- blockCommentStart: jsonMode ? null : '/*',
1048
- blockCommentEnd: jsonMode ? null : '*/',
1049
- blockCommentContinue: jsonMode ? null : ' * ',
1050
- lineComment: jsonMode ? null : '//',
1051
- fold: 'brace',
1052
- closeBrackets: '()[]{}\'\'""``',
1053
-
1054
- helperType: jsonMode ? 'json' : 'javascript',
1055
- jsonldMode: jsonldMode,
1056
- jsonMode: jsonMode,
1057
-
1058
- expressionAllowed: expressionAllowed,
1059
-
1060
- skipExpression: function (state) {
1061
- parseJS(state, 'atom', 'atom', 'true', new CodeMirror.StringStream('', 2, null));
1062
- },
1063
- };
1064
- });
1065
-
1066
- CodeMirror.registerHelper('wordChars', 'javascript', /[\w$]/);
1067
-
1068
- CodeMirror.defineMIME('text/javascript', 'javascript');
1069
- CodeMirror.defineMIME('text/ecmascript', 'javascript');
1070
- CodeMirror.defineMIME('application/javascript', 'javascript');
1071
- CodeMirror.defineMIME('application/x-javascript', 'javascript');
1072
- CodeMirror.defineMIME('application/ecmascript', 'javascript');
1073
- CodeMirror.defineMIME('application/json', { name: 'javascript', json: true });
1074
- CodeMirror.defineMIME('application/x-json', { name: 'javascript', json: true });
1075
- CodeMirror.defineMIME('application/manifest+json', { name: 'javascript', json: true });
1076
- CodeMirror.defineMIME('application/ld+json', { name: 'javascript', jsonld: true });
1077
- CodeMirror.defineMIME('text/typescript', { name: 'javascript', typescript: true });
1078
- CodeMirror.defineMIME('application/typescript', { name: 'javascript', typescript: true });
1079
- });
assets/js/codemirror@5.63.1.min.js DELETED
@@ -1 +0,0 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).CodeMirror=t()}(this,function(){"use strict";var e=navigator.userAgent,t=navigator.platform,d=/gecko\/\d/i.test(e),n=/MSIE \d/.test(e),r=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(e),i=/Edge\/(\d+)/.exec(e),w=n||r||i,v=w&&(n?document.documentMode||6:+(i||r)[1]),f=!i&&/WebKit\//.test(e),r=f&&/Qt\/\d+\.\d+/.test(e),o=!i&&/Chrome\//.test(e),p=/Opera\//.test(e),c=/Apple Computer/.test(navigator.vendor),l=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(e),u=/PhantomJS/.test(e),s=c&&(/Mobile\/\w+/.test(e)||2<navigator.maxTouchPoints),a=/Android/.test(e),h=s||a||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(e),g=s||/Mac/.test(t),m=/\bCrOS\b/.test(e),y=/win/i.test(t),e=p&&e.match(/Version\/(\d*\.\d*)/);(e=e&&Number(e[1]))&&15<=e&&(f=!(p=!1));var b=g&&(r||p&&(null==e||e<12.11)),x=d||w&&9<=v;function C(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}var S=function(e,t){var n=e.className,r=C(t).exec(n);r&&(t=n.slice(r.index+r[0].length),e.className=n.slice(0,r.index)+(t?r[1]+t:""))};function L(e){for(var t=e.childNodes.length;0<t;--t)e.removeChild(e.firstChild);return e}function k(e,t){return L(e).appendChild(t)}function M(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)i.appendChild(t[o]);return i}function T(e,t,n,r){r=M(e,t,n,r);return r.setAttribute("role","presentation"),r}function N(e,t){if(3==t.nodeType&&(t=t.parentNode),e.contains)return e.contains(t);do{if((t=11==t.nodeType?t.host:t)==e)return!0}while(t=t.parentNode)}function O(){var t;try{t=document.activeElement}catch(e){t=document.body||null}for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return t}function A(e,t){var n=e.className;C(t).test(n)||(e.className+=(n?" ":"")+t)}function D(e,t){for(var n=e.split(" "),r=0;r<n.length;r++)n[r]&&!C(n[r]).test(t)&&(t+=" "+n[r]);return t}var W=document.createRange?function(e,t,n,r){var i=document.createRange();return i.setEnd(r||e,n),i.setStart(e,t),i}:function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r},H=function(e){e.select()};function F(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function P(e,t,n){for(var r in t=t||{},e)!e.hasOwnProperty(r)||!1===n&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function E(e,t,n,r,i){null==t&&-1==(t=e.search(/[^\s\u00a0]/))&&(t=e.length);for(var o=r||0,l=i||0;;){var s=e.indexOf("\t",o);if(s<0||t<=s)return l+(t-o);l+=s-o,l+=n-l%n,o=s+1}}s?H=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:w&&(H=function(e){try{e.select()}catch(e){}});function I(){this.id=null,this.f=null,this.time=0,this.handler=F(this.onTimeout,this)}function R(e,t){for(var n=0;n<e.length;++n)if(e[n]==t)return n;return-1}I.prototype.onTimeout=function(e){e.id=0,e.time<=+new Date?e.f():setTimeout(e.handler,e.time-+new Date)};var z=50,B={toString:function(){return"CodeMirror.Pass"}},G={scroll:!(I.prototype.set=function(e,t){this.f=t;t=+new Date+e;(!this.id||t<this.time)&&(clearTimeout(this.id),this.id=setTimeout(this.handler,e),this.time=t)})},U={origin:"*mouse"},V={origin:"+move"};function K(e,t,n){for(var r=0,i=0;;){var o=e.indexOf("\t",r),l=(o=-1==o?e.length:o)-r;if(o==e.length||t<=i+l)return r+Math.min(l,t-i);if(i+=o-r,r=o+1,t<=(i+=n-i%n))return r}}var j=[""];function X(e){for(;j.length<=e;)j.push(Y(j)+" ");return j[e]}function Y(e){return e[e.length-1]}function _(e,t){for(var n=[],r=0;r<e.length;r++)n[r]=t(e[r],r);return n}function $(){}function q(e,t){e=Object.create?Object.create(e):($.prototype=e,new $);return t&&P(t,e),e}var Z=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;function Q(e){return/\w/.test(e)||"€"<e&&(e.toUpperCase()!=e.toLowerCase()||Z.test(e))}function J(e,t){return t?!!(-1<t.source.indexOf("\\w")&&Q(e))||t.test(e):Q(e)}function ee(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return;return 1}var te=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function ne(e){return 768<=e.charCodeAt(0)&&te.test(e)}function re(e,t,n){for(;(n<0?0<t:t<e.length)&&ne(e.charAt(t));)t+=n;return t}function ie(e,t,n){for(var r=n<t?-1:1;;){if(t==n)return t;var i=(t+n)/2,i=r<0?Math.ceil(i):Math.floor(i);if(i==t)return e(i)?t:n;e(i)?n=i:t=i+r}}var oe=null;function le(e,t,n){var r;oe=null;for(var i=0;i<e.length;++i){var o=e[i];if(o.from<t&&o.to>t)return i;o.to==t&&(o.from!=o.to&&"before"==n?r=i:oe=i),o.from==t&&(o.from!=o.to&&"before"!=n?r=i:oe=i)}return null!=r?r:oe}var se,ae,ue,ce,he,de=(se=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,ae=/[stwN]/,ue=/[LRr]/,ce=/[Lb1n]/,he=/[1n]/,function(e,t){var n="ltr"==t?"L":"R";if(0==e.length||"ltr"==t&&!se.test(e))return!1;for(var r,i=e.length,o=[],l=0;l<i;++l)o.push((r=e.charCodeAt(l))<=247?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(r):1424<=r&&r<=1524?"R":1536<=r&&r<=1785?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(r-1536):1774<=r&&r<=2220?"r":8192<=r&&r<=8203?"w":8204==r?"b":"L");for(var s=0,a=n;s<i;++s){var u=o[s];"m"==u?o[s]=a:a=u}for(var c=0,h=n;c<i;++c){var d=o[c];"1"==d&&"r"==h?o[c]="n":ue.test(d)&&"r"==(h=d)&&(o[c]="R")}for(var f=1,p=o[0];f<i-1;++f){var g=o[f];"+"==g&&"1"==p&&"1"==o[f+1]?o[f]="1":","!=g||p!=o[f+1]||"1"!=p&&"n"!=p||(o[f]=p),p=g}for(var m=0;m<i;++m){var v=o[m];if(","==v)o[m]="N";else if("%"==v){for(var y=void 0,y=m+1;y<i&&"%"==o[y];++y);for(var b=m&&"!"==o[m-1]||y<i&&"1"==o[y]?"1":"N",w=m;w<y;++w)o[w]=b;m=y-1}}for(var x=0,C=n;x<i;++x){var S=o[x];"L"==C&&"1"==S?o[x]="L":ue.test(S)&&(C=S)}for(var L=0;L<i;++L)if(ae.test(o[L])){for(var k=void 0,k=L+1;k<i&&ae.test(o[k]);++k);for(var T="L"==(L?o[L-1]:n),M=T==("L"==(k<i?o[k]:n))?T?"L":"R":n,N=L;N<k;++N)o[N]=M;L=k-1}for(var O,A=[],D=0;D<i;)if(ce.test(o[D])){var W=D;for(++D;D<i&&ce.test(o[D]);++D);A.push(new fe(0,W,D))}else{var H=D,F=A.length,P="rtl"==t?1:0;for(++D;D<i&&"L"!=o[D];++D);for(var E=H;E<D;)if(he.test(o[E])){H<E&&(A.splice(F,0,new fe(1,H,E)),F+=P);var I=E;for(++E;E<D&&he.test(o[E]);++E);A.splice(F,0,new fe(2,I,E)),F+=P,H=E}else++E;H<D&&A.splice(F,0,new fe(1,H,D))}return"ltr"==t&&(1==A[0].level&&(O=e.match(/^\s+/))&&(A[0].from=O[0].length,A.unshift(new fe(0,0,O[0].length))),1==Y(A).level&&(O=e.match(/\s+$/))&&(Y(A).to-=O[0].length,A.push(new fe(0,i-O[0].length,i)))),"rtl"==t?A.reverse():A});function fe(e,t,n){this.level=e,this.from=t,this.to=n}function pe(e,t){var n=e.order;return n=null==n?e.order=de(e.text,t):n}var ge=[],me=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):(e=e._handlers||(e._handlers={}))[t]=(e[t]||ge).concat(n)};function ve(e,t){return e._handlers&&e._handlers[t]||ge}function ye(e,t,n){var r;e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent?e.detachEvent("on"+t,n):!(e=(r=e._handlers)&&r[t])||-1<(n=R(e,n))&&(r[t]=e.slice(0,n).concat(e.slice(n+1)))}function be(e,t){var n=ve(e,t);if(n.length)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)}function we(e,t,n){return"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}}),be(e,n||t.type,e,t),Te(t)||t.codemirrorIgnore}function xe(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var n=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==R(n,t[r])&&n.push(t[r])}function Ce(e,t){return 0<ve(e,t).length}function Se(e){e.prototype.on=function(e,t){me(this,e,t)},e.prototype.off=function(e,t){ye(this,e,t)}}function Le(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function ke(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function Te(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function Me(e){Le(e),ke(e)}function Ne(e){return e.target||e.srcElement}function Oe(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),t=g&&e.ctrlKey&&1==t?3:t}var Ae,De,We=function(){if(w&&v<9)return!1;var e=M("div");return"draggable"in e||"dragDrop"in e}();var He=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;t<=r;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),l=o.indexOf("\r");-1!=l?(n.push(o.slice(0,l)),t+=l+1):(n.push(o),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Fe=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(e){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(e){}return!(!t||t.parentElement()!=e)&&0!=t.compareEndPoints("StartToEnd",t)},Pe="oncopy"in(r=M("div"))||(r.setAttribute("oncopy","return;"),"function"==typeof r.oncopy),Ee=null;var Ie={},Re={};function ze(e){if("string"==typeof e&&Re.hasOwnProperty(e))e=Re[e];else if(e&&"string"==typeof e.name&&Re.hasOwnProperty(e.name)){var t=Re[e.name];(e=q(t="string"==typeof t?{name:t}:t,e)).name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return ze("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return ze("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function Be(e,t){t=ze(t);var n=Ie[t.name];if(!n)return Be(e,"text/plain");var r=n(e,t);if(Ge.hasOwnProperty(t.name)){var i,o=Ge[t.name];for(i in o)o.hasOwnProperty(i)&&(r.hasOwnProperty(i)&&(r["_"+i]=r[i]),r[i]=o[i])}if(r.name=t.name,t.helperType&&(r.helperType=t.helperType),t.modeProps)for(var l in t.modeProps)r[l]=t.modeProps[l];return r}var Ge={};function Ue(e,t){P(t,Ge.hasOwnProperty(e)?Ge[e]:Ge[e]={})}function Ve(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n,r={};for(n in t){var i=t[n];i instanceof Array&&(i=i.concat([])),r[n]=i}return r}function Ke(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function je(e,t,n){return!e.startState||e.startState(t,n)}var Xe=function(e,t,n){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Ye(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(t<o){n=i;break}t-=o}return n.lines[t]}function _e(e,t,n){var r=[],i=t.line;return e.iter(t.line,n.line+1,function(e){e=e.text;i==n.line&&(e=e.slice(0,n.ch)),i==t.line&&(e=e.slice(t.ch)),r.push(e),++i}),r}function $e(e,t,n){var r=[];return e.iter(t,n,function(e){r.push(e.text)}),r}function qe(e,t){var n=t-e.height;if(n)for(var r=e;r;r=r.parent)r.height+=n}function Ze(e){if(null==e.parent)return null;for(var t=e.parent,n=R(t.lines,e),r=t.parent;r;r=(t=r).parent)for(var i=0;r.children[i]!=t;++i)n+=r.children[i].chunkSize();return n+t.first}function Qe(e,t){var n=e.first;e:do{for(var r=0;r<e.children.length;++r){var i=e.children[r],o=i.height;if(t<o){e=i;continue e}t-=o,n+=i.chunkSize()}return n}while(!e.lines);for(var l=0;l<e.lines.length;++l){var s=e.lines[l].height;if(t<s)break;t-=s}return n+l}function Je(e,t){return t>=e.first&&t<e.first+e.size}function et(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function tt(e,t,n){if(void 0===n&&(n=null),!(this instanceof tt))return new tt(e,t,n);this.line=e,this.ch=t,this.sticky=n}function nt(e,t){return e.line-t.line||e.ch-t.ch}function rt(e,t){return e.sticky==t.sticky&&0==nt(e,t)}function it(e){return tt(e.line,e.ch)}function ot(e,t){return nt(e,t)<0?t:e}function lt(e,t){return nt(e,t)<0?e:t}function st(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function at(e,t){if(t.line<e.first)return tt(e.first,0);var n=e.first+e.size-1;return t.line>n?tt(n,Ye(e,n).text.length):(e=Ye(e,(n=t).line).text.length,null==(t=n.ch)||e<t?tt(n.line,e):t<0?tt(n.line,0):n)}function ut(e,t){for(var n=[],r=0;r<t.length;r++)n[r]=at(e,t[r]);return n}Xe.prototype.eol=function(){return this.pos>=this.string.length},Xe.prototype.sol=function(){return this.pos==this.lineStart},Xe.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Xe.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},Xe.prototype.eat=function(e){var t=this.string.charAt(this.pos),e="string"==typeof e?t==e:t&&(e.test?e.test(t):e(t));if(e)return++this.pos,t},Xe.prototype.eatWhile=function(e){for(var t=this.pos;this.eat(e););return this.pos>t},Xe.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Xe.prototype.skipToEnd=function(){this.pos=this.string.length},Xe.prototype.skipTo=function(e){e=this.string.indexOf(e,this.pos);if(-1<e)return this.pos=e,!0},Xe.prototype.backUp=function(e){this.pos-=e},Xe.prototype.column=function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=E(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?E(this.string,this.lineStart,this.tabSize):0)},Xe.prototype.indentation=function(){return E(this.string,null,this.tabSize)-(this.lineStart?E(this.string,this.lineStart,this.tabSize):0)},Xe.prototype.match=function(e,t,n){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&0<r.index?null:(r&&!1!==t&&(this.pos+=r[0].length),r)}r=function(e){return n?e.toLowerCase():e};if(r(this.string.substr(this.pos,e.length))==r(e))return!1!==t&&(this.pos+=e.length),!0},Xe.prototype.current=function(){return this.string.slice(this.start,this.pos)},Xe.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},Xe.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},Xe.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};function ct(e,t){this.state=e,this.lookAhead=t}var ht=function(e,t,n,r){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=r||0,this.baseTokens=null,this.baseTokenPos=1};function dt(t,n,r,e){var a=[t.state.modeGen],i={};xt(t,n.text,t.doc.mode,r,function(e,t){return a.push(e,t)},i,e);for(var u=r.state,o=0;o<t.state.overlays.length;++o)!function(e){r.baseTokens=a;var o=t.state.overlays[e],l=1,s=0;r.state=!0,xt(t,n.text,o.mode,r,function(e,t){for(var n=l;s<e;){var r=a[l];e<r&&a.splice(l,1,e,a[l+1],r),l+=2,s=Math.min(e,r)}if(t)if(o.opaque)a.splice(n,l-n,e,"overlay "+t),l=n+2;else for(;n<l;n+=2){var i=a[n+1];a[n+1]=(i?i+" ":"")+"overlay "+t}},i),r.state=u,r.baseTokens=null,r.baseTokenPos=1}(o);return{styles:a,classes:i.bgClass||i.textClass?i:null}}function ft(e,t,n){var r,i,o;return t.styles&&t.styles[0]==e.state.modeGen||(r=pt(e,Ze(t)),i=t.text.length>e.options.maxHighlightLength&&Ve(e.doc.mode,r.state),o=dt(e,t,r),i&&(r.state=i),t.stateAfter=r.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))),t.styles}function pt(n,r,e){var t=n.doc,i=n.display;if(!t.mode.startState)return new ht(t,!0,r);var o=function(e,t,n){for(var r,i,o=e.doc,l=n?-1:t-(e.doc.mode.innerMode?1e3:100),s=t;l<s;--s){if(s<=o.first)return o.first;var a=Ye(o,s-1),u=a.stateAfter;if(u&&(!n||s+(u instanceof ct?u.lookAhead:0)<=o.modeFrontier))return s;a=E(a.text,null,e.options.tabSize);(null==i||a<r)&&(i=s-1,r=a)}return i}(n,r,e),l=o>t.first&&Ye(t,o-1).stateAfter,s=l?ht.fromSaved(t,l,o):new ht(t,je(t.mode),o);return t.iter(o,r,function(e){gt(n,e.text,s);var t=s.line;e.stateAfter=t==r-1||t%5==0||t>=i.viewFrom&&t<i.viewTo?s.save():null,s.nextLine()}),e&&(t.modeFrontier=s.line),s}function gt(e,t,n,r){var i=e.doc.mode,o=new Xe(t,e.options.tabSize,n);for(o.start=o.pos=r||0,""==t&&mt(i,n.state);!o.eol();)vt(i,o,n.state),o.start=o.pos}function mt(e,t){if(e.blankLine)return e.blankLine(t);if(e.innerMode){t=Ke(e,t);return t.mode.blankLine?t.mode.blankLine(t.state):void 0}}function vt(e,t,n,r){for(var i=0;i<10;i++){r&&(r[0]=Ke(e,n).mode);var o=e.token(t,n);if(t.pos>t.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}ht.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},ht.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},ht.prototype.nextLine=function(){this.line++,0<this.maxLookAhead&&this.maxLookAhead--},ht.fromSaved=function(e,t,n){return t instanceof ct?new ht(e,Ve(e.mode,t.state),n,t.lookAhead):new ht(e,Ve(e.mode,t),n)},ht.prototype.save=function(e){e=!1!==e?Ve(this.doc.mode,this.state):this.state;return 0<this.maxLookAhead?new ct(e,this.maxLookAhead):e};var yt=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n};function bt(e,t,n,r){var i,o,l=e.doc,s=l.mode,a=Ye(l,(t=at(l,t)).line),u=pt(e,t.line,n),c=new Xe(a.text,e.options.tabSize,u);for(r&&(o=[]);(r||c.pos<t.ch)&&!c.eol();)c.start=c.pos,i=vt(s,c,u.state),r&&o.push(new yt(c,i,Ve(l.mode,u.state)));return r?o:new yt(c,i,u.state)}function wt(e,t){if(e)for(;;){var n=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;e=e.slice(0,n.index)+e.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==t[r]?t[r]=n[2]:new RegExp("(?:^|\\s)"+n[2]+"(?:$|\\s)").test(t[r])||(t[r]+=" "+n[2])}return e}function xt(e,t,n,r,i,o,l){var s=n.flattenSpans;null==s&&(s=e.options.flattenSpans);var a=0,u=null,c=new Xe(t,e.options.tabSize,r),h=e.options.addModeClass&&[null];for(""==t&&wt(mt(n,r.state),o);!c.eol();){var d,f=c.pos>e.options.maxHighlightLength?(s=!1,l&&gt(e,t,r,c.pos),c.pos=t.length,null):wt(vt(n,c,r.state,h),o);if(!h||(d=h[0].name)&&(f="m-"+(f?d+" "+f:d)),!s||u!=f){for(;a<c.start;)i(a=Math.min(c.start,a+5e3),u);u=f}c.start=c.pos}for(;a<c.pos;){var p=Math.min(c.pos,a+5e3);i(p,u),a=p}}var Ct=!1,St=!1;function Lt(e,t,n){this.marker=e,this.from=t,this.to=n}function kt(e,t){if(e)for(var n=0;n<e.length;++n){var r=e[n];if(r.marker==t)return r}}function Tt(e,t){if(t.full)return null;var n=Je(e,t.from.line)&&Ye(e,t.from.line).markedSpans,r=Je(e,t.to.line)&&Ye(e,t.to.line).markedSpans;if(!n&&!r)return null;var i=t.from.ch,o=t.to.ch,e=0==nt(t.from,t.to),l=function(e,t,n){var r;if(e)for(var i=0;i<e.length;++i){var o,l=e[i],s=l.marker;!(null==l.from||(s.inclusiveLeft?l.from<=t:l.from<t))&&(l.from!=t||"bookmark"!=s.type||n&&l.marker.insertLeft)||(o=null==l.to||(s.inclusiveRight?l.to>=t:l.to>t),(r=r||[]).push(new Lt(s,l.from,o?null:l.to)))}return r}(n,i,e),s=function(e,t,n){var r;if(e)for(var i=0;i<e.length;++i){var o,l=e[i],s=l.marker;!(null==l.to||(s.inclusiveRight?l.to>=t:l.to>t))&&(l.from!=t||"bookmark"!=s.type||n&&!l.marker.insertLeft)||(o=null==l.from||(s.inclusiveLeft?l.from<=t:l.from<t),(r=r||[]).push(new Lt(s,o?null:l.from-t,null==l.to?null:l.to-t)))}return r}(r,o,e),a=1==t.text.length,u=Y(t.text).length+(a?i:0);if(l)for(var c=0;c<l.length;++c){var h,d=l[c];null==d.to&&((h=kt(s,d.marker))?a&&(d.to=null==h.to?null:h.to+u):d.to=i)}if(s)for(var f=0;f<s.length;++f){var p=s[f];null!=p.to&&(p.to+=u),null==p.from?kt(l,p.marker)||(p.from=u,a&&(l=l||[]).push(p)):(p.from+=u,a&&(l=l||[]).push(p))}l=l&&Mt(l),s&&s!=l&&(s=Mt(s));var g=[l];if(!a){var m,v=t.text.length-2;if(0<v&&l)for(var y=0;y<l.length;++y)null==l[y].to&&(m=m||[]).push(new Lt(l[y].marker,null,null));for(var b=0;b<v;++b)g.push(m);g.push(s)}return g}function Mt(e){for(var t=0;t<e.length;++t){var n=e[t];null!=n.from&&n.from==n.to&&!1!==n.marker.clearWhenEmpty&&e.splice(t--,1)}return e.length?e:null}function Nt(e){var t=e.markedSpans;if(t){for(var n=0;n<t.length;++n)t[n].marker.detachLine(e);e.markedSpans=null}}function Ot(e,t){if(t){for(var n=0;n<t.length;++n)t[n].marker.attachLine(e);e.markedSpans=t}}function At(e){return e.inclusiveLeft?-1:0}function Dt(e){return e.inclusiveRight?1:0}function Wt(e,t){var n=e.lines.length-t.lines.length;if(0!=n)return n;var r=e.find(),i=t.find(),n=nt(r.from,i.from)||At(e)-At(t);if(n)return-n;i=nt(r.to,i.to)||Dt(e)-Dt(t);return i||t.id-e.id}function Ht(e,t){var n,r=St&&e.markedSpans;if(r)for(var i,o=0;o<r.length;++o)(i=r[o]).marker.collapsed&&null==(t?i.from:i.to)&&(!n||Wt(n,i.marker)<0)&&(n=i.marker);return n}function Ft(e){return Ht(e,!0)}function Pt(e){return Ht(e,!1)}function Et(e,t,n,r,i){var t=Ye(e,t),o=St&&t.markedSpans;if(o)for(var l=0;l<o.length;++l){var s=o[l];if(s.marker.collapsed){var a=s.marker.find(0),u=nt(a.from,n)||At(s.marker)-At(i),c=nt(a.to,r)||Dt(s.marker)-Dt(i);if(!(0<=u&&c<=0||u<=0&&0<=c)&&(u<=0&&(s.marker.inclusiveRight&&i.inclusiveLeft?0<=nt(a.to,n):0<nt(a.to,n))||0<=u&&(s.marker.inclusiveRight&&i.inclusiveLeft?nt(a.from,r)<=0:nt(a.from,r)<0)))return 1}}}function It(e){for(var t;t=Ft(e);)e=t.find(-1,!0).line;return e}function Rt(e,t){var n=Ye(e,t),e=It(n);return n==e?t:Ze(e)}function zt(e,t){if(t>e.lastLine())return t;var n,r=Ye(e,t);if(!Bt(e,r))return t;for(;n=Pt(r);)r=n.find(1,!0).line;return Ze(r)+1}function Bt(e,t){var n=St&&t.markedSpans;if(n)for(var r,i=0;i<n.length;++i)if((r=n[i]).marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&function e(t,n,r){if(null==r.to){var i=r.marker.find(1,!0);return e(t,i.line,kt(i.line.markedSpans,r.marker))}if(r.marker.inclusiveRight&&r.to==n.text.length)return!0;for(var o=void 0,l=0;l<n.markedSpans.length;++l)if((o=n.markedSpans[l]).marker.collapsed&&!o.marker.widgetNode&&o.from==r.to&&(null==o.to||o.to!=r.from)&&(o.marker.inclusiveLeft||r.marker.inclusiveRight)&&e(t,n,o))return!0}(e,t,r))return!0}}function Gt(e){for(var t=0,n=(e=It(e)).parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==e)break;t+=i.height}for(var o=n.parent;o;o=(n=o).parent)for(var l=0;l<o.children.length;++l){var s=o.children[l];if(s==n)break;t+=s.height}return t}function Ut(e){if(0==e.height)return 0;for(var t,n=e.text.length,r=e;t=Ft(r);){var i=t.find(0,!0),r=i.from.line;n+=i.from.ch-i.to.ch}for(r=e;t=Pt(r);){var o=t.find(0,!0);n-=r.text.length-o.from.ch,n+=(r=o.to.line).text.length-o.to.ch}return n}function Vt(e){var n=e.display,e=e.doc;n.maxLine=Ye(e,e.first),n.maxLineLength=Ut(n.maxLine),n.maxLineChanged=!0,e.iter(function(e){var t=Ut(e);t>n.maxLineLength&&(n.maxLineLength=t,n.maxLine=e)})}var Kt=function(e,t,n){this.text=e,Ot(this,t),this.height=n?n(this):1};Kt.prototype.lineNo=function(){return Ze(this)},Se(Kt);var jt={},Xt={};function Yt(e,t){if(!e||/^\s*$/.test(e))return null;t=t.addModeClass?Xt:jt;return t[e]||(t[e]=e.replace(/\S+/g,"cm-$&"))}function _t(e,t){var n=T("span",null,null,f?"padding-right: .1px":null),r={pre:T("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:e.getOption("lineWrapping")};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o=i?t.rest[i-1]:t.line,l=void 0;r.pos=0,r.addToken=qt,function(e){if(null!=De)return De;var t=k(e,document.createTextNode("AخA")),n=W(t,0,1).getBoundingClientRect(),t=W(t,1,2).getBoundingClientRect();return L(e),n&&n.left!=n.right&&(De=t.right-n.right<3)}(e.display.measure)&&(l=pe(o,e.doc.direction))&&(r.addToken=function(h,d){return function(e,t,n,r,i,o,l){n=n?n+" cm-force-border":"cm-force-border";for(var s=e.pos,a=s+t.length;;){for(var u=void 0,c=0;c<d.length&&!((u=d[c]).to>s&&u.from<=s);c++);if(u.to>=a)return h(e,t,n,r,i,o,l);h(e,t.slice(0,u.to-s),n,r,null,o,l),r=null,t=t.slice(u.to-s),s=u.to}}}(r.addToken,l)),r.map=[],function(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var l,s,a,u,c,h,d,f=i.length,p=0,g=1,m="",v=0;;){if(v==p){a=u=c=s="",h=d=null,v=1/0;for(var y=[],b=void 0,w=0;w<r.length;++w){var x=r[w],C=x.marker;if("bookmark"==C.type&&x.from==p&&C.widgetNode)y.push(C);else if(x.from<=p&&(null==x.to||x.to>p||C.collapsed&&x.to==p&&x.from==p)){if(null!=x.to&&x.to!=p&&v>x.to&&(v=x.to,u=""),C.className&&(a+=" "+C.className),C.css&&(s=(s?s+";":"")+C.css),C.startStyle&&x.from==p&&(c+=" "+C.startStyle),C.endStyle&&x.to==v&&(b=b||[]).push(C.endStyle,x.to),C.title&&((d=d||{}).title=C.title),C.attributes)for(var S in C.attributes)(d=d||{})[S]=C.attributes[S];C.collapsed&&(!h||Wt(h.marker,C)<0)&&(h=x)}else x.from>p&&v>x.from&&(v=x.from)}if(b)for(var L=0;L<b.length;L+=2)b[L+1]==v&&(u+=" "+b[L]);if(!h||h.from==p)for(var k=0;k<y.length;++k)Zt(t,0,y[k]);if(h&&(h.from||0)==p){if(Zt(t,(null==h.to?f+1:h.to)-p,h.marker,null==h.from),null==h.to)return;h.to==p&&(h=!1)}}if(f<=p)break;for(var T=Math.min(f,v);;){if(m){var M,N=p+m.length;if(h||(M=T<N?m.slice(0,T-p):m,t.addToken(t,M,l?l+a:a,c,p+M.length==v?u:"",s,d)),T<=N){m=m.slice(T-p),p=T;break}p=N,c=""}m=i.slice(o,o=n[g++]),l=Yt(n[g++],t.cm.options)}}else for(var O=1;O<n.length;O+=2)t.addToken(t,i.slice(o,o=n[O]),Yt(n[O+1],t.cm.options))}(o,r,ft(e,o,t!=e.display.externalMeasured&&Ze(o))),o.styleClasses&&(o.styleClasses.bgClass&&(r.bgClass=D(o.styleClasses.bgClass,r.bgClass||"")),o.styleClasses.textClass&&(r.textClass=D(o.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(function(e){null==Ae&&(t=M("span","​"),k(e,M("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Ae=t.offsetWidth<=1&&2<t.offsetHeight&&!(w&&v<8)));var t=Ae?M("span","​"):M("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return t.setAttribute("cm-text",""),t}(e.display.measure))),0==i?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return f&&(n=r.content.lastChild,(/\bcm-tab\b/.test(n.className)||n.querySelector&&n.querySelector(".cm-tab"))&&(r.content.className="cm-tab-wrap-hack")),be(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=D(r.pre.className,r.textClass||"")),r}function $t(e){var t=M("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function qt(e,t,n,r,i,o,l){if(t){var s=e.splitSpaces?function(e,t){if(1<e.length&&!/ /.test(e))return e;for(var n=t,r="",i=0;i<e.length;i++){var o=e.charAt(i);" "!=o||!n||i!=e.length-1&&32!=e.charCodeAt(i+1)||(o=" "),r+=o,n=" "==o}return r}(t,e.trailingSpace):t,a=e.cm.state.specialChars,u=!1;if(a.test(t))for(var c=document.createDocumentFragment(),h=0;;){a.lastIndex=h;var d=a.exec(t),f=d?d.index-h:t.length-h;if(f&&(p=document.createTextNode(s.slice(h,h+f)),w&&v<9?c.appendChild(M("span",[p])):c.appendChild(p),e.map.push(e.pos,e.pos+f,p),e.col+=f,e.pos+=f),!d)break;h+=1+f;var p=void 0;"\t"==d[0]?(f=(f=e.cm.options.tabSize)-e.col%f,(p=c.appendChild(M("span",X(f),"cm-tab"))).setAttribute("role","presentation"),p.setAttribute("cm-text","\t"),e.col+=f):("\r"==d[0]||"\n"==d[0]?(p=c.appendChild(M("span","\r"==d[0]?"␍":"␤","cm-invalidchar"))).setAttribute("cm-text",d[0]):((p=e.cm.options.specialCharPlaceholder(d[0])).setAttribute("cm-text",d[0]),w&&v<9?c.appendChild(M("span",[p])):c.appendChild(p)),e.col+=1),e.map.push(e.pos,e.pos+1,p),e.pos++}else e.col+=t.length,c=document.createTextNode(s),e.map.push(e.pos,e.pos+t.length,c),w&&v<9&&(u=!0),e.pos+=t.length;if(e.trailingSpace=32==s.charCodeAt(t.length-1),n||r||i||u||o||l){n=n||"";r&&(n+=r),i&&(n+=i);var g=M("span",[c],n,o);if(l)for(var m in l)l.hasOwnProperty(m)&&"style"!=m&&"class"!=m&&g.setAttribute(m,l[m]);return e.content.appendChild(g)}e.content.appendChild(c)}}function Zt(e,t,n,r){var i=!r&&n.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!r&&e.cm.display.input.needsContentAttribute&&(i=i||e.content.appendChild(document.createElement("span"))).setAttribute("cm-marker",n.id),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function Qt(e,t,n){this.line=t,this.rest=function(e){for(var t,n;t=Pt(e);)e=t.find(1,!0).line,(n=n||[]).push(e);return n}(t),this.size=this.rest?Ze(Y(this.rest))-n+1:1,this.node=this.text=null,this.hidden=Bt(e,t)}function Jt(e,t,n){for(var r=[],i=t;i<n;i=l){var o=new Qt(e.doc,Ye(e.doc,i),i),l=i+o.size;r.push(o)}return r}var en=null;function tn(e,t){e=e.ownsGroup;if(e)try{!function(e){var t=e.delayedCallbacks,n=0;do{for(;n<t.length;n++)t[n].call(null);for(var r=0;r<e.ops.length;r++){var i=e.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++].call(null,i.cm)}}while(n<t.length)}(e)}finally{en=null,t(e)}}var nn=null;function rn(e,t){var n=ve(e,t);if(n.length){var r,i=Array.prototype.slice.call(arguments,2);en?r=en.delayedCallbacks:nn?r=nn:(r=nn=[],setTimeout(on,0));for(var o=0;o<n.length;++o)!function(e){r.push(function(){return n[e].apply(null,i)})}(o)}}function on(){var e=nn;nn=null;for(var t=0;t<e.length;++t)e[t]()}function ln(e,t,n,r){for(var i=0;i<t.changes.length;i++){var o=t.changes[i];"text"==o?function(e,t){var n=t.text.className,r=an(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,un(e,t)):n&&(t.text.className=n)}(e,t):"gutter"==o?cn(e,t,n,r):"class"==o?un(e,t):"widget"==o&&function(e,t,n){t.alignable&&(t.alignable=null);for(var r=C("CodeMirror-linewidget"),i=t.node.firstChild,o=void 0;i;i=o)o=i.nextSibling,r.test(i.className)&&t.node.removeChild(i);hn(e,t,n)}(e,t,r)}t.changes=null}function sn(e){return e.node==e.text&&(e.node=M("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),w&&v<8&&(e.node.style.zIndex=2)),e.node}function an(e,t){var n=e.display.externalMeasured;return n&&n.line==t.line?(e.display.externalMeasured=null,t.measure=n.measure,n.built):_t(e,t)}function un(e,t){var n,r;n=e,(r=(i=t).bgClass?i.bgClass+" "+(i.line.bgClass||""):i.line.bgClass)&&(r+=" CodeMirror-linebackground"),i.background?r?i.background.className=r:(i.background.parentNode.removeChild(i.background),i.background=null):r&&(e=sn(i),i.background=e.insertBefore(M("div",null,r),e.firstChild),n.display.input.setUneditable(i.background)),t.line.wrapClass?sn(t).className=t.line.wrapClass:t.node!=t.text&&(t.node.className="");var i=t.textClass?t.textClass+" "+(t.line.textClass||""):t.line.textClass;t.text.className=i||""}function cn(e,t,n,r){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null),t.gutterBackground&&(t.node.removeChild(t.gutterBackground),t.gutterBackground=null),t.line.gutterClass&&(o=sn(t),t.gutterBackground=M("div",null,"CodeMirror-gutter-background "+t.line.gutterClass,"left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),e.display.input.setUneditable(t.gutterBackground),o.insertBefore(t.gutterBackground,t.text));var i=t.line.gutterMarkers;if(e.options.lineNumbers||i){var o=sn(t),l=t.gutter=M("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px");if(l.setAttribute("aria-hidden","true"),e.display.input.setUneditable(l),o.insertBefore(l,t.text),t.line.gutterClass&&(l.className+=" "+t.line.gutterClass),!e.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(t.lineNumber=l.appendChild(M("div",et(e.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),i)for(var s=0;s<e.display.gutterSpecs.length;++s){var a=e.display.gutterSpecs[s].className,u=i.hasOwnProperty(a)&&i[a];u&&l.appendChild(M("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[a]+"px; width: "+r.gutterWidth[a]+"px"))}}}function hn(e,t,n){if(dn(e,t.line,t,n,!0),t.rest)for(var r=0;r<t.rest.length;r++)dn(e,t.rest[r],t,n,!1)}function dn(e,t,n,r,i){if(t.widgets)for(var o=sn(n),l=0,s=t.widgets;l<s.length;++l){var a=s[l],u=M("div",[a.node],"CodeMirror-linewidget"+(a.className?" "+a.className:""));a.handleMouseEvents||u.setAttribute("cm-ignore-events","true"),function(e,t,n,r){e.noHScroll&&((n.alignable||(n.alignable=[])).push(t),n=r.wrapperWidth,t.style.left=r.fixedPos+"px",e.coverGutter||(n-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=n+"px");e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}(a,u,n,r),e.display.input.setUneditable(u),i&&a.above?o.insertBefore(u,n.gutter||n.text):o.appendChild(u),rn(a,"redraw")}}function fn(e){if(null!=e.height)return e.height;var t,n=e.doc.cm;return n?(N(document.body,e.node)||(t="position: relative;",e.coverGutter&&(t+="margin-left: -"+n.display.gutters.offsetWidth+"px;"),e.noHScroll&&(t+="width: "+n.display.wrapper.clientWidth+"px;"),k(n.display.measure,M("div",[e.node],null,t))),e.height=e.node.parentNode.offsetHeight):0}function pn(e,t){for(var n=Ne(t);n!=e.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==e.sizer&&n!=e.mover)return 1}function gn(e){return e.lineSpace.offsetTop}function mn(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function vn(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=k(e.measure,M("pre","x","CodeMirror-line-like")),t=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,t={left:parseInt(t.paddingLeft),right:parseInt(t.paddingRight)};return isNaN(t.left)||isNaN(t.right)||(e.cachedPaddingH=t),t}function yn(e){return z-e.display.nativeBarWidth}function bn(e){return e.display.scroller.clientWidth-yn(e)-e.display.barWidth}function wn(e){return e.display.scroller.clientHeight-yn(e)-e.display.barHeight}function xn(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var i=0;i<e.rest.length;i++)if(Ze(e.rest[i])>n)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function Cn(e,t,n,r){return kn(e,Ln(e,t),n,r)}function Sn(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[er(e,t)];e=e.display.externalMeasured;return e&&t>=e.lineN&&t<e.lineN+e.size?e:void 0}function Ln(e,t){var n,r,i=Ze(t),o=Sn(e,i);o&&!o.text?o=null:o&&o.changes&&(ln(e,o,i,$n(e)),e.curOp.forceUpdate=!0),o||(n=e,e=Ze(r=It(r=t)),(r=n.display.externalMeasured=new Qt(n.doc,r,e)).lineN=e,e=r.built=_t(n,r),r.text=e.pre,k(n.display.lineMeasure,e.pre),o=r);i=xn(o,t,i);return{line:t,view:o,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function kn(e,t,n,r,i){var o,l=(n=t.before?-1:n)+(r||"");return t.cache.hasOwnProperty(l)?o=t.cache[l]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(function(e,t,n){var r=e.options.lineWrapping,e=r&&bn(e);if(!t.measure.heights||r&&t.measure.width!=e){var i=t.measure.heights=[];if(r){t.measure.width=e;for(var o=t.text.firstChild.getClientRects(),l=0;l<o.length-1;l++){var s=o[l],a=o[l+1];2<Math.abs(s.bottom-a.bottom)&&i.push((s.bottom+a.top)/2-n.top)}}i.push(n.bottom-n.top)}}(e,t.view,t.rect),t.hasHeights=!0),(o=function(e,t,n,r){var i,o=Nn(t.map,n,r),l=o.node,s=o.start,a=o.end,u=o.collapse;if(3==l.nodeType){for(var c=0;c<4;c++){for(;s&&ne(t.line.text.charAt(o.coverStart+s));)--s;for(;o.coverStart+a<o.coverEnd&&ne(t.line.text.charAt(o.coverStart+a));)++a;if((i=w&&v<9&&0==s&&a==o.coverEnd-o.coverStart?l.parentNode.getBoundingClientRect():function(e,t){var n=Mn;if("left"==t)for(var r=0;r<e.length&&(n=e[r]).left==n.right;r++);else for(var i=e.length-1;0<=i&&(n=e[i]).left==n.right;i--);return n}(W(l,s,a).getClientRects(),r)).left||i.right||0==s)break;a=s,s-=1,u="right"}w&&v<11&&(i=function(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!function(e){if(null!=Ee)return Ee;var e=(t=k(e,M("span","x"))).getBoundingClientRect(),t=W(t,0,1).getBoundingClientRect();return Ee=1<Math.abs(e.left-t.left)}(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,e=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*e,bottom:t.bottom*e}}(e.display.measure,i))}else 0<s&&(u=r="right"),i=e.options.lineWrapping&&1<(g=l.getClientRects()).length?g["right"==r?g.length-1:0]:l.getBoundingClientRect();!(w&&v<9)||s||i&&(i.left||i.right)||(m=l.parentNode.getClientRects()[0],i=m?{left:m.left,right:m.left+_n(e.display),top:m.top,bottom:m.bottom}:Mn);for(var h=i.top-t.rect.top,n=i.bottom-t.rect.top,d=(h+n)/2,f=t.view.measure.heights,p=0;p<f.length-1&&!(d<f[p]);p++);var g=p?f[p-1]:0,m=f[p],m={left:("right"==u?i.right:i.left)-t.rect.left,right:("left"==u?i.left:i.right)-t.rect.left,top:g,bottom:m};i.left||i.right||(m.bogus=!0);e.options.singleCursorHeightPerLine||(m.rtop=h,m.rbottom=n);return m}(e,t,n,r)).bogus||(t.cache[l]=o)),{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}var Tn,Mn={left:0,right:0,top:0,bottom:0};function Nn(e,t,n){for(var r,i,o,l,s,a,u=0;u<e.length;u+=3)if(s=e[u],a=e[u+1],t<s?(i=0,o=1,l="left"):t<a?o=(i=t-s)+1:(u==e.length-3||t==a&&e[u+3]>t)&&(i=(o=a-s)-1,a<=t&&(l="right")),null!=i){if(r=e[u+2],s==a&&n==(r.insertLeft?"left":"right")&&(l=n),"left"==n&&0==i)for(;u&&e[u-2]==e[u-3]&&e[u-1].insertLeft;)r=e[2+(u-=3)],l="left";if("right"==n&&i==a-s)for(;u<e.length-3&&e[u+3]==e[u+4]&&!e[u+5].insertLeft;)r=e[(u+=3)+2],l="right";break}return{node:r,start:i,end:o,collapse:l,coverStart:s,coverEnd:a}}function On(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function An(e){e.display.externalMeasure=null,L(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)On(e.display.view[t])}function Dn(e){An(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function Wn(){return o&&a?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Hn(){return o&&a?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):window.pageYOffset||(document.documentElement||document.body).scrollTop}function Fn(e){var t=0;if(e.widgets)for(var n=0;n<e.widgets.length;++n)e.widgets[n].above&&(t+=fn(e.widgets[n]));return t}function Pn(e,t,n,r,i){if(i||(i=Fn(t),n.top+=i,n.bottom+=i),"line"==r)return n;r=r||"local";t=Gt(t);return"local"==r?t+=gn(e.display):t-=e.display.viewOffset,"page"!=r&&"window"!=r||(t+=(e=e.display.lineSpace.getBoundingClientRect()).top+("window"==r?0:Hn()),r=e.left+("window"==r?0:Wn()),n.left+=r,n.right+=r),n.top+=t,n.bottom+=t,n}function En(e,t,n){if("div"==n)return t;var r=t.left,t=t.top;"page"==n?(r-=Wn(),t-=Hn()):"local"!=n&&n||(r+=(n=e.display.sizer.getBoundingClientRect()).left,t+=n.top);e=e.display.lineSpace.getBoundingClientRect();return{left:r-e.left,top:t-e.top}}function In(e,t,n,r,i){return Pn(e,r=r||Ye(e.doc,t.line),Cn(e,r,t.ch,i),n)}function Rn(n,e,r,i,o,l){function s(e,t){e=kn(n,o,e,t?"right":"left",l);return t?e.left=e.right:e.right=e.left,Pn(n,i,e,r)}i=i||Ye(n.doc,e.line),o=o||Ln(n,i);var a=pe(i,n.doc.direction),t=e.ch,u=e.sticky;if(t>=i.text.length?(t=i.text.length,u="before"):t<=0&&(t=0,u="after"),!a)return s("before"==u?t-1:t,"before"==u);function c(e,t,n){return s(n?e-1:e,1==a[t].level!=n)}var h=le(a,t,u),e=oe,h=c(t,h,"before"==u);return null!=e&&(h.other=c(t,e,"before"!=u)),h}function zn(e,t){var n=0;t=at(e.doc,t),e.options.lineWrapping||(n=_n(e.display)*t.ch);t=Ye(e.doc,t.line),e=Gt(t)+gn(e.display);return{left:n,right:n,top:e,bottom:e+t.height}}function Bn(e,t,n,r,i){n=tt(e,t,n);return n.xRel=i,r&&(n.outside=r),n}function Gn(e,t,n){var r=e.doc;if((n+=e.display.viewOffset)<0)return Bn(r.first,0,null,-1,-1);var i=Qe(r,n),o=r.first+r.size-1;if(o<i)return Bn(r.first+r.size-1,Ye(r,o).text.length,null,1,1);t<0&&(t=0);for(var l=Ye(r,i);;){var s=function(n,e,t,r,i){i-=Gt(e);var o=Ln(n,e),l=Fn(e),s=0,a=e.text.length,u=!0,c=pe(e,n.doc.direction);c&&(f=(n.options.lineWrapping?Xn:jn)(n,e,t,o,c,r,i),u=1!=f.level,s=u?f.from:f.to-1,a=u?f.to:f.from-1);var h=null,d=null,c=ie(function(e){var t=kn(n,o,e);return t.top+=l,t.bottom+=l,Kn(t,r,i,!1)&&(t.top<=i&&t.left<=r&&(h=e,d=t),1)},s,a),f=!1;{var p,g;d?(p=r-d.left<d.right-r,c=h+((g=p==u)?0:1),g=g?"after":"before",p=p?d.left:d.right):(u||c!=a&&c!=s||c++,g=0==c||c!=e.text.length&&kn(n,o,c-(u?1:0)).bottom+l<=i==u?"after":"before",u=Rn(n,tt(t,c,g),"line",e,o),p=u.left,f=i<u.top?-1:i>=u.bottom?1:0)}return c=re(e.text,c,1),Bn(t,c,g,f,r-p)}(e,l,i,t,n),a=function(e,t){var n,r=St&&e.markedSpans;if(r)for(var i=0;i<r.length;++i){var o=r[i];o.marker.collapsed&&(null==o.from||o.from<t)&&(null==o.to||o.to>t)&&(!n||Wt(n,o.marker)<0)&&(n=o.marker)}return n}(l,s.ch+(0<s.xRel||0<s.outside?1:0));if(!a)return s;a=a.find(1);if(a.line==i)return a;l=Ye(r,i=a.line)}}function Un(t,e,n,r){r-=Fn(e);var i=e.text.length,e=ie(function(e){return kn(t,n,e-1).bottom<=r},i,0);return{begin:e,end:i=ie(function(e){return kn(t,n,e).top>r},e,i)}}function Vn(e,t,n,r){return Un(e,t,n=n||Ln(e,t),Pn(e,t,kn(e,n,r),"line").top)}function Kn(e,t,n,r){return!(e.bottom<=n)&&(e.top>n||(r?e.left:e.right)>t)}function jn(n,r,i,o,l,s,a){var e,t=ie(function(e){var t=l[e],e=1!=t.level;return Kn(Rn(n,tt(i,e?t.to:t.from,e?"before":"after"),"line",r,o),s,a,!0)},0,l.length-1),u=l[t];return 0<t&&(e=1!=u.level,Kn(e=Rn(n,tt(i,e?u.from:u.to,e?"after":"before"),"line",r,o),s,a,!0)&&e.top>a&&(u=l[t-1])),u}function Xn(e,t,n,r,i,o,l){var l=Un(e,t,r,l),s=l.begin,a=l.end;/\s/.test(t.text.charAt(a-1))&&a--;for(var u=null,c=null,h=0;h<i.length;h++){var d,f=i[h];f.from>=a||f.to<=s||(d=(d=kn(e,r,1!=f.level?Math.min(a,f.to)-1:Math.max(s,f.from)).right)<o?o-d+1e9:d-o,(!u||d<c)&&(u=f,c=d))}return u=(u=(u=u||i[i.length-1]).from<s?{from:s,to:u.to,level:u.level}:u).to>a?{from:u.from,to:a,level:u.level}:u}function Yn(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Tn){Tn=M("pre",null,"CodeMirror-line-like");for(var t=0;t<49;++t)Tn.appendChild(document.createTextNode("x")),Tn.appendChild(M("br"));Tn.appendChild(document.createTextNode("x"))}k(e.measure,Tn);var n=Tn.offsetHeight/50;return 3<n&&(e.cachedTextHeight=n),L(e.measure),n||1}function _n(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=M("span","xxxxxxxxxx"),n=M("pre",[t],"CodeMirror-line-like");k(e.measure,n);t=t.getBoundingClientRect(),t=(t.right-t.left)/10;return 2<t&&(e.cachedCharWidth=t),t||10}function $n(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,l=0;o;o=o.nextSibling,++l){var s=e.display.gutterSpecs[l].className;n[s]=o.offsetLeft+o.clientLeft+i,r[s]=o.clientWidth}return{fixedPos:qn(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function qn(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function Zn(r){var i=Yn(r.display),o=r.options.lineWrapping,l=o&&Math.max(5,r.display.scroller.clientWidth/_n(r.display)-3);return function(e){if(Bt(r.doc,e))return 0;var t=0;if(e.widgets)for(var n=0;n<e.widgets.length;n++)e.widgets[n].height&&(t+=e.widgets[n].height);return o?t+(Math.ceil(e.text.length/l)||1)*i:t+i}}function Qn(e){var t=e.doc,n=Zn(e);t.iter(function(e){var t=n(e);t!=e.height&&qe(e,t)})}function Jn(e,t,n,r){var i=e.display;if(!n&&"true"==Ne(t).getAttribute("cm-not-content"))return null;var o,i=i.lineSpace.getBoundingClientRect();try{o=t.clientX-i.left,s=t.clientY-i.top}catch(e){return null}var l,s=Gn(e,o,s);return r&&0<s.xRel&&(l=Ye(e.doc,s.line).text).length==s.ch&&(l=E(l,l.length,e.options.tabSize)-l.length,s=tt(s.line,Math.max(0,Math.round((o-vn(e.display).left)/_n(e.display))-l))),s}function er(e,t){if(t>=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,r=0;r<n.length;r++)if((t-=n[r].size)<0)return r}function tr(e,t,n,r){null==t&&(t=e.doc.first),null==n&&(n=e.doc.first+e.doc.size);var i,o,l=e.display;(r=r||0)&&n<l.viewTo&&(null==l.updateLineNumbers||l.updateLineNumbers>t)&&(l.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=l.viewTo?St&&Rt(e.doc,t)<l.viewTo&&rr(e):n<=l.viewFrom?St&&zt(e.doc,n+r)>l.viewFrom?rr(e):(l.viewFrom+=r,l.viewTo+=r):t<=l.viewFrom&&n>=l.viewTo?rr(e):t<=l.viewFrom?(i=ir(e,n,n+r,1))?(l.view=l.view.slice(i.index),l.viewFrom=i.lineN,l.viewTo+=r):rr(e):n>=l.viewTo?(o=ir(e,t,t,-1))?(l.view=l.view.slice(0,o.index),l.viewTo=o.lineN):rr(e):(i=ir(e,t,t,-1),o=ir(e,n,n+r,1),i&&o?(l.view=l.view.slice(0,i.index).concat(Jt(e,i.lineN,o.lineN)).concat(l.view.slice(o.index)),l.viewTo+=r):rr(e));e=l.externalMeasured;e&&(n<e.lineN?e.lineN+=r:t<e.lineN+e.size&&(l.externalMeasured=null))}function nr(e,t,n){e.curOp.viewChanged=!0;var r=e.display,i=e.display.externalMeasured;i&&t>=i.lineN&&t<i.lineN+i.size&&(r.externalMeasured=null),t<r.viewFrom||t>=r.viewTo||(null==(t=r.view[er(e,t)]).node||-1==R(t=t.changes||(t.changes=[]),n)&&t.push(n))}function rr(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function ir(e,t,n,r){var i,o=er(e,t),l=e.display.view;if(!St||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var s=e.display.viewFrom,a=0;a<o;a++)s+=l[a].size;if(s!=t){if(0<r){if(o==l.length-1)return null;i=s+l[o].size-t,o++}else i=s-t;t+=i,n+=i}for(;Rt(e.doc,n)!=n;){if(o==(r<0?0:l.length-1))return null;n+=r*l[o-(r<0?1:0)].size,o+=r}return{index:o,lineN:n}}function or(e){for(var t=e.display.view,n=0,r=0;r<t.length;r++){var i=t[r];i.hidden||i.node&&!i.changes||++n}return n}function lr(e){e.display.input.showSelection(e.display.input.prepareSelection())}function sr(e,t){void 0===t&&(t=!0);for(var n,r,i=e.doc,o={},l=o.cursors=document.createDocumentFragment(),s=o.selection=document.createDocumentFragment(),a=0;a<i.sel.ranges.length;a++)!t&&a==i.sel.primIndex||((n=i.sel.ranges[a]).from().line>=e.display.viewTo||n.to().line<e.display.viewFrom||(((r=n.empty())||e.options.showCursorWhenSelecting)&&ar(e,n.head,l),r||function(i,e,t){var n=i.display,o=i.doc,l=document.createDocumentFragment(),r=vn(i.display),S=r.left,L=Math.max(n.sizerWidth,bn(i)-n.sizer.offsetLeft)-r.right,k="ltr"==o.direction;function T(e,t,n,r){t<0&&(t=0),t=Math.round(t),r=Math.round(r),l.appendChild(M("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px;\n top: "+t+"px; width: "+(null==n?L-e:n)+"px;\n height: "+(r-t)+"px"))}function s(n,g,m){var v,y,r=Ye(o,n),b=r.text.length;function w(e,t){return In(i,tt(n,e),"div",r,t)}function x(e,t,n){e=Vn(i,r,null,e),t="ltr"==t==("after"==n)?"left":"right";return w("after"==n?e.begin:e.end-(/\s/.test(r.text.charAt(e.end-1))?2:1),t)[t]}var C=pe(r,o.direction);return function(e,t,n,r){if(!e)return r(t,n,"ltr",0);for(var i=!1,o=0;o<e.length;++o){var l=e[o];(l.from<n&&l.to>t||t==n&&l.to==t)&&(r(Math.max(l.from,t),Math.min(l.to,n),1==l.level?"rtl":"ltr",o),i=!0)}i||r(t,n,"ltr")}(C,g||0,null==m?b:m,function(e,t,n,r){var i,o,l,s,a="ltr"==n,u=w(e,a?"left":"right"),c=w(t-1,a?"right":"left"),h=null==g&&0==e,d=null==m&&t==b,f=0==r,p=!C||r==C.length-1;c.top-u.top<=3?(i=(k?h:d)&&f?S:(a?u:c).left,r=(k?d:h)&&p?L:(a?c:u).right,T(i,u.top,r-i,u.bottom)):(n=a?(o=k&&h&&f?S:u.left,l=k?L:x(e,n,"before"),s=k?S:x(t,n,"after"),k&&d&&p?L:c.right):(o=k?x(e,n,"before"):S,l=!k&&h&&f?L:u.right,s=!k&&d&&p?S:c.left,k?x(t,n,"after"):L),T(o,u.top,l-o,u.bottom),u.bottom<c.top&&T(S,u.bottom,null,c.top),T(s,c.top,n-s,c.bottom)),(!v||ur(u,v)<0)&&(v=u),ur(c,v)<0&&(v=c),(!y||ur(u,y)<0)&&(y=u),ur(c,y)<0&&(y=c)}),{start:v,end:y}}var a=e.from(),n=e.to();a.line==n.line?s(a.line,a.ch,n.ch):(r=Ye(o,a.line),e=Ye(o,n.line),e=It(r)==It(e),r=s(a.line,a.ch,e?r.text.length+1:null).end,n=s(n.line,e?0:null,n.ch).start,e&&(r.top<n.top-2?(T(r.right,r.top,null,r.bottom),T(S,n.top,n.left,n.bottom)):T(r.right,r.top,n.left-r.right,r.bottom)),r.bottom<n.top&&T(S,r.bottom,null,n.top));t.appendChild(l)}(e,n,s)));return o}function ar(e,t,n){var r=Rn(e,t,"div",null,null,!e.options.singleCursorHeightPerLine),i=n.appendChild(M("div"," ","CodeMirror-cursor"));i.style.left=r.left+"px",i.style.top=r.top+"px",i.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",!/\bcm-fat-cursor\b/.test(e.getWrapperElement().className)||0<(t=In(e,t,"div",null,null)).right-t.left&&(i.style.width=t.right-t.left+"px"),r.other&&((n=n.appendChild(M("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"))).style.display="",n.style.left=r.other.left+"px",n.style.top=r.other.top+"px",n.style.height=.85*(r.other.bottom-r.other.top)+"px")}function ur(e,t){return e.top-t.top||e.left-t.left}function cr(e){var t,n;e.state.focused&&(t=e.display,clearInterval(t.blinker),n=!0,t.cursorDiv.style.visibility="",0<e.options.cursorBlinkRate?t.blinker=setInterval(function(){e.hasFocus()||pr(e),t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden"))}function hr(e){e.hasFocus()||(e.display.input.focus(),e.state.focused||fr(e))}function dr(e){e.state.delayingBlurEvent=!0,setTimeout(function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,e.state.focused&&pr(e))},100)}function fr(e,t){e.state.delayingBlurEvent&&!e.state.draggingText&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(be(e,"focus",e,t),e.state.focused=!0,A(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),f&&setTimeout(function(){return e.display.input.reset(!0)},20)),e.display.input.receivedFocus()),cr(e))}function pr(e,t){e.state.delayingBlurEvent||(e.state.focused&&(be(e,"blur",e,t),e.state.focused=!1,S(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150))}function gr(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=Math.max(0,t.scroller.getBoundingClientRect().top),i=t.lineDiv.getBoundingClientRect().top,o=0,l=0;l<t.view.length;l++){var s,a=t.view[l],u=e.options.lineWrapping,c=void 0,h=0;if(!a.hidden){i+=a.line.height,w&&v<8?(c=(s=a.node.offsetTop+a.node.offsetHeight)-n,n=s):(c=(d=a.node.getBoundingClientRect()).bottom-d.top,!u&&a.text.firstChild&&(h=a.text.firstChild.getBoundingClientRect().right-d.left-1));var d=a.line.height-c;if((.005<d||d<-.005)&&(i<r&&(o-=d),qe(a.line,c),mr(a.line),a.rest))for(var f=0;f<a.rest.length;f++)mr(a.rest[f]);h>e.display.sizerWidth&&((h=Math.ceil(h/_n(e.display)))>e.display.maxLineLength&&(e.display.maxLineLength=h,e.display.maxLine=a.line,e.display.maxLineChanged=!0))}}2<Math.abs(o)&&(t.scroller.scrollTop+=o)}function mr(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t){var n=e.widgets[t],r=n.node.parentNode;r&&(n.height=r.offsetHeight)}}function vr(e,t,n){var r=n&&null!=n.top?Math.max(0,n.top):e.scroller.scrollTop,r=Math.floor(r-gn(e)),i=n&&null!=n.bottom?n.bottom:r+e.wrapper.clientHeight,o=Qe(t,r),r=Qe(t,i);return n&&n.ensure&&(i=n.ensure.from.line,n=n.ensure.to.line,i<o?r=Qe(t,Gt(Ye(t,o=i))+e.wrapper.clientHeight):Math.min(n,t.lastLine())>=r&&(o=Qe(t,Gt(Ye(t,n))-e.wrapper.clientHeight),r=n)),{from:o,to:Math.max(r,o+1)}}function yr(e,t){var n=e.display,r=Yn(e.display);t.top<0&&(t.top=0);var i=(e.curOp&&null!=e.curOp.scrollTop?e.curOp:n.scroller).scrollTop,o=wn(e),l={};t.bottom-t.top>o&&(t.bottom=t.top+o);var s=e.doc.height+mn(n),a=t.top<r,r=t.bottom>s-r;t.top<i?l.scrollTop=a?0:t.top:t.bottom>i+o&&((u=Math.min(t.top,(r?s:t.bottom)-o))!=i&&(l.scrollTop=u));var i=e.options.fixedGutter?0:n.gutters.offsetWidth,u=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft-i,e=bn(e)-n.gutters.offsetWidth,n=t.right-t.left>e;return n&&(t.right=t.left+e),t.left<10?l.scrollLeft=0:t.left<u?l.scrollLeft=Math.max(0,t.left+i-(n?0:10)):t.right>e+u-3&&(l.scrollLeft=t.right+(n?0:10)-e),l}function br(e,t){null!=t&&(Cr(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc:e.curOp).scrollTop+t)}function wr(e){Cr(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function xr(e,t,n){null==t&&null==n||Cr(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Cr(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Sr(e,zn(e,t.from),zn(e,t.to),t.margin))}function Sr(e,t,n,r){r=yr(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-r,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+r});xr(e,r.scrollLeft,r.scrollTop)}function Lr(e,t){Math.abs(e.doc.scrollTop-t)<2||(d||Kr(e,{top:t}),kr(e,t,!0),d&&Kr(e),zr(e,100))}function kr(e,t,n){t=Math.max(0,Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t)),e.display.scroller.scrollTop==t&&!n||(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function Tr(e,t,n,r){t=Math.max(0,Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth)),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!r||(e.doc.scrollLeft=t,Yr(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Mr(e){var t=e.display,n=t.gutters.offsetWidth,r=Math.round(e.doc.height+mn(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+yn(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}e=function(e,t,n){this.cm=n;var r=this.vert=M("div",[M("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=M("div",[M("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");r.tabIndex=i.tabIndex=-1,e(r),e(i),me(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")}),me(i,"scroll",function(){i.clientWidth&&t(i.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,w&&v<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};e.prototype.update=function(e){var t,n=e.scrollWidth>e.clientWidth+1,r=e.scrollHeight>e.clientHeight+1,i=e.nativeBarWidth;return r?(this.vert.style.display="block",this.vert.style.bottom=n?i+"px":"0",t=e.viewHeight-(n?i:0),this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+t)+"px"):(this.vert.style.display="",this.vert.firstChild.style.height="0"),n?(this.horiz.style.display="block",this.horiz.style.right=r?i+"px":"0",this.horiz.style.left=e.barLeft+"px",t=e.viewWidth-e.barLeft-(r?i:0),this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+t)+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0"),!this.checkedZeroWidth&&0<e.clientHeight&&(0==i&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:r?i:0,bottom:n?i:0}},e.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},e.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},e.prototype.zeroWidthHack=function(){this.horiz.style.height=this.vert.style.width=g&&!l?"12px":"18px",this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new I,this.disableVert=new I},e.prototype.enableZeroWidthBar=function(n,r,i){n.style.pointerEvents="auto",r.set(1e3,function e(){var t=n.getBoundingClientRect();("vert"==i?document.elementFromPoint(t.right-1,(t.top+t.bottom)/2):document.elementFromPoint((t.right+t.left)/2,t.bottom-1))!=n?n.style.pointerEvents="none":r.set(1e3,e)})},e.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};r=function(){};function Nr(e,t){t=t||Mr(e);var n=e.display.barWidth,r=e.display.barHeight;Or(e,t);for(var i=0;i<4&&n!=e.display.barWidth||r!=e.display.barHeight;i++)n!=e.display.barWidth&&e.options.lineWrapping&&gr(e),Or(e,Mr(e)),n=e.display.barWidth,r=e.display.barHeight}function Or(e,t){var n=e.display,r=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px",n.heightForcer.style.borderBottom=r.bottom+"px solid transparent",r.right&&r.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=r.bottom+"px",n.scrollbarFiller.style.width=r.right+"px"):n.scrollbarFiller.style.display="",r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}r.prototype.update=function(){return{bottom:0,right:0}},r.prototype.setScrollLeft=function(){},r.prototype.setScrollTop=function(){},r.prototype.clear=function(){};var Ar={native:e,null:r};function Dr(n){n.display.scrollbars&&(n.display.scrollbars.clear(),n.display.scrollbars.addClass&&S(n.display.wrapper,n.display.scrollbars.addClass)),n.display.scrollbars=new Ar[n.options.scrollbarStyle](function(e){n.display.wrapper.insertBefore(e,n.display.scrollbarFiller),me(e,"mousedown",function(){n.state.focused&&setTimeout(function(){return n.display.input.focus()},0)}),e.setAttribute("cm-not-content","true")},function(e,t){("horizontal"==t?Tr:Lr)(n,e)},n),n.display.scrollbars.addClass&&A(n.display.wrapper,n.display.scrollbars.addClass)}var Wr=0;function Hr(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Wr,markArrays:null},e=e.curOp,en?en.ops.push(e):e.ownsGroup=en={ops:[e],delayedCallbacks:[]}}function Fr(e){e=e.curOp;e&&tn(e,function(e){for(var t=0;t<e.ops.length;t++)e.ops[t].cm.curOp=null;!function(e){for(var t=e.ops,n=0;n<t.length;n++)!function(e){var t=e.cm,n=t.display;(function(e){var t=e.display;!t.scrollbarsClipped&&t.scroller.offsetWidth&&(t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth,t.heightForcer.style.height=yn(e)+"px",t.sizer.style.marginBottom=-t.nativeBarWidth+"px",t.sizer.style.borderRightWidth=yn(e)+"px",t.scrollbarsClipped=!0)})(t),e.updateMaxLine&&Vt(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<n.viewFrom||e.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new Gr(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}(t[n]);for(var r=0;r<t.length;r++)!function(e){e.updatedDisplay=e.mustUpdate&&Ur(e.cm,e.update)}(t[r]);for(var i=0;i<t.length;i++)!function(e){var t=e.cm,n=t.display;e.updatedDisplay&&gr(t);e.barMeasure=Mr(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Cn(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+yn(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-bn(t)));(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}(t[i]);for(var o=0;o<t.length;o++)!function(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft<t.doc.scrollLeft&&Tr(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0),t.display.maxLineChanged=!1);var n=e.focus&&e.focus==O();e.preparedSelection&&t.display.input.showSelection(e.preparedSelection,n);!e.updatedDisplay&&e.startHeight==t.doc.height||Nr(t,e.barMeasure);e.updatedDisplay&&Xr(t,e.barMeasure);e.selectionChanged&&cr(t);t.state.focused&&e.updateInput&&t.display.input.reset(e.typing);n&&hr(e.cm)}(t[o]);for(var l=0;l<t.length;l++)!function(e){var t=e.cm,n=t.display,r=t.doc;e.updatedDisplay&&Vr(t,e.update);null==n.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(n.wheelStartX=n.wheelStartY=null);null!=e.scrollTop&&kr(t,e.scrollTop,e.forceScroll);null!=e.scrollLeft&&Tr(t,e.scrollLeft,!0,!0);{var i;e.scrollToPos&&(i=function(e,t,n,r){null==r&&(r=0),e.options.lineWrapping||t!=n||(n="before"==t.sticky?tt(t.line,t.ch+1,"before"):t,t=t.ch?tt(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t);for(var i=0;i<5;i++){var o,l=!1,s=Rn(e,t),a=n&&n!=t?Rn(e,n):s,u=yr(e,o={left:Math.min(s.left,a.left),top:Math.min(s.top,a.top)-r,right:Math.max(s.left,a.left),bottom:Math.max(s.bottom,a.bottom)+r}),s=e.doc.scrollTop,a=e.doc.scrollLeft;if(null!=u.scrollTop&&(Lr(e,u.scrollTop),1<Math.abs(e.doc.scrollTop-s)&&(l=!0)),null!=u.scrollLeft&&(Tr(e,u.scrollLeft),1<Math.abs(e.doc.scrollLeft-a)&&(l=!0)),!l)break}return o}(t,at(r,e.scrollToPos.from),at(r,e.scrollToPos.to),e.scrollToPos.margin),function(e,t){var n,r,i;we(e,"scrollCursorIntoView")||(r=(n=e.display).sizer.getBoundingClientRect(),i=null,t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null==i||u||(t=M("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-gn(e.display))+"px;\n height: "+(t.bottom-t.top+yn(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;"),e.display.lineSpace.appendChild(t),t.scrollIntoView(i),e.display.lineSpace.removeChild(t)))}(t,i))}var o=e.maybeHiddenMarkers,l=e.maybeUnhiddenMarkers;if(o)for(var s=0;s<o.length;++s)o[s].lines.length||be(o[s],"hide");if(l)for(var a=0;a<l.length;++a)l[a].lines.length&&be(l[a],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&be(t,"changes",t,e.changeObjs);e.update&&e.update.finish()}(t[l])}(e)})}function Pr(e,t){if(e.curOp)return t();Hr(e);try{return t()}finally{Fr(e)}}function Er(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Hr(e);try{return t.apply(e,arguments)}finally{Fr(e)}}}function Ir(e){return function(){if(this.curOp)return e.apply(this,arguments);Hr(this);try{return e.apply(this,arguments)}finally{Fr(this)}}}function Rr(t){return function(){var e=this.cm;if(!e||e.curOp)return t.apply(this,arguments);Hr(e);try{return t.apply(this,arguments)}finally{Fr(e)}}}function zr(e,t){e.doc.highlightFrontier<e.display.viewTo&&e.state.highlight.set(t,F(Br,e))}function Br(l){var s,a,u,c=l.doc;c.highlightFrontier>=l.display.viewTo||(s=+new Date+l.options.workTime,a=pt(l,c.highlightFrontier),u=[],c.iter(a.line,Math.min(c.first+c.size,l.display.viewTo+500),function(e){if(a.line>=l.display.viewFrom){var t=e.styles,n=e.text.length>l.options.maxHighlightLength?Ve(c.mode,a.state):null,r=dt(l,e,a,!0);n&&(a.state=n),e.styles=r.styles;n=e.styleClasses,r=r.classes;r?e.styleClasses=r:n&&(e.styleClasses=null);for(var i=!t||t.length!=e.styles.length||n!=r&&(!n||!r||n.bgClass!=r.bgClass||n.textClass!=r.textClass),o=0;!i&&o<t.length;++o)i=t[o]!=e.styles[o];i&&u.push(a.line),e.stateAfter=a.save(),a.nextLine()}else e.text.length<=l.options.maxHighlightLength&&gt(l,e.text,a),e.stateAfter=a.line%5==0?a.save():null,a.nextLine();if(+new Date>s)return zr(l,l.options.workDelay),!0}),c.highlightFrontier=a.line,c.modeFrontier=Math.max(c.modeFrontier,a.line),u.length&&Pr(l,function(){for(var e=0;e<u.length;e++)nr(l,u[e],"text")}))}var Gr=function(e,t,n){var r=e.display;this.viewport=t,this.visible=vr(r,e.doc,t),this.editorIsHidden=!r.wrapper.offsetWidth,this.wrapperHeight=r.wrapper.clientHeight,this.wrapperWidth=r.wrapper.clientWidth,this.oldDisplayWidth=bn(e),this.force=n,this.dims=$n(e),this.events=[]};function Ur(e,t){var n=e.display,r=e.doc;if(t.editorIsHidden)return rr(e),!1;if(!t.force&&t.visible.from>=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==or(e))return!1;_r(e)&&(rr(e),t.dims=$n(e));var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),l=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom)),n.viewTo>l&&n.viewTo-l<20&&(l=Math.min(i,n.viewTo)),St&&(o=Rt(e.doc,o),l=zt(e.doc,l));var s=o!=n.viewFrom||l!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;r=o,i=l,0==(l=(o=e).display).view.length||r>=l.viewTo||i<=l.viewFrom?(l.view=Jt(o,r,i),l.viewFrom=r):(l.viewFrom>r?l.view=Jt(o,r,l.viewFrom).concat(l.view):l.viewFrom<r&&(l.view=l.view.slice(er(o,r))),l.viewFrom=r,l.viewTo<i?l.view=l.view.concat(Jt(o,l.viewTo,i)):l.viewTo>i&&(l.view=l.view.slice(0,er(o,i)))),l.viewTo=i,n.viewOffset=Gt(Ye(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";o=or(e);if(!s&&0==o&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;l=function(e){if(e.hasFocus())return null;var t=O();if(!t||!N(e.display.lineDiv,t))return null;var n={activeElt:t};return!window.getSelection||(t=window.getSelection()).anchorNode&&t.extend&&N(e.display.lineDiv,t.anchorNode)&&(n.anchorNode=t.anchorNode,n.anchorOffset=t.anchorOffset,n.focusNode=t.focusNode,n.focusOffset=t.focusOffset),n}(e);return 4<o&&(n.lineDiv.style.display="none"),function(n,e,t){var r=n.display,i=n.options.lineNumbers,o=r.lineDiv,l=o.firstChild;function s(e){var t=e.nextSibling;return f&&g&&n.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e),t}for(var a=r.view,u=r.viewFrom,c=0;c<a.length;c++){var h=a[c];if(!h.hidden)if(h.node&&h.node.parentNode==o){for(;l!=h.node;)l=s(l);var d=i&&null!=e&&e<=u&&h.lineNumber;h.changes&&(-1<R(h.changes,"gutter")&&(d=!1),ln(n,h,u,t)),d&&(L(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(et(n.options,u)))),l=h.node.nextSibling}else{d=function(e,t,n,r){var i=an(e,t);return t.text=t.node=i.pre,i.bgClass&&(t.bgClass=i.bgClass),i.textClass&&(t.textClass=i.textClass),un(e,t),cn(e,t,n,r),hn(e,t,r),t.node}(n,h,u,t);o.insertBefore(d,l)}u+=h.size}for(;l;)l=s(l)}(e,n.updateLineNumbers,t.dims),4<o&&(n.lineDiv.style.display=""),n.renderedView=n.view,(i=l)&&i.activeElt&&i.activeElt!=O()&&(i.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(i.activeElt.nodeName)&&i.anchorNode&&N(document.body,i.anchorNode)&&N(document.body,i.focusNode)&&(o=window.getSelection(),(l=document.createRange()).setEnd(i.anchorNode,i.anchorOffset),l.collapse(!1),o.removeAllRanges(),o.addRange(l),o.extend(i.focusNode,i.focusOffset))),L(n.cursorDiv),L(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,s&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,zr(e,400)),!(n.updateLineNumbers=null)}function Vr(e,t){for(var n=t.viewport,r=!0;;r=!1){if(r&&e.options.lineWrapping&&t.oldDisplayWidth!=bn(e))r&&(t.visible=vr(e.display,e.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(e.doc.height+mn(e.display)-wn(e),n.top)}),t.visible=vr(e.display,e.doc,n),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!Ur(e,t))break;gr(e);var i=Mr(e);lr(e),Nr(e,i),Xr(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function Kr(e,t){var n=new Gr(e,t);Ur(e,n)&&(gr(e),Vr(e,n),t=Mr(e),lr(e),Nr(e,t),Xr(e,t),n.finish())}function jr(e){var t=e.gutters.offsetWidth;e.sizer.style.marginLeft=t+"px",rn(e,"gutterChanged",e)}function Xr(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+yn(e)+"px"}function Yr(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=qn(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",l=0;l<n.length;l++)if(!n[l].hidden){e.options.fixedGutter&&(n[l].gutter&&(n[l].gutter.style.left=o),n[l].gutterBackground&&(n[l].gutterBackground.style.left=o));var s=n[l].alignable;if(s)for(var a=0;a<s.length;a++)s[a].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+i+"px")}}function _r(e){if(e.options.lineNumbers){var t=e.doc,n=et(e.options,t.first+t.size-1),r=e.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(M("div",[M("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),t=i.firstChild.offsetWidth,i=i.offsetWidth-t;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(t,r.lineGutter.offsetWidth-i)+1,r.lineNumWidth=r.lineNumInnerWidth+i,r.lineNumChars=r.lineNumInnerWidth?n.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",jr(e.display),1}}}function $r(e,t){for(var n=[],r=!1,i=0;i<e.length;i++){var o=e[i],l=null;if("string"!=typeof o&&(l=o.style,o=o.className),"CodeMirror-linenumbers"==o){if(!t)continue;r=!0}n.push({className:o,style:l})}return t&&!r&&n.push({className:"CodeMirror-linenumbers",style:null}),n}function qr(e){var t=e.gutters,n=e.gutterSpecs;L(t),e.lineGutter=null;for(var r=0;r<n.length;++r){var i=n[r],o=i.className,l=i.style,i=t.appendChild(M("div",null,"CodeMirror-gutter "+o));l&&(i.style.cssText=l),"CodeMirror-linenumbers"==o&&((e.lineGutter=i).style.width=(e.lineNumWidth||1)+"px")}t.style.display=n.length?"":"none",jr(e)}function Zr(e){qr(e.display),tr(e),Yr(e)}function Qr(e,t,n,r){var i=this;this.input=n,i.scrollbarFiller=M("div",null,"CodeMirror-scrollbar-filler"),i.scrollbarFiller.setAttribute("cm-not-content","true"),i.gutterFiller=M("div",null,"CodeMirror-gutter-filler"),i.gutterFiller.setAttribute("cm-not-content","true"),i.lineDiv=T("div",null,"CodeMirror-code"),i.selectionDiv=M("div",null,null,"position: relative; z-index: 1"),i.cursorDiv=M("div",null,"CodeMirror-cursors"),i.measure=M("div",null,"CodeMirror-measure"),i.lineMeasure=M("div",null,"CodeMirror-measure"),i.lineSpace=T("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");var o=T("div",[i.lineSpace],"CodeMirror-lines");i.mover=M("div",[o],null,"position: relative"),i.sizer=M("div",[i.mover],"CodeMirror-sizer"),i.sizerWidth=null,i.heightForcer=M("div",null,null,"position: absolute; height: "+z+"px; width: 1px;"),i.gutters=M("div",null,"CodeMirror-gutters"),i.lineGutter=null,i.scroller=M("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll"),i.scroller.setAttribute("tabIndex","-1"),i.wrapper=M("div",[i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror"),i.wrapper.setAttribute("translate","no"),w&&v<8&&(i.gutters.style.zIndex=-1,i.scroller.style.paddingRight=0),f||d&&h||(i.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper)),i.viewFrom=i.viewTo=t.first,i.reportedViewFrom=i.reportedViewTo=t.first,i.view=[],i.renderedView=null,i.externalMeasured=null,i.viewOffset=0,i.lastWrapHeight=i.lastWrapWidth=0,i.updateLineNumbers=null,i.nativeBarWidth=i.barHeight=i.barWidth=0,i.scrollbarsClipped=!1,i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null,i.alignWidgets=!1,i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null,i.maxLine=null,i.maxLineLength=0,i.maxLineChanged=!1,i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null,i.shift=!1,i.selForContextMenu=null,i.activeTouch=null,i.gutterSpecs=$r(r.gutters,r.lineNumbers),qr(i),n.init(i)}Gr.prototype.signal=function(e,t){Ce(e,t)&&this.events.push(arguments)},Gr.prototype.finish=function(){for(var e=0;e<this.events.length;e++)be.apply(null,this.events[e])};var Jr=0,ei=null;function ti(e){var t=e.wheelDeltaX,n=e.wheelDeltaY;return null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail),null==n&&e.detail&&e.axis==e.VERTICAL_AXIS?n=e.detail:null==n&&(n=e.wheelDelta),{x:t,y:n}}function ni(e){e=ti(e);return e.x*=ei,e.y*=ei,e}function ri(e,t){var n=ti(t),r=n.x,i=n.y,o=ei;0===event.deltaMode&&(r=t.deltaX,i=t.deltaY,o=1);var l=e.display,s=l.scroller,a=s.scrollWidth>s.clientWidth,n=s.scrollHeight>s.clientHeight;if(r&&a||i&&n){if(i&&g&&f)e:for(var u=t.target,c=l.view;u!=s;u=u.parentNode)for(var h=0;h<c.length;h++)if(c[h].node==u){e.display.currentWheelTarget=u;break e}if(r&&!d&&!p&&null!=o)return i&&n&&Lr(e,Math.max(0,s.scrollTop+i*o)),Tr(e,Math.max(0,s.scrollLeft+r*o)),i&&!n||Le(t),void(l.wheelStartX=null);i&&null!=o&&(n=(a=e.doc.scrollTop)+l.wrapper.clientHeight,(o=i*o)<0?a=Math.max(0,a+o-50):n=Math.min(e.doc.height,n+o+50),Kr(e,{top:a,bottom:n})),Jr<20&&0!==t.deltaMode&&(null==l.wheelStartX?(l.wheelStartX=s.scrollLeft,l.wheelStartY=s.scrollTop,l.wheelDX=r,l.wheelDY=i,setTimeout(function(){var e,t;null!=l.wheelStartX&&(t=s.scrollLeft-l.wheelStartX,t=(e=s.scrollTop-l.wheelStartY)&&l.wheelDY&&e/l.wheelDY||t&&l.wheelDX&&t/l.wheelDX,l.wheelStartX=l.wheelStartY=null,t&&(ei=(ei*Jr+t)/(Jr+1),++Jr))},200)):(l.wheelDX+=r,l.wheelDY+=i))}}w?ei=-.53:d?ei=15:o?ei=-.7:c&&(ei=-1/3);var ii=function(e,t){this.ranges=e,this.primIndex=t};ii.prototype.primary=function(){return this.ranges[this.primIndex]},ii.prototype.equals=function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var n=this.ranges[t],r=e.ranges[t];if(!rt(n.anchor,r.anchor)||!rt(n.head,r.head))return!1}return!0},ii.prototype.deepCopy=function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new oi(it(this.ranges[t].anchor),it(this.ranges[t].head));return new ii(e,this.primIndex)},ii.prototype.somethingSelected=function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},ii.prototype.contains=function(e,t){t=t||e;for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(0<=nt(t,r.from())&&nt(e,r.to())<=0)return n}return-1};var oi=function(e,t){this.anchor=e,this.head=t};function li(e,t,n){var r=e&&e.options.selectionsMayTouch,e=t[n];t.sort(function(e,t){return nt(e.from(),t.from())}),n=R(t,e);for(var i=1;i<t.length;i++){var o,l=t[i],s=t[i-1],a=nt(s.to(),l.from());(r&&!l.empty()?0<a:0<=a)&&(o=lt(s.from(),l.from()),a=ot(s.to(),l.to()),s=s.empty()?l.from()==l.head:s.from()==s.head,i<=n&&--n,t.splice(--i,2,new oi(s?a:o,s?o:a)))}return new ii(t,n)}function si(e,t){return new ii([new oi(e,t||e)],0)}function ai(e){return e.text?tt(e.from.line+e.text.length-1,Y(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function ui(e,t){if(nt(e,t.from)<0)return e;if(nt(e,t.to)<=0)return ai(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=ai(t).ch-t.to.ch),tt(n,r)}function ci(e,t){for(var n=[],r=0;r<e.sel.ranges.length;r++){var i=e.sel.ranges[r];n.push(new oi(ui(i.anchor,t),ui(i.head,t)))}return li(e.cm,n,e.sel.primIndex)}function hi(e,t,n){return e.line==t.line?tt(n.line,e.ch-t.ch+n.ch):tt(n.line+(e.line-t.line),e.ch)}function di(e){e.doc.mode=Be(e.options,e.doc.modeOption),fi(e)}function fi(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.modeFrontier=e.doc.highlightFrontier=e.doc.first,zr(e,100),e.state.modeGen++,e.curOp&&tr(e)}function pi(e,t){return 0==t.from.ch&&0==t.to.ch&&""==Y(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function gi(e,o,t,l){function i(e){return t?t[e]:null}function n(e,t,n){var r,i;r=n,i=l,(n=e).text=t,n.stateAfter&&(n.stateAfter=null),n.styles&&(n.styles=null),null!=n.order&&(n.order=null),Nt(n),Ot(n,r),(i=i?i(n):1)!=n.height&&qe(n,i),rn(e,"change",e,o)}function r(e,t){for(var n=[],r=e;r<t;++r)n.push(new Kt(c[r],i(r),l));return n}var s,a=o.from,u=o.to,c=o.text,h=Ye(e,a.line),d=Ye(e,u.line),f=Y(c),p=i(c.length-1),g=u.line-a.line;o.full?(e.insert(0,r(0,c.length)),e.remove(c.length,e.size-c.length)):pi(e,o)?(s=r(0,c.length-1),n(d,d.text,p),g&&e.remove(a.line,g),s.length&&e.insert(a.line,s)):h==d?1==c.length?n(h,h.text.slice(0,a.ch)+f+h.text.slice(u.ch),p):((s=r(1,c.length-1)).push(new Kt(f+h.text.slice(u.ch),p,l)),n(h,h.text.slice(0,a.ch)+c[0],i(0)),e.insert(a.line+1,s)):1==c.length?(n(h,h.text.slice(0,a.ch)+c[0]+d.text.slice(u.ch),i(0)),e.remove(a.line+1,g)):(n(h,h.text.slice(0,a.ch)+c[0],i(0)),n(d,f+d.text.slice(u.ch),p),p=r(1,c.length-1),1<g&&e.remove(a.line+1,g-1),e.insert(a.line+1,p)),rn(e,"change",e,o)}function mi(e,s,a){!function e(t,n,r){if(t.linked)for(var i=0;i<t.linked.length;++i){var o,l=t.linked[i];l.doc!=n&&(o=r&&l.sharedHist,a&&!o||(s(l.doc,o),e(l.doc,t,o)))}}(e,null,!0)}function vi(e,t){if(t.cm)throw new Error("This document is already in use.");Qn((e.doc=t).cm=e),di(e),yi(e),e.options.direction=t.direction,e.options.lineWrapping||Vt(e),e.options.mode=t.modeOption,tr(e)}function yi(e){("rtl"==e.doc.direction?A:S)(e.display.lineDiv,"CodeMirror-rtl")}function bi(e){this.done=[],this.undone=[],this.undoDepth=e?e.undoDepth:1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e?e.maxGeneration:1}function wi(e,t){var n={from:it(t.from),to:ai(t),text:_e(e,t.from,t.to)};return ki(e,n,t.from.line,t.to.line+1),mi(e,function(e){return ki(e,n,t.from.line,t.to.line+1),0},!0),n}function xi(e){for(;e.length;){if(!Y(e).ranges)break;e.pop()}}function Ci(e,t,n,r){var i=e.history;i.undone.length=0;var o,l,s=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&i.lastModTime>s-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=(a=i).lastOp==r?(xi(a.done),Y(a.done)):a.done.length&&!Y(a.done).ranges?Y(a.done):1<a.done.length&&!a.done[a.done.length-2].ranges?(a.done.pop(),Y(a.done)):void 0))l=Y(o.changes),0==nt(t.from,t.to)&&0==nt(t.from,l.to)?l.to=ai(t):o.changes.push(wi(e,t));else{var a=Y(i.done);for(a&&a.ranges||Li(e.sel,i.done),o={changes:[wi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,l||be(e,"historyAdded")}function Si(e,t,n,r){var i,o,l,s=e.history,a=r&&r.origin;n==s.lastSelOp||a&&s.lastSelOrigin==a&&(s.lastModTime==s.lastSelTime&&s.lastOrigin==a||(i=e,o=a,l=Y(s.done),e=t,"*"==(o=o.charAt(0))||"+"==o&&l.ranges.length==e.ranges.length&&l.somethingSelected()==e.somethingSelected()&&new Date-i.history.lastSelTime<=(i.cm?i.cm.options.historyEventDelay:500)))?s.done[s.done.length-1]=t:Li(t,s.done),s.lastSelTime=+new Date,s.lastSelOrigin=a,s.lastSelOp=n,r&&!1!==r.clearRedo&&xi(s.undone)}function Li(e,t){var n=Y(t);n&&n.ranges&&n.equals(e)||t.push(e)}function ki(t,n,e,r){var i=n["spans_"+t.id],o=0;t.iter(Math.max(t.first,e),Math.min(t.first+t.size,r),function(e){e.markedSpans&&((i=i||(n["spans_"+t.id]={}))[o]=e.markedSpans),++o})}function Ti(e,t){var n=t["spans_"+e.id];if(!n)return null;for(var r=[],i=0;i<t.text.length;++i)r.push(function(e){if(!e)return null;for(var t,n=0;n<e.length;++n)e[n].marker.explicitlyCleared?t=t||e.slice(0,n):t&&t.push(e[n]);return t?t.length?t:null:e}(n[i]));return r}function Mi(e,t){var n=Ti(e,t),r=Tt(e,t);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],l=r[i];if(o&&l)e:for(var s=0;s<l.length;++s){for(var a=l[s],u=0;u<o.length;++u)if(o[u].marker==a.marker)continue e;o.push(a)}else l&&(n[i]=l)}return n}function Ni(e,t,n){for(var r=[],i=0;i<e.length;++i){var o=e[i];if(o.ranges)r.push(n?ii.prototype.deepCopy.call(o):o);else{var l=o.changes,s=[];r.push({changes:s});for(var a=0;a<l.length;++a){var u,c=l[a];if(s.push({from:c.from,to:c.to,text:c.text}),t)for(var h in c)(u=h.match(/^spans_(\d+)$/))&&-1<R(t,Number(u[1]))&&(Y(s)[h]=c[h],delete c[h])}}}return r}function Oi(e,t,n,r){if(r){r=e.anchor;return n&&((e=nt(t,r)<0)!=nt(n,r)<0?(r=t,t=n):e!=nt(t,n)<0&&(t=n)),new oi(r,t)}return new oi(n||t,t)}function Ai(e,t,n,r,i){null==i&&(i=e.cm&&(e.cm.display.shift||e.extend)),Pi(e,new ii([Oi(e.sel.primary(),t,n,i)],0),r)}function Di(e,t,n){for(var r=[],i=e.cm&&(e.cm.display.shift||e.extend),o=0;o<e.sel.ranges.length;o++)r[o]=Oi(e.sel.ranges[o],t[o],null,i);Pi(e,li(e.cm,r,e.sel.primIndex),n)}function Wi(e,t,n,r){var i=e.sel.ranges.slice(0);i[t]=n,Pi(e,li(e.cm,i,e.sel.primIndex),r)}function Hi(e,t,n,r){Pi(e,si(t,n),r)}function Fi(e,t,n){var r=e.history.done,i=Y(r);i&&i.ranges?Ei(e,r[r.length-1]=t,n):Pi(e,t,n)}function Pi(e,t,n){Ei(e,t,n),Si(e,e.sel,e.cm?e.cm.curOp.id:NaN,n)}function Ei(e,t,n){var r,i;(Ce(e,"beforeSelectionChange")||e.cm&&Ce(e.cm,"beforeSelectionChange"))&&(r=e,i=n,i={ranges:(o=t).ranges,update:function(e){this.ranges=[];for(var t=0;t<e.length;t++)this.ranges[t]=new oi(at(r,e[t].anchor),at(r,e[t].head))},origin:i&&i.origin},be(r,"beforeSelectionChange",r,i),r.cm&&be(r.cm,"beforeSelectionChange",r.cm,i),t=i.ranges!=o.ranges?li(r.cm,i.ranges,i.ranges.length-1):o);var o=n&&n.bias||(nt(t.primary().head,e.sel.primary().head)<0?-1:1);Ii(e,zi(e,t,o,!0)),n&&!1===n.scroll||!e.cm||"nocursor"==e.cm.getOption("readOnly")||wr(e.cm)}function Ii(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=1,e.cm.curOp.selectionChanged=!0,xe(e.cm)),rn(e,"cursorActivity",e))}function Ri(e){Ii(e,zi(e,e.sel,null,!1))}function zi(e,t,n,r){for(var i,o=0;o<t.ranges.length;o++){var l=t.ranges[o],s=t.ranges.length==e.sel.ranges.length&&e.sel.ranges[o],a=Gi(e,l.anchor,s&&s.anchor,n,r),s=Gi(e,l.head,s&&s.head,n,r);!i&&a==l.anchor&&s==l.head||((i=i||t.ranges.slice(0,o))[o]=new oi(a,s))}return i?li(e.cm,i,t.primIndex):t}function Bi(e,t,n,r,i){var o=Ye(e,t.line);if(o.markedSpans)for(var l=0;l<o.markedSpans.length;++l){var s=o.markedSpans[l],a=s.marker,u="selectLeft"in a?!a.selectLeft:a.inclusiveLeft,c="selectRight"in a?!a.selectRight:a.inclusiveRight;if((null==s.from||(u?s.from<=t.ch:s.from<t.ch))&&(null==s.to||(c?s.to>=t.ch:s.to>t.ch))){if(i&&(be(a,"beforeCursorEnter"),a.explicitlyCleared)){if(o.markedSpans){--l;continue}break}if(a.atomic){if(n){var h=a.find(r<0?1:-1),s=void 0;if((h=(r<0?c:u)?Ui(e,h,-r,h&&h.line==t.line?o:null):h)&&h.line==t.line&&(s=nt(h,n))&&(r<0?s<0:0<s))return Bi(e,h,t,r,i)}a=a.find(r<0?-1:1);return(a=(r<0?u:c)?Ui(e,a,r,a.line==t.line?o:null):a)?Bi(e,a,t,r,i):null}}}return t}function Gi(e,t,n,r,i){r=r||1,r=Bi(e,t,n,r,i)||!i&&Bi(e,t,n,r,!0)||Bi(e,t,n,-r,i)||!i&&Bi(e,t,n,-r,!0);return r||(e.cantEdit=!0,tt(e.first,0))}function Ui(e,t,n,r){return n<0&&0==t.ch?t.line>e.first?at(e,tt(t.line-1)):null:0<n&&t.ch==(r||Ye(e,t.line)).text.length?t.line<e.first+e.size-1?tt(t.line+1,0):null:new tt(t.line,t.ch+n)}function Vi(e){e.setSelection(tt(e.firstLine(),0),tt(e.lastLine()),G)}function Ki(i,e,t){var o={canceled:!1,from:e.from,to:e.to,text:e.text,origin:e.origin,cancel:function(){return o.canceled=!0}};return t&&(o.update=function(e,t,n,r){e&&(o.from=at(i,e)),t&&(o.to=at(i,t)),n&&(o.text=n),void 0!==r&&(o.origin=r)}),be(i,"beforeChange",i,o),i.cm&&be(i.cm,"beforeChange",i.cm,o),o.canceled?(i.cm&&(i.cm.curOp.updateInput=2),null):{from:o.from,to:o.to,text:o.text,origin:o.origin}}function ji(e,t,n){if(e.cm){if(!e.cm.curOp)return Er(e.cm,ji)(e,t,n);if(e.cm.state.suppressEdits)return}if(!(Ce(e,"beforeChange")||e.cm&&Ce(e.cm,"beforeChange"))||(t=Ki(e,t,!0))){var r=Ct&&!n&&function(e,t,n){var r=null;if(e.iter(t.line,n.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var n=e.markedSpans[t].marker;!n.readOnly||r&&-1!=R(r,n)||(r=r||[]).push(n)}}),!r)return null;for(var i=[{from:t,to:n}],o=0;o<r.length;++o)for(var l=r[o],s=l.find(0),a=0;a<i.length;++a){var u,c,h,d=i[a];nt(d.to,s.from)<0||0<nt(d.from,s.to)||(u=[a,1],c=nt(d.from,s.from),h=nt(d.to,s.to),(c<0||!l.inclusiveLeft&&!c)&&u.push({from:d.from,to:s.from}),(0<h||!l.inclusiveRight&&!h)&&u.push({from:s.to,to:d.to}),i.splice.apply(i,u),a+=u.length-3)}return i}(e,t.from,t.to);if(r)for(var i=r.length-1;0<=i;--i)Xi(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text,origin:t.origin});else Xi(e,t)}}function Xi(e,n){var t,r;1==n.text.length&&""==n.text[0]&&0==nt(n.from,n.to)||(t=ci(e,n),Ci(e,n,t,e.cm?e.cm.curOp.id:NaN),$i(e,n,t,Tt(e,n)),r=[],mi(e,function(e,t){t||-1!=R(r,e.history)||(Ji(e.history,n),r.push(e.history)),$i(e,n,null,Tt(e,n))}))}function Yi(i,o,e){var t=i.cm&&i.cm.state.suppressEdits;if(!t||e){for(var l,n=i.history,r=i.sel,s="undo"==o?n.done:n.undone,a="undo"==o?n.undone:n.done,u=0;u<s.length&&(l=s[u],e?!l.ranges||l.equals(i.sel):l.ranges);u++);if(u!=s.length){for(n.lastOrigin=n.lastSelOrigin=null;;){if(!(l=s.pop()).ranges){if(t)return void s.push(l);break}if(Li(l,a),e&&!l.equals(i.sel))return void Pi(i,l,{clearRedo:!1});r=l}var c=[];Li(r,a),a.push({changes:c,generation:n.generation}),n.generation=l.generation||++n.maxGeneration;for(var h=Ce(i,"beforeChange")||i.cm&&Ce(i.cm,"beforeChange"),d=l.changes.length-1;0<=d;--d){var f=function(e){var n=l.changes[e];if(n.origin=o,h&&!Ki(i,n,!1))return s.length=0,{};c.push(wi(i,n));var t=e?ci(i,n):Y(s);$i(i,n,t,Mi(i,n)),!e&&i.cm&&i.cm.scrollIntoView({from:n.from,to:ai(n)});var r=[];mi(i,function(e,t){t||-1!=R(r,e.history)||(Ji(e.history,n),r.push(e.history)),$i(e,n,null,Mi(e,n))})}(d);if(f)return f.v}}}}function _i(e,t){if(0!=t&&(e.first+=t,e.sel=new ii(_(e.sel.ranges,function(e){return new oi(tt(e.anchor.line+t,e.anchor.ch),tt(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){tr(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;r<n.viewTo;r++)nr(e.cm,r,"gutter")}}function $i(e,t,n,r){if(e.cm&&!e.cm.curOp)return Er(e.cm,$i)(e,t,n,r);var i;t.to.line<e.first?_i(e,t.text.length-1-(t.to.line-t.from.line)):t.from.line>e.lastLine()||(t.from.line<e.first&&(_i(e,i=t.text.length-1-(e.first-t.from.line)),t={from:tt(e.first,0),to:tt(t.to.line+i,t.to.ch),text:[Y(t.text)],origin:t.origin}),i=e.lastLine(),(t=t.to.line>i?{from:t.from,to:tt(i,Ye(e,i).text.length),text:[t.text[0]],origin:t.origin}:t).removed=_e(e,t.from,t.to),n=n||ci(e,t),e.cm?function(e,t,n){var r=e.doc,i=e.display,o=t.from,l=t.to,s=!1,a=o.line;e.options.lineWrapping||(a=Ze(It(Ye(r,o.line))),r.iter(a,l.line+1,function(e){if(e==i.maxLine)return s=!0}));-1<r.sel.contains(t.from,t.to)&&xe(e);gi(r,t,n,Zn(e)),e.options.lineWrapping||(r.iter(a,o.line+t.text.length,function(e){var t=Ut(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,s=!1)}),s&&(e.curOp.updateMaxLine=!0));(function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontier<t-10)){for(var n=e.first,r=t-1;n<r;r--){var i=Ye(e,r).stateAfter;if(i&&(!(i instanceof ct)||r+i.lookAhead<t)){n=r+1;break}}e.highlightFrontier=Math.min(e.highlightFrontier,n)}})(r,o.line),zr(e,400);a=t.text.length-(l.line-o.line)-1;t.full?tr(e):o.line!=l.line||1!=t.text.length||pi(e.doc,t)?tr(e,o.line,l.line+1,a):nr(e,o.line,"text");r=Ce(e,"changes"),a=Ce(e,"change");(a||r)&&(t={from:o,to:l,text:t.text,removed:t.removed,origin:t.origin},a&&rn(e,"change",e,t),r&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(t));e.display.selForContextMenu=null}(e.cm,t,r):gi(e,t,r),Ei(e,n,G),e.cantEdit&&Gi(e,tt(e.firstLine(),0))&&(e.cantEdit=!1))}function qi(e,t,n,r,i){var o;nt(r=r||n,n)<0&&(n=(o=[r,n])[0],r=o[1]),"string"==typeof t&&(t=e.splitLines(t)),ji(e,{from:n,to:r,text:t,origin:i})}function Zi(e,t,n,r){n<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function Qi(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i],l=!0;if(o.ranges){o.copied||((o=e[i]=o.deepCopy()).copied=!0);for(var s=0;s<o.ranges.length;s++)Zi(o.ranges[s].anchor,t,n,r),Zi(o.ranges[s].head,t,n,r)}else{for(var a=0;a<o.changes.length;++a){var u=o.changes[a];if(n<u.from.line)u.from=tt(u.from.line+r,u.from.ch),u.to=tt(u.to.line+r,u.to.ch);else if(t<=u.to.line){l=!1;break}}l||(e.splice(0,i+1),i=0)}}}function Ji(e,t){var n=t.from.line,r=t.to.line,t=t.text.length-(r-n)-1;Qi(e.done,n,r,t),Qi(e.undone,n,r,t)}function eo(e,t,n,r){var i=t,o=t;return"number"==typeof t?o=Ye(e,st(e,t)):i=Ze(t),null==i?null:(r(o,i)&&e.cm&&nr(e.cm,i,n),o)}function to(e){this.lines=e,this.parent=null;for(var t=0,n=0;n<e.length;++n)e[n].parent=this,t+=e[n].height;this.height=t}function no(e){this.children=e;for(var t=0,n=0,r=0;r<e.length;++r){var i=e[r];t+=i.chunkSize(),n+=i.height,i.parent=this}this.size=t,this.height=n,this.parent=null}oi.prototype.from=function(){return lt(this.anchor,this.head)},oi.prototype.to=function(){return ot(this.anchor,this.head)},oi.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},to.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n,r=e,i=e+t;r<i;++r){var o=this.lines[r];this.height-=o.height,(n=o).parent=null,Nt(n),rn(o,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,n){this.height+=n,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,n){for(var r=e+t;e<r;++e)if(n(this.lines[e]))return!0}},no.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var n,r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(e<o){var l=Math.min(t,o-e),s=i.height;if(i.removeInner(e,l),this.height-=s-i.height,o==l&&(this.children.splice(r--,1),i.parent=null),0==(t-=l))break;e=0}else e-=o}this.size-t<25&&(1<this.children.length||!(this.children[0]instanceof to))&&(this.collapse(n=[]),this.children=[new to(n)],this.children[0].parent=this)},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,n){this.size+=t.length,this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(e<=o){if(i.insertInner(e,t,n),i.lines&&50<i.lines.length){for(var l=i.lines.length%25+25,s=l;s<i.lines.length;){var a=new to(i.lines.slice(s,s+=25));i.height-=a.height,this.children.splice(++r,0,a),a.parent=this}i.lines=i.lines.slice(0,l),this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t,n=new no(e.children.splice(e.children.length-5,5))}while(e.parent?(e.size-=n.size,e.height-=n.height,t=R(e.parent.children,e),e.parent.children.splice(t+1,0,n)):(((t=new no(e.children)).parent=e).children=[t,n],e=t),n.parent=e.parent,10<e.children.length);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(e<o){var l=Math.min(t,o-e);if(i.iterN(e,l,n))return!0;if(0==(t-=l))break;e=0}else e-=o}}};function ro(e,t,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.doc=e,this.node=t}function io(e,t,n){Gt(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&br(e,n)}ro.prototype.clear=function(){var e=this.doc.cm,t=this.line.widgets,n=this.line,r=Ze(n);if(null!=r&&t){for(var i=0;i<t.length;++i)t[i]==this&&t.splice(i--,1);t.length||(n.widgets=null);var o=fn(this);qe(n,Math.max(0,n.height-o)),e&&(Pr(e,function(){io(e,n,-o),nr(e,r,"widget")}),rn(e,"lineWidgetCleared",e,this,r))}},ro.prototype.changed=function(){var e=this,t=this.height,n=this.doc.cm,r=this.line;this.height=null;var i=fn(this)-t;i&&(Bt(this.doc,r)||qe(r,r.height+i),n&&Pr(n,function(){n.curOp.forceUpdate=!0,io(n,r,i),rn(n,"lineWidgetChanged",n,e,Ze(r))}))},Se(ro);function oo(e,t){this.lines=[],this.type=t,this.doc=e,this.id=++lo}var lo=0;function so(r,i,o,e,t){if(e&&e.shared)return function(e,n,r,i,o){(i=P(i)).shared=!1;var l=[so(e,n,r,i,o)],s=l[0],a=i.widgetNode;return mi(e,function(e){a&&(i.widgetNode=a.cloneNode(!0)),l.push(so(e,at(e,n),at(e,r),i,o));for(var t=0;t<e.linked.length;++t)if(e.linked[t].isParent)return;s=Y(l)}),new ao(l,s)}(r,i,o,e,t);if(r.cm&&!r.cm.curOp)return Er(r.cm,so)(r,i,o,e,t);var l=new oo(r,t),t=nt(i,o);if(e&&P(e,l,!1),0<t||0==t&&!1!==l.clearWhenEmpty)return l;if(l.replacedWith&&(l.collapsed=!0,l.widgetNode=T("span",[l.replacedWith],"CodeMirror-widget"),e.handleMouseEvents||l.widgetNode.setAttribute("cm-ignore-events","true"),e.insertLeft&&(l.widgetNode.insertLeft=!0)),l.collapsed){if(Et(r,i.line,i,o,l)||i.line!=o.line&&Et(r,o.line,i,o,l))throw new Error("Inserting collapsed marker partially overlapping an existing one");St=!0}l.addToHistory&&Ci(r,{from:i,to:o,origin:"markText"},r.sel,NaN);var s,a=i.line,u=r.cm;if(r.iter(a,o.line+1,function(e){var t,n;u&&l.collapsed&&!u.options.lineWrapping&&It(e)==u.display.maxLine&&(s=!0),l.collapsed&&a!=i.line&&qe(e,0),t=e,n=new Lt(l,a==i.line?i.ch:null,a==o.line?o.ch:null),(e=(e=r.cm&&r.cm.curOp)&&window.WeakSet&&(e.markedSpans||(e.markedSpans=new WeakSet)))&&e.has(t.markedSpans)?t.markedSpans.push(n):(t.markedSpans=t.markedSpans?t.markedSpans.concat([n]):[n],e&&e.add(t.markedSpans)),n.marker.attachLine(t),++a}),l.collapsed&&r.iter(i.line,o.line+1,function(e){Bt(r,e)&&qe(e,0)}),l.clearOnEnter&&me(l,"beforeCursorEnter",function(){return l.clear()}),l.readOnly&&(Ct=!0,(r.history.done.length||r.history.undone.length)&&r.clearHistory()),l.collapsed&&(l.id=++lo,l.atomic=!0),u){if(s&&(u.curOp.updateMaxLine=!0),l.collapsed)tr(u,i.line,o.line+1);else if(l.className||l.startStyle||l.endStyle||l.css||l.attributes||l.title)for(var n=i.line;n<=o.line;n++)nr(u,n,"text");l.atomic&&Ri(u.doc),rn(u,"markerAdded",u,l)}return l}oo.prototype.clear=function(){if(!this.explicitlyCleared){var e,t=this.doc.cm,n=t&&!t.curOp;n&&Hr(t),!Ce(this,"clear")||(e=this.find())&&rn(this,"clear",e.from,e.to);for(var r=null,i=null,o=0;o<this.lines.length;++o){var l=this.lines[o],s=kt(l.markedSpans,this);t&&!this.collapsed?nr(t,Ze(l),"text"):t&&(null!=s.to&&(i=Ze(l)),null!=s.from&&(r=Ze(l))),l.markedSpans=function(e,t){for(var n,r=0;r<e.length;++r)e[r]!=t&&(n=n||[]).push(e[r]);return n}(l.markedSpans,s),null==s.from&&this.collapsed&&!Bt(this.doc,l)&&t&&qe(l,Yn(t.display))}if(t&&this.collapsed&&!t.options.lineWrapping)for(var a=0;a<this.lines.length;++a){var u=It(this.lines[a]),c=Ut(u);c>t.display.maxLineLength&&(t.display.maxLine=u,t.display.maxLineLength=c,t.display.maxLineChanged=!0)}null!=r&&t&&this.collapsed&&tr(t,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&Ri(t.doc)),t&&rn(t,"markerCleared",t,this,r,i),n&&Fr(t),this.parent&&this.parent.clear()}},oo.prototype.find=function(e,t){var n,r;null==e&&"bookmark"==this.type&&(e=1);for(var i=0;i<this.lines.length;++i){var o=this.lines[i],l=kt(o.markedSpans,this);if(null!=l.from&&(n=tt(t?o:Ze(o),l.from),-1==e))return n;if(null!=l.to&&(r=tt(t?o:Ze(o),l.to),1==e))return r}return n&&{from:n,to:r}},oo.prototype.changed=function(){var n=this,r=this.find(-1,!0),i=this,o=this.doc.cm;r&&o&&Pr(o,function(){var e=r.line,t=Ze(r.line),t=Sn(o,t);t&&(On(t),o.curOp.selectionChanged=o.curOp.forceUpdate=!0),o.curOp.updateMaxLine=!0,Bt(i.doc,e)||null==i.height||(t=i.height,i.height=null,(t=fn(i)-t)&&qe(e,e.height+t)),rn(o,"markerChanged",o,n)})},oo.prototype.attachLine=function(e){var t;!this.lines.length&&this.doc.cm&&((t=this.doc.cm.curOp).maybeHiddenMarkers&&-1!=R(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)),this.lines.push(e)},oo.prototype.detachLine=function(e){this.lines.splice(R(this.lines,e),1),!this.lines.length&&this.doc.cm&&((e=this.doc.cm.curOp).maybeHiddenMarkers||(e.maybeHiddenMarkers=[])).push(this)},Se(oo);var ao=function(e,t){this.markers=e,this.primary=t;for(var n=0;n<e.length;++n)e[n].parent=this};function uo(e){return e.findMarks(tt(e.first,0),e.clipPos(tt(e.lastLine())),function(e){return e.parent})}function co(o){for(var e=0;e<o.length;e++)!function(e){var t=o[e],n=[t.primary.doc];mi(t.primary.doc,function(e){return n.push(e)});for(var r=0;r<t.markers.length;r++){var i=t.markers[r];-1==R(n,i.doc)&&(i.parent=null,t.markers.splice(r--,1))}}(e)}ao.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();rn(this,"clear")}},ao.prototype.find=function(e,t){return this.primary.find(e,t)},Se(ao);function ho(e,t,n,r,i){if(!(this instanceof ho))return new ho(e,t,n,r,i);null==n&&(n=0),no.call(this,[new to([new Kt("",null)])]),this.first=n,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,n=tt(this.modeFrontier=this.highlightFrontier=n,0),this.sel=si(n),this.history=new bi(null),this.id=++fo,this.modeOption=t,this.lineSep=r,this.direction="rtl"==i?"rtl":"ltr",this.extend=!1,"string"==typeof e&&(e=this.splitLines(e)),gi(this,{from:n,to:n,text:e}),Pi(this,si(n),G)}var fo=0;(ho.prototype=q(no.prototype,{constructor:ho,iter:function(e,t,n){n?this.iterN(e-this.first,t-e,n):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var n=0,r=0;r<t.length;++r)n+=t[r].height;this.insertInner(e-this.first,t,n)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=$e(this,this.first,this.first+this.size);return!1===e?t:t.join(e||this.lineSeparator())},setValue:Rr(function(e){var t=tt(this.first,0),n=this.first+this.size-1;ji(this,{from:t,to:tt(n,Ye(this,n).text.length),text:this.splitLines(e),origin:"setValue",full:!0},!0),this.cm&&xr(this.cm,0,0),Pi(this,si(t),G)}),replaceRange:function(e,t,n,r){qi(this,e,t=at(this,t),n=n?at(this,n):t,r)},getRange:function(e,t,n){t=_e(this,at(this,e),at(this,t));return!1===n?t:""===n?t.join(""):t.join(n||this.lineSeparator())},getLine:function(e){e=this.getLineHandle(e);return e&&e.text},getLineHandle:function(e){if(Je(this,e))return Ye(this,e)},getLineNumber:Ze,getLineHandleVisualStart:function(e){return It(e="number"==typeof e?Ye(this,e):e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return at(this,e)},getCursor:function(e){var t=this.sel.primary(),t=null==e||"head"==e?t.head:"anchor"==e?t.anchor:"end"==e||"to"==e||!1===e?t.to():t.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:Rr(function(e,t,n){Hi(this,at(this,"number"==typeof e?tt(e,t||0):e),null,n)}),setSelection:Rr(function(e,t,n){Hi(this,at(this,e),at(this,t||e),n)}),extendSelection:Rr(function(e,t,n){Ai(this,at(this,e),t&&at(this,t),n)}),extendSelections:Rr(function(e,t){Di(this,ut(this,e),t)}),extendSelectionsBy:Rr(function(e,t){Di(this,ut(this,_(this.sel.ranges,e)),t)}),setSelections:Rr(function(e,t,n){if(e.length){for(var r=[],i=0;i<e.length;i++)r[i]=new oi(at(this,e[i].anchor),at(this,e[i].head||e[i].anchor));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),Pi(this,li(this.cm,r,t),n)}}),addSelection:Rr(function(e,t,n){var r=this.sel.ranges.slice(0);r.push(new oi(at(this,e),at(this,t||e))),Pi(this,li(this.cm,r,r.length-1),n)}),getSelection:function(e){for(var t=this.sel.ranges,n=0;n<t.length;n++)var r=_e(this,t[n].from(),t[n].to()),i=i?i.concat(r):r;return!1===e?i:i.join(e||this.lineSeparator())},getSelections:function(e){for(var t=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=_e(this,n[r].from(),n[r].to());!1!==e&&(i=i.join(e||this.lineSeparator())),t[r]=i}return t},replaceSelection:function(e,t,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=e;this.replaceSelections(r,t,n||"+input")},replaceSelections:Rr(function(e,t,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var l=i.ranges[o];r[o]={from:l.from(),to:l.to(),text:this.splitLines(e[o]),origin:n}}for(var t=t&&"end"!=t&&function(e,t,n){for(var r=[],i=u=tt(e.first,0),o=0;o<t.length;o++){var l=t[o],s=hi(l.from,u,i),a=hi(ai(l),u,i),u=l.to,i=a;"around"==n?(l=nt((l=e.sel.ranges[o]).head,l.anchor)<0,r[o]=new oi(l?a:s,l?s:a)):r[o]=new oi(s,s)}return new ii(r,e.sel.primIndex)}(this,r,t),s=r.length-1;0<=s;s--)ji(this,r[s]);t?Fi(this,t):this.cm&&wr(this.cm)}),undo:Rr(function(){Yi(this,"undo")}),redo:Rr(function(){Yi(this,"redo")}),undoSelection:Rr(function(){Yi(this,"undo",!0)}),redoSelection:Rr(function(){Yi(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var i=0;i<e.undone.length;i++)e.undone[i].ranges||++n;return{undo:t,redo:n}},clearHistory:function(){var t=this;this.history=new bi(this.history),mi(this,function(e){return e.history=t.history},!0)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Ni(this.history.done),undone:Ni(this.history.undone)}},setHistory:function(e){var t=this.history=new bi(this.history);t.done=Ni(e.done.slice(0),null,!0),t.undone=Ni(e.undone.slice(0),null,!0)},setGutterMarker:Rr(function(e,n,r){return eo(this,e,"gutter",function(e){var t=e.gutterMarkers||(e.gutterMarkers={});return!(t[n]=r)&&ee(t)&&(e.gutterMarkers=null),1})}),clearGutter:Rr(function(t){var n=this;this.iter(function(e){e.gutterMarkers&&e.gutterMarkers[t]&&eo(n,e,"gutter",function(){return e.gutterMarkers[t]=null,ee(e.gutterMarkers)&&(e.gutterMarkers=null),1})})}),lineInfo:function(e){var t;if("number"==typeof e){if(!Je(this,e))return null;if(!(e=Ye(this,t=e)))return null}else if(null==(t=Ze(e)))return null;return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},addLineClass:Rr(function(e,n,r){return eo(this,e,"gutter"==n?"gutter":"class",function(e){var t="text"==n?"textClass":"background"==n?"bgClass":"gutter"==n?"gutterClass":"wrapClass";if(e[t]){if(C(r).test(e[t]))return;e[t]+=" "+r}else e[t]=r;return 1})}),removeLineClass:Rr(function(e,o,l){return eo(this,e,"gutter"==o?"gutter":"class",function(e){var t="text"==o?"textClass":"background"==o?"bgClass":"gutter"==o?"gutterClass":"wrapClass",n=e[t];if(n){if(null==l)e[t]=null;else{var r=n.match(C(l));if(!r)return;var i=r.index+r[0].length;e[t]=n.slice(0,r.index)+(r.index&&i!=n.length?" ":"")+n.slice(i)||null}return 1}})}),addLineWidget:Rr(function(e,t,n){return e=e,i=new ro(r=this,t,n),(o=r.cm)&&i.noHScroll&&(o.display.alignWidgets=!0),eo(r,e,"widget",function(e){var t=e.widgets||(e.widgets=[]);return null==i.insertAt?t.push(i):t.splice(Math.min(t.length,Math.max(0,i.insertAt)),0,i),i.line=e,o&&!Bt(r,e)&&(t=Gt(e)<r.scrollTop,qe(e,e.height+fn(i)),t&&br(o,i.height),o.curOp.forceUpdate=!0),1}),o&&rn(o,"lineWidgetAdded",o,i,"number"==typeof e?e:Ze(e)),i;var r,i,o}),removeLineWidget:function(e){e.clear()},markText:function(e,t,n){return so(this,at(this,e),at(this,t),n,n&&n.type||"range")},setBookmark:function(e,t){t={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared,handleMouseEvents:t&&t.handleMouseEvents};return so(this,e=at(this,e),e,t,"bookmark")},findMarksAt:function(e){var t=[],n=Ye(this,(e=at(this,e)).line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=e.ch)&&(null==i.to||i.to>=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(i,o,l){i=at(this,i),o=at(this,o);var s=[],a=i.line;return this.iter(i.line,o.line+1,function(e){var t=e.markedSpans;if(t)for(var n=0;n<t.length;n++){var r=t[n];null!=r.to&&a==i.line&&i.ch>=r.to||null==r.from&&a!=i.line||null!=r.from&&a==o.line&&r.from>=o.ch||l&&!l(r.marker)||s.push(r.marker.parent||r.marker)}++a}),s},getAllMarks:function(){var r=[];return this.iter(function(e){var t=e.markedSpans;if(t)for(var n=0;n<t.length;++n)null!=t[n].from&&r.push(t[n].marker)}),r},posFromIndex:function(t){var n,r=this.first,i=this.lineSeparator().length;return this.iter(function(e){e=e.text.length+i;if(t<e)return n=t,!0;t-=e,++r}),at(this,tt(r,n))},indexFromPos:function(e){var t=(e=at(this,e)).ch;if(e.line<this.first||e.ch<0)return 0;var n=this.lineSeparator().length;return this.iter(this.first,e.line,function(e){t+=e.text.length+n}),t},copy:function(e){var t=new ho($e(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){var t=this.first,n=this.first+this.size;null!=(e=e||{}).from&&e.from>t&&(t=e.from),null!=e.to&&e.to<n&&(n=e.to);t=new ho($e(this,t,n),e.mode||this.modeOption,t,this.lineSep,this.direction);return e.sharedHist&&(t.history=this.history),(this.linked||(this.linked=[])).push({doc:t,sharedHist:e.sharedHist}),t.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n],i=r.find(),o=e.clipPos(i.from),i=e.clipPos(i.to);nt(o,i)&&(i=so(e,o,i,r.primary,r.primary.type),r.markers.push(i),i.parent=r)}}(t,uo(this)),t},unlinkDoc:function(e){if(e instanceof cl&&(e=e.doc),this.linked)for(var t=0;t<this.linked.length;++t)if(this.linked[t].doc==e){this.linked.splice(t,1),e.unlinkDoc(this),co(uo(this));break}var n;e.history==this.history&&(n=[e.id],mi(e,function(e){return n.push(e.id)},!0),e.history=new bi(null),e.history.done=Ni(this.history.done,n),e.history.undone=Ni(this.history.undone,n))},iterLinkedDocs:function(e){mi(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(e){return this.lineSep?e.split(this.lineSep):He(e)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:Rr(function(e){var t;(e="rtl"!=e?"ltr":e)!=this.direction&&(this.direction=e,this.iter(function(e){return e.order=null}),this.cm&&Pr(t=this.cm,function(){yi(t),tr(t)}))})})).eachLine=ho.prototype.iter;var po=0;function go(e){var r=this;if(mo(r),!we(r,e)&&!pn(r.display,e)){Le(e),w&&(po=+new Date);var t=Jn(r,e,!0),n=e.dataTransfer.files;if(t&&!r.isReadOnly())if(n&&n.length&&window.FileReader&&window.File)for(var i=n.length,o=Array(i),l=0,s=function(){++l==i&&Er(r,function(){var e={from:t=at(r.doc,t),to:t,text:r.doc.splitLines(o.filter(function(e){return null!=e}).join(r.doc.lineSeparator())),origin:"paste"};ji(r.doc,e),Fi(r.doc,si(at(r.doc,t),at(r.doc,ai(e))))})()},a=0;a<n.length;a++)!function(e,t){var n;r.options.allowDropFileTypes&&-1==R(r.options.allowDropFileTypes,e.type)?s():((n=new FileReader).onerror=function(){return s()},n.onload=function(){var e=n.result;/[\x00-\x08\x0e-\x1f]{2}/.test(e)||(o[t]=e),s()},n.readAsText(e))}(n[a],a);else{if(r.state.draggingText&&-1<r.doc.sel.contains(t))return r.state.draggingText(e),void setTimeout(function(){return r.display.input.focus()},20);try{var u,c=e.dataTransfer.getData("Text");if(c){if(r.state.draggingText&&!r.state.draggingText.copy&&(u=r.listSelections()),Ei(r.doc,si(t,t)),u)for(var h=0;h<u.length;++h)qi(r.doc,"",u[h].anchor,u[h].head,"drag");r.replaceSelection(c,"around","paste"),r.display.input.focus()}}catch(e){}}}}function mo(e){e.display.dragCursor&&(e.display.lineSpace.removeChild(e.display.dragCursor),e.display.dragCursor=null)}function vo(t){if(document.getElementsByClassName){for(var e=document.getElementsByClassName("CodeMirror"),n=[],r=0;r<e.length;r++){var i=e[r].CodeMirror;i&&n.push(i)}n.length&&n[0].operation(function(){for(var e=0;e<n.length;e++)t(n[e])})}}var yo=!1;function bo(){var e;yo||(me(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,vo(wo)},100))}),me(window,"blur",function(){return vo(pr)}),yo=!0)}function wo(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,t.scrollbarsClipped=!1,e.setSize()}for(var xo={3:"Pause",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",224:"Mod",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},Co=0;Co<10;Co++)xo[Co+48]=xo[Co+96]=String(Co);for(var So=65;So<=90;So++)xo[So]=String.fromCharCode(So);for(var Lo=1;Lo<=12;Lo++)xo[Lo+111]=xo[Lo+63235]="F"+Lo;var ko={};function To(e){var t,n,r,i,o=e.split(/-(?!$)/);e=o[o.length-1];for(var l=0;l<o.length-1;l++){var s=o[l];if(/^(cmd|meta|m)$/i.test(s))i=!0;else if(/^a(lt)?$/i.test(s))t=!0;else if(/^(c|ctrl|control)$/i.test(s))n=!0;else{if(!/^s(hift)?$/i.test(s))throw new Error("Unrecognized modifier name: "+s);r=!0}}return t&&(e="Alt-"+e),n&&(e="Ctrl-"+e),i&&(e="Cmd-"+e),e=r?"Shift-"+e:e}function Mo(e){var t,n,r={};for(t in e)if(e.hasOwnProperty(t)){var i=e[t];if(!/^(name|fallthrough|(de|at)tach)$/.test(t))if("..."!=i){for(var o=_(t.split(" "),To),l=0;l<o.length;l++){var s=void 0,a=void 0,s=l==o.length-1?(a=o.join(" "),i):(a=o.slice(0,l+1).join(" "),"..."),u=r[a];if(u){if(u!=s)throw new Error("Inconsistent bindings for "+a)}else r[a]=s}delete e[t]}else delete e[t]}for(n in r)e[n]=r[n];return e}function No(e,t,n,r){var i=(t=Wo(t)).call?t.call(e,r):t[e];if(!1===i)return"nothing";if("..."===i)return"multi";if(null!=i&&n(i))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return No(e,t.fallthrough,n,r);for(var o=0;o<t.fallthrough.length;o++){var l=No(e,t.fallthrough[o],n,r);if(l)return l}}}function Oo(e){e="string"==typeof e?e:xo[e.keyCode];return"Ctrl"==e||"Alt"==e||"Shift"==e||"Mod"==e}function Ao(e,t,n){var r=e;return t.altKey&&"Alt"!=r&&(e="Alt-"+e),(b?t.metaKey:t.ctrlKey)&&"Ctrl"!=r&&(e="Ctrl-"+e),(b?t.ctrlKey:t.metaKey)&&"Mod"!=r&&(e="Cmd-"+e),e=!n&&t.shiftKey&&"Shift"!=r?"Shift-"+e:e}function Do(e,t){if(p&&34==e.keyCode&&e.char)return!1;var n=xo[e.keyCode];return null!=n&&!e.altGraphKey&&Ao(n=3==e.keyCode&&e.code?e.code:n,e,t)}function Wo(e){return"string"==typeof e?ko[e]:e}function Ho(t,e){for(var n=t.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=e(n[i]);r.length&&nt(o.from,Y(r).to)<=0;){var l=r.pop();if(nt(l.from,o.from)<0){o.from=l.from;break}}r.push(o)}Pr(t,function(){for(var e=r.length-1;0<=e;e--)qi(t.doc,"",r[e].from,r[e].to,"+delete");wr(t)})}function Fo(e,t,n){n=re(e.text,t+n,n);return n<0||n>e.text.length?null:n}function Po(e,t,n){e=Fo(e,t.ch,n);return null==e?null:new tt(t.line,e,n<0?"after":"before")}function Eo(e,t,n,r,i){if(e){"rtl"==t.doc.direction&&(i=-i);var o=pe(n,t.doc.direction);if(o){var l,s,a,e=i<0?Y(o):o[0],o=i<0==(1==e.level)?"after":"before";return 0<e.level||"rtl"==t.doc.direction?(l=Ln(t,n),s=i<0?n.text.length-1:0,a=kn(t,l,s).top,s=ie(function(e){return kn(t,l,e).top==a},i<0==(1==e.level)?e.from:e.to-1,s),"before"==o&&(s=Fo(n,s,1))):s=i<0?e.to:e.from,new tt(r,s,o)}}return new tt(r,i<0?n.text.length:0,i<0?"before":"after")}function Io(t,n,s,e){var a=pe(n,t.doc.direction);if(!a)return Po(n,s,e);s.ch>=n.text.length?(s.ch=n.text.length,s.sticky="before"):s.ch<=0&&(s.ch=0,s.sticky="after");var r=le(a,s.ch,s.sticky),i=a[r];if("ltr"==t.doc.direction&&i.level%2==0&&(0<e?i.to>s.ch:i.from<s.ch))return Po(n,s,e);function u(e,t){return Fo(n,e instanceof tt?e.ch:e,t)}function o(e){return t.options.lineWrapping?(l=l||Ln(t,n),Vn(t,n,l,e)):{begin:0,end:n.text.length}}var l,c=o("before"==s.sticky?u(s,-1):s.ch);if("rtl"==t.doc.direction||1==i.level){var h=1==i.level==e<0,d=u(s,h?1:-1);if(null!=d&&(h?d<=i.to&&d<=c.end:d>=i.from&&d>=c.begin))return new tt(s.line,d,h?"before":"after")}h=function(e,t,n){for(var r=function(e,t){return t?new tt(s.line,u(e,1),"before"):new tt(s.line,e,"after")};0<=e&&e<a.length;e+=t){var i=a[e],o=0<t==(1!=i.level),l=o?n.begin:u(n.end,-1);if(i.from<=l&&l<i.to)return r(l,o);if(l=o?i.from:u(i.to,-1),n.begin<=l&&l<n.end)return r(l,o)}},r=h(r+e,e,c);if(r)return r;c=0<e?c.end:u(c.begin,-1);return null==c||0<e&&c==n.text.length||!(r=h(0<e?0:a.length-1,e,o(c)))?null:r}ko.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},ko.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},ko.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},ko.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},ko.default=g?ko.macDefault:ko.pcDefault;var Ro={selectAll:Vi,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),G)},killLine:function(n){return Ho(n,function(e){if(e.empty()){var t=Ye(n.doc,e.head.line).text.length;return e.head.ch==t&&e.head.line<n.lastLine()?{from:e.head,to:tt(e.head.line+1,0)}:{from:e.head,to:tt(e.head.line,t)}}return{from:e.from(),to:e.to()}})},deleteLine:function(t){return Ho(t,function(e){return{from:tt(e.from().line,0),to:at(t.doc,tt(e.to().line+1,0))}})},delLineLeft:function(e){return Ho(e,function(e){return{from:tt(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(n){return Ho(n,function(e){var t=n.charCoords(e.head,"div").top+5;return{from:n.coordsChar({left:0,top:t},"div"),to:e.from()}})},delWrappedLineRight:function(n){return Ho(n,function(e){var t=n.charCoords(e.head,"div").top+5,t=n.coordsChar({left:n.display.lineDiv.offsetWidth+100,top:t},"div");return{from:e.from(),to:t}})},undo:function(e){return e.undo()},redo:function(e){return e.redo()},undoSelection:function(e){return e.undoSelection()},redoSelection:function(e){return e.redoSelection()},goDocStart:function(e){return e.extendSelection(tt(e.firstLine(),0))},goDocEnd:function(e){return e.extendSelection(tt(e.lastLine()))},goLineStart:function(t){return t.extendSelectionsBy(function(e){return zo(t,e.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(t){return t.extendSelectionsBy(function(e){return Bo(t,e.head)},{origin:"+move",bias:1})},goLineEnd:function(t){return t.extendSelectionsBy(function(e){return function(e,t){var n=Ye(e.doc,t),r=function(e){for(var t;t=Pt(e);)e=t.find(1,!0).line;return e}(n);r!=n&&(t=Ze(r));return Eo(!0,e,n,t,-1)}(t,e.head.line)},{origin:"+move",bias:-1})},goLineRight:function(t){return t.extendSelectionsBy(function(e){e=t.cursorCoords(e.head,"div").top+5;return t.coordsChar({left:t.display.lineDiv.offsetWidth+100,top:e},"div")},V)},goLineLeft:function(t){return t.extendSelectionsBy(function(e){e=t.cursorCoords(e.head,"div").top+5;return t.coordsChar({left:0,top:e},"div")},V)},goLineLeftSmart:function(n){return n.extendSelectionsBy(function(e){var t=n.cursorCoords(e.head,"div").top+5,t=n.coordsChar({left:0,top:t},"div");return t.ch<n.getLine(t.line).search(/\S/)?Bo(n,e.head):t},V)},goLineUp:function(e){return e.moveV(-1,"line")},goLineDown:function(e){return e.moveV(1,"line")},goPageUp:function(e){return e.moveV(-1,"page")},goPageDown:function(e){return e.moveV(1,"page")},goCharLeft:function(e){return e.moveH(-1,"char")},goCharRight:function(e){return e.moveH(1,"char")},goColumnLeft:function(e){return e.moveH(-1,"column")},goColumnRight:function(e){return e.moveH(1,"column")},goWordLeft:function(e){return e.moveH(-1,"word")},goGroupRight:function(e){return e.moveH(1,"group")},goGroupLeft:function(e){return e.moveH(-1,"group")},goWordRight:function(e){return e.moveH(1,"word")},delCharBefore:function(e){return e.deleteH(-1,"codepoint")},delCharAfter:function(e){return e.deleteH(1,"char")},delWordBefore:function(e){return e.deleteH(-1,"word")},delWordAfter:function(e){return e.deleteH(1,"word")},delGroupBefore:function(e){return e.deleteH(-1,"group")},delGroupAfter:function(e){return e.deleteH(1,"group")},indentAuto:function(e){return e.indentSelection("smart")},indentMore:function(e){return e.indentSelection("add")},indentLess:function(e){return e.indentSelection("subtract")},insertTab:function(e){return e.replaceSelection("\t")},insertSoftTab:function(e){for(var t=[],n=e.listSelections(),r=e.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),o=E(e.getLine(o.line),o.ch,r);t.push(X(r-o%r))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(l){return Pr(l,function(){for(var e,t,n,r=l.listSelections(),i=[],o=0;o<r.length;o++)r[o].empty()&&(e=r[o].head,(t=Ye(l.doc,e.line).text)&&(0<(e=e.ch==t.length?new tt(e.line,e.ch-1):e).ch?(e=new tt(e.line,e.ch+1),l.replaceRange(t.charAt(e.ch-1)+t.charAt(e.ch-2),tt(e.line,e.ch-2),e,"+transpose")):e.line>l.doc.first&&((n=Ye(l.doc,e.line-1).text)&&(e=new tt(e.line,1),l.replaceRange(t.charAt(0)+l.doc.lineSeparator()+n.charAt(n.length-1),tt(e.line-1,n.length-1),e,"+transpose")))),i.push(new oi(e,e)));l.setSelections(i)})},newlineAndIndent:function(r){return Pr(r,function(){for(var e=(t=r.listSelections()).length-1;0<=e;e--)r.replaceRange(r.doc.lineSeparator(),t[e].anchor,t[e].head,"+input");for(var t=r.listSelections(),n=0;n<t.length;n++)r.indentLine(t[n].from().line,null,!0);wr(r)})},openLine:function(e){return e.replaceSelection("\n","start")},toggleOverwrite:function(e){return e.toggleOverwrite()}};function zo(e,t){var n=Ye(e.doc,t),r=It(n);return Eo(!0,e,r,t=r!=n?Ze(r):t,1)}function Bo(e,t){var n=zo(e,t.line),r=Ye(e.doc,n.line),e=pe(r,e.doc.direction);if(e&&0!=e[0].level)return n;r=Math.max(n.ch,r.text.search(/\S/)),t=t.line==n.line&&t.ch<=r&&t.ch;return tt(n.line,t?0:r,n.sticky)}function Go(e,t,n){if("string"==typeof t&&!(t=Ro[t]))return!1;e.display.input.ensurePolled();var r=e.display.shift,i=!1;try{e.isReadOnly()&&(e.state.suppressEdits=!0),n&&(e.display.shift=!1),i=t(e)!=B}finally{e.display.shift=r,e.state.suppressEdits=!1}return i}var Uo=new I;function Vo(e,t,n,r){var i=e.state.keySeq;if(i){if(Oo(t))return"handled";if(/\'$/.test(t)?e.state.keySeq=null:Uo.set(50,function(){e.state.keySeq==i&&(e.state.keySeq=null,e.display.input.reset())}),Ko(e,i+" "+t,n,r))return!0}return Ko(e,t,n,r)}function Ko(e,t,n,r){r=function(e,t,n){for(var r=0;r<e.state.keyMaps.length;r++){var i=No(t,e.state.keyMaps[r],n,e);if(i)return i}return e.options.extraKeys&&No(t,e.options.extraKeys,n,e)||No(t,e.options.keyMap,n,e)}(e,t,r);return"multi"==r&&(e.state.keySeq=t),"handled"==r&&rn(e,"keyHandled",e,t,n),"handled"!=r&&"multi"!=r||(Le(n),cr(e)),!!r}function jo(t,e){var n=Do(e,!0);return!!n&&(e.shiftKey&&!t.state.keySeq?Vo(t,"Shift-"+n,e,function(e){return Go(t,e,!0)})||Vo(t,n,e,function(e){if("string"==typeof e?/^go[A-Z]/.test(e):e.motion)return Go(t,e)}):Vo(t,n,e,function(e){return Go(t,e)}))}var Xo=null;function Yo(e){var t,n,r,i=this;function o(e){18!=e.keyCode&&e.altKey||(S(r,"CodeMirror-crosshair"),ye(document,"keyup",o),ye(document,"mouseover",o))}e.target&&e.target!=i.display.input.getField()||(i.curOp.focus=O(),we(i,e)||(w&&v<11&&27==e.keyCode&&(e.returnValue=!1),t=e.keyCode,i.display.shift=16==t||e.shiftKey,n=jo(i,e),p&&(Xo=n?t:null,!n&&88==t&&!Pe&&(g?e.metaKey:e.ctrlKey)&&i.replaceSelection("",null,"cut")),d&&!g&&!n&&46==t&&e.shiftKey&&!e.ctrlKey&&document.execCommand&&document.execCommand("cut"),18!=t||/\bCodeMirror-crosshair\b/.test(i.display.lineDiv.className)||(A(r=i.display.lineDiv,"CodeMirror-crosshair"),me(document,"keyup",o),me(document,"mouseover",o))))}function _o(e){16==e.keyCode&&(this.doc.sel.shift=!1),we(this,e)}function $o(e){var t=this;if(!(e.target&&e.target!=t.display.input.getField()||pn(t.display,e)||we(t,e)||e.ctrlKey&&!e.altKey||g&&e.metaKey)){var n,r=e.keyCode,i=e.charCode;if(p&&r==Xo)return Xo=null,void Le(e);p&&(!e.which||e.which<10)&&jo(t,e)||"\b"!=(i=String.fromCharCode(null==i?r:i))&&(Vo(n=t,"'"+i+"'",e,function(e){return Go(n,e,!0)})||t.display.input.onKeyPress(e))}}function qo(e,t,n){this.time=e,this.pos=t,this.button=n}var Zo,Qo;function Jo(e){var t,n,r,i,o,l=this,s=l.display;we(l,e)||s.activeTouch&&s.input.supportsTouch()||(s.input.ensurePolled(),s.shift=e.shiftKey,pn(s,e)?f||(s.scroller.draggable=!1,setTimeout(function(){return s.scroller.draggable=!0},100)):nl(l,e)||(t=Jn(l,e),n=Oe(e),i=t?(r=t,i=n,o=+new Date,Qo&&Qo.compare(o,r,i)?(Zo=Qo=null,"triple"):Zo&&Zo.compare(o,r,i)?(Qo=new qo(o,r,i),Zo=null,"double"):(Zo=new qo(o,r,i),Qo=null,"single")):"single",window.focus(),1==n&&l.state.selectingText&&l.state.selectingText(e),t&&function(n,e,r,t,i){var o="Click";"double"==t?o="Double"+o:"triple"==t&&(o="Triple"+o);return Vo(n,Ao(o=(1==e?"Left":2==e?"Middle":"Right")+o,i),i,function(e){if(!(e="string"==typeof e?Ro[e]:e))return!1;var t=!1;try{n.isReadOnly()&&(n.state.suppressEdits=!0),t=e(n,r)!=B}finally{n.state.suppressEdits=!1}return t})}(l,n,t,i,e)||(1==n?t?function(e,t,n,r){w?setTimeout(F(hr,e),0):e.curOp.focus=O();var i,o=function(e,t,n){var r=e.getOption("configureMouse"),i=r?r(e,t,n):{};null==i.unit&&(r=m?n.shiftKey&&n.metaKey:n.altKey,i.unit=r?"rectangle":"single"==t?"char":"double"==t?"word":"line");null!=i.extend&&!e.doc.extend||(i.extend=e.doc.extend||n.shiftKey);null==i.addNew&&(i.addNew=g?n.metaKey:n.ctrlKey);null==i.moveOnDrag&&(i.moveOnDrag=!(g?n.altKey:n.ctrlKey));return i}(e,n,r),l=e.doc.sel;(e.options.dragDrop&&We&&!e.isReadOnly()&&"single"==n&&-1<(i=l.contains(t))&&(nt((i=l.ranges[i]).from(),t)<0||0<t.xRel)&&(0<nt(i.to(),t)||t.xRel<0)?function(t,n,r,i){var o=t.display,l=!1,s=Er(t,function(e){f&&(o.scroller.draggable=!1),t.state.draggingText=!1,t.state.delayingBlurEvent&&(t.hasFocus()?t.state.delayingBlurEvent=!1:dr(t)),ye(o.wrapper.ownerDocument,"mouseup",s),ye(o.wrapper.ownerDocument,"mousemove",a),ye(o.scroller,"dragstart",u),ye(o.scroller,"drop",s),l||(Le(e),i.addNew||Ai(t.doc,r,null,null,i.extend),f&&!c||w&&9==v?setTimeout(function(){o.wrapper.ownerDocument.body.focus({preventScroll:!0}),o.input.focus()},20):o.input.focus())}),a=function(e){l=l||10<=Math.abs(n.clientX-e.clientX)+Math.abs(n.clientY-e.clientY)},u=function(){return l=!0};f&&(o.scroller.draggable=!0);(t.state.draggingText=s).copy=!i.moveOnDrag,me(o.wrapper.ownerDocument,"mouseup",s),me(o.wrapper.ownerDocument,"mousemove",a),me(o.scroller,"dragstart",u),me(o.scroller,"drop",s),t.state.delayingBlurEvent=!0,setTimeout(function(){return o.input.focus()},20),o.scroller.dragDrop&&o.scroller.dragDrop()}:function(d,e,f,p){w&&dr(d);var l=d.display,g=d.doc;Le(e);var m,v,y=g.sel,t=y.ranges;p.addNew&&!p.extend?(v=g.sel.contains(f),m=-1<v?t[v]:new oi(f,f)):(m=g.sel.primary(),v=g.sel.primIndex);"rectangle"==p.unit?(p.addNew||(m=new oi(f,f)),f=Jn(d,e,!0,!0),v=-1):(e=el(d,f,p.unit),m=p.extend?Oi(m,e.anchor,e.head,p.extend):e);p.addNew?-1==v?(v=t.length,Pi(g,li(d,t.concat([m]),v),{scroll:!1,origin:"*mouse"})):1<t.length&&t[v].empty()&&"char"==p.unit&&!p.extend?(Pi(g,li(d,t.slice(0,v).concat(t.slice(v+1)),0),{scroll:!1,origin:"*mouse"}),y=g.sel):Wi(g,v,m,U):(Pi(g,new ii([m],v=0),U),y=g.sel);var b=f;function s(e){if(0!=nt(b,e))if(b=e,"rectangle"==p.unit){for(var t=[],n=d.options.tabSize,r=E(Ye(g,f.line).text,f.ch,n),i=E(Ye(g,e.line).text,e.ch,n),o=Math.min(r,i),l=Math.max(r,i),s=Math.min(f.line,e.line),a=Math.min(d.lastLine(),Math.max(f.line,e.line));s<=a;s++){var u=Ye(g,s).text,c=K(u,o,n);o==l?t.push(new oi(tt(s,c),tt(s,c))):u.length>c&&t.push(new oi(tt(s,c),tt(s,K(u,l,n))))}t.length||t.push(new oi(f,f)),Pi(g,li(d,y.ranges.slice(0,v).concat(t),v),{origin:"*mouse",scroll:!1}),d.scrollIntoView(e)}else{var h,r=m,i=el(d,e,p.unit),e=r.anchor,e=0<nt(i.anchor,e)?(h=i.head,lt(r.from(),i.anchor)):(h=i.anchor,ot(r.to(),i.head)),i=y.ranges.slice(0);i[v]=function(e,t){var n=t.anchor,r=t.head,i=Ye(e.doc,n.line);if(0==nt(n,r)&&n.sticky==r.sticky)return t;var o=pe(i);if(!o)return t;var l=le(o,n.ch,n.sticky),s=o[l];if(s.from!=n.ch&&s.to!=n.ch)return t;i=l+(s.from==n.ch==(1!=s.level)?0:1);if(0==i||i==o.length)return t;a=r.line!=n.line?0<(r.line-n.line)*("ltr"==e.doc.direction?1:-1):(e=le(o,r.ch,r.sticky),a=e-l||(r.ch-n.ch)*(1==s.level?-1:1),e==i-1||e==i?a<0:0<a);var i=o[i+(a?-1:0)],a=a==(1==i.level),i=a?i.from:i.to,a=a?"after":"before";return n.ch==i&&n.sticky==a?t:new oi(new tt(n.line,i,a),r)}(d,new oi(at(g,e),h)),Pi(g,li(d,i,v),U)}}var a=l.wrapper.getBoundingClientRect(),u=0;function n(e){d.state.selectingText=!1,u=1/0,e&&(Le(e),l.input.focus()),ye(l.wrapper.ownerDocument,"mousemove",r),ye(l.wrapper.ownerDocument,"mouseup",i),g.history.lastSelOrigin=null}var r=Er(d,function(e){(0!==e.buttons&&Oe(e)?function e(t){var n,r,i=++u,o=Jn(d,t,!0,"rectangle"==p.unit);o&&(0!=nt(o,b)?(d.curOp.focus=O(),s(o),n=vr(l,g),(o.line>=n.to||o.line<n.from)&&setTimeout(Er(d,function(){u==i&&e(t)}),150)):(r=t.clientY<a.top?-20:t.clientY>a.bottom?20:0)&&setTimeout(Er(d,function(){u==i&&(l.scroller.scrollTop+=r,e(t))}),50))}:n)(e)}),i=Er(d,n);d.state.selectingText=i,me(l.wrapper.ownerDocument,"mousemove",r),me(l.wrapper.ownerDocument,"mouseup",i)})(e,r,t,o)}(l,t,i,e):Ne(e)==s.scroller&&Le(e):2==n?(t&&Ai(l.doc,t),setTimeout(function(){return s.input.focus()},20)):3==n&&(x?l.display.input.onContextMenu(e):dr(l)))))}function el(e,t,n){if("char"==n)return new oi(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new oi(tt(t.line,0),at(e.doc,tt(t.line+1,0)));t=n(e,t);return new oi(t.from,t.to)}function tl(e,t,n,r){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(e){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&Le(t);var l=e.display,r=l.lineDiv.getBoundingClientRect();if(o>r.bottom||!Ce(e,n))return Te(t);o-=r.top-l.viewOffset;for(var s=0;s<e.display.gutterSpecs.length;++s){var a=l.gutters.childNodes[s];if(a&&a.getBoundingClientRect().right>=i)return be(e,n,e,Qe(e.doc,o),e.display.gutterSpecs[s].className,t),Te(t)}}function nl(e,t){return tl(e,t,"gutterClick",!0)}function rl(e,t){var n,r;pn(e.display,t)||(r=t,Ce(n=e,"gutterContextMenu")&&tl(n,r,"gutterContextMenu",!1))||we(e,t,"contextmenu")||x||e.display.input.onContextMenu(t)}function il(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Dn(e)}qo.prototype.compare=function(e,t,n){return this.time+400>e&&0==nt(t,this.pos)&&n==this.button};var ol={toString:function(){return"CodeMirror.Init"}},ll={},sl={};function al(e,t,n){!t!=!(n&&n!=ol)&&(n=e.display.dragFunctions,(t=t?me:ye)(e.display.scroller,"dragstart",n.start),t(e.display.scroller,"dragenter",n.enter),t(e.display.scroller,"dragover",n.over),t(e.display.scroller,"dragleave",n.leave),t(e.display.scroller,"drop",n.drop))}function ul(e){e.options.lineWrapping?(A(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(S(e.display.wrapper,"CodeMirror-wrap"),Vt(e)),Qn(e),tr(e),Dn(e),setTimeout(function(){return Nr(e)},100)}function cl(e,t){var n=this;if(!(this instanceof cl))return new cl(e,t);this.options=t=t?P(t):{},P(ll,t,!1);var r=t.value;"string"==typeof r?r=new ho(r,t.mode,null,t.lineSeparator,t.direction):t.mode&&(r.modeOption=t.mode),this.doc=r;var i,o=new cl.inputStyles[t.inputStyle](this),o=this.display=new Qr(e,r,o,t);for(i in il(o.wrapper.CodeMirror=this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Dr(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new I,keySeq:null,specialChars:null},t.autofocus&&!h&&o.input.focus(),w&&v<11&&setTimeout(function(){return n.display.input.reset(!0)},20),function(r){var i=r.display;me(i.scroller,"mousedown",Er(r,Jo)),me(i.scroller,"dblclick",w&&v<11?Er(r,function(e){var t;we(r,e)||(!(t=Jn(r,e))||nl(r,e)||pn(r.display,e)||(Le(e),t=r.findWordAt(t),Ai(r.doc,t.anchor,t.head)))}):function(e){return we(r,e)||Le(e)});me(i.scroller,"contextmenu",function(e){return rl(r,e)}),me(i.input.getField(),"contextmenu",function(e){i.scroller.contains(e.target)||rl(r,e)});var n,o={end:0};function l(){i.activeTouch&&(n=setTimeout(function(){return i.activeTouch=null},1e3),(o=i.activeTouch).end=+new Date)}function s(e,t){if(null==t.left)return 1;var n=t.left-e.left,e=t.top-e.top;return 400<n*n+e*e}me(i.scroller,"touchstart",function(e){var t;we(r,e)||function(e){if(1==e.touches.length){e=e.touches[0];return e.radiusX<=1&&e.radiusY<=1}}(e)||nl(r,e)||(i.input.ensurePolled(),clearTimeout(n),t=+new Date,i.activeTouch={start:t,moved:!1,prev:t-o.end<=300?o:null},1==e.touches.length&&(i.activeTouch.left=e.touches[0].pageX,i.activeTouch.top=e.touches[0].pageY))}),me(i.scroller,"touchmove",function(){i.activeTouch&&(i.activeTouch.moved=!0)}),me(i.scroller,"touchend",function(e){var t,n=i.activeTouch;n&&!pn(i,e)&&null!=n.left&&!n.moved&&new Date-n.start<300&&(t=r.coordsChar(i.activeTouch,"page"),t=!n.prev||s(n,n.prev)?new oi(t,t):!n.prev.prev||s(n,n.prev.prev)?r.findWordAt(t):new oi(tt(t.line,0),at(r.doc,tt(t.line+1,0))),r.setSelection(t.anchor,t.head),r.focus(),Le(e)),l()}),me(i.scroller,"touchcancel",l),me(i.scroller,"scroll",function(){i.scroller.clientHeight&&(Lr(r,i.scroller.scrollTop),Tr(r,i.scroller.scrollLeft,!0),be(r,"scroll",r))}),me(i.scroller,"mousewheel",function(e){return ri(r,e)}),me(i.scroller,"DOMMouseScroll",function(e){return ri(r,e)}),me(i.wrapper,"scroll",function(){return i.wrapper.scrollTop=i.wrapper.scrollLeft=0}),i.dragFunctions={enter:function(e){we(r,e)||Me(e)},over:function(e){var t,n;we(r,e)||((n=Jn(t=r,n=e))&&(ar(t,n,n=document.createDocumentFragment()),t.display.dragCursor||(t.display.dragCursor=M("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),t.display.lineSpace.insertBefore(t.display.dragCursor,t.display.cursorDiv)),k(t.display.dragCursor,n)),Me(e))},start:function(e){var t,n;t=r,n=e,w&&(!t.state.draggingText||+new Date-po<100)?Me(n):we(t,n)||pn(t.display,n)||(n.dataTransfer.setData("Text",t.getSelection()),n.dataTransfer.effectAllowed="copyMove",n.dataTransfer.setDragImage&&!c&&((e=M("img",null,null,"position: fixed; left: 0; top: 0;")).src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",p&&(e.width=e.height=1,t.display.wrapper.appendChild(e),e._top=e.offsetTop),n.dataTransfer.setDragImage(e,0,0),p&&e.parentNode.removeChild(e)))},drop:Er(r,go),leave:function(e){we(r,e)||mo(r)}};var e=i.input.getField();me(e,"keyup",function(e){return _o.call(r,e)}),me(e,"keydown",Er(r,Yo)),me(e,"keypress",Er(r,$o)),me(e,"focus",function(e){return fr(r,e)}),me(e,"blur",function(e){return pr(r,e)})}(this),bo(),Hr(this),this.curOp.forceUpdate=!0,vi(this,r),t.autofocus&&!h||this.hasFocus()?setTimeout(function(){n.hasFocus()&&!n.state.focused&&fr(n)},20):pr(this),sl)sl.hasOwnProperty(i)&&sl[i](this,t[i],ol);_r(this),t.finishInit&&t.finishInit(this);for(var l=0;l<hl.length;++l)hl[l](this);Fr(this),f&&t.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}cl.defaults=ll,cl.optionHandlers=sl;var hl=[];function dl(e,t,n,r){var i,o=e.doc;"smart"==(n=null==n?"add":n)&&(o.mode.indent?i=pt(e,t).state:n="prev");var l=e.options.tabSize,s=Ye(o,t),a=E(s.text,null,l);s.stateAfter&&(s.stateAfter=null);var u=s.text.match(/^\s*/)[0];if(r||/\S/.test(s.text)){if("smart"==n&&((c=o.mode.indent(i,s.text.slice(u.length),s.text))==B||150<c)){if(!r)return;n="prev"}}else c=0,n="not";"prev"==n?c=t>o.first?E(Ye(o,t-1).text,null,l):0:"add"==n?c=a+e.options.indentUnit:"subtract"==n?c=a-e.options.indentUnit:"number"==typeof n&&(c=a+n);var c=Math.max(0,c),h="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(c/l);f;--f)d+=l,h+="\t";if(d<c&&(h+=X(c-d)),h!=u)return qi(o,h,tt(t,0),tt(t,u.length),"+input"),!(s.stateAfter=null);for(var p=0;p<o.sel.ranges.length;p++){var g=o.sel.ranges[p];if(g.head.line==t&&g.head.ch<u.length){g=tt(t,u.length);Wi(o,p,new oi(g,g));break}}}cl.defineInitHook=function(e){return hl.push(e)};var fl=null;function pl(e){fl=e}function gl(e,t,n,r,i){var o=e.doc;e.display.shift=!1,r=r||o.sel;var l=+new Date-200,s="paste"==i||e.state.pasteIncoming>l,a=He(t),u=null;if(s&&1<r.ranges.length)if(fl&&fl.text.join("\n")==t){if(r.ranges.length%fl.text.length==0)for(var u=[],c=0;c<fl.text.length;c++)u.push(o.splitLines(fl.text[c]))}else a.length==r.ranges.length&&e.options.pasteLinesPerSelection&&(u=_(a,function(e){return[e]}));for(var h=e.curOp.updateInput,d=r.ranges.length-1;0<=d;d--){var f=r.ranges[d],p=f.from(),g=f.to();f.empty()&&(n&&0<n?p=tt(p.line,p.ch-n):e.state.overwrite&&!s?g=tt(g.line,Math.min(Ye(o,g.line).text.length,g.ch+Y(a).length)):s&&fl&&fl.lineWise&&fl.text.join("\n")==a.join("\n")&&(p=g=tt(p.line,0)));g={from:p,to:g,text:u?u[d%u.length]:a,origin:i||(s?"paste":e.state.cutIncoming>l?"cut":"+input")};ji(e.doc,g),rn(e,"inputRead",e,g)}t&&!s&&vl(e,t),wr(e),e.curOp.updateInput<2&&(e.curOp.updateInput=h),e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=-1}function ml(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");return n&&(e.preventDefault(),t.isReadOnly()||t.options.disableInput||Pr(t,function(){return gl(t,n,0,null,"paste")}),1)}function vl(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,r=n.ranges.length-1;0<=r;r--){var i=n.ranges[r];if(!(100<i.head.ch||r&&n.ranges[r-1].head.line==i.head.line)){var o=e.getModeAt(i.head),l=!1;if(o.electricChars){for(var s=0;s<o.electricChars.length;s++)if(-1<t.indexOf(o.electricChars.charAt(s))){l=dl(e,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(Ye(e.doc,i.head.line).text.slice(0,i.head.ch))&&(l=dl(e,i.head.line,"smart"));l&&rn(e,"electricInput",e,i.head.line)}}}function yl(e){for(var t=[],n=[],r=0;r<e.doc.sel.ranges.length;r++){var i=e.doc.sel.ranges[r].head.line,i={anchor:tt(i,0),head:tt(i+1,0)};n.push(i),t.push(e.getRange(i.anchor,i.head))}return{text:t,ranges:n}}function bl(e,t,n,r){e.setAttribute("autocorrect",n?"":"off"),e.setAttribute("autocapitalize",r?"":"off"),e.setAttribute("spellcheck",!!t)}function wl(){var e=M("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),t=M("div",[e],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");return f?e.style.width="1000px":e.setAttribute("wrap","off"),s&&(e.style.border="1px solid black"),bl(e),t}function xl(i,o,l,s,a){var e=o,t=l,u=Ye(i,o.line),c=a&&"rtl"==i.direction?-l:l;function n(e){var t,n,r;if(null==(n="codepoint"==s?(t=u.text.charCodeAt(o.ch+(0<l?0:-1)),isNaN(t)?null:(n=0<l?55296<=t&&t<56320:56320<=t&&t<57343,new tt(o.line,Math.max(0,Math.min(u.text.length,o.ch+l*(n?2:1))),-l))):a?Io(i.cm,u,o,l):Po(u,o,l))){if(e||(r=o.line+c)<i.first||r>=i.first+i.size||(o=new tt(r,o.ch,o.sticky),!(u=Ye(i,r))))return;o=Eo(a,i.cm,u,o.line,c)}else o=n;return 1}if("char"==s||"codepoint"==s)n();else if("column"==s)n(!0);else if("word"==s||"group"==s)for(var r=null,h="group"==s,d=i.cm&&i.cm.getHelper(o,"wordChars"),f=!0;!(l<0)||n(!f);f=!1){var p=u.text.charAt(o.ch)||"\n",p=J(p,d)?"w":h&&"\n"==p?"n":!h||/\s/.test(p)?null:"p";if(!h||f||p||(p="s"),r&&r!=p){l<0&&(l=1,n(),o.sticky="after");break}if(p&&(r=p),0<l&&!n(!f))break}t=Gi(i,o,e,t,!0);return rt(e,t)&&(t.hitSide=!0),t}function Cl(e,t,n,r){var i,o,l,s=e.doc,a=t.left;for("page"==r?(i=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),i=Math.max(i-.5*Yn(e.display),3),o=(0<n?t.bottom:t.top)+n*i):"line"==r&&(o=0<n?t.bottom+3:t.top-3);(l=Gn(e,a,o)).outside;){if(n<0?o<=0:o>=s.height){l.hitSide=!0;break}o+=5*n}return l}e=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new I,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Sl(e,t){var n=Sn(e,t.line);if(!n||n.hidden)return null;var r=Ye(e.doc,t.line),n=xn(n,r,t.line),r=pe(r,e.doc.direction),e="left";r&&(e=le(r,t.ch)%2?"right":"left");e=Nn(n.map,t.ch,e);return e.offset="right"==e.collapse?e.end:e.start,e}function Ll(e,t){return t&&(e.bad=!0),e}function kl(e,t,n){var r;if(t==e.display.lineDiv){if(!(r=e.display.lineDiv.childNodes[n]))return Ll(e.clipPos(tt(e.display.viewTo-1)),!0);t=null,n=0}else for(r=t;;r=r.parentNode){if(!r||r==e.display.lineDiv)return null;if(r.parentNode&&r.parentNode==e.display.lineDiv)break}for(var i=0;i<e.display.view.length;i++){var o=e.display.view[i];if(o.node==r)return function(u,e,t){var n=u.text.firstChild,r=!1;if(!e||!N(n,e))return Ll(tt(Ze(u.line),0),!0);if(e==n&&(r=!0,e=n.childNodes[t],t=0,!e)){var i=u.rest?Y(u.rest):u.line;return Ll(tt(Ze(i),i.text.length),r)}var i=3==e.nodeType?e:null,o=e;i||1!=e.childNodes.length||3!=e.firstChild.nodeType||(i=e.firstChild,t=t&&i.nodeValue.length);for(;o.parentNode!=n;)o=o.parentNode;var c=u.measure,h=c.maps;function l(e,t,n){for(var r=-1;r<(h?h.length:0);r++)for(var i=r<0?c.map:h[r],o=0;o<i.length;o+=3){var l=i[o+2];if(l==e||l==t){var s=Ze(r<0?u.line:u.rest[r]),a=i[o]+n;return tt(s,a=n<0||l!=e?i[o+(n?1:0)]:a)}}}var s=l(i,o,t);if(s)return Ll(s,r);for(var a=o.nextSibling,d=i?i.nodeValue.length-t:0;a;a=a.nextSibling){if(s=l(a,a.firstChild,0))return Ll(tt(s.line,s.ch-d),r);d+=a.textContent.length}for(var f=o.previousSibling,p=t;f;f=f.previousSibling){if(s=l(f,f.firstChild,-1))return Ll(tt(s.line,s.ch+p),r);p+=f.textContent.length}}(o,t,n)}}e.prototype.init=function(e){var t=this,o=this,l=o.cm,s=o.div=e.lineDiv;function a(e){for(var t=e.target;t;t=t.parentNode){if(t==s)return 1;if(/\bCodeMirror-(?:line)?widget\b/.test(t.className))break}}function n(e){if(a(e)&&!we(l,e)){if(l.somethingSelected())pl({lineWise:!1,text:l.getSelections()}),"cut"==e.type&&l.replaceSelection("",null,"cut");else{if(!l.options.lineWiseCopyCut)return;var t=yl(l);pl({lineWise:!0,text:t.text}),"cut"==e.type&&l.operation(function(){l.setSelections(t.ranges,0,G),l.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var n=fl.text.join("\n");if(e.clipboardData.setData("Text",n),e.clipboardData.getData("Text")==n)return void e.preventDefault()}var r=wl(),e=r.firstChild;l.display.lineSpace.insertBefore(r,l.display.lineSpace.firstChild),e.value=fl.text.join("\n");var i=O();H(e),setTimeout(function(){l.display.lineSpace.removeChild(r),i.focus(),i==s&&o.showPrimarySelection()},50)}}s.contentEditable=!0,bl(s,l.options.spellcheck,l.options.autocorrect,l.options.autocapitalize),me(s,"paste",function(e){!a(e)||we(l,e)||ml(e,l)||v<=11&&setTimeout(Er(l,function(){return t.updateFromDOM()}),20)}),me(s,"compositionstart",function(e){t.composing={data:e.data,done:!1}}),me(s,"compositionupdate",function(e){t.composing||(t.composing={data:e.data,done:!1})}),me(s,"compositionend",function(e){t.composing&&(e.data!=t.composing.data&&t.readFromDOMSoon(),t.composing.done=!0)}),me(s,"touchstart",function(){return o.forceCompositionEnd()}),me(s,"input",function(){t.composing||t.readFromDOMSoon()}),me(s,"copy",n),me(s,"cut",n)},e.prototype.screenReaderLabelChanged=function(e){e?this.div.setAttribute("aria-label",e):this.div.removeAttribute("aria-label")},e.prototype.prepareSelection=function(){var e=sr(this.cm,!1);return e.focus=O()==this.div,e},e.prototype.showSelection=function(e,t){e&&this.cm.display.view.length&&((e.focus||t)&&this.showPrimarySelection(),this.showMultipleSelections(e))},e.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()},e.prototype.showPrimarySelection=function(){var e=this.getSelection(),t=this.cm,n=t.doc.sel.primary(),r=n.from(),i=n.to();if(t.display.viewTo==t.display.viewFrom||r.line>=t.display.viewTo||i.line<t.display.viewFrom)e.removeAllRanges();else{var o=kl(t,e.anchorNode,e.anchorOffset),n=kl(t,e.focusNode,e.focusOffset);if(!o||o.bad||!n||n.bad||0!=nt(lt(o,n),r)||0!=nt(ot(o,n),i)){n=t.display.view,r=r.line>=t.display.viewFrom&&Sl(t,r)||{node:n[0].measure.map[2],offset:0},i=i.line<t.display.viewTo&&Sl(t,i);if(i||(i={node:(s=(s=n[n.length-1].measure).maps?s.maps[s.maps.length-1]:s.map)[s.length-1],offset:s[s.length-2]-s[s.length-3]}),r&&i){var l,s=e.rangeCount&&e.getRangeAt(0);try{l=W(r.node,r.offset,i.offset,i.node)}catch(e){}l&&(!d&&t.state.focused?(e.collapse(r.node,r.offset),l.collapsed||(e.removeAllRanges(),e.addRange(l))):(e.removeAllRanges(),e.addRange(l)),s&&null==e.anchorNode?e.addRange(s):d&&this.startGracePeriod()),this.rememberSelection()}else e.removeAllRanges()}}},e.prototype.startGracePeriod=function(){var e=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){e.gracePeriod=!1,e.selectionChanged()&&e.cm.operation(function(){return e.cm.curOp.selectionChanged=!0})},20)},e.prototype.showMultipleSelections=function(e){k(this.cm.display.cursorDiv,e.cursors),k(this.cm.display.selectionDiv,e.selection)},e.prototype.rememberSelection=function(){var e=this.getSelection();this.lastAnchorNode=e.anchorNode,this.lastAnchorOffset=e.anchorOffset,this.lastFocusNode=e.focusNode,this.lastFocusOffset=e.focusOffset},e.prototype.selectionInEditor=function(){var e=this.getSelection();if(!e.rangeCount)return!1;e=e.getRangeAt(0).commonAncestorContainer;return N(this.div,e)},e.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()&&O()==this.div||this.showSelection(this.prepareSelection(),!0),this.div.focus())},e.prototype.blur=function(){this.div.blur()},e.prototype.getField=function(){return this.div},e.prototype.supportsTouch=function(){return!0},e.prototype.receivedFocus=function(){var e=this,t=this;this.selectionInEditor()?setTimeout(function(){return e.pollSelection()},20):Pr(this.cm,function(){return t.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,function e(){t.cm.state.focused&&(t.pollSelection(),t.polling.set(t.cm.options.pollInterval,e))})},e.prototype.selectionChanged=function(){var e=this.getSelection();return e.anchorNode!=this.lastAnchorNode||e.anchorOffset!=this.lastAnchorOffset||e.focusNode!=this.lastFocusNode||e.focusOffset!=this.lastFocusOffset},e.prototype.pollSelection=function(){if(null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var e,t,n=this.getSelection(),r=this.cm;if(a&&o&&this.cm.display.gutterSpecs.length&&function(e){for(var t=e;t;t=t.parentNode)if(/CodeMirror-gutter-wrapper/.test(t.className))return!0;return!1}(n.anchorNode))return this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),void this.focus();this.composing||(this.rememberSelection(),e=kl(r,n.anchorNode,n.anchorOffset),t=kl(r,n.focusNode,n.focusOffset),e&&t&&Pr(r,function(){Pi(r.doc,si(e,t),G),(e.bad||t.bad)&&(r.curOp.selectionChanged=!0)}))}},e.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var e,t=this.cm,n=t.display,r=t.doc.sel.primary(),i=r.from(),r=r.to();if(0==i.ch&&i.line>t.firstLine()&&(i=tt(i.line-1,Ye(t.doc,i.line-1).length)),r.ch==Ye(t.doc,r.line).text.length&&r.line<t.lastLine()&&(r=tt(r.line+1,0)),i.line<n.viewFrom||r.line>n.viewTo-1)return!1;var o,l=i.line==n.viewFrom||0==(l=er(t,i.line))?(e=Ze(n.view[0].line),n.view[0].node):(e=Ze(n.view[l].line),n.view[l-1].node.nextSibling),r=er(t,r.line),r=r==n.view.length-1?(o=n.viewTo-1,n.lineDiv.lastChild):(o=Ze(n.view[r+1].line)-1,n.view[r+1].node.previousSibling);if(!l)return!1;for(var s=t.doc.splitLines(function(l,e,t,s,a){var n="",u=!1,c=l.doc.lineSeparator(),h=!1;function d(){u&&(n+=c,h&&(n+=c),u=h=!1)}function f(e){e&&(d(),n+=e)}for(;!function e(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(n)f(n);else if(n=t.getAttribute("cm-marker"))(n=l.findMarks(tt(s,0),tt(a+1,0),(o=+n,function(e){return e.id==o}))).length&&(r=n[0].find(0))&&f(_e(l.doc,r.from,r.to).join(c));else if("false"!=t.getAttribute("contenteditable")){var r=/^(pre|div|p|li|table|br)$/i.test(t.nodeName);if(/^br$/i.test(t.nodeName)||0!=t.textContent.length){r&&d();for(var i=0;i<t.childNodes.length;i++)e(t.childNodes[i]);/^(pre|p)$/i.test(t.nodeName)&&(h=!0),r&&(u=!0)}}}else 3==t.nodeType&&f(t.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "));var o}(e),e!=t;)e=e.nextSibling,h=!1;return n}(t,l,r,e,o)),a=_e(t.doc,tt(e,0),tt(o,Ye(t.doc,o).text.length));1<s.length&&1<a.length;)if(Y(s)==Y(a))s.pop(),a.pop(),o--;else{if(s[0]!=a[0])break;s.shift(),a.shift(),e++}for(var u=0,c=0,h=s[0],d=a[0],f=Math.min(h.length,d.length);u<f&&h.charCodeAt(u)==d.charCodeAt(u);)++u;for(var p=Y(s),g=Y(a),m=Math.min(p.length-(1==s.length?u:0),g.length-(1==a.length?u:0));c<m&&p.charCodeAt(p.length-c-1)==g.charCodeAt(g.length-c-1);)++c;if(1==s.length&&1==a.length&&e==i.line)for(;u&&u>i.ch&&p.charCodeAt(p.length-c-1)==g.charCodeAt(g.length-c-1);)u--,c++;s[s.length-1]=p.slice(0,p.length-c).replace(/^\u200b+/,""),s[0]=s[0].slice(u).replace(/\u200b+$/,"");l=tt(e,u),r=tt(o,a.length?Y(a).length-c:0);return 1<s.length||s[0]||nt(l,r)?(qi(t.doc,s,l,r,"+input"),!0):void 0},e.prototype.ensurePolled=function(){this.forceCompositionEnd()},e.prototype.reset=function(){this.forceCompositionEnd()},e.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},e.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()},80))},e.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||Pr(this.cm,function(){return tr(e.cm)})},e.prototype.setUneditable=function(e){e.contentEditable="false"},e.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly()||Er(this.cm,gl)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},e.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},e.prototype.onContextMenu=function(){},e.prototype.resetPosition=function(){},e.prototype.needsContentAttribute=!0;var Tl,Ml,Nl,Ol,Al,r=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new I,this.hasSelection=!1,this.composing=null};function Dl(e,t,r,n){Tl.defaults[e]=t,r&&(Ml[e]=n?function(e,t,n){n!=ol&&r(e,t,n)}:r)}r.prototype.init=function(n){var e=this,r=this,i=this.cm;this.createField(n);var o=this.textarea;function t(e){if(!we(i,e)){if(i.somethingSelected())pl({lineWise:!1,text:i.getSelections()});else{if(!i.options.lineWiseCopyCut)return;var t=yl(i);pl({lineWise:!0,text:t.text}),"cut"==e.type?i.setSelections(t.ranges,null,G):(r.prevInput="",o.value=t.text.join("\n"),H(o))}"cut"==e.type&&(i.state.cutIncoming=+new Date)}}n.wrapper.insertBefore(this.wrapper,n.wrapper.firstChild),s&&(o.style.width="0px"),me(o,"input",function(){w&&9<=v&&e.hasSelection&&(e.hasSelection=null),r.poll()}),me(o,"paste",function(e){we(i,e)||ml(e,i)||(i.state.pasteIncoming=+new Date,r.fastPoll())}),me(o,"cut",t),me(o,"copy",t),me(n.scroller,"paste",function(e){if(!pn(n,e)&&!we(i,e)){if(!o.dispatchEvent)return i.state.pasteIncoming=+new Date,void r.focus();var t=new Event("paste");t.clipboardData=e.clipboardData,o.dispatchEvent(t)}}),me(n.lineSpace,"selectstart",function(e){pn(n,e)||Le(e)}),me(o,"compositionstart",function(){var e=i.getCursor("from");r.composing&&r.composing.range.clear(),r.composing={start:e,range:i.markText(e,i.getCursor("to"),{className:"CodeMirror-composing"})}}),me(o,"compositionend",function(){r.composing&&(r.poll(),r.composing.range.clear(),r.composing=null)})},r.prototype.createField=function(e){this.wrapper=wl(),this.textarea=this.wrapper.firstChild},r.prototype.screenReaderLabelChanged=function(e){e?this.textarea.setAttribute("aria-label",e):this.textarea.removeAttribute("aria-label")},r.prototype.prepareSelection=function(){var e,t=this.cm,n=t.display,r=t.doc,i=sr(t);return t.options.moveInputWithCursor&&(e=Rn(t,r.sel.primary().head,"div"),t=n.wrapper.getBoundingClientRect(),r=n.lineDiv.getBoundingClientRect(),i.teTop=Math.max(0,Math.min(n.wrapper.clientHeight-10,e.top+r.top-t.top)),i.teLeft=Math.max(0,Math.min(n.wrapper.clientWidth-10,e.left+r.left-t.left))),i},r.prototype.showSelection=function(e){var t=this.cm.display;k(t.cursorDiv,e.cursors),k(t.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},r.prototype.reset=function(e){var t,n;this.contextMenuPending||this.composing||((t=this.cm).somethingSelected()?(this.prevInput="",n=t.getSelection(),this.textarea.value=n,t.state.focused&&H(this.textarea),w&&9<=v&&(this.hasSelection=n)):e||(this.prevInput=this.textarea.value="",w&&9<=v&&(this.hasSelection=null)))},r.prototype.getField=function(){return this.textarea},r.prototype.supportsTouch=function(){return!1},r.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!h||O()!=this.textarea))try{this.textarea.focus()}catch(e){}},r.prototype.blur=function(){this.textarea.blur()},r.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},r.prototype.receivedFocus=function(){this.slowPoll()},r.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){e.poll(),e.cm.state.focused&&e.slowPoll()})},r.prototype.fastPoll=function(){var t=!1,n=this;n.pollingFast=!0,n.polling.set(20,function e(){n.poll()||t?(n.pollingFast=!1,n.slowPoll()):(t=!0,n.polling.set(60,e))})},r.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,r=this.prevInput;if(this.contextMenuPending||!t.state.focused||Fe(n)&&!r&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var i=n.value;if(i==r&&!t.somethingSelected())return!1;if(w&&9<=v&&this.hasSelection===i||g&&/[\uf700-\uf7ff]/.test(i))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||r||(r="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var l=0,s=Math.min(r.length,i.length);l<s&&r.charCodeAt(l)==i.charCodeAt(l);)++l;return Pr(t,function(){gl(t,i.slice(l),r.length-l,null,e.composing?"*compose":null),1e3<i.length||-1<i.indexOf("\n")?n.value=e.prevInput="":e.prevInput=i,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},r.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},r.prototype.onKeyPress=function(){w&&9<=v&&(this.hasSelection=null),this.fastPoll()},r.prototype.onContextMenu=function(e){var n=this,r=n.cm,i=r.display,o=n.textarea;n.contextMenuPending&&n.contextMenuPending();var l,s,t,a,u=Jn(r,e),c=i.scroller.scrollTop;function h(){var e,t;null!=o.selectionStart&&(t="​"+((e=r.somethingSelected())?o.value:""),o.value="⇚",o.value=t,n.prevInput=e?"":"​",o.selectionStart=1,o.selectionEnd=t.length,i.selForContextMenu=r.doc.sel)}function d(){var e,t;n.contextMenuPending==d&&(n.contextMenuPending=!1,n.wrapper.style.cssText=s,o.style.cssText=l,w&&v<9&&i.scrollbars.setScrollTop(i.scroller.scrollTop=c),null!=o.selectionStart&&((!w||v<9)&&h(),e=0,t=function(){i.selForContextMenu==r.doc.sel&&0==o.selectionStart&&0<o.selectionEnd&&"​"==n.prevInput?Er(r,Vi)(r):e++<10?i.detectingSelectAll=setTimeout(t,500):(i.selForContextMenu=null,i.input.reset())},i.detectingSelectAll=setTimeout(t,200)))}u&&!p&&(r.options.resetSelectionOnContextMenu&&-1==r.doc.sel.contains(u)&&Er(r,Pi)(r.doc,si(u),G),l=o.style.cssText,s=n.wrapper.style.cssText,u=n.wrapper.offsetParent.getBoundingClientRect(),n.wrapper.style.cssText="position: static",o.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-u.top-5)+"px; left: "+(e.clientX-u.left-5)+"px;\n z-index: 1000; background: "+(w?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",f&&(t=window.scrollY),i.input.focus(),f&&window.scrollTo(null,t),i.input.reset(),r.somethingSelected()||(o.value=n.prevInput=" "),n.contextMenuPending=d,i.selForContextMenu=r.doc.sel,clearTimeout(i.detectingSelectAll),w&&9<=v&&h(),x?(Me(e),a=function(){ye(window,"mouseup",a),setTimeout(d,20)},me(window,"mouseup",a)):setTimeout(d,50))},r.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e,this.textarea.readOnly=!!e},r.prototype.setUneditable=function(){},r.prototype.needsContentAttribute=!1,Ml=(Tl=cl).optionHandlers,Tl.defineOption=Dl,Tl.Init=ol,Dl("value","",function(e,t){return e.setValue(t)},!0),Dl("mode",null,function(e,t){e.doc.modeOption=t,di(e)},!0),Dl("indentUnit",2,di,!0),Dl("indentWithTabs",!1),Dl("smartIndent",!0),Dl("tabSize",4,function(e){fi(e),Dn(e),tr(e)},!0),Dl("lineSeparator",null,function(e,r){if(e.doc.lineSep=r){var i=[],o=e.doc.first;e.doc.iter(function(e){for(var t=0;;){var n=e.text.indexOf(r,t);if(-1==n)break;t=n+r.length,i.push(tt(o,n))}o++});for(var t=i.length-1;0<=t;t--)qi(e.doc,r,i[t],tt(i[t].line,i[t].ch+r.length))}}),Dl("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=ol&&e.refresh()}),Dl("specialCharPlaceholder",$t,function(e){return e.refresh()},!0),Dl("electricChars",!0),Dl("inputStyle",h?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),Dl("spellcheck",!1,function(e,t){return e.getInputField().spellcheck=t},!0),Dl("autocorrect",!1,function(e,t){return e.getInputField().autocorrect=t},!0),Dl("autocapitalize",!1,function(e,t){return e.getInputField().autocapitalize=t},!0),Dl("rtlMoveVisually",!y),Dl("wholeLineUpdateBefore",!0),Dl("theme","default",function(e){il(e),Zr(e)},!0),Dl("keyMap","default",function(e,t,n){t=Wo(t),n=n!=ol&&Wo(n);n&&n.detach&&n.detach(e,t),t.attach&&t.attach(e,n||null)}),Dl("extraKeys",null),Dl("configureMouse",null),Dl("lineWrapping",!1,ul,!0),Dl("gutters",[],function(e,t){e.display.gutterSpecs=$r(t,e.options.lineNumbers),Zr(e)},!0),Dl("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?qn(e.display)+"px":"0",e.refresh()},!0),Dl("coverGutterNextToScrollbar",!1,function(e){return Nr(e)},!0),Dl("scrollbarStyle","native",function(e){Dr(e),Nr(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0),Dl("lineNumbers",!1,function(e,t){e.display.gutterSpecs=$r(e.options.gutters,t),Zr(e)},!0),Dl("firstLineNumber",1,Zr,!0),Dl("lineNumberFormatter",function(e){return e},Zr,!0),Dl("showCursorWhenSelecting",!1,lr,!0),Dl("resetSelectionOnContextMenu",!0),Dl("lineWiseCopyCut",!0),Dl("pasteLinesPerSelection",!0),Dl("selectionsMayTouch",!1),Dl("readOnly",!1,function(e,t){"nocursor"==t&&(pr(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)}),Dl("screenReaderLabel",null,function(e,t){e.display.input.screenReaderLabelChanged(t=""===t?null:t)}),Dl("disableInput",!1,function(e,t){t||e.display.input.reset()},!0),Dl("dragDrop",!0,al),Dl("allowDropFileTypes",null),Dl("cursorBlinkRate",530),Dl("cursorScrollMargin",0),Dl("cursorHeight",1,lr,!0),Dl("singleCursorHeightPerLine",!0,lr,!0),Dl("workTime",100),Dl("workDelay",100),Dl("flattenSpans",!0,fi,!0),Dl("addModeClass",!1,fi,!0),Dl("pollInterval",100),Dl("undoDepth",200,function(e,t){return e.doc.history.undoDepth=t}),Dl("historyEventDelay",1250),Dl("viewportMargin",10,function(e){return e.refresh()},!0),Dl("maxHighlightLength",1e4,fi,!0),Dl("moveInputWithCursor",!0,function(e,t){t||e.display.input.resetPosition()}),Dl("tabindex",null,function(e,t){return e.display.input.getField().tabIndex=t||""}),Dl("autofocus",null),Dl("direction","ltr",function(e,t){return e.doc.setDirection(t)},!0),Dl("phrases",null),Ol=(Nl=cl).optionHandlers,Al=Nl.helpers={},Nl.prototype={constructor:Nl,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,t){var n=this.options,r=n[e];n[e]==t&&"mode"!=e||(n[e]=t,Ol.hasOwnProperty(e)&&Er(this,Ol[e])(this,t,r),be(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Wo(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;n<t.length;++n)if(t[n]==e||t[n].name==e)return t.splice(n,1),!0},addOverlay:Ir(function(e,t){var n=e.token?e:Nl.getMode(this.options,e);if(n.startState)throw new Error("Overlays may not be stateful.");!function(e,t,n){for(var r=0,i=n(t);r<e.length&&n(e[r])<=i;)r++;e.splice(r,0,t)}(this.state.overlays,{mode:n,modeSpec:e,opaque:t&&t.opaque,priority:t&&t.priority||0},function(e){return e.priority}),this.state.modeGen++,tr(this)}),removeOverlay:Ir(function(e){for(var t=this.state.overlays,n=0;n<t.length;++n){var r=t[n].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(n,1),this.state.modeGen++,void tr(this)}}),indentLine:Ir(function(e,t,n){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),Je(this.doc,e)&&dl(this,e,t,n)}),indentSelection:Ir(function(e){for(var t=this.doc.sel.ranges,n=-1,r=0;r<t.length;r++){var i=t[r];if(i.empty())i.head.line>n&&(dl(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&wr(this));else{for(var o=i.from(),l=i.to(),i=Math.max(n,o.line),n=Math.min(this.lastLine(),l.line-(l.ch?0:1))+1,s=i;s<n;++s)dl(this,s,e);i=this.doc.sel.ranges;0==o.ch&&t.length==i.length&&0<i[r].from().ch&&Wi(this.doc,r,new oi(o,i[r].to()),G)}}}),getTokenAt:function(e,t){return bt(this,e,t)},getLineTokens:function(e,t){return bt(this,tt(e),t,!0)},getTokenTypeAt:function(e){e=at(this.doc,e);var t,n=ft(this,Ye(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var l=r+i>>1;if((l?n[2*l-1]:0)>=o)i=l;else{if(!(n[2*l+1]<o)){t=n[2*l+2];break}r=1+l}}e=t?t.indexOf("overlay "):-1;return e<0?t:0==e?null:t.slice(0,e-1)},getModeAt:function(e){var t=this.doc.mode;return t.innerMode?Nl.innerMode(t,this.getTokenAt(e).state).mode:t},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var n=[];if(!Al.hasOwnProperty(t))return n;var r=Al[t],i=this.getModeAt(e);if("string"==typeof i[t])r[i[t]]&&n.push(r[i[t]]);else if(i[t])for(var o=0;o<i[t].length;o++){var l=r[i[t][o]];l&&n.push(l)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var s=0;s<r._global.length;s++){var a=r._global[s];a.pred(i,this)&&-1==R(n,a.val)&&n.push(a.val)}return n},getStateAfter:function(e,t){var n=this.doc;return pt(this,(e=st(n,null==e?n.first+n.size-1:e))+1,t).state},cursorCoords:function(e,t){var n=this.doc.sel.primary(),n=null==e?n.head:"object"==typeof e?at(this.doc,e):e?n.from():n.to();return Rn(this,n,t||"page")},charCoords:function(e,t){return In(this,at(this.doc,e),t||"page")},coordsChar:function(e,t){return Gn(this,(e=En(this,e,t||"page")).left,e.top)},lineAtHeight:function(e,t){return e=En(this,{top:e,left:0},t||"page").top,Qe(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t,n){var r,i=!1,e="number"==typeof e?(r=this.doc.first+this.doc.size-1,e<this.doc.first?e=this.doc.first:r<e&&(e=r,i=!0),Ye(this.doc,e)):e;return Pn(this,e,{top:0,left:0},t||"page",n||i).top+(i?this.doc.height-Gt(e):0)},defaultTextHeight:function(){return Yn(this.display)},defaultCharWidth:function(){return _n(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o,l,s=this.display,a=(e=Rn(this,at(this.doc,e))).bottom,u=e.left;t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),s.sizer.appendChild(t),"over"==r?a=e.top:"above"!=r&&"near"!=r||(o=Math.max(s.wrapper.clientHeight,this.doc.height),l=Math.max(s.sizer.clientWidth,s.lineSpace.clientWidth),("above"==r||e.bottom+t.offsetHeight>o)&&e.top>t.offsetHeight?a=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=o&&(a=e.bottom),u+t.offsetWidth>l&&(u=l-t.offsetWidth)),t.style.top=a+"px",t.style.left=t.style.right="","right"==i?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&(n=this,t={left:u,top:a,right:u+t.offsetWidth,bottom:a+t.offsetHeight},null!=(t=yr(n,t)).scrollTop&&Lr(n,t.scrollTop),null!=t.scrollLeft&&Tr(n,t.scrollLeft))},triggerOnKeyDown:Ir(Yo),triggerOnKeyPress:Ir($o),triggerOnKeyUp:_o,triggerOnMouseDown:Ir(Jo),execCommand:function(e){if(Ro.hasOwnProperty(e))return Ro[e].call(null,this)},triggerElectric:Ir(function(e){vl(this,e)}),findPosH:function(e,t,n,r){var i=1;t<0&&(i=-1,t=-t);for(var o=at(this.doc,e),l=0;l<t&&!(o=xl(this.doc,o,i,n,r)).hitSide;++l);return o},moveH:Ir(function(t,n){var r=this;this.extendSelectionsBy(function(e){return r.display.shift||r.doc.extend||e.empty()?xl(r.doc,e.head,t,n,r.options.rtlMoveVisually):t<0?e.from():e.to()},V)}),deleteH:Ir(function(n,r){var e=this.doc.sel,i=this.doc;e.somethingSelected()?i.replaceSelection("",null,"+delete"):Ho(this,function(e){var t=xl(i,e.head,n,r,!1);return n<0?{from:t,to:e.head}:{from:e.head,to:t}})}),findPosV:function(e,t,n,r){var i=1,o=r;t<0&&(i=-1,t=-t);for(var l=at(this.doc,e),s=0;s<t;++s){var a=Rn(this,l,"div");if(null==o?o=a.left:a.left=o,(l=Cl(this,a,i,n)).hitSide)break}return l},moveV:Ir(function(r,i){var o=this,l=this.doc,s=[],a=!this.display.shift&&!l.extend&&l.sel.somethingSelected();if(l.extendSelectionsBy(function(e){if(a)return r<0?e.from():e.to();var t=Rn(o,e.head,"div");null!=e.goalColumn&&(t.left=e.goalColumn),s.push(t.left);var n=Cl(o,t,r,i);return"page"==i&&e==l.sel.primary()&&br(o,In(o,n,"div").top-t.top),n},V),s.length)for(var e=0;e<l.sel.ranges.length;e++)l.sel.ranges[e].goalColumn=s[e]}),findWordAt:function(e){var t=Ye(this.doc,e.line).text,n=e.ch,r=e.ch;if(t){var i=this.getHelper(e,"wordChars");"before"!=e.sticky&&r!=t.length||!n?++r:--n;for(var o=t.charAt(n),l=J(o,i)?function(e){return J(e,i)}:/\s/.test(o)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!J(e)};0<n&&l(t.charAt(n-1));)--n;for(;r<t.length&&l(t.charAt(r));)++r}return new oi(tt(e.line,n),tt(e.line,r))},toggleOverwrite:function(e){null!=e&&e==this.state.overwrite||(((this.state.overwrite=!this.state.overwrite)?A:S)(this.display.cursorDiv,"CodeMirror-overwrite"),be(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return this.display.input.getField()==O()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:Ir(function(e,t){xr(this,e,t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-yn(this)-this.display.barHeight,width:e.scrollWidth-yn(this)-this.display.barWidth,clientHeight:wn(this),clientWidth:bn(this)}},scrollIntoView:Ir(function(e,t){var n;null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:tt(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line?(n=e,Cr(t=this),t.curOp.scrollToPos=n):Sr(this,e.from,e.to,e.margin)}),setSize:Ir(function(e,t){function n(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(this.display.wrapper.style.width=n(e)),null!=t&&(this.display.wrapper.style.height=n(t)),this.options.lineWrapping&&An(this);var i=this.display.viewFrom;this.doc.iter(i,this.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){nr(r,i,"widget");break}++i}),this.curOp.forceUpdate=!0,be(this,"refresh",this)}),operation:function(e){return Pr(this,e)},startOperation:function(){return Hr(this)},endOperation:function(){return Fr(this)},refresh:Ir(function(){var e=this.display.cachedTextHeight;tr(this),this.curOp.forceUpdate=!0,Dn(this),xr(this,this.doc.scrollLeft,this.doc.scrollTop),jr(this.display),(null==e||.5<Math.abs(e-Yn(this.display))||this.options.lineWrapping)&&Qn(this),be(this,"refresh",this)}),swapDoc:Ir(function(e){var t=this.doc;return t.cm=null,this.state.selectingText&&this.state.selectingText(),vi(this,e),Dn(this),this.display.input.reset(),xr(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,rn(this,"swapDoc",this,t),t}),phrase:function(e){var t=this.options.phrases;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},Se(Nl),Nl.registerHelper=function(e,t,n){Al.hasOwnProperty(e)||(Al[e]=Nl[e]={_global:[]}),Al[e][t]=n},Nl.registerGlobalHelper=function(e,t,n,r){Nl.registerHelper(e,t,r),Al[e]._global.push({pred:n,val:r})};var Wl,Hl,Fl="iter insert remove copy getEditor constructor".split(" ");for(Wl in ho.prototype)ho.prototype.hasOwnProperty(Wl)&&R(Fl,Wl)<0&&(cl.prototype[Wl]=function(e){return function(){return e.apply(this.doc,arguments)}}(ho.prototype[Wl]));return Se(ho),cl.inputStyles={textarea:r,contenteditable:e},cl.defineMode=function(e){cl.defaults.mode||"null"==e||(cl.defaults.mode=e),function(e,t){2<arguments.length&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Ie[e]=t}.apply(this,arguments)},cl.defineMIME=function(e,t){Re[e]=t},cl.defineMode("null",function(){return{token:function(e){return e.skipToEnd()}}}),cl.defineMIME("text/plain","null"),cl.defineExtension=function(e,t){cl.prototype[e]=t},cl.defineDocExtension=function(e,t){ho.prototype[e]=t},cl.fromTextArea=function(t,n){var e;function r(){t.value=s.getValue()}if((n=n?P(n):{}).value=t.value,!n.tabindex&&t.tabIndex&&(n.tabindex=t.tabIndex),!n.placeholder&&t.placeholder&&(n.placeholder=t.placeholder),null==n.autofocus&&(e=O(),n.autofocus=e==t||null!=t.getAttribute("autofocus")&&e==document.body),t.form&&(me(t.form,"submit",r),!n.leaveSubmitMethodAlone)){var i=t.form,o=i.submit;try{var l=i.submit=function(){r(),i.submit=o,i.submit(),i.submit=l}}catch(e){}}n.finishInit=function(e){e.save=r,e.getTextArea=function(){return t},e.toTextArea=function(){e.toTextArea=isNaN,r(),t.parentNode.removeChild(e.getWrapperElement()),t.style.display="",t.form&&(ye(t.form,"submit",r),n.leaveSubmitMethodAlone||"function"!=typeof t.form.submit||(t.form.submit=o))}},t.style.display="none";var s=cl(function(e){return t.parentNode.insertBefore(e,t.nextSibling)},n);return s},(Hl=cl).off=ye,Hl.on=me,Hl.wheelEventPixels=ni,Hl.Doc=ho,Hl.splitLines=He,Hl.countColumn=E,Hl.findColumn=K,Hl.isWordChar=Q,Hl.Pass=B,Hl.signal=be,Hl.Line=Kt,Hl.changeEnd=ai,Hl.scrollbarModel=Ar,Hl.Pos=tt,Hl.cmpPos=nt,Hl.modes=Ie,Hl.mimeModes=Re,Hl.resolveMode=ze,Hl.getMode=Be,Hl.modeExtensions=Ge,Hl.extendMode=Ue,Hl.copyState=Ve,Hl.startState=je,Hl.innerMode=Ke,Hl.commands=Ro,Hl.keyMap=ko,Hl.keyName=Do,Hl.isModifierKey=Oo,Hl.lookupKey=No,Hl.normalizeKeyMap=Mo,Hl.StringStream=Xe,Hl.SharedTextMarker=ao,Hl.TextMarker=oo,Hl.LineWidget=ro,Hl.e_preventDefault=Le,Hl.e_stopPropagation=ke,Hl.e_stop=Me,Hl.addClass=A,Hl.contains=N,Hl.rmClass=S,Hl.keyNames=xo,cl.version="5.63.1",cl});
assets/js/hyperscript@0.9.6.js ADDED
@@ -0,0 +1,7351 @@
1
+
2
+ 'use strict';
3
+
4
+ /**
5
+ * @typedef {Object} Hyperscript
6
+ */
7
+
8
+ (function (self, factory) {
9
+ const _hyperscript = factory(self)
10
+
11
+ if (typeof exports === 'object' && typeof exports['nodeName'] !== 'string') {
12
+ module.exports = _hyperscript
13
+ } else {
14
+ self['_hyperscript'] = _hyperscript
15
+ if ('document' in self) self['_hyperscript'].browserInit()
16
+ }
17
+ })(typeof self !== 'undefined' ? self : this, (globalScope) => {
18
+
19
+ /**
20
+ * @type {Object}
21
+ * @property {DynamicConverter[]} dynamicResolvers
22
+ *
23
+ * @callback DynamicConverter
24
+ * @param {String} str
25
+ * @param {*} value
26
+ * @returns {*}
27
+ */
28
+ const conversions = {
29
+ dynamicResolvers: [
30
+ function(str, value){
31
+ if (str === "Fixed") {
32
+ return Number(value).toFixed();
33
+ } else if (str.indexOf("Fixed:") === 0) {
34
+ let num = str.split(":")[1];
35
+ return Number(value).toFixed(parseInt(num));
36
+ }
37
+ }
38
+ ],
39
+ String: function (val) {
40
+ if (val.toString) {
41
+ return val.toString();
42
+ } else {
43
+ return "" + val;
44
+ }
45
+ },
46
+ Int: function (val) {
47
+ return parseInt(val);
48
+ },
49
+ Float: function (val) {
50
+ return parseFloat(val);
51
+ },
52
+ Number: function (val) {
53
+ return Number(val);
54
+ },
55
+ Date: function (val) {
56
+ return new Date(val);
57
+ },
58
+ Array: function (val) {
59
+ return Array.from(val);
60
+ },
61
+ JSON: function (val) {
62
+ return JSON.stringify(val);
63
+ },
64
+ Object: function (val) {
65
+ if (val instanceof String) {
66
+ val = val.toString();
67
+ }
68
+ if (typeof val === "string") {
69
+ return JSON.parse(val);
70
+ } else {
71
+ return Object.assign({}, val);
72
+ }
73
+ },
74
+ }
75
+
76
+ const config = {
77
+ attributes: "_, script, data-script",
78
+ defaultTransition: "all 500ms ease-in",
79
+ disableSelector: "[disable-scripting], [data-disable-scripting]",
80
+ conversions,
81
+ }
82
+
83
+ class Lexer {
84
+ static OP_TABLE = {
85
+ "+": "PLUS",
86
+ "-": "MINUS",
87
+ "*": "MULTIPLY",
88
+ "/": "DIVIDE",
89
+ ".": "PERIOD",
90
+ "..": "ELLIPSIS",
91
+ "\\": "BACKSLASH",
92
+ ":": "COLON",
93
+ "%": "PERCENT",
94
+ "|": "PIPE",
95
+ "!": "EXCLAMATION",
96
+ "?": "QUESTION",
97
+ "#": "POUND",
98
+ "&": "AMPERSAND",
99
+ $: "DOLLAR",
100
+ ";": "SEMI",
101
+ ",": "COMMA",
102
+ "(": "L_PAREN",
103
+ ")": "R_PAREN",
104
+ "<": "L_ANG",
105
+ ">": "R_ANG",
106
+ "<=": "LTE_ANG",
107
+ ">=": "GTE_ANG",
108
+ "==": "EQ",
109
+ "===": "EQQ",
110
+ "!=": "NEQ",
111
+ "!==": "NEQQ",
112
+ "{": "L_BRACE",
113
+ "}": "R_BRACE",
114
+ "[": "L_BRACKET",
115
+ "]": "R_BRACKET",
116
+ "=": "EQUALS",
117
+ };
118
+
119
+ /**
120
+ * isValidCSSClassChar returns `true` if the provided character is valid in a CSS class.
121
+ * @param {string} c
122
+ * @returns boolean
123
+ */
124
+ static isValidCSSClassChar(c) {
125
+ return Lexer.isAlpha(c) || Lexer.isNumeric(c) || c === "-" || c === "_" || c === ":";
126
+ }
127
+
128
+ /**
129
+ * isValidCSSIDChar returns `true` if the provided character is valid in a CSS ID
130
+ * @param {string} c
131
+ * @returns boolean
132
+ */
133
+ static isValidCSSIDChar(c) {
134
+ return Lexer.isAlpha(c) || Lexer.isNumeric(c) || c === "-" || c === "_" || c === ":";
135
+ }
136
+
137
+ /**
138
+ * isWhitespace returns `true` if the provided character is whitespace.
139
+ * @param {string} c
140
+ * @returns boolean
141
+ */
142
+ static isWhitespace(c) {
143
+ return c === " " || c === "\t" || Lexer.isNewline(c);
144
+ }
145
+
146
+ /**
147
+ * positionString returns a string representation of a Token's line and column details.
148
+ * @param {Token} token
149
+ * @returns string
150
+ */
151
+ static positionString(token) {
152
+ return "[Line: " + token.line + ", Column: " + token.column + "]";
153
+ }
154
+
155
+ /**
156
+ * isNewline returns `true` if the provided character is a carrage return or newline
157
+ * @param {string} c
158
+ * @returns boolean
159
+ */
160
+ static isNewline(c) {
161
+ return c === "\r" || c === "\n";
162
+ }
163
+
164
+ /**
165
+ * isNumeric returns `true` if the provided character is a number (0-9)
166
+ * @param {string} c
167
+ * @returns boolean
168
+ */
169
+ static isNumeric(c) {
170
+ return c >= "0" && c <= "9";
171
+ }
172
+
173
+ /**
174
+ * isAlpha returns `true` if the provided character is a letter in the alphabet
175
+ * @param {string} c
176
+ * @returns boolean
177
+ */
178
+ static isAlpha(c) {
179
+ return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z");
180
+ }
181
+
182
+ /**
183
+ * @param {string} c
184
+ * @param {boolean} [dollarIsOp]
185
+ * @returns boolean
186
+ */
187
+ static isIdentifierChar(c, dollarIsOp) {
188
+ return c === "_" || c === "$";
189
+ }
190
+
191
+ /**
192
+ * @param {string} c
193
+ * @returns boolean
194
+ */
195
+ static isReservedChar(c) {
196
+ return c === "`" || c === "^";
197
+ }
198
+
199
+ /**
200
+ * @param {Token[]} tokens
201
+ * @returns {boolean}
202
+ */
203
+ static isValidSingleQuoteStringStart(tokens) {
204
+ if (tokens.length > 0) {
205
+ var previousToken = tokens[tokens.length - 1];
206
+ if (
207
+ previousToken.type === "IDENTIFIER" ||
208
+ previousToken.type === "CLASS_REF" ||
209
+ previousToken.type === "ID_REF"
210
+ ) {
211
+ return false;
212
+ }
213
+ if (previousToken.op && (previousToken.value === ">" || previousToken.value === ")")) {
214
+ return false;
215
+ }
216
+ }
217
+ return true;
218
+ }
219
+
220
+ /**
221
+ * @param {string} string
222
+ * @param {boolean} [template]
223
+ * @returns {Tokens}
224
+ */
225
+ static tokenize(string, template) {
226
+ var tokens = /** @type {Token[]}*/ [];
227
+ var source = string;
228
+ var position = 0;
229
+ var column = 0;
230
+ var line = 1;
231
+ var lastToken = "<START>";
232
+ var templateBraceCount = 0;
233
+
234
+ function inTemplate() {
235
+ return template && templateBraceCount === 0;
236
+ }
237
+
238
+ while (position < source.length) {
239
+ if (currentChar() === "-" && nextChar() === "-" && (Lexer.isWhitespace(charAfterThat()) || charAfterThat() === "")) {
240
+ consumeComment();
241
+ } else {
242
+ if (Lexer.isWhitespace(currentChar())) {
243
+ tokens.push(consumeWhitespace());
244
+ } else if (
245
+ !possiblePrecedingSymbol() &&
246
+ currentChar() === "." &&
247
+ (Lexer.isAlpha(nextChar()) || nextChar() === "{")
248
+ ) {
249
+ tokens.push(consumeClassReference());
250
+ } else if (
251
+ !possiblePrecedingSymbol() &&
252
+ currentChar() === "#" &&
253
+ (Lexer.isAlpha(nextChar()) || nextChar() === "{")
254
+ ) {
255
+ tokens.push(consumeIdReference());
256
+ } else if (currentChar() === "[" && nextChar() === "@") {
257
+ tokens.push(consumeAttributeReference());
258
+ } else if (currentChar() === "@") {
259
+ tokens.push(consumeShortAttributeReference());
260
+ } else if (currentChar() === "*" && Lexer.isAlpha(nextChar())) {
261
+ tokens.push(consumeStyleReference());
262
+ } else if (Lexer.isAlpha(currentChar()) || (!inTemplate() && Lexer.isIdentifierChar(currentChar()))) {
263
+ tokens.push(consumeIdentifier());
264
+ } else if (Lexer.isNumeric(currentChar())) {
265
+ tokens.push(consumeNumber());
266
+ } else if (!inTemplate() && (currentChar() === '"' || currentChar() === "`")) {
267
+ tokens.push(consumeString());
268
+ } else if (!inTemplate() && currentChar() === "'") {
269
+ if (Lexer.isValidSingleQuoteStringStart(tokens)) {
270
+ tokens.push(consumeString());
271
+ } else {
272
+ tokens.push(consumeOp());
273
+ }
274
+ } else if (Lexer.OP_TABLE[currentChar()]) {
275
+ if (lastToken === "$" && currentChar() === "{") {
276
+ templateBraceCount++;
277
+ }
278
+ if (currentChar() === "}") {
279
+ templateBraceCount--;
280
+ }
281
+ tokens.push(consumeOp());
282
+ } else if (inTemplate() || Lexer.isReservedChar(currentChar())) {
283
+ tokens.push(makeToken("RESERVED", consumeChar()));
284
+ } else {
285
+ if (position < source.length) {
286
+ throw Error("Unknown token: " + currentChar() + " ");
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ return new Tokens(tokens, [], source);
293
+
294
+ /**
295
+ * @param {string} [type]
296
+ * @param {string} [value]
297
+ * @returns {Token}
298
+ */
299
+ function makeOpToken(type, value) {
300
+ var token = makeToken(type, value);
301
+ token.op = true;
302
+ return token;
303
+ }
304
+
305
+ /**
306
+ * @param {string} [type]
307
+ * @param {string} [value]
308
+ * @returns {Token}
309
+ */
310
+ function makeToken(type, value) {
311
+ return {
312
+ type: type,
313
+ value: value,
314
+ start: position,
315
+ end: position + 1,
316
+ column: column,
317
+ line: line,
318
+ };
319
+ }
320
+
321
+ function consumeComment() {
322
+ while (currentChar() && !Lexer.isNewline(currentChar())) {
323
+ consumeChar();
324
+ }
325
+ consumeChar();
326
+ }
327
+
328
+ /**
329
+ * @returns Token
330
+ */
331
+ function consumeClassReference() {
332
+ var classRef = makeToken("CLASS_REF");
333
+ var value = consumeChar();
334
+ if (currentChar() === "{") {
335
+ classRef.template = true;
336
+ value += consumeChar();
337
+ while (currentChar() && currentChar() !== "}") {
338
+ value += consumeChar();
339
+ }
340
+ if (currentChar() !== "}") {
341
+ throw Error("Unterminated class reference");
342
+ } else {
343
+ value += consumeChar(); // consume final curly
344
+ }
345
+ } else {
346
+ while (Lexer.isValidCSSClassChar(currentChar())) {
347
+ value += consumeChar();
348
+ }
349
+ }
350
+ classRef.value = value;
351
+ classRef.end = position;
352
+ return classRef;
353
+ }
354
+
355
+ /**
356
+ * @returns Token
357
+ */
358
+ function consumeAttributeReference() {
359
+ var attributeRef = makeToken("ATTRIBUTE_REF");
360
+ var value = consumeChar();
361
+ while (position < source.length && currentChar() !== "]") {
362
+ value += consumeChar();
363
+ }
364
+ if (currentChar() === "]") {
365
+ value += consumeChar();
366
+ }
367
+ attributeRef.value = value;
368
+ attributeRef.end = position;
369
+ return attributeRef;
370
+ }
371
+
372
+ function consumeShortAttributeReference() {
373
+ var attributeRef = makeToken("ATTRIBUTE_REF");
374
+ var value = consumeChar();
375
+ while (Lexer.isValidCSSIDChar(currentChar())) {
376
+ value += consumeChar();
377
+ }
378
+ attributeRef.value = value;
379
+ attributeRef.end = position;
380
+ return attributeRef;
381
+ }
382
+
383
+ function consumeStyleReference() {
384
+ var styleRef = makeToken("STYLE_REF");
385
+ var value = consumeChar();
386
+ while (Lexer.isAlpha(currentChar()) || currentChar() === "-") {
387
+ value += consumeChar();
388
+ }
389
+ styleRef.value = value;
390
+ styleRef.end = position;
391
+ return styleRef;
392
+ }
393
+
394
+ /**
395
+ * @returns Token
396
+ */
397
+ function consumeIdReference() {
398
+ var idRef = makeToken("ID_REF");
399
+ var value = consumeChar();
400
+ if (currentChar() === "{") {
401
+ idRef.template = true;
402
+ value += consumeChar();
403
+ while (currentChar() && currentChar() !== "}") {
404
+ value += consumeChar();
405
+ }
406
+ if (currentChar() !== "}") {
407
+ throw Error("Unterminated id reference");
408
+ } else {
409
+ consumeChar(); // consume final quote
410
+ }
411
+ } else {
412
+ while (Lexer.isValidCSSIDChar(currentChar())) {
413
+ value += consumeChar();
414
+ }
415
+ }
416
+ idRef.value = value;
417
+ idRef.end = position;
418
+ return idRef;
419
+ }
420
+
421
+ /**
422
+ * @returns Token
423
+ */
424
+ function consumeIdentifier() {
425
+ var identifier = makeToken("IDENTIFIER");
426
+ var value = consumeChar();
427
+ while (Lexer.isAlpha(currentChar()) ||
428
+ Lexer.isNumeric(currentChar()) ||
429
+ Lexer.isIdentifierChar(currentChar())) {
430
+ value += consumeChar();
431
+ }
432
+ if (currentChar() === "!" && value === "beep") {
433
+ value += consumeChar();
434
+ }
435
+ identifier.value = value;
436
+ identifier.end = position;
437
+ return identifier;
438
+ }
439
+
440
+ /**
441
+ * @returns Token
442
+ */
443
+ function consumeNumber() {
444
+ var number = makeToken("NUMBER");
445
+ var value = consumeChar();
446
+ while (Lexer.isNumeric(currentChar())) {
447
+ value += consumeChar();
448
+ }
449
+ if (currentChar() === "." && Lexer.isNumeric(nextChar())) {
450
+ value += consumeChar();
451
+ }
452
+ while (Lexer.isNumeric(currentChar())) {
453
+ value += consumeChar();
454
+ }
455
+ number.value = value;
456
+ number.end = position;
457
+ return number;
458
+ }
459
+
460
+ /**
461
+ * @returns Token
462
+ */
463
+ function consumeOp() {
464
+ var op = makeOpToken();
465
+ var value = consumeChar(); // consume leading char
466
+ while (currentChar() && Lexer.OP_TABLE[value + currentChar()]) {
467
+ value += consumeChar();
468
+ }
469
+ op.type = Lexer.OP_TABLE[value];
470
+ op.value = value;
471
+ op.end = position;
472
+ return op;
473
+ }
474
+
475
+ /**
476
+ * @returns Token
477
+ */
478
+ function consumeString() {
479
+ var string = makeToken("STRING");
480
+ var startChar = consumeChar(); // consume leading quote
481
+ var value = "";
482
+ while (currentChar() && currentChar() !== startChar) {
483
+ if (currentChar() === "\\") {
484
+ consumeChar(); // consume escape char and get the next one
485
+ let nextChar = consumeChar();
486
+ if (nextChar === "b") {
487
+ value += "\b";
488
+ } else if (nextChar === "f") {
489
+ value += "\f";
490
+ } else if (nextChar === "n") {
491
+ value += "\n";
492
+ } else if (nextChar === "r") {
493
+ value += "\r";
494
+ } else if (nextChar === "t") {
495
+ value += "\t";
496
+ } else if (nextChar === "v") {
497
+ value += "\v";
498
+ } else {
499
+ value += nextChar;
500
+ }
501
+ } else {
502
+ value += consumeChar();
503
+ }
504
+ }
505
+ if (currentChar() !== startChar) {
506
+ throw Error("Unterminated string at " + Lexer.positionString(string));
507
+ } else {
508
+ consumeChar(); // consume final quote
509
+ }
510
+ string.value = value;
511
+ string.end = position;
512
+ string.template = startChar === "`";
513
+ return string;
514
+ }
515
+
516
+ /**
517
+ * @returns string
518
+ */
519
+ function currentChar() {
520
+ return source.charAt(position);
521
+ }
522
+
523
+ /**
524
+ * @returns string
525
+ */
526
+ function nextChar() {
527
+ return source.charAt(position + 1);
528
+ }
529
+
530
+ function charAfterThat() {
531
+ return source.charAt(position + 2);
532
+ }
533
+
534
+ /**
535
+ * @returns string
536
+ */
537
+ function consumeChar() {
538
+ lastToken = currentChar();
539
+ position++;
540
+ column++;
541
+ return lastToken;
542
+ }
543
+
544
+ /**
545
+ * @returns boolean
546
+ */
547
+ function possiblePrecedingSymbol() {
548
+ return (
549
+ Lexer.isAlpha(lastToken) ||
550
+ Lexer.isNumeric(lastToken) ||
551
+ lastToken === ")" ||
552
+ lastToken === "\"" ||
553
+ lastToken === "'" ||
554
+ lastToken === "`" ||
555
+ lastToken === "}" ||
556
+ lastToken === "]"
557
+ );
558
+ }
559
+
560
+ /**
561
+ * @returns Token
562
+ */
563
+ function consumeWhitespace() {
564
+ var whitespace = makeToken("WHITESPACE");
565
+ var value = "";
566
+ while (currentChar() && Lexer.isWhitespace(currentChar())) {
567
+ if (Lexer.isNewline(currentChar())) {
568
+ column = 0;
569
+ line++;
570
+ }
571
+ value += consumeChar();
572
+ }
573
+ whitespace.value = value;
574
+ whitespace.end = position;
575
+ return whitespace;
576
+ }
577
+ }
578
+
579
+ /**
580
+ * @param {string} string
581
+ * @param {boolean} [template]
582
+ * @returns {Tokens}
583
+ */
584
+ tokenize(string, template) {
585
+ return Lexer.tokenize(string, template)
586
+ }
587
+ }
588
+
589
+ /**
590
+ * @typedef {Object} Token
591
+ * @property {string} [type]
592
+ * @property {string} [value]
593
+ * @property {number} [start]
594
+ * @property {number} [end]
595
+ * @property {number} [column]
596
+ * @property {number} [line]
597
+ * @property {boolean} [op] `true` if this token represents an operator
598
+ * @property {boolean} [template] `true` if this token is a template, for class refs, id refs, strings
599
+ */
600
+
601
+ class Tokens {
602
+ constructor(tokens, consumed, source) {
603
+ this.tokens = tokens
604
+ this.consumed = consumed
605
+ this.source = source
606
+
607
+ this.consumeWhitespace(); // consume initial whitespace
608
+ }
609
+
610
+ get list() {
611
+ return this.tokens
612
+ }
613
+
614
+ /** @type Token | null */
615
+ _lastConsumed = null;
616
+
617
+ consumeWhitespace() {
618
+ while (this.token(0, true).type === "WHITESPACE") {
619
+ this.consumed.push(this.tokens.shift());
620
+ }
621
+ }
622
+
623
+ /**
624
+ * @param {Tokens} tokens
625
+ * @param {*} error
626
+ */
627
+ raiseError(tokens, error) {
628
+ Parser.raiseParseError(tokens, error);
629
+ }
630
+
631
+ /**
632
+ * @param {string} value
633
+ * @returns {Token}
634
+ */
635
+ requireOpToken(value) {
636
+ var token = this.matchOpToken(value);
637
+ if (token) {
638
+ return token;
639
+ } else {
640
+ this.raiseError(this, "Expected '" + value + "' but found '" + this.currentToken().value + "'");
641
+ }
642
+ }
643
+
644
+ /**
645
+ * @param {string} op1
646
+ * @param {string} [op2]
647
+ * @param {string} [op3]
648
+ * @returns {Token | void}
649
+ */
650
+ matchAnyOpToken(op1, op2, op3) {
651
+ for (var i = 0; i < arguments.length; i++) {
652
+ var opToken = arguments[i];
653
+ var match = this.matchOpToken(opToken);
654
+ if (match) {
655
+ return match;
656
+ }
657
+ }
658
+ }
659
+
660
+ /**
661
+ * @param {string} op1
662
+ * @param {string} [op2]
663
+ * @param {string} [op3]
664
+ * @returns {Token | void}
665
+ */
666
+ matchAnyToken(op1, op2, op3) {
667
+ for (var i = 0; i < arguments.length; i++) {
668
+ var opToken = arguments[i];
669
+ var match = this.matchToken(opToken);
670
+ if (match) {
671
+ return match;
672
+ }
673
+ }
674
+ }
675
+
676
+ /**
677
+ * @param {string} value
678
+ * @returns {Token | void}
679
+ */
680
+ matchOpToken(value) {
681
+ if (this.currentToken() && this.currentToken().op && this.currentToken().value === value) {
682
+ return this.consumeToken();
683
+ }
684
+ }
685
+
686
+ /**
687
+ * @param {string} type1
688
+ * @param {string} [type2]
689
+ * @param {string} [type3]
690
+ * @param {string} [type4]
691
+ * @returns {Token}
692
+ */
693
+ requireTokenType(type1, type2, type3, type4) {
694
+ var token = this.matchTokenType(type1, type2, type3, type4);
695
+ if (token) {
696
+ return token;
697
+ } else {
698
+ this.raiseError(this, "Expected one of " + JSON.stringify([type1, type2, type3]));
699
+ }
700
+ }
701
+
702
+ /**
703
+ * @param {string} type1
704
+ * @param {string} [type2]
705
+ * @param {string} [type3]
706
+ * @param {string} [type4]
707
+ * @returns {Token | void}
708
+ */
709
+ matchTokenType(type1, type2, type3, type4) {
710
+ if (
711
+ this.currentToken() &&
712
+ this.currentToken().type &&
713
+ [type1, type2, type3, type4].indexOf(this.currentToken().type) >= 0
714
+ ) {
715
+ return this.consumeToken();
716
+ }
717
+ }
718
+
719
+ /**
720
+ * @param {string} value
721
+ * @param {string} [type]
722
+ * @returns {Token}
723
+ */
724
+ requireToken(value, type) {
725
+ var token = this.matchToken(value, type);
726
+ if (token) {
727
+ return token;
728
+ } else {
729
+ this.raiseError(this, "Expected '" + value + "' but found '" + this.currentToken().value + "'");
730
+ }
731
+ }
732
+
733
+ peekToken(value, peek, type) {
734
+ return this.tokens[peek] && this.tokens[peek].value === value && this.tokens[peek].type === type
735
+ }
736
+
737
+ /**
738
+ * @param {string} value
739
+ * @param {string} [type]
740
+ * @returns {Token | void}
741
+ */
742
+ matchToken(value, type) {
743
+ if (this.follows.indexOf(value) !== -1) {
744
+ return; // disallowed token here
745
+ }
746
+ var type = type || "IDENTIFIER";
747
+ if (this.currentToken() && this.currentToken().value === value && this.currentToken().type === type) {
748
+ return this.consumeToken();
749
+ }
750
+ }
751
+
752
+ /**
753
+ * @returns {Token}
754
+ */
755
+ consumeToken() {
756
+ var match = this.tokens.shift();
757
+ this.consumed.push(match);
758
+ this._lastConsumed = match;
759
+ this.consumeWhitespace(); // consume any whitespace
760
+ return match;
761
+ }
762
+
763
+ /**
764
+ * @param {string} value
765
+ * @param {string} [type]
766
+ * @returns {Token[]}
767
+ */
768
+ consumeUntil(value, type) {
769
+ /** @type Token[] */
770
+ var tokenList = [];
771
+ var currentToken = this.token(0, true);
772
+
773
+ while (
774
+ (type == null || currentToken.type !== type) &&
775
+ (value == null || currentToken.value !== value) &&
776
+ currentToken.type !== "EOF"
777
+ ) {
778
+ var match = this.tokens.shift();
779
+ this.consumed.push(match);
780
+ tokenList.push(currentToken);
781
+ currentToken = this.token(0, true);
782
+ }
783
+ this.consumeWhitespace(); // consume any whitespace
784
+ return tokenList;
785
+ }
786
+
787
+ /**
788
+ * @returns {string}
789
+ */
790
+ lastWhitespace() {
791
+ if (this.consumed[this.consumed.length - 1] && this.consumed[this.consumed.length - 1].type === "WHITESPACE") {
792
+ return this.consumed[this.consumed.length - 1].value;
793
+ } else {
794
+ return "";
795
+ }
796
+ }
797
+
798
+ consumeUntilWhitespace() {
799
+ return this.consumeUntil(null, "WHITESPACE");
800
+ }
801
+
802
+ /**
803
+ * @returns {boolean}
804
+ */
805
+ hasMore() {
806
+ return this.tokens.length > 0;
807
+ }
808
+
809
+ /**
810
+ * @param {number} n
811
+ * @param {boolean} [dontIgnoreWhitespace]
812
+ * @returns {Token}
813
+ */
814
+ token(n, dontIgnoreWhitespace) {
815
+ var /**@type {Token}*/ token;
816
+ var i = 0;
817
+ do {
818
+ if (!dontIgnoreWhitespace) {
819
+ while (this.tokens[i] && this.tokens[i].type === "WHITESPACE") {
820
+ i++;
821
+ }
822
+ }
823
+ token = this.tokens[i];
824
+ n--;
825
+ i++;
826
+ } while (n > -1);
827
+ if (token) {
828
+ return token;
829
+ } else {
830
+ return {
831
+ type: "EOF",
832
+ value: "<<<EOF>>>",
833
+ };
834
+ }
835
+ }
836
+
837
+ /**
838
+ * @returns {Token}
839
+ */
840
+ currentToken() {
841
+ return this.token(0);
842
+ }
843
+
844
+ /**
845
+ * @returns {Token | null}
846
+ */
847
+ lastMatch() {
848
+ return this._lastConsumed;
849
+ }
850
+
851
+ /**
852
+ * @returns {string}
853
+ */
854
+ static sourceFor = function () {
855
+ return this.programSource.substring(this.startToken.start, this.endToken.end);
856
+ }
857
+
858
+ /**
859
+ * @returns {string}
860
+ */
861
+ static lineFor = function () {
862
+ return this.programSource.split("\n")[this.startToken.line - 1];
863
+ }
864
+
865
+ follows = [];
866
+
867
+ pushFollow(str) {
868
+ this.follows.push(str);
869
+ }
870
+
871
+ popFollow() {
872
+ this.follows.pop();
873
+ }
874
+
875
+ clearFollows() {
876
+ var tmp = this.follows;
877
+ this.follows = [];
878
+ return tmp;
879
+ }
880
+
881
+ restoreFollows(f) {
882
+ this.follows = f;
883
+ }
884
+ }
885
+
886
+ /**
887
+ * @callback ParseRule
888
+ * @param {Parser} parser
889
+ * @param {Runtime} runtime
890
+ * @param {Tokens} tokens
891
+ * @param {*} root
892
+ * @returns {ASTNode | undefined}
893
+ *
894
+ * @typedef {Object} ASTNode
895
+ * @member {boolean} isFeature
896
+ * @member {string} type
897
+ * @member {any[]} args
898
+ * @member {(this: ASTNode, ctx:Context, root:any, ...args:any) => any} op
899
+ * @member {(this: ASTNode, context?:Context) => any} evaluate
900
+ * @member {ASTNode} parent
901
+ * @member {Set<ASTNode>} children
902
+ * @member {ASTNode} root
903
+ * @member {String} keyword
904
+ * @member {Token} endToken
905
+ * @member {ASTNode} next
906
+ * @member {(context:Context) => ASTNode} resolveNext
907
+ * @member {EventSource} eventSource
908
+ * @member {(this: ASTNode) => void} install
909
+ * @member {(this: ASTNode, context:Context) => void} execute
910
+ * @member {(this: ASTNode, target: object, source: object, args?: Object) => void} apply
911
+ *
912
+ *
913
+ */
914
+
915
+ class Parser {
916
+ /**
917
+ *
918
+ * @param {Runtime} runtime
919
+ */
920
+ constructor(runtime) {
921
+ this.runtime = runtime
922
+
923
+ this.possessivesDisabled = false
924
+
925
+ /* ============================================================================================ */
926
+ /* Core hyperscript Grammar Elements */
927
+ /* ============================================================================================ */
928
+ this.addGrammarElement("feature", function (parser, runtime, tokens) {
929
+ if (tokens.matchOpToken("(")) {
930
+ var featureElement = parser.requireElement("feature", tokens);
931
+ tokens.requireOpToken(")");
932
+ return featureElement;
933
+ }
934
+
935
+ var featureDefinition = parser.FEATURES[tokens.currentToken().value];
936
+ if (featureDefinition) {
937
+ return featureDefinition(parser, runtime, tokens);
938
+ }
939
+ });
940
+
941
+ this.addGrammarElement("command", function (parser, runtime, tokens) {
942
+ if (tokens.matchOpToken("(")) {
943
+ const commandElement = parser.requireElement("command", tokens);
944
+ tokens.requireOpToken(")");
945
+ return commandElement;
946
+ }
947
+
948
+ var commandDefinition = parser.COMMANDS[tokens.currentToken().value];
949
+ let commandElement;
950
+ if (commandDefinition) {
951
+ commandElement = commandDefinition(parser, runtime, tokens);
952
+ } else if (tokens.currentToken().type === "IDENTIFIER") {
953
+ commandElement = parser.parseElement("pseudoCommand", tokens);
954
+ }
955
+ if (commandElement) {
956
+ return parser.parseElement("indirectStatement", tokens, commandElement);
957
+ }
958
+
959
+ return commandElement;
960
+ });
961
+
962
+ this.addGrammarElement("commandList", function (parser, runtime, tokens) {
963
+ var cmd = parser.parseElement("command", tokens);
964
+ if (cmd) {
965
+ tokens.matchToken("then");
966
+ const next = parser.parseElement("commandList", tokens);
967
+ if (next) cmd.next = next;
968
+ return cmd;
969
+ }
970
+ });
971
+
972
+ this.addGrammarElement("leaf", function (parser, runtime, tokens) {
973
+ var result = parser.parseAnyOf(parser.LEAF_EXPRESSIONS, tokens);
974
+ // symbol is last so it doesn't consume any constants
975
+ if (result == null) {
976
+ return parser.parseElement("symbol", tokens);
977
+ }
978
+
979
+ return result;
980
+ });
981
+
982
+ this.addGrammarElement("indirectExpression", function (parser, runtime, tokens, root) {
983
+ for (var i = 0; i < parser.INDIRECT_EXPRESSIONS.length; i++) {
984
+ var indirect = parser.INDIRECT_EXPRESSIONS[i];
985
+ root.endToken = tokens.lastMatch();
986
+ var result = parser.parseElement(indirect, tokens, root);
987
+ if (result) {
988
+ return result;
989
+ }
990
+ }
991
+ return root;
992
+ });
993
+
994
+ this.addGrammarElement("indirectStatement", function (parser, runtime, tokens, root) {
995
+ if (tokens.matchToken("unless")) {
996
+ root.endToken = tokens.lastMatch();
997
+ var conditional = parser.requireElement("expression", tokens);
998
+ var unless = {
999
+ type: "unlessStatementModifier",
1000
+ args: [conditional],
1001
+ op: function (context, conditional) {
1002
+ if (conditional) {
1003
+ return this.next;
1004
+ } else {
1005
+ return root;
1006
+ }
1007
+ },
1008
+ execute: function (context) {
1009
+ return runtime.unifiedExec(this, context);
1010
+ },
1011
+ };
1012
+ root.parent = unless;
1013
+ return unless;
1014
+ }
1015
+ return root;
1016
+ });
1017
+
1018
+ this.addGrammarElement("primaryExpression", function (parser, runtime, tokens) {
1019
+ var leaf = parser.parseElement("leaf", tokens);
1020
+ if (leaf) {
1021
+ return parser.parseElement("indirectExpression", tokens, leaf);
1022
+ }
1023
+ parser.raiseParseError(tokens, "Unexpected value: " + tokens.currentToken().value);
1024
+ });
1025
+ }
1026
+
1027
+ use(plugin) {
1028
+ plugin(this)
1029
+ return this
1030
+ }
1031
+
1032
+ /** @type {Object<string,ParseRule>} */
1033
+ GRAMMAR = {};
1034
+
1035
+ /** @type {Object<string,ParseRule>} */
1036
+ COMMANDS = {};
1037
+
1038
+ /** @type {Object<string,ParseRule>} */
1039
+ FEATURES = {};
1040
+
1041
+ /** @type {string[]} */
1042
+ LEAF_EXPRESSIONS = [];
1043
+ /** @type {string[]} */
1044
+ INDIRECT_EXPRESSIONS = [];
1045
+
1046
+ /**
1047
+ * @param {*} parseElement
1048
+ * @param {*} start
1049
+ * @param {Tokens} tokens
1050
+ */
1051
+ initElt(parseElement, start, tokens) {
1052
+ parseElement.startToken = start;
1053
+ parseElement.sourceFor = Tokens.sourceFor;
1054
+ parseElement.lineFor = Tokens.lineFor;
1055
+ parseElement.programSource = tokens.source;
1056
+ }
1057
+
1058
+ /**
1059
+ * @param {string} type
1060
+ * @param {Tokens} tokens
1061
+ * @param {ASTNode?} root
1062
+ * @returns {ASTNode}
1063
+ */
1064
+ parseElement(type, tokens, root = undefined) {
1065
+ var elementDefinition = this.GRAMMAR[type];
1066
+ if (elementDefinition) {
1067
+ var start = tokens.currentToken();
1068
+ var parseElement = elementDefinition(this, this.runtime, tokens, root);
1069
+ if (parseElement) {
1070
+ this.initElt(parseElement, start, tokens);
1071
+ parseElement.endToken = parseElement.endToken || tokens.lastMatch();
1072
+ var root = parseElement.root;
1073
+ while (root != null) {
1074
+ this.initElt(root, start, tokens);
1075
+ root = root.root;
1076
+ }
1077
+ }
1078
+ return parseElement;
1079
+ }
1080
+ }
1081
+
1082
+ /**
1083
+ * @param {string} type
1084
+ * @param {Tokens} tokens
1085
+ * @param {string} [message]
1086
+ * @param {*} [root]
1087
+ * @returns {ASTNode}
1088
+ */
1089
+ requireElement(type, tokens, message, root) {
1090
+ var result = this.parseElement(type, tokens, root);
1091
+ if (!result) Parser.raiseParseError(tokens, message || "Expected " + type);
1092
+ // @ts-ignore
1093
+ return result;
1094
+ }
1095
+
1096
+ /**
1097
+ * @param {string[]} types
1098
+ * @param {Tokens} tokens
1099
+ * @returns {ASTNode}
1100
+ */
1101
+ parseAnyOf(types, tokens) {
1102
+ for (var i = 0; i < types.length; i++) {
1103
+ var type = types[i];
1104
+ var expression = this.parseElement(type, tokens);
1105
+ if (expression) {
1106
+ return expression;
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ /**
1112
+ * @param {string} name
1113
+ * @param {ParseRule} definition
1114
+ */
1115
+ addGrammarElement(name, definition) {
1116
+ this.GRAMMAR[name] = definition;
1117
+ }
1118
+
1119
+ /**
1120
+ * @param {string} keyword
1121
+ * @param {ParseRule} definition
1122
+ */
1123
+ addCommand(keyword, definition) {
1124
+ var commandGrammarType = keyword + "Command";
1125
+ var commandDefinitionWrapper = function (parser, runtime, tokens) {
1126
+ const commandElement = definition(parser, runtime, tokens);
1127
+ if (commandElement) {
1128
+ commandElement.type = commandGrammarType;
1129
+ commandElement.execute = function (context) {
1130
+ context.meta.command = commandElement;
1131
+ return runtime.unifiedExec(this, context);
1132
+ };
1133
+ return commandElement;
1134
+ }
1135
+ };
1136
+ this.GRAMMAR[commandGrammarType] = commandDefinitionWrapper;
1137
+ this.COMMANDS[keyword] = commandDefinitionWrapper;
1138
+ }
1139
+
1140
+ /**
1141
+ * @param {string} keyword
1142
+ * @param {ParseRule} definition
1143
+ */
1144
+ addFeature(keyword, definition) {
1145
+ var featureGrammarType = keyword + "Feature";
1146
+
1147
+ /** @type {ParseRule} */
1148
+ var featureDefinitionWrapper = function (parser, runtime, tokens) {
1149
+ var featureElement = definition(parser, runtime, tokens);
1150
+ if (featureElement) {
1151
+ featureElement.isFeature = true;
1152
+ featureElement.keyword = keyword;
1153
+ featureElement.type = featureGrammarType;
1154
+ return featureElement;
1155
+ }
1156
+ };
1157
+ this.GRAMMAR[featureGrammarType] = featureDefinitionWrapper;
1158
+ this.FEATURES[keyword] = featureDefinitionWrapper;
1159
+ }
1160
+
1161
+ /**
1162
+ * @param {string} name
1163
+ * @param {ParseRule} definition
1164
+ */
1165
+ addLeafExpression(name, definition) {
1166
+ this.LEAF_EXPRESSIONS.push(name);
1167
+ this.addGrammarElement(name, definition);
1168
+ }
1169
+
1170
+ /**
1171
+ * @param {string} name
1172
+ * @param {ParseRule} definition
1173
+ */
1174
+ addIndirectExpression(name, definition) {
1175
+ this.INDIRECT_EXPRESSIONS.push(name);
1176
+ this.addGrammarElement(name, definition);
1177
+ }
1178
+
1179
+ /**
1180
+ *
1181
+ * @param {Tokens} tokens
1182
+ * @returns string
1183
+ */
1184
+ static createParserContext(tokens) {
1185
+ var currentToken = tokens.currentToken();
1186
+ var source = tokens.source;
1187
+ var lines = source.split("\n");
1188
+ var line = currentToken && currentToken.line ? currentToken.line - 1 : lines.length - 1;
1189
+ var contextLine = lines[line];
1190
+ var offset = currentToken && currentToken.line ? currentToken.column : contextLine.length - 1;
1191
+ return contextLine + "\n" + " ".repeat(offset) + "^^\n\n";
1192
+ }
1193
+
1194
+ /**
1195
+ * @param {Tokens} tokens
1196
+ * @param {string} [message]
1197
+ */
1198
+ static raiseParseError(tokens, message) {
1199
+ message =
1200
+ (message || "Unexpected Token : " + tokens.currentToken().value) + "\n\n" + Parser.createParserContext(tokens);
1201
+ var error = new Error(message);
1202
+ error["tokens"] = tokens;
1203
+ throw error;
1204
+ }
1205
+
1206
+ /**
1207
+ * @param {Tokens} tokens
1208
+ * @param {string} [message]
1209
+ */
1210
+ raiseParseError(tokens, message) {
1211
+ Parser.raiseParseError(tokens, message)
1212
+ }
1213
+
1214
+ /**
1215
+ * @param {Tokens} tokens
1216
+ * @returns {ASTNode}
1217
+ */
1218
+ parseHyperScript(tokens) {
1219
+ var result = this.parseElement("hyperscript", tokens);
1220
+ if (tokens.hasMore()) this.raiseParseError(tokens);
1221
+ if (result) return result;
1222
+ }
1223
+
1224
+ /**
1225
+ * @param {ASTNode | undefined} elt
1226
+ * @param {ASTNode} parent
1227
+ */
1228
+ setParent(elt, parent) {
1229
+ if (typeof elt === 'object') {
1230
+ elt.parent = parent;
1231
+ if (typeof parent === 'object') {
1232
+ parent.children = (parent.children || new Set());
1233
+ parent.children.add(elt)
1234
+ }
1235
+ this.setParent(elt.next, parent);
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * @param {Token} token
1241
+ * @returns {ParseRule}
1242
+ */
1243
+ commandStart(token) {
1244
+ return this.COMMANDS[token.value];
1245
+ }
1246
+
1247
+ /**
1248
+ * @param {Token} token
1249
+ * @returns {ParseRule}
1250
+ */
1251
+ featureStart(token) {
1252
+ return this.FEATURES[token.value];
1253
+ }
1254
+
1255
+ /**
1256
+ * @param {Token} token
1257
+ * @returns {boolean}
1258
+ */
1259
+ commandBoundary(token) {
1260
+ if (
1261
+ token.value == "end" ||
1262
+ token.value == "then" ||
1263
+ token.value == "else" ||
1264
+ token.value == "otherwise" ||
1265
+ token.value == ")" ||
1266
+ this.commandStart(token) ||
1267
+ this.featureStart(token) ||
1268
+ token.type == "EOF"
1269
+ ) {
1270
+ return true;
1271
+ }
1272
+ return false;
1273
+ }
1274
+
1275
+ /**
1276
+ * @param {Tokens} tokens
1277
+ * @returns {(string | ASTNode)[]}
1278
+ */
1279
+ parseStringTemplate(tokens) {
1280
+ /** @type {(string | ASTNode)[]} */
1281
+ var returnArr = [""];
1282
+ do {
1283
+ returnArr.push(tokens.lastWhitespace());
1284
+ if (tokens.currentToken().value === "$") {
1285
+ tokens.consumeToken();
1286
+ var startingBrace = tokens.matchOpToken("{");
1287
+ returnArr.push(this.requireElement("expression", tokens));
1288
+ if (startingBrace) {
1289
+ tokens.requireOpToken("}");
1290
+ }
1291
+ returnArr.push("");
1292
+ } else if (tokens.currentToken().value === "\\") {
1293
+ tokens.consumeToken(); // skip next
1294
+ tokens.consumeToken();
1295
+ } else {
1296
+ var token = tokens.consumeToken();
1297
+ returnArr[returnArr.length - 1] += token ? token.value : "";
1298
+ }
1299
+ } while (tokens.hasMore());
1300
+ returnArr.push(tokens.lastWhitespace());
1301
+ return returnArr;
1302
+ }
1303
+
1304
+ /**
1305
+ * @param {ASTNode} commandList
1306
+ */
1307
+ ensureTerminated(commandList) {
1308
+ const runtime = this.runtime
1309
+ var implicitReturn = {
1310
+ type: "implicitReturn",
1311
+ op: function (context) {
1312
+ context.meta.returned = true;
1313
+ if (context.meta.resolve) {
1314
+ context.meta.resolve();
1315
+ }
1316
+ return runtime.HALT;
1317
+ },
1318
+ execute: function (ctx) {
1319
+ // do nothing
1320
+ },
1321
+ };
1322
+
1323
+ var end = commandList;
1324
+ while (end.next) {
1325
+ end = end.next;
1326
+ }
1327
+ end.next = implicitReturn;
1328
+ }
1329
+ }
1330
+
1331
+ class Runtime {
1332
+ /**
1333
+ *
1334
+ * @param {Lexer} [lexer]
1335
+ * @param {Parser} [parser]
1336
+ */
1337
+ constructor(lexer, parser) {
1338
+ this.lexer = lexer ?? new Lexer;
1339
+ this.parser = parser ?? new Parser(this)
1340
+ .use(hyperscriptCoreGrammar)
1341
+ .use(hyperscriptWebGrammar);
1342
+ this.parser.runtime = this
1343
+ }
1344
+
1345
+ /**
1346
+ * @param {HTMLElement} elt
1347
+ * @param {string} selector
1348
+ * @returns boolean
1349
+ */
1350
+ matchesSelector(elt, selector) {
1351
+ // noinspection JSUnresolvedVariable
1352
+ var matchesFunction =
1353
+ // @ts-ignore
1354
+ elt.matches || elt.matchesSelector || elt.msMatchesSelector || elt.mozMatchesSelector || elt.webkitMatchesSelector || elt.oMatchesSelector;
1355
+ return matchesFunction && matchesFunction.call(elt, selector);
1356
+ }
1357
+
1358
+ /**
1359
+ * @param {string} eventName
1360
+ * @param {Object} [detail]
1361
+ * @returns {Event}
1362
+ */
1363
+ makeEvent(eventName, detail) {
1364
+ var evt;
1365
+ if (globalScope.Event && typeof globalScope.Event === "function") {
1366
+ evt = new Event(eventName, {
1367
+ bubbles: true,
1368
+ cancelable: true,
1369
+ });
1370
+ evt['detail'] = detail;
1371
+ } else {
1372
+ evt = document.createEvent("CustomEvent");
1373
+ evt.initCustomEvent(eventName, true, true, detail);
1374
+ }
1375
+ return evt;
1376
+ }
1377
+
1378
+ /**
1379
+ * @param {Element} elt
1380
+ * @param {string} eventName
1381
+ * @param {Object} [detail]
1382
+ * @param {Element} [sender]
1383
+ * @returns {boolean}
1384
+ */
1385
+ triggerEvent(elt, eventName, detail, sender) {
1386
+ detail = detail || {};
1387
+ detail["sender"] = sender;
1388
+ var event = this.makeEvent(eventName, detail);
1389
+ var eventResult = elt.dispatchEvent(event);
1390
+ return eventResult;
1391
+ }
1392
+
1393
+ /**
1394
+ * isArrayLike returns `true` if the provided value is an array or
1395
+ * a NodeList (which is close enough to being an array for our purposes).
1396
+ *
1397
+ * @param {any} value
1398
+ * @returns {value is Array | NodeList}
1399
+ */
1400
+ isArrayLike(value) {
1401
+ return Array.isArray(value) ||
1402
+ (typeof NodeList !== 'undefined' && (value instanceof NodeList || value instanceof HTMLCollection));
1403
+ }
1404
+
1405
+ /**
1406
+ * isIterable returns `true` if the provided value supports the
1407
+ * iterator protocol.
1408
+ *
1409
+ * @param {any} value
1410
+ * @returns {value is Iterable}
1411
+ */
1412
+ isIterable(value) {
1413
+ return typeof value === 'object'
1414
+ && Symbol.iterator in value
1415
+ && typeof value[Symbol.iterator] === 'function';
1416
+ }
1417
+
1418
+ /**
1419
+ * shouldAutoIterate returns `true` if the provided value
1420
+ * should be implicitly iterated over when accessing properties,
1421
+ * and as the target of some commands.
1422
+ *
1423
+ * Currently, this is when the value is an {ElementCollection}
1424
+ * or {isArrayLike} returns true.
1425
+ *
1426
+ * @param {any} value
1427
+ * @returns {value is (any[] | ElementCollection)}
1428
+ */
1429
+ shouldAutoIterate(value) {
1430
+ return value[shouldAutoIterateSymbol] ||
1431
+ this.isArrayLike(value);
1432
+ }
1433
+
1434
+ /**
1435
+ * forEach executes the provided `func` on every item in the `value` array.
1436
+ * if `value` is a single item (and not an array) then `func` is simply called
1437
+ * once. If `value` is null, then no further actions are taken.
1438
+ *
1439
+ * @template T
1440
+ * @param {T | Iterable<T>} value
1441
+ * @param {(item: T) => void} func
1442
+ */
1443
+ forEach(value, func) {
1444
+ if (value == null) {
1445
+ // do nothing
1446
+ } else if (this.isIterable(value)) {
1447
+ for (const nth of value) {
1448
+ func(nth);
1449
+ }
1450
+ } else if (this.isArrayLike(value)) {
1451
+ for (var i = 0; i < value.length; i++) {
1452
+ func(value[i]);
1453
+ }
1454
+ } else {
1455
+ func(value);
1456
+ }
1457
+ }
1458
+
1459
+ /**
1460
+ * implicitLoop executes the provided `func` on:
1461
+ * - every item of {value}, if {value} should be auto-iterated
1462
+ * (see {shouldAutoIterate})
1463
+ * - {value} otherwise
1464
+ *
1465
+ * @template T
1466
+ * @param {ElementCollection | T | T[]} value
1467
+ * @param {(item: T) => void} func
1468
+ */
1469
+ implicitLoop(value, func) {
1470
+ if (this.shouldAutoIterate(value)) {
1471
+ for (const x of value) func(x);
1472
+ } else {
1473
+ func(value);
1474
+ }
1475
+ }
1476
+
1477
+ wrapArrays(args) {
1478
+ var arr = [];
1479
+ for (var i = 0; i < args.length; i++) {
1480
+ var arg = args[i];
1481
+ if (Array.isArray(arg)) {
1482
+ arr.push(Promise.all(arg));
1483
+ } else {
1484
+ arr.push(arg);
1485
+ }
1486
+ }
1487
+ return arr;
1488
+ }
1489
+
1490
+ unwrapAsyncs(values) {
1491
+ for (var i = 0; i < values.length; i++) {
1492
+ var value = values[i];
1493
+ if (value.asyncWrapper) {
1494
+ values[i] = value.value;
1495
+ }
1496
+ if (Array.isArray(value)) {
1497
+ for (var j = 0; j < value.length; j++) {
1498
+ var valueElement = value[j];
1499
+ if (valueElement.asyncWrapper) {
1500
+ value[j] = valueElement.value;
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ }
1506
+
1507
+ static HALT = {};
1508
+ HALT = Runtime.HALT;
1509
+
1510
+ /**
1511
+ * @param {ASTNode} command
1512
+ * @param {Context} ctx
1513
+ */
1514
+ unifiedExec(command, ctx) {
1515
+ while (true) {
1516
+ try {
1517
+ var next = this.unifiedEval(command, ctx);
1518
+ } catch (e) {
1519
+ if (ctx.meta.handlingFinally) {
1520
+ console.error(" Exception in finally block: ", e);
1521
+ next = Runtime.HALT;
1522
+ } else {
1523
+ this.registerHyperTrace(ctx, e);
1524
+ if (ctx.meta.errorHandler && !ctx.meta.handlingError) {
1525
+ ctx.meta.handlingError = true;
1526
+ ctx.locals[ctx.meta.errorSymbol] = e;
1527
+ command = ctx.meta.errorHandler;
1528
+ continue;
1529
+ } else {
1530
+ ctx.meta.currentException = e;
1531
+ next = Runtime.HALT;
1532
+ }
1533
+ }
1534
+ }
1535
+ if (next == null) {
1536
+ console.error(command, " did not return a next element to execute! context: ", ctx);
1537
+ return;
1538
+ } else if (next.then) {
1539
+ next.then(resolvedNext => {
1540
+ this.unifiedExec(resolvedNext, ctx);
1541
+ }).catch(reason => {
1542
+ this.unifiedExec({ // Anonymous command to simply throw the exception
1543
+ op: function(){
1544
+ throw reason;
1545
+ }
1546
+ }, ctx);
1547
+ });
1548
+ return;
1549
+ } else if (next === Runtime.HALT) {
1550
+ if (ctx.meta.finallyHandler && !ctx.meta.handlingFinally) {
1551
+ ctx.meta.handlingFinally = true;
1552
+ command = ctx.meta.finallyHandler;
1553
+ } else {
1554
+ if (ctx.meta.onHalt) {
1555
+ ctx.meta.onHalt();
1556
+ }
1557
+ if (ctx.meta.currentException) {
1558
+ if (ctx.meta.reject) {
1559
+ ctx.meta.reject(ctx.meta.currentException);
1560
+ return;
1561
+ } else {
1562
+ throw ctx.meta.currentException;
1563
+ }
1564
+ } else {
1565
+ return;
1566
+ }
1567
+ }
1568
+ } else {
1569
+ command = next; // move to the next command
1570
+ }
1571
+ }
1572
+ }
1573
+
1574
+ /**
1575
+ * @param {*} parseElement
1576
+ * @param {Context} ctx
1577
+ * @returns {*}
1578
+ */
1579
+ unifiedEval(parseElement, ctx) {
1580
+ /** @type any[] */
1581
+ var args = [ctx];
1582
+ var async = false;
1583
+ var wrappedAsyncs = false;
1584
+
1585
+ if (parseElement.args) {
1586
+ for (var i = 0; i < parseElement.args.length; i++) {
1587
+ var argument = parseElement.args[i];
1588
+ if (argument == null) {
1589
+ args.push(null);
1590
+ } else if (Array.isArray(argument)) {
1591
+ var arr = [];
1592
+ for (var j = 0; j < argument.length; j++) {
1593
+ var element = argument[j];
1594
+ var value = element ? element.evaluate(ctx) : null; // OK
1595
+ if (value) {
1596
+ if (value.then) {
1597
+ async = true;
1598
+ } else if (value.asyncWrapper) {
1599
+ wrappedAsyncs = true;
1600
+ }
1601
+ }
1602
+ arr.push(value);
1603
+ }
1604
+ args.push(arr);
1605
+ } else if (argument.evaluate) {
1606
+ var value = argument.evaluate(ctx); // OK
1607
+ if (value) {
1608
+ if (value.then) {
1609
+ async = true;
1610
+ } else if (value.asyncWrapper) {
1611
+ wrappedAsyncs = true;
1612
+ }
1613
+ }
1614
+ args.push(value);
1615
+ } else {
1616
+ args.push(argument);
1617
+ }
1618
+ }
1619
+ }
1620
+ if (async) {
1621
+ return new Promise((resolve, reject) => {
1622
+ args = this.wrapArrays(args);
1623
+ Promise.all(args)
1624
+ .then(function (values) {
1625
+ if (wrappedAsyncs) {
1626
+ this.unwrapAsyncs(values);
1627
+ }
1628
+ try {
1629
+ var apply = parseElement.op.apply(parseElement, values);
1630
+ resolve(apply);
1631
+ } catch (e) {
1632
+ reject(e);
1633
+ }
1634
+ })
1635
+ .catch(function (reason) {
1636
+ reject(reason);
1637
+ });
1638
+ });
1639
+ } else {
1640
+ if (wrappedAsyncs) {
1641
+ this.unwrapAsyncs(args);
1642
+ }
1643
+ return parseElement.op.apply(parseElement, args);
1644
+ }
1645
+ }
1646
+
1647
+ _scriptAttrs = null;
1648
+
1649
+ /**
1650
+ * getAttributes returns the attribute name(s) to use when
1651
+ * locating hyperscript scripts in a DOM element. If no value
1652
+ * has been configured, it defaults to config.attributes
1653
+ * @returns string[]
1654
+ */
1655
+ getScriptAttributes() {
1656
+ if (this._scriptAttrs == null) {
1657
+ this._scriptAttrs = config.attributes.replace(/ /g, "").split(",");
1658
+ }
1659
+ return this._scriptAttrs;
1660
+ }
1661
+
1662
+ /**
1663
+ * @param {Element} elt
1664
+ * @returns {string | null}
1665
+ */
1666
+ getScript(elt) {
1667
+ for (var i = 0; i < this.getScriptAttributes().length; i++) {
1668
+ var scriptAttribute = this.getScriptAttributes()[i];
1669
+ if (elt.hasAttribute && elt.hasAttribute(scriptAttribute)) {
1670
+ return elt.getAttribute(scriptAttribute);
1671
+ }
1672
+ }
1673
+ if (elt instanceof HTMLScriptElement && elt.type === "text/hyperscript") {
1674
+ return elt.innerText;
1675
+ }
1676
+ return null;
1677
+ }
1678
+
1679
+ hyperscriptFeaturesMap = new WeakMap
1680
+
1681
+ /**
1682
+ * @param {*} elt
1683
+ * @returns {Object}
1684
+ */
1685
+ getHyperscriptFeatures(elt) {
1686
+ var hyperscriptFeatures = this.hyperscriptFeaturesMap.get(elt);
1687
+ if (typeof hyperscriptFeatures === 'undefined') {
1688
+ if (elt) {
1689
+ // in some rare cases, elt is null and this line crashes
1690
+ this.hyperscriptFeaturesMap.set(elt, hyperscriptFeatures = {});
1691
+ }
1692
+ }
1693
+ return hyperscriptFeatures;
1694
+ }
1695
+
1696
+ /**
1697
+ * @param {Object} owner
1698
+ * @param {Context} ctx
1699
+ */
1700
+ addFeatures(owner, ctx) {
1701
+ if (owner) {
1702
+ Object.assign(ctx.locals, this.getHyperscriptFeatures(owner));
1703
+ this.addFeatures(owner.parentElement, ctx);
1704
+ }
1705
+ }
1706
+
1707
+ /**
1708
+ * @param {*} owner
1709
+ * @param {*} feature
1710
+ * @param {*} hyperscriptTarget
1711
+ * @param {*} event
1712
+ * @returns {Context}
1713
+ */
1714
+ makeContext(owner, feature, hyperscriptTarget, event) {
1715
+ return new Context(owner, feature, hyperscriptTarget, event, this)
1716
+ }
1717
+
1718
+ /**
1719
+ * @returns string
1720
+ */
1721
+ getScriptSelector() {
1722
+ return this.getScriptAttributes()
1723
+ .map(function (attribute) {
1724
+ return "[" + attribute + "]";
1725
+ })
1726
+ .join(", ");
1727
+ }
1728
+
1729
+ /**
1730
+ * @param {any} value
1731
+ * @param {string} type
1732
+ * @returns {any}
1733
+ */
1734
+ convertValue(value, type) {
1735
+ var dynamicResolvers = conversions.dynamicResolvers;
1736
+ for (var i = 0; i < dynamicResolvers.length; i++) {
1737
+ var dynamicResolver = dynamicResolvers[i];
1738
+ var converted = dynamicResolver(type, value);
1739
+ if (converted !== undefined) {
1740
+ return converted;
1741
+ }
1742
+ }
1743
+
1744
+ if (value == null) {
1745
+ return null;
1746
+ }
1747
+ var converter = conversions[type];
1748
+ if (converter) {
1749
+ return converter(value);
1750
+ }
1751
+
1752
+ throw "Unknown conversion : " + type;
1753
+ }
1754
+
1755
+ /**
1756
+ * @param {string} src
1757
+ * @returns {ASTNode}
1758
+ */
1759
+ parse(src) {
1760
+ const lexer = this.lexer, parser = this.parser
1761
+ var tokens = lexer.tokenize(src);
1762
+ if (this.parser.commandStart(tokens.currentToken())) {
1763
+ var commandList = parser.requireElement("commandList", tokens);
1764
+ if (tokens.hasMore()) parser.raiseParseError(tokens);
1765
+ parser.ensureTerminated(commandList);
1766
+ return commandList;
1767
+ } else if (parser.featureStart(tokens.currentToken())) {
1768
+ var hyperscript = parser.requireElement("hyperscript", tokens);
1769
+ if (tokens.hasMore()) parser.raiseParseError(tokens);
1770
+ return hyperscript;
1771
+ } else {
1772
+ var expression = parser.requireElement("expression", tokens);
1773
+ if (tokens.hasMore()) parser.raiseParseError(tokens);
1774
+ return expression;
1775
+ }
1776
+ }
1777
+
1778
+ /**
1779
+ *
1780
+ * @param {ASTNode} elt
1781
+ * @param {Context} ctx
1782
+ * @returns {any}
1783
+ */
1784
+ evaluateNoPromise(elt, ctx) {
1785
+ let result = elt.evaluate(ctx);
1786
+ if (result.next) {
1787
+ throw new Error(Tokens.sourceFor.call(elt) + " returned a Promise in a context that they are not allowed.");
1788
+ }
1789
+ return result;
1790
+ }
1791
+
1792
+ /**
1793
+ * @param {string} src
1794
+ * @param {Partial<Context>} [ctx]
1795
+ * @param {Object} [args]
1796
+ * @returns {any}
1797
+ */
1798
+ evaluate(src, ctx, args) {
1799
+ class HyperscriptModule extends EventTarget {
1800
+ constructor(mod) {
1801
+ super();
1802
+ this.module = mod;
1803
+ }
1804
+ toString() {
1805
+ return this.module.id;
1806
+ }
1807
+ }
1808
+
1809
+ var body = 'document' in globalScope
1810
+ ? globalScope.document.body
1811
+ : new HyperscriptModule(args && args.module);
1812
+ ctx = Object.assign(this.makeContext(body, null, body, null), ctx || {});
1813
+ var element = this.parse(src);
1814
+ if (element.execute) {
1815
+ element.execute(ctx);
1816
+ return ctx.result;
1817
+ } else if (element.apply) {
1818
+ element.apply(body, body, args);
1819
+ return this.getHyperscriptFeatures(body);
1820
+ } else {
1821
+ return element.evaluate(ctx);
1822
+ }
1823
+
1824
+ function makeModule() {
1825
+ return {}
1826
+ }
1827
+ }
1828
+
1829
+ /**
1830
+ * @param {HTMLElement} elt
1831
+ */
1832
+ processNode(elt) {
1833
+ var selector = this.getScriptSelector();
1834
+ if (this.matchesSelector(elt, selector)) {
1835
+ this.initElement(elt, elt);
1836
+ }
1837
+ if (elt instanceof HTMLScriptElement && elt.type === "text/hyperscript") {
1838
+ this.initElement(elt, document.body);
1839
+ }
1840
+ if (elt.querySelectorAll) {
1841
+ this.forEach(elt.querySelectorAll(selector + ", [type='text/hyperscript']"), elt => {
1842
+ this.initElement(elt, elt instanceof HTMLScriptElement && elt.type === "text/hyperscript" ? document.body : elt);
1843
+ });
1844
+ }
1845
+ }
1846
+
1847
+ /**
1848
+ * @param {Element} elt
1849
+ * @param {Element} [target]
1850
+ */
1851
+ initElement(elt, target) {
1852
+ if (elt.closest && elt.closest(config.disableSelector)) {
1853
+ return;
1854
+ }
1855
+ var internalData = this.getInternalData(elt);
1856
+ if (!internalData.initialized) {
1857
+ var src = this.getScript(elt);
1858
+ if (src) {
1859
+ try {
1860
+ internalData.initialized = true;
1861
+ internalData.script = src;
1862
+ const lexer = this.lexer, parser = this.parser
1863
+ var tokens = lexer.tokenize(src);
1864
+ var hyperScript = parser.parseHyperScript(tokens);
1865
+ if (!hyperScript) return;
1866
+ hyperScript.apply(target || elt, elt);
1867
+ setTimeout(() => {
1868
+ this.triggerEvent(target || elt, "load", {
1869
+ hyperscript: true,
1870
+ });
1871
+ }, 1);
1872
+ } catch (e) {
1873
+ this.triggerEvent(elt, "exception", {
1874
+ error: e,
1875
+ });
1876
+ console.error(
1877
+ "hyperscript errors were found on the following element:",
1878
+ elt,
1879
+ "\n\n",
1880
+ e.message,
1881
+ e.stack
1882
+ );
1883
+ }
1884
+ }
1885
+ }
1886
+ }
1887
+
1888
+ internalDataMap = new WeakMap
1889
+
1890
+ /**
1891
+ * @param {Element} elt
1892
+ * @returns {Object}
1893
+ */
1894
+ getInternalData(elt) {
1895
+ var internalData = this.internalDataMap.get(elt);
1896
+ if (typeof internalData === 'undefined') {
1897
+ this.internalDataMap.set(elt, internalData = {});
1898
+ }
1899
+ return internalData;
1900
+ }
1901
+
1902
+ /**
1903
+ * @param {any} value
1904
+ * @param {string} typeString
1905
+ * @param {boolean} [nullOk]
1906
+ * @returns {boolean}
1907
+ */
1908
+ typeCheck(value, typeString, nullOk) {
1909
+ if (value == null && nullOk) {
1910
+ return true;
1911
+ }
1912
+ var typeName = Object.prototype.toString.call(value).slice(8, -1);
1913
+ return typeName === typeString;
1914
+ }
1915
+
1916
+ getElementScope(context) {
1917
+ var elt = context.meta && context.meta.owner;
1918
+ if (elt) {
1919
+ var internalData = this.getInternalData(elt);
1920
+ var scopeName = "elementScope";
1921
+ if (context.meta.feature && context.meta.feature.behavior) {
1922
+ scopeName = context.meta.feature.behavior + "Scope";
1923
+ }
1924
+ var elementScope = getOrInitObject(internalData, scopeName);
1925
+ return elementScope;
1926
+ } else {
1927
+ return {}; // no element, return empty scope
1928
+ }
1929
+ }
1930
+
1931
+ /**
1932
+ * @param {string} str
1933
+ * @returns {boolean}
1934
+ */
1935
+ isReservedWord(str) {
1936
+ return ["meta", "it", "result", "locals", "event", "target", "detail", "sender", "body"].includes(str)
1937
+ }
1938
+
1939
+ /**
1940
+ * @param {any} context
1941
+ * @returns {boolean}
1942
+ */
1943
+ isHyperscriptContext(context) {
1944
+ return context instanceof Context;
1945
+ }
1946
+
1947
+ /**
1948
+ * @param {string} str
1949
+ * @param {Context} context
1950
+ * @returns {any}
1951
+ */
1952
+ resolveSymbol(str, context, type) {
1953
+ if (str === "me" || str === "my" || str === "I") {
1954
+ return context.me;
1955
+ }
1956
+ if (str === "it" || str === "its" || str === "result") {
1957
+ return context.result;
1958
+ }
1959
+ if (str === "you" || str === "your" || str === "yourself") {
1960
+ return context.you;
1961
+ } else {
1962
+ if (type === "global") {
1963
+ return globalScope[str];
1964
+ } else if (type === "element") {
1965
+ var elementScope = this.getElementScope(context);
1966
+ return elementScope[str];
1967
+ } else if (type === "local") {
1968
+ return context.locals[str];
1969
+ } else {
1970
+ // meta scope (used for event conditionals)
1971
+ if (context.meta && context.meta.context) {
1972
+ var fromMetaContext = context.meta.context[str];
1973
+ if (typeof fromMetaContext !== "undefined") {
1974
+ return fromMetaContext;
1975
+ }
1976
+ }
1977
+ if (this.isHyperscriptContext(context) && !this.isReservedWord(str)) {
1978
+ // local scope
1979
+ var fromContext = context.locals[str];
1980
+ } else {
1981
+ // direct get from normal JS object or top-level of context
1982
+ var fromContext = context[str];
1983
+ }
1984
+ if (typeof fromContext !== "undefined") {
1985
+ return fromContext;
1986
+ } else {
1987
+ // element scope
1988
+ var elementScope = this.getElementScope(context);
1989
+ fromContext = elementScope[str];
1990
+ if (typeof fromContext !== "undefined") {
1991
+ return fromContext;
1992
+ } else {
1993
+ // global scope
1994
+ return globalScope[str];
1995
+ }
1996
+ }
1997
+ }
1998
+ }
1999
+ }
2000
+
2001
+ setSymbol(str, context, type, value) {
2002
+ if (type === "global") {
2003
+ globalScope[str] = value;
2004
+ } else if (type === "element") {
2005
+ var elementScope = this.getElementScope(context);
2006
+ elementScope[str] = value;
2007
+ } else if (type === "local") {
2008
+ context.locals[str] = value;
2009
+ } else {
2010
+ if (this.isHyperscriptContext(context) && !this.isReservedWord(str) && typeof context.locals[str] !== "undefined") {
2011
+ // local scope
2012
+ context.locals[str] = value;
2013
+ } else {
2014
+ // element scope
2015
+ var elementScope = this.getElementScope(context);
2016
+ var fromContext = elementScope[str];
2017
+ if (typeof fromContext !== "undefined") {
2018
+ elementScope[str] = value;
2019
+ } else {
2020
+ if (this.isHyperscriptContext(context) && !this.isReservedWord(str)) {
2021
+ // local scope
2022
+ context.locals[str] = value;
2023
+ } else {
2024
+ // direct set on normal JS object or top-level of context
2025
+ context[str] = value;
2026
+ }
2027
+ }
2028
+ }
2029
+ }
2030
+ }
2031
+
2032
+ /**
2033
+ * @param {ASTNode} command
2034
+ * @param {Context} context
2035
+ * @returns {undefined | ASTNode}
2036
+ */
2037
+ findNext(command, context) {
2038
+ if (command) {
2039
+ if (command.resolveNext) {
2040
+ return command.resolveNext(context);
2041
+ } else if (command.next) {
2042
+ return command.next;
2043
+ } else {
2044
+ return this.findNext(command.parent, context);
2045
+ }
2046
+ }
2047
+ }
2048
+
2049
+ /**
2050
+ * @param {Object<string,any>} root
2051
+ * @param {string} property
2052
+ * @param {Getter} getter
2053
+ * @returns {any}
2054
+ *
2055
+ * @callback Getter
2056
+ * @param {Object<string,any>} root
2057
+ * @param {string} property
2058
+ */
2059
+ flatGet(root, property, getter) {
2060
+ if (root != null) {
2061
+ var val = getter(root, property);
2062
+ if (typeof val !== "undefined") {
2063
+ return val;
2064
+ }
2065
+
2066
+ if (this.shouldAutoIterate(root)) {
2067
+ // flat map
2068
+ var result = [];
2069
+ for (var component of root) {
2070
+ var componentValue = getter(component, property);
2071
+ result.push(componentValue);
2072
+ }
2073
+ return result;
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ resolveProperty(root, property) {
2079
+ return this.flatGet(root, property, (root, property) => root[property] )
2080
+ }
2081
+
2082
+ resolveAttribute(root, property) {
2083
+ return this.flatGet(root, property, (root, property) => root.getAttribute && root.getAttribute(property) )
2084
+ }
2085
+
2086
+ /**
2087
+ *
2088
+ * @param {Object<string, any>} root
2089
+ * @param {string} property
2090
+ * @returns {string}
2091
+ */
2092
+ resolveStyle(root, property) {
2093
+ return this.flatGet(root, property, (root, property) => root.style && root.style[property] )
2094
+ }
2095
+
2096
+ /**
2097
+ *
2098
+ * @param {Object<string, any>} root
2099
+ * @param {string} property
2100
+ * @returns {string}
2101
+ */
2102
+ resolveComputedStyle(root, property) {
2103
+ return this.flatGet(root, property, (root, property) => getComputedStyle(
2104
+ /** @type {Element} */ (root)).getPropertyValue(property) )
2105
+ }
2106
+
2107
+ /**
2108
+ * @param {Element} elt
2109
+ * @param {string[]} nameSpace
2110
+ * @param {string} name
2111
+ * @param {any} value
2112
+ */
2113
+ assignToNamespace(elt, nameSpace, name, value) {
2114
+ let root
2115
+ if (typeof document !== "undefined" && elt === document.body) {
2116
+ root = globalScope;
2117
+ } else {
2118
+ root = this.getHyperscriptFeatures(elt);
2119
+ }
2120
+ while (nameSpace.length > 0) {
2121
+ var propertyName = nameSpace.shift();
2122
+ var newRoot = root[propertyName];
2123
+ if (newRoot == null) {
2124
+ newRoot = {};
2125
+ root[propertyName] = newRoot;
2126
+ }
2127
+ root = newRoot;
2128
+ }
2129
+
2130
+ root[name] = value;
2131
+ }
2132
+
2133
+ getHyperTrace(ctx, thrown) {
2134
+ var trace = [];
2135
+ var root = ctx;
2136
+ while (root.meta.caller) {
2137
+ root = root.meta.caller;
2138
+ }
2139
+ if (root.meta.traceMap) {
2140
+ return root.meta.traceMap.get(thrown, trace);
2141
+ }
2142
+ }
2143
+
2144
+ registerHyperTrace(ctx, thrown) {
2145
+ var trace = [];
2146
+ var root = null;
2147
+ while (ctx != null) {
2148
+ trace.push(ctx);
2149
+ root = ctx;
2150
+ ctx = ctx.meta.caller;
2151
+ }
2152
+ if (root.meta.traceMap == null) {
2153
+ root.meta.traceMap = new Map(); // TODO - WeakMap?
2154
+ }
2155
+ if (!root.meta.traceMap.get(thrown)) {
2156
+ var traceEntry = {
2157
+ trace: trace,
2158
+ print: function (logger) {
2159
+ logger = logger || console.error;
2160
+ logger("hypertrace /// ");
2161
+ var maxLen = 0;
2162
+ for (var i = 0; i < trace.length; i++) {
2163
+ maxLen = Math.max(maxLen, trace[i].meta.feature.displayName.length);
2164
+ }
2165
+ for (var i = 0; i < trace.length; i++) {
2166
+ var traceElt = trace[i];
2167
+ logger(
2168
+ " ->",
2169
+ traceElt.meta.feature.displayName.padEnd(maxLen + 2),
2170
+ "-",
2171
+ traceElt.meta.owner
2172
+ );
2173
+ }
2174
+ },
2175
+ };
2176
+ root.meta.traceMap.set(thrown, traceEntry);
2177
+ }
2178
+ }
2179
+
2180
+ /**
2181
+ * @param {string} str
2182
+ * @returns {string}
2183
+ */
2184
+ escapeSelector(str) {
2185
+ return str.replace(/:/g, function (str) {
2186
+ return "\\" + str;
2187
+ });
2188
+ }
2189
+
2190
+ /**
2191
+ * @param {any} value
2192
+ * @param {*} elt
2193
+ */
2194
+ nullCheck(value, elt) {
2195
+ if (value == null) {
2196
+ throw new Error("'" + elt.sourceFor() + "' is null");
2197
+ }
2198
+ }
2199
+
2200
+ /**
2201
+ * @param {any} value
2202
+ * @returns {boolean}
2203
+ */
2204
+ isEmpty(value) {
2205
+ return value == undefined || value.length === 0;
2206
+ }
2207
+
2208
+ /**
2209
+ * @param {any} value
2210
+ * @returns {boolean}
2211
+ */
2212
+ doesExist(value) {
2213
+ if(value == null){
2214
+ return false;
2215
+ }
2216
+ if (this.shouldAutoIterate(value)) {
2217
+ for (const elt of value) {
2218
+ return true;
2219
+ }
2220
+ }
2221
+ return false;
2222
+ }
2223
+
2224
+ /**
2225
+ * @param {Node} node
2226
+ * @returns {Document|ShadowRoot}
2227
+ */
2228
+ getRootNode(node) {
2229
+ if (node && node instanceof Node) {
2230
+ var rv = node.getRootNode();
2231
+ if (rv instanceof Document || rv instanceof ShadowRoot) return rv;
2232
+ }
2233
+ return document;
2234
+ }
2235
+
2236
+ /**
2237
+ *
2238
+ * @param {Element} elt
2239
+ * @param {ASTNode} onFeature
2240
+ * @returns {EventQueue}
2241
+ *
2242
+ * @typedef {{queue:Array, executing:boolean}} EventQueue
2243
+ */
2244
+ getEventQueueFor(elt, onFeature) {
2245
+ let internalData = this.getInternalData(elt);
2246
+ var eventQueuesForElt = internalData.eventQueues;
2247
+ if (eventQueuesForElt == null) {
2248
+ eventQueuesForElt = new Map();
2249
+ internalData.eventQueues = eventQueuesForElt;
2250
+ }
2251
+ var eventQueueForFeature = eventQueuesForElt.get(onFeature);
2252
+ if (eventQueueForFeature == null) {
2253
+ eventQueueForFeature = {queue:[], executing:false};
2254
+ eventQueuesForElt.set(onFeature, eventQueueForFeature);
2255
+ }
2256
+ return eventQueueForFeature;
2257
+ }
2258
+
2259
+ /** @type string | null */
2260
+ // @ts-ignore
2261
+ hyperscriptUrl = "document" in globalScope ? document.currentScript.src : null;
2262
+ }
2263
+
2264
+ class Context {
2265
+ /**
2266
+ * @param {*} owner
2267
+ * @param {*} feature
2268
+ * @param {*} hyperscriptTarget
2269
+ * @param {*} event
2270
+ */
2271
+ constructor(owner, feature, hyperscriptTarget, event, runtime) {
2272
+ this.meta = {
2273
+ parser: runtime.parser,
2274
+ lexer: runtime.lexer,
2275
+ runtime,
2276
+ owner: owner,
2277
+ feature: feature,
2278
+ iterators: {},
2279
+ ctx: this
2280
+ }
2281
+ this.locals = {};
2282
+ this.me = hyperscriptTarget,
2283
+ this.you = undefined
2284
+ this.result = undefined
2285
+ this.event = event;
2286
+ this.target = event ? event.target : null;
2287
+ this.detail = event ? event.detail : null;
2288
+ this.sender = event ? event.detail ? event.detail.sender : null : null;
2289
+ this.body = "document" in globalScope ? document.body : null;
2290
+ runtime.addFeatures(owner, this);
2291
+ }
2292
+ }
2293
+
2294
+ class ElementCollection {
2295
+ constructor(css, relativeToElement, escape) {
2296
+ this._css = css;
2297
+ this.relativeToElement = relativeToElement;
2298
+ this.escape = escape;
2299
+ this[shouldAutoIterateSymbol] = true;
2300
+ }
2301
+
2302
+ get css() {
2303
+ if (this.escape) {
2304
+ return Runtime.prototype.escapeSelector(this._css);
2305
+ } else {
2306
+ return this._css;
2307
+ }
2308
+ }
2309
+
2310
+ get className() {
2311
+ return this._css.substr(1);
2312
+ }
2313
+
2314
+ get id() {
2315
+ return this.className();
2316
+ }
2317
+
2318
+ contains(elt) {
2319
+ for (let element of this) {
2320
+ if (element.contains(elt)) {
2321
+ return true;
2322
+ }
2323
+ }
2324
+ return false;
2325
+ }
2326
+
2327
+ get length() {
2328
+ return this.selectMatches().length;
2329
+ }
2330
+
2331
+ [Symbol.iterator]() {
2332
+ let query = this.selectMatches();
2333
+ return query [Symbol.iterator]();
2334
+ }
2335
+
2336
+ selectMatches() {
2337
+ let query = Runtime.prototype.getRootNode(this.relativeToElement).querySelectorAll(this.css);
2338
+ return query;
2339
+ }
2340
+ }
2341
+
2342
+ const shouldAutoIterateSymbol = Symbol()
2343
+
2344
+ function getOrInitObject(root, prop) {
2345
+ var value = root[prop];
2346
+ if (value) {
2347
+ return value;
2348
+ } else {
2349
+ var newObj = {};
2350
+ root[prop] = newObj;
2351
+ return newObj;
2352
+ }
2353
+ }
2354
+
2355
+ /**
2356
+ * parseJSON parses a JSON string into a corresponding value. If the
2357
+ * value passed in is not valid JSON, then it logs an error and returns `null`.
2358
+ *
2359
+ * @param {string} jString
2360
+ * @returns any
2361
+ */
2362
+ function parseJSON(jString) {
2363
+ try {
2364
+ return JSON.parse(jString);
2365
+ } catch (error) {
2366
+ logError(error);
2367
+ return null;
2368
+ }
2369
+ }
2370
+
2371
+ /**
2372
+ * logError writes an error message to the Javascript console. It can take any
2373
+ * value, but msg should commonly be a simple string.
2374
+ * @param {*} msg
2375
+ */
2376
+ function logError(msg) {
2377
+ if (console.error) {
2378
+ console.error(msg);
2379
+ } else if (console.log) {
2380
+ console.log("ERROR: ", msg);
2381
+ }
2382
+ }
2383
+
2384
+ // TODO: JSDoc description of what's happening here
2385
+ function varargConstructor(Cls, args) {
2386
+ return new (Cls.bind.apply(Cls, [Cls].concat(args)))();
2387
+ }
2388
+
2389
+ // Grammar
2390
+
2391
+ /**
2392
+ * @param {Parser} parser
2393
+ */
2394
+ function hyperscriptCoreGrammar(parser) {
2395
+ parser.addLeafExpression("parenthesized", function (parser, _runtime, tokens) {
2396
+ if (tokens.matchOpToken("(")) {
2397
+ var follows = tokens.clearFollows();
2398
+ try {
2399
+ var expr = parser.requireElement("expression", tokens);
2400
+ } finally {
2401
+ tokens.restoreFollows(follows);
2402
+ }
2403
+ tokens.requireOpToken(")");
2404
+ return expr;
2405
+ }
2406
+ });
2407
+
2408
+ parser.addLeafExpression("string", function (parser, runtime, tokens) {
2409
+ var stringToken = tokens.matchTokenType("STRING");
2410
+ if (!stringToken) return;
2411
+ var rawValue = stringToken.value;
2412
+ /** @type {any[]} */
2413
+ var args;
2414
+ if (stringToken.template) {
2415
+ var innerTokens = Lexer.tokenize(rawValue, true);
2416
+ args = parser.parseStringTemplate(innerTokens);
2417
+ } else {
2418
+ args = [];
2419
+ }
2420
+ return {
2421
+ type: "string",
2422
+ token: stringToken,
2423
+ args: args,
2424
+ op: function (context) {
2425
+ var returnStr = "";
2426
+ for (var i = 1; i < arguments.length; i++) {
2427
+ var val = arguments[i];
2428
+ if (val !== undefined) {
2429
+ returnStr += val;
2430
+ }
2431
+ }
2432
+ return returnStr;
2433
+ },
2434
+ evaluate: function (context) {
2435
+ if (args.length === 0) {
2436
+ return rawValue;
2437
+ } else {
2438
+ return runtime.unifiedEval(this, context);
2439
+ }
2440
+ },
2441
+ };
2442
+ });
2443
+
2444
+ parser.addGrammarElement("nakedString", function (parser, runtime, tokens) {
2445
+ if (tokens.hasMore()) {
2446
+ var tokenArr = tokens.consumeUntilWhitespace();
2447
+ tokens.matchTokenType("WHITESPACE");
2448
+ return {
2449
+ type: "nakedString",
2450
+ tokens: tokenArr,
2451
+ evaluate: function (context) {
2452
+ return tokenArr
2453
+ .map(function (t) {
2454
+ return t.value;
2455
+ })
2456
+ .join("");
2457
+ },
2458
+ };
2459
+ }
2460
+ });
2461
+
2462
+ parser.addLeafExpression("number", function (parser, runtime, tokens) {
2463
+ var number = tokens.matchTokenType("NUMBER");
2464
+ if (!number) return;
2465
+ var numberToken = number;
2466
+ var value = parseFloat(number.value);
2467
+ return {
2468
+ type: "number",
2469
+ value: value,
2470
+ numberToken: numberToken,
2471
+ evaluate: function () {
2472
+ return value;
2473
+ },
2474
+ };
2475
+ });
2476
+
2477
+ parser.addLeafExpression("idRef", function (parser, runtime, tokens) {
2478
+ var elementId = tokens.matchTokenType("ID_REF");
2479
+ if (!elementId) return;
2480
+ // TODO - unify these two expression types
2481
+ if (elementId.template) {
2482
+ var templateValue = elementId.value.substr(2, elementId.value.length - 2);
2483
+ var innerTokens = Lexer.tokenize(templateValue);
2484
+ var innerExpression = parser.requireElement("expression", innerTokens);
2485
+ return {
2486
+ type: "idRefTemplate",
2487
+ args: [innerExpression],
2488
+ op: function (context, arg) {
2489
+ return runtime.getRootNode(context.me).getElementById(arg);
2490
+ },
2491
+ evaluate: function (context) {
2492
+ return runtime.unifiedEval(this, context);
2493
+ },
2494
+ };
2495
+ } else {
2496
+ const value = elementId.value.substr(1);
2497
+ return {
2498
+ type: "idRef",
2499
+ css: elementId.value,
2500
+ value: value,
2501
+ evaluate: function (context) {
2502
+ return (
2503
+ runtime.getRootNode(context.me).getElementById(value)
2504
+ );
2505
+ },
2506
+ };
2507
+ }
2508
+ });
2509
+
2510
+ parser.addLeafExpression("classRef", function (parser, runtime, tokens) {
2511
+ var classRef = tokens.matchTokenType("CLASS_REF");
2512
+
2513
+ if (!classRef) return;
2514
+
2515
+ // TODO - unify these two expression types
2516
+ if (classRef.template) {
2517
+ var templateValue = classRef.value.substr(2, classRef.value.length - 2);
2518
+ var innerTokens = Lexer.tokenize(templateValue);
2519
+ var innerExpression = parser.requireElement("expression", innerTokens);
2520
+ return {
2521
+ type: "classRefTemplate",
2522
+ args: [innerExpression],
2523
+ op: function (context, arg) {
2524
+ return new ElementCollection("." + arg, context.me, true)
2525
+ },
2526
+ evaluate: function (context) {
2527
+ return runtime.unifiedEval(this, context);
2528
+ },
2529
+ };
2530
+ } else {
2531
+ const css = classRef.value;
2532
+ return {
2533
+ type: "classRef",
2534
+ css: css,
2535
+ evaluate: function (context) {
2536
+ return new ElementCollection(css, context.me, true)
2537
+ },
2538
+ };
2539
+ }
2540
+ });
2541
+
2542
+ class TemplatedQueryElementCollection extends ElementCollection {
2543
+ constructor(css, relativeToElement, templateParts) {
2544
+ super(css, relativeToElement);
2545
+ this.templateParts = templateParts;
2546
+ this.elements = templateParts.filter(elt => elt instanceof Element);
2547
+ }
2548
+
2549
+ get css() {
2550
+ let rv = "", i = 0
2551
+ for (const val of this.templateParts) {
2552
+ if (val instanceof Element) {
2553
+ rv += "[data-hs-query-id='" + i++ + "']";
2554
+ } else rv += val;
2555
+ }
2556
+ return rv;
2557
+ }
2558
+
2559
+ [Symbol.iterator]() {
2560
+ this.elements.forEach((el, i) => el.dataset.hsQueryId = i);
2561
+ const rv = super[Symbol.iterator]();
2562
+ this.elements.forEach(el => el.removeAttribute('data-hs-query-id'));
2563
+ return rv;
2564
+ }
2565
+ }
2566
+
2567
+ parser.addLeafExpression("queryRef", function (parser, runtime, tokens) {
2568
+ var queryStart = tokens.matchOpToken("<");
2569
+ if (!queryStart) return;
2570
+ var queryTokens = tokens.consumeUntil("/");
2571
+ tokens.requireOpToken("/");
2572
+ tokens.requireOpToken(">");
2573
+ var queryValue = queryTokens
2574
+ .map(function (t) {
2575
+ if (t.type === "STRING") {
2576
+ return '"' + t.value + '"';
2577
+ } else {
2578
+ return t.value;
2579
+ }
2580
+ })
2581
+ .join("");
2582
+
2583
+ if (queryValue.indexOf("$") >= 0) {
2584
+ var template = true;
2585
+ var innerTokens = Lexer.tokenize(queryValue, true);
2586
+ var args = parser.parseStringTemplate(innerTokens);
2587
+ }
2588
+
2589
+ return {
2590
+ type: "queryRef",
2591
+ css: queryValue,
2592
+ args: args,
2593
+ op: function (context, ...args) {
2594
+ if (template) {
2595
+ return new TemplatedQueryElementCollection(queryValue, context.me, args)
2596
+ } else {
2597
+ return new ElementCollection(queryValue, context.me)
2598
+ }
2599
+ },
2600
+ evaluate: function (context) {
2601
+ return runtime.unifiedEval(this, context);
2602
+ },
2603
+ };
2604
+ });
2605
+
2606
+ parser.addLeafExpression("attributeRef", function (parser, runtime, tokens) {
2607
+ var attributeRef = tokens.matchTokenType("ATTRIBUTE_REF");
2608
+ if (!attributeRef) return;
2609
+ var outerVal = attributeRef.value;
2610
+ if (outerVal.indexOf("[") === 0) {
2611
+ var innerValue = outerVal.substring(2, outerVal.length - 1);
2612
+ } else {
2613
+ var innerValue = outerVal.substring(1);
2614
+ }
2615
+ var css = "[" + innerValue + "]";
2616
+ var split = innerValue.split("=");
2617
+ var name = split[0];
2618
+ var value = split[1];
2619
+ if (value) {
2620
+ // strip quotes
2621
+ if (value.indexOf('"') === 0) {
2622
+ value = value.substring(1, value.length - 1);
2623
+ }
2624
+ }
2625
+ return {
2626
+ type: "attributeRef",
2627
+ name: name,
2628
+ css: css,
2629
+ value: value,
2630
+ op: function (context) {
2631
+ var target = context.you || context.me;
2632
+ if (target) {
2633
+ return target.getAttribute(name);
2634
+ }
2635
+ },
2636
+ evaluate: function (context) {
2637
+ return runtime.unifiedEval(this, context);
2638
+ },
2639
+ };
2640
+ });
2641
+
2642
+ parser.addLeafExpression("styleRef", function (parser, runtime, tokens) {
2643
+ var styleRef = tokens.matchTokenType("STYLE_REF");
2644
+ if (!styleRef) return;
2645
+ var styleProp = styleRef.value.substr(1);
2646
+ if (styleProp.startsWith("computed-")) {
2647
+ styleProp = styleProp.substr("computed-".length);
2648
+ return {
2649
+ type: "computedStyleRef",
2650
+ name: styleProp,
2651
+ op: function (context) {
2652
+ var target = context.you || context.me;
2653
+ if (target) {
2654
+ return runtime.resolveComputedStyle(target, styleProp);
2655
+ }
2656
+ },
2657
+ evaluate: function (context) {
2658
+ return runtime.unifiedEval(this, context);
2659
+ },
2660
+ };
2661
+ } else {
2662
+ return {
2663
+ type: "styleRef",
2664
+ name: styleProp,
2665
+ op: function (context) {
2666
+ var target = context.you || context.me;
2667
+ if (target) {
2668
+ return runtime.resolveStyle(target, styleProp);
2669
+ }
2670
+ },
2671
+ evaluate: function (context) {
2672
+ return runtime.unifiedEval(this, context);
2673
+ },
2674
+ };
2675
+ }
2676
+ });
2677
+
2678
+ parser.addGrammarElement("objectKey", function (parser, runtime, tokens) {
2679
+ var token;
2680
+ if ((token = tokens.matchTokenType("STRING"))) {
2681
+ return {
2682
+ type: "objectKey",
2683
+ key: token.value,
2684
+ evaluate: function () {
2685
+ return token.value;
2686
+ },
2687
+ };
2688
+ } else if (tokens.matchOpToken("[")) {
2689
+ var expr = parser.parseElement("expression", tokens);
2690
+ tokens.requireOpToken("]");
2691
+ return {
2692
+ type: "objectKey",
2693
+ expr: expr,
2694
+ args: [expr],
2695
+ op: function (ctx, expr) {
2696
+ return expr;
2697
+ },
2698
+ evaluate: function (context) {
2699
+ return runtime.unifiedEval(this, context);
2700
+ },
2701
+ };
2702
+ } else {
2703
+ var key = "";
2704
+ do {
2705
+ token = tokens.matchTokenType("IDENTIFIER") || tokens.matchOpToken("-");
2706
+ if (token) key += token.value;
2707
+ } while (token);
2708
+ return {
2709
+ type: "objectKey",
2710
+ key: key,
2711
+ evaluate: function () {
2712
+ return key;
2713
+ },
2714
+ };
2715
+ }
2716
+ });
2717
+
2718
+ parser.addLeafExpression("objectLiteral", function (parser, runtime, tokens) {
2719
+ if (!tokens.matchOpToken("{")) return;
2720
+ var keyExpressions = [];
2721
+ var valueExpressions = [];
2722
+ if (!tokens.matchOpToken("}")) {
2723
+ do {
2724
+ var name = parser.requireElement("objectKey", tokens);
2725
+ tokens.requireOpToken(":");
2726
+ var value = parser.requireElement("expression", tokens);
2727
+ valueExpressions.push(value);
2728
+ keyExpressions.push(name);
2729
+ } while (tokens.matchOpToken(","));
2730
+ tokens.requireOpToken("}");
2731
+ }
2732
+ return {
2733
+ type: "objectLiteral",
2734
+ args: [keyExpressions, valueExpressions],
2735
+ op: function (context, keys, values) {
2736
+ var returnVal = {};
2737
+ for (var i = 0; i < keys.length; i++) {
2738
+ returnVal[keys[i]] = values[i];
2739
+ }
2740
+ return returnVal;
2741
+ },
2742
+ evaluate: function (context) {
2743
+ return runtime.unifiedEval(this, context);
2744
+ },
2745
+ };
2746
+ });
2747
+
2748
+ parser.addGrammarElement("nakedNamedArgumentList", function (parser, runtime, tokens) {
2749
+ var fields = [];
2750
+ var valueExpressions = [];
2751
+ if (tokens.currentToken().type === "IDENTIFIER") {
2752
+ do {
2753
+ var name = tokens.requireTokenType("IDENTIFIER");
2754
+ tokens.requireOpToken(":");
2755
+ var value = parser.requireElement("expression", tokens);
2756
+ valueExpressions.push(value);
2757
+ fields.push({ name: name, value: value });
2758
+ } while (tokens.matchOpToken(","));
2759
+ }
2760
+ return {
2761
+ type: "namedArgumentList",
2762
+ fields: fields,
2763
+ args: [valueExpressions],
2764
+ op: function (context, values) {
2765
+ var returnVal = { _namedArgList_: true };
2766
+ for (var i = 0; i < values.length; i++) {
2767
+ var field = fields[i];
2768
+ returnVal[field.name.value] = values[i];
2769
+ }
2770
+ return returnVal;
2771
+ },
2772
+ evaluate: function (context) {
2773
+ return runtime.unifiedEval(this, context);
2774
+ },
2775
+ };
2776
+ });
2777
+
2778
+ parser.addGrammarElement("namedArgumentList", function (parser, runtime, tokens) {
2779
+ if (!tokens.matchOpToken("(")) return;
2780
+ var elt = parser.requireElement("nakedNamedArgumentList", tokens);
2781
+ tokens.requireOpToken(")");
2782
+ return elt;
2783
+ });
2784
+
2785
+ parser.addGrammarElement("symbol", function (parser, runtime, tokens) {
2786
+ /** @scope {SymbolScope} */
2787
+ var scope = "default";
2788
+ if (tokens.matchToken("global")) {
2789
+ scope = "global";
2790
+ } else if (tokens.matchToken("element") || tokens.matchToken("module")) {
2791
+ scope = "element";
2792
+ // optional possessive
2793
+ if (tokens.matchOpToken("'")) {
2794
+ tokens.requireToken("s");
2795
+ }
2796
+ } else if (tokens.matchToken("local")) {
2797
+ scope = "local";
2798
+ }
2799
+
2800
+ // TODO better look ahead here
2801
+ let eltPrefix = tokens.matchOpToken(":");
2802
+ let identifier = tokens.matchTokenType("IDENTIFIER");
2803
+ if (identifier) {
2804
+ var name = identifier.value;
2805
+ if (eltPrefix) {
2806
+ name = ":" + name;
2807
+ }
2808
+ if (scope === "default") {
2809
+ if (name.indexOf("$") === 0) {
2810
+ scope = "global";
2811
+ }
2812
+ if (name.indexOf(":") === 0) {
2813
+ scope = "element";
2814
+ }
2815
+ }
2816
+ return {
2817
+ type: "symbol",
2818
+ token: identifier,
2819
+ scope: scope,
2820
+ name: name,
2821
+ evaluate: function (context) {
2822
+ return runtime.resolveSymbol(name, context, scope);
2823
+ },
2824
+ };
2825
+ }
2826
+ });
2827
+
2828
+ parser.addGrammarElement("implicitMeTarget", function (parser, runtime, tokens) {
2829
+ return {
2830
+ type: "implicitMeTarget",
2831
+ evaluate: function (context) {
2832
+ return context.you || context.me;
2833
+ },
2834
+ };
2835
+ });
2836
+
2837
+ parser.addLeafExpression("boolean", function (parser, runtime, tokens) {
2838
+ var booleanLiteral = tokens.matchToken("true") || tokens.matchToken("false");
2839
+ if (!booleanLiteral) return;
2840
+ const value = booleanLiteral.value === "true";
2841
+ return {
2842
+ type: "boolean",
2843
+ evaluate: function (context) {
2844
+ return value;
2845
+ },
2846
+ };
2847
+ });
2848
+
2849
+ parser.addLeafExpression("null", function (parser, runtime, tokens) {
2850
+ if (tokens.matchToken("null")) {
2851
+ return {
2852
+ type: "null",
2853
+ evaluate: function (context) {
2854
+ return null;
2855
+ },
2856
+ };
2857
+ }
2858
+ });
2859
+
2860
+ parser.addLeafExpression("arrayLiteral", function (parser, runtime, tokens) {
2861
+ if (!tokens.matchOpToken("[")) return;
2862
+ var values = [];
2863
+ if (!tokens.matchOpToken("]")) {
2864
+ do {
2865
+ var expr = parser.requireElement("expression", tokens);
2866
+ values.push(expr);
2867
+ } while (tokens.matchOpToken(","));
2868
+ tokens.requireOpToken("]");
2869
+ }
2870
+ return {
2871
+ type: "arrayLiteral",
2872
+ values: values,
2873
+ args: [values],
2874
+ op: function (context, values) {
2875
+ return values;
2876
+ },
2877
+ evaluate: function (context) {
2878
+ return runtime.unifiedEval(this, context);
2879
+ },
2880
+ };
2881
+ });
2882
+
2883
+ parser.addLeafExpression("blockLiteral", function (parser, runtime, tokens) {
2884
+ if (!tokens.matchOpToken("\\")) return;
2885
+ var args = [];
2886
+ var arg1 = tokens.matchTokenType("IDENTIFIER");
2887
+ if (arg1) {
2888
+ args.push(arg1);
2889
+ while (tokens.matchOpToken(",")) {
2890
+ args.push(tokens.requireTokenType("IDENTIFIER"));
2891
+ }
2892
+ }
2893
+ // TODO compound op token
2894
+ tokens.requireOpToken("-");
2895
+ tokens.requireOpToken(">");
2896
+ var expr = parser.requireElement("expression", tokens);
2897
+ return {
2898
+ type: "blockLiteral",
2899
+ args: args,
2900
+ expr: expr,
2901
+ evaluate: function (ctx) {
2902
+ var returnFunc = function () {
2903
+ //TODO - push scope
2904
+ for (var i = 0; i < args.length; i++) {
2905
+ ctx.locals[args[i].value] = arguments[i];
2906
+ }
2907
+ return expr.evaluate(ctx); //OK
2908
+ };
2909
+ return returnFunc;
2910
+ },
2911
+ };
2912
+ });
2913
+
2914
+ parser.addIndirectExpression("propertyAccess", function (parser, runtime, tokens, root) {
2915
+ if (!tokens.matchOpToken(".")) return;
2916
+ var prop = tokens.requireTokenType("IDENTIFIER");
2917
+ var propertyAccess = {
2918
+ type: "propertyAccess",
2919
+ root: root,
2920
+ prop: prop,
2921
+ args: [root],
2922
+ op: function (_context, rootVal) {
2923
+ var value = runtime.resolveProperty(rootVal, prop.value);
2924
+ return value;
2925
+ },
2926
+ evaluate: function (context) {
2927
+ return runtime.unifiedEval(this, context);
2928
+ },
2929
+ };
2930
+ return parser.parseElement("indirectExpression", tokens, propertyAccess);
2931
+ });
2932
+
2933
+ parser.addIndirectExpression("of", function (parser, runtime, tokens, root) {
2934
+ if (!tokens.matchToken("of")) return;
2935
+ var newRoot = parser.requireElement("unaryExpression", tokens);
2936
+ // find the urroot
2937
+ var childOfUrRoot = null;
2938
+ var urRoot = root;
2939
+ while (urRoot.root) {
2940
+ childOfUrRoot = urRoot;
2941
+ urRoot = urRoot.root;
2942
+ }
2943
+ if (urRoot.type !== "symbol" && urRoot.type !== "attributeRef" && urRoot.type !== "styleRef" && urRoot.type !== "computedStyleRef") {
2944
+ parser.raiseParseError(tokens, "Cannot take a property of a non-symbol: " + urRoot.type);
2945
+ }
2946
+ var attribute = urRoot.type === "attributeRef";
2947
+ var style = urRoot.type === "styleRef" || urRoot.type === "computedStyleRef";
2948
+ if (attribute || style) {
2949
+ var attributeElt = urRoot
2950
+ }
2951
+ var prop = urRoot.name;
2952
+
2953
+ var propertyAccess = {
2954
+ type: "ofExpression",
2955
+ prop: urRoot.token,
2956
+ root: newRoot,
2957
+ attribute: attributeElt,
2958
+ expression: root,
2959
+ args: [newRoot],
2960
+ op: function (context, rootVal) {
2961
+ if (attribute) {
2962
+ return runtime.resolveAttribute(rootVal, prop);
2963
+ } else if (style) {
2964
+ if (urRoot.type === "computedStyleRef") {
2965
+ return runtime.resolveComputedStyle(rootVal, prop);
2966
+ } else {
2967
+ return runtime.resolveStyle(rootVal, prop);
2968
+ }
2969
+ } else {
2970
+ return runtime.resolveProperty(rootVal, prop);
2971
+ }
2972
+ },
2973
+ evaluate: function (context) {
2974
+ return runtime.unifiedEval(this, context);
2975
+ },
2976
+ };
2977
+
2978
+ if (urRoot.type === "attributeRef") {
2979
+ propertyAccess.attribute = urRoot;
2980
+ }
2981
+ if (childOfUrRoot) {
2982
+ childOfUrRoot.root = propertyAccess;
2983
+ childOfUrRoot.args = [propertyAccess];
2984
+ } else {
2985
+ root = propertyAccess;
2986
+ }
2987
+
2988
+ return parser.parseElement("indirectExpression", tokens, root);
2989
+ });
2990
+
2991
+ parser.addIndirectExpression("possessive", function (parser, runtime, tokens, root) {
2992
+ if (parser.possessivesDisabled) {
2993
+ return;
2994
+ }
2995
+ var apostrophe = tokens.matchOpToken("'");
2996
+ if (
2997
+ apostrophe ||
2998
+ (root.type === "symbol" &&
2999
+ (root.name === "my" || root.name === "its" || root.name === "your") &&
3000
+ (tokens.currentToken().type === "IDENTIFIER" || tokens.currentToken().type === "ATTRIBUTE_REF" || tokens.currentToken().type === "STYLE_REF"))
3001
+ ) {
3002
+ if (apostrophe) {
3003
+ tokens.requireToken("s");
3004
+ }
3005
+ var attribute = parser.parseElement("attributeRef", tokens);
3006
+ if (attribute == null) {
3007
+ var style = parser.parseElement("styleRef", tokens);
3008
+ if (style == null) {
3009
+ var prop = tokens.requireTokenType("IDENTIFIER");
3010
+ }
3011
+ }
3012
+ var propertyAccess = {
3013
+ type: "possessive",
3014
+ root: root,
3015
+ attribute: attribute || style,
3016
+ prop: prop,
3017
+ args: [root],
3018
+ op: function (context, rootVal) {
3019
+ if (attribute) {
3020
+ // @ts-ignore
3021
+ var value = runtime.resolveAttribute(rootVal, attribute.name);
3022
+ } else if (style) {
3023
+ var value
3024
+ if (style.type === 'computedStyleRef') {
3025
+ value = runtime.resolveComputedStyle(rootVal, style['name']);
3026
+ } else {
3027
+ value = runtime.resolveStyle(rootVal, style['name']);
3028
+ }
3029
+ } else {
3030
+ var value = runtime.resolveProperty(rootVal, prop.value);
3031
+ }
3032
+ return value;
3033
+ },
3034
+ evaluate: function (context) {
3035
+ return runtime.unifiedEval(this, context);
3036
+ },
3037
+ };
3038
+ return parser.parseElement("indirectExpression", tokens, propertyAccess);
3039
+ }
3040
+ });
3041
+
3042
+ parser.addIndirectExpression("inExpression", function (parser, runtime, tokens, root) {
3043
+ if (!tokens.matchToken("in")) return;
3044
+ var target = parser.requireElement("unaryExpression", tokens);
3045
+ var propertyAccess = {
3046
+ type: "inExpression",
3047
+ root: root,
3048
+ args: [root, target],
3049
+ op: function (context, rootVal, target) {
3050
+ var returnArr = [];
3051
+ if (rootVal.css) {
3052
+ runtime.implicitLoop(target, function (targetElt) {
3053
+ var results = targetElt.querySelectorAll(rootVal.css);
3054
+ for (var i = 0; i < results.length; i++) {
3055
+ returnArr.push(results[i]);
3056
+ }
3057
+ });
3058
+ } else if (rootVal instanceof Element) {
3059
+ var within = false;
3060
+ runtime.implicitLoop(target, function (targetElt) {
3061
+ if (targetElt.contains(rootVal)) {
3062
+ within = true;
3063
+ }
3064
+ });
3065
+ if(within) {
3066
+ return rootVal;
3067
+ }
3068
+ } else {
3069
+ runtime.implicitLoop(rootVal, function (rootElt) {
3070
+ runtime.implicitLoop(target, function (targetElt) {
3071
+ if (rootElt === targetElt) {
3072
+ returnArr.push(rootElt);
3073
+ }
3074
+ });
3075
+ });
3076
+ }
3077
+ return returnArr;
3078
+ },
3079
+ evaluate: function (context) {
3080
+ return runtime.unifiedEval(this, context);
3081
+ },
3082
+ };
3083
+ return parser.parseElement("indirectExpression", tokens, propertyAccess);
3084
+ });
3085
+
3086
+ parser.addIndirectExpression("asExpression", function (parser, runtime, tokens, root) {
3087
+ if (!tokens.matchToken("as")) return;
3088
+ tokens.matchToken("a") || tokens.matchToken("an");
3089
+ var conversion = parser.requireElement("dotOrColonPath", tokens).evaluate(); // OK No promise
3090
+ var propertyAccess = {
3091
+ type: "asExpression",
3092
+ root: root,
3093
+ args: [root],
3094
+ op: function (context, rootVal) {
3095
+ return runtime.convertValue(rootVal, conversion);
3096
+ },
3097
+ evaluate: function (context) {
3098
+ return runtime.unifiedEval(this, context);
3099
+ },
3100
+ };
3101
+ return parser.parseElement("indirectExpression", tokens, propertyAccess);
3102
+ });
3103
+
3104
+ parser.addIndirectExpression("functionCall", function (parser, runtime, tokens, root) {
3105
+ if (!tokens.matchOpToken("(")) return;
3106
+ var args = [];
3107
+ if (!tokens.matchOpToken(")")) {
3108
+ do {
3109
+ args.push(parser.requireElement("expression", tokens));
3110
+ } while (tokens.matchOpToken(","));
3111
+ tokens.requireOpToken(")");
3112
+ }
3113
+
3114
+ if (root.root) {
3115
+ var functionCall = {
3116
+ type: "functionCall",
3117
+ root: root,
3118
+ argExressions: args,
3119
+ args: [root.root, args],
3120
+ op: function (context, rootRoot, args) {
3121
+ runtime.nullCheck(rootRoot, root.root);
3122
+ var func = rootRoot[root.prop.value];
3123
+ runtime.nullCheck(func, root);
3124
+ if (func.hyperfunc) {
3125
+ args.push(context);
3126
+ }
3127
+ return func.apply(rootRoot, args);
3128
+ },
3129
+ evaluate: function (context) {
3130
+ return runtime.unifiedEval(this, context);
3131
+ },
3132
+ };
3133
+ } else {
3134
+ var functionCall = {
3135
+ type: "functionCall",
3136
+ root: root,
3137
+ argExressions: args,
3138
+ args: [root, args],
3139
+ op: function (context, func, argVals) {
3140
+ runtime.nullCheck(func, root);
3141
+ if (func.hyperfunc) {
3142
+ argVals.push(context);
3143
+ }
3144
+ var apply = func.apply(null, argVals);
3145
+ return apply;
3146
+ },
3147
+ evaluate: function (context) {
3148
+ return runtime.unifiedEval(this, context);
3149
+ },
3150
+ };
3151
+ }
3152
+ return parser.parseElement("indirectExpression", tokens, functionCall);
3153
+ });
3154
+
3155
+ parser.addIndirectExpression("attributeRefAccess", function (parser, runtime, tokens, root) {
3156
+ var attribute = parser.parseElement("attributeRef", tokens);
3157
+ if (!attribute) return;
3158
+ var attributeAccess = {
3159
+ type: "attributeRefAccess",
3160
+ root: root,
3161
+ attribute: attribute,
3162
+ args: [root],
3163
+ op: function (_ctx, rootVal) {
3164
+ // @ts-ignore
3165
+ var value = runtime.resolveAttribute(rootVal, attribute.name);
3166
+ return value;
3167
+ },
3168
+ evaluate: function (context) {
3169
+ return runtime.unifiedEval(this, context);
3170
+ },
3171
+ };
3172
+ return attributeAccess;
3173
+ });
3174
+
3175
+ parser.addIndirectExpression("arrayIndex", function (parser, runtime, tokens, root) {
3176
+ if (!tokens.matchOpToken("[")) return;
3177
+ var andBefore = false;
3178
+ var andAfter = false;
3179
+ var firstIndex = null;
3180
+ var secondIndex = null;
3181
+
3182
+ if (tokens.matchOpToken("..")) {
3183
+ andBefore = true;
3184
+ firstIndex = parser.requireElement("expression", tokens);
3185
+ } else {
3186
+ firstIndex = parser.requireElement("expression", tokens);
3187
+
3188
+ if (tokens.matchOpToken("..")) {
3189
+ andAfter = true;
3190
+ var current = tokens.currentToken();
3191
+ if (current.type !== "R_BRACKET") {
3192
+ secondIndex = parser.parseElement("expression", tokens);
3193
+ }
3194
+ }
3195
+ }
3196
+ tokens.requireOpToken("]");
3197
+
3198
+ var arrayIndex = {
3199
+ type: "arrayIndex",
3200
+ root: root,
3201
+ prop: firstIndex,
3202
+ firstIndex: firstIndex,
3203
+ secondIndex: secondIndex,
3204
+ args: [root, firstIndex, secondIndex],
3205
+ op: function (_ctx, root, firstIndex, secondIndex) {
3206
+ if (root == null) {
3207
+ return null;
3208
+ }
3209
+ if (andBefore) {
3210
+ if (firstIndex < 0) {
3211
+ firstIndex = root.length + firstIndex;
3212
+ }
3213
+ return root.slice(0, firstIndex + 1); // returns all items from beginning to firstIndex (inclusive)
3214
+ } else if (andAfter) {
3215
+ if (secondIndex != null) {
3216
+ if (secondIndex < 0) {
3217
+ secondIndex = root.length + secondIndex;
3218
+ }
3219
+ return root.slice(firstIndex, secondIndex + 1); // returns all items from firstIndex to secondIndex (inclusive)
3220
+ } else {
3221
+ return root.slice(firstIndex); // returns from firstIndex to end of array
3222
+ }
3223
+ } else {
3224
+ return root[firstIndex];
3225
+ }
3226
+ },
3227
+ evaluate: function (context) {
3228
+ return runtime.unifiedEval(this, context);
3229
+ },
3230
+ };
3231
+
3232
+ return parser.parseElement("indirectExpression", tokens, arrayIndex);
3233
+ });
3234
+
3235
+ // taken from https://drafts.csswg.org/css-values-4/#relative-length
3236
+ // and https://drafts.csswg.org/css-values-4/#absolute-length
3237
+ // (NB: we do not support `in` dues to conflicts w/ the hyperscript grammar)
3238
+ var STRING_POSTFIXES = [
3239
+ 'em', 'ex', 'cap', 'ch', 'ic', 'rem', 'lh', 'rlh', 'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax',
3240
+ 'cm', 'mm', 'Q', 'pc', 'pt', 'px'
3241
+ ];
3242
+ parser.addGrammarElement("postfixExpression", function (parser, runtime, tokens) {
3243
+ var root = parser.parseElement("primaryExpression", tokens);
3244
+
3245
+ let stringPosfix = tokens.matchAnyToken.apply(tokens, STRING_POSTFIXES) || tokens.matchOpToken("%");
3246
+ if (stringPosfix) {
3247
+ return {
3248
+ type: "stringPostfix",
3249
+ postfix: stringPosfix.value,
3250
+ args: [root],
3251
+ op: function (context, val) {
3252
+ return "" + val + stringPosfix.value;
3253
+ },
3254
+ evaluate: function (context) {
3255
+ return runtime.unifiedEval(this, context);
3256
+ },
3257
+ };
3258
+ }
3259
+
3260
+ var timeFactor = null;
3261
+ if (tokens.matchToken("s") || tokens.matchToken("seconds")) {
3262
+ timeFactor = 1000;
3263
+ } else if (tokens.matchToken("ms") || tokens.matchToken("milliseconds")) {
3264
+ timeFactor = 1;
3265
+ }
3266
+ if (timeFactor) {
3267
+ return {
3268
+ type: "timeExpression",
3269
+ time: root,
3270
+ factor: timeFactor,
3271
+ args: [root],
3272
+ op: function (_context, val) {
3273
+ return val * timeFactor;
3274
+ },
3275
+ evaluate: function (context) {
3276
+ return runtime.unifiedEval(this, context);
3277
+ },
3278
+ };
3279
+ }
3280
+
3281
+ if (tokens.matchOpToken(":")) {
3282
+ var typeName = tokens.requireTokenType("IDENTIFIER");
3283
+ var nullOk = !tokens.matchOpToken("!");
3284
+ return {
3285
+ type: "typeCheck",
3286
+ typeName: typeName,
3287
+ nullOk: nullOk,
3288
+ args: [root],
3289
+ op: function (context, val) {
3290
+ var passed = runtime.typeCheck(val, typeName.value, nullOk);
3291
+ if (passed) {
3292
+ return val;
3293
+ } else {
3294
+ throw new Error("Typecheck failed! Expected: " + typeName.value);
3295
+ }
3296
+ },
3297
+ evaluate: function (context) {
3298
+ return runtime.unifiedEval(this, context);
3299
+ },
3300
+ };
3301
+ } else {
3302
+ return root;
3303
+ }
3304
+ });
3305
+
3306
+ parser.addGrammarElement("logicalNot", function (parser, runtime, tokens) {
3307
+ if (!tokens.matchToken("not")) return;
3308
+ var root = parser.requireElement("unaryExpression", tokens);
3309
+ return {
3310
+ type: "logicalNot",
3311
+ root: root,
3312
+ args: [root],
3313
+ op: function (context, val) {
3314
+ return !val;
3315
+ },
3316
+ evaluate: function (context) {
3317
+ return runtime.unifiedEval(this, context);
3318
+ },
3319
+ };
3320
+ });
3321
+
3322
+ parser.addGrammarElement("noExpression", function (parser, runtime, tokens) {
3323
+ if (!tokens.matchToken("no")) return;
3324
+ var root = parser.requireElement("unaryExpression", tokens);
3325
+ return {
3326
+ type: "noExpression",
3327
+ root: root,
3328
+ args: [root],
3329
+ op: function (_context, val) {
3330
+ return runtime.isEmpty(val);
3331
+ },
3332
+ evaluate: function (context) {
3333
+ return runtime.unifiedEval(this, context);
3334
+ },
3335
+ };
3336
+ });
3337
+
3338
+ parser.addLeafExpression("some", function (parser, runtime, tokens) {
3339
+ if (!tokens.matchToken("some")) return;
3340
+ var root = parser.requireElement("expression", tokens);
3341
+ return {
3342
+ type: "noExpression",
3343
+ root: root,
3344
+ args: [root],
3345
+ op: function (_context, val) {
3346
+ return !runtime.isEmpty(val);
3347
+ },
3348
+ evaluate(context) {
3349
+ return runtime.unifiedEval(this, context);
3350
+ },
3351
+ };
3352
+ });
3353
+
3354
+ parser.addGrammarElement("negativeNumber", function (parser, runtime, tokens) {
3355
+ if (!tokens.matchOpToken("-")) return;
3356
+ var root = parser.requireElement("unaryExpression", tokens);
3357
+ return {
3358
+ type: "negativeNumber",
3359
+ root: root,
3360
+ args: [root],
3361
+ op: function (context, value) {
3362
+ return -1 * value;
3363
+ },
3364
+ evaluate: function (context) {
3365
+ return runtime.unifiedEval(this, context);
3366
+ },
3367
+ };
3368
+ });
3369
+
3370
+ parser.addGrammarElement("unaryExpression", function (parser, runtime, tokens) {
3371
+ tokens.matchToken("the"); // optional "the"
3372
+ return parser.parseAnyOf(
3373
+ ["beepExpression", "logicalNot", "relativePositionalExpression", "positionalExpression", "noExpression", "negativeNumber", "postfixExpression"],
3374
+ tokens
3375
+ );
3376
+ });
3377
+
3378
+ parser.addGrammarElement("beepExpression", function (parser, runtime, tokens) {
3379
+ if (!tokens.matchToken("beep!")) return;
3380
+ var expression = parser.parseElement("unaryExpression", tokens);
3381
+ if (expression) {
3382
+ expression['booped'] = true;
3383
+ var originalEvaluate = expression.evaluate;
3384
+ expression.evaluate = function(ctx){
3385
+ let value = originalEvaluate.apply(expression, arguments);
3386
+ let element = ctx.me;
3387
+ if (runtime.triggerEvent(element, "hyperscript:beep", {element, expression, value})) {
3388
+ var typeName;
3389
+ if (value) {
3390
+ if (value instanceof ElementCollection){
3391
+ typeName = "ElementCollection";
3392
+ } else if (value.constructor) {
3393
+ typeName = value.constructor.name;
3394
+ } else {
3395
+ typeName = "unknown";
3396
+ }
3397
+ } else {
3398
+ typeName = "object (null)"
3399
+ }
3400
+ var logValue = value;
3401
+ if (typeName === "String") {
3402
+ logValue = '"' + logValue + '"';
3403
+ } else if (value instanceof ElementCollection) {
3404
+ logValue = Array.from(value);
3405
+ }
3406
+ console.log("///_ BEEP! The expression (" + Tokens.sourceFor.call(expression).substr(6) + ") evaluates to:", logValue, "of type " + typeName);
3407
+ }
3408
+ return value;
3409
+ }
3410
+ return expression;
3411
+ }
3412
+ });
3413
+
3414
+ var scanForwardQuery = function(start, root, match, wrap) {
3415
+ var results = root.querySelectorAll(match);
3416
+ for (var i = 0; i < results.length; i++) {
3417
+ var elt = results[i];
3418
+ if (elt.compareDocumentPosition(start) === Node.DOCUMENT_POSITION_PRECEDING) {
3419
+ return elt;
3420
+ }
3421
+ }
3422
+ if (wrap) {
3423
+ return results[0];
3424
+ }
3425
+ }
3426
+
3427
+ var scanBackwardsQuery = function(start, root, match, wrap) {
3428
+ var results = root.querySelectorAll(match);
3429
+ for (var i = results.length - 1; i >= 0; i--) {
3430
+ var elt = results[i];
3431
+ if (elt.compareDocumentPosition(start) === Node.DOCUMENT_POSITION_FOLLOWING) {
3432
+ return elt;
3433
+ }
3434
+ }
3435
+ if (wrap) {
3436
+ return results[results.length - 1];
3437
+ }
3438
+ }
3439
+
3440
+ var scanForwardArray = function(start, array, match, wrap) {
3441
+ var matches = [];
3442
+ Runtime.prototype.forEach(array, function(elt){
3443
+ if (elt.matches(match) || elt === start) {
3444
+ matches.push(elt);
3445
+ }
3446
+ })
3447
+ for (var i = 0; i < matches.length - 1; i++) {
3448
+ var elt = matches[i];
3449
+ if (elt === start) {
3450
+ return matches[i + 1];
3451
+ }
3452
+ }
3453
+ if (wrap) {
3454
+ var first = matches[0];
3455
+ if (first && first.matches(match)) {
3456
+ return first;
3457
+ }
3458
+ }
3459
+ }
3460
+
3461
+ var scanBackwardsArray = function(start, array, match, wrap) {
3462
+ return scanForwardArray(start, Array.from(array).reverse(), match, wrap);
3463
+ }
3464
+
3465
+ parser.addGrammarElement("relativePositionalExpression", function (parser, runtime, tokens) {
3466
+ var op = tokens.matchAnyToken("next", "previous");
3467
+ if (!op) return;
3468
+ if (op.value === "next") {
3469
+ var forwardSearch = true;
3470
+ }
3471
+
3472
+ var thing = parser.parseElement("expression", tokens);
3473
+
3474
+ if (tokens.matchToken("from")) {
3475
+ tokens.pushFollow("in");
3476
+ try {
3477
+ var from = parser.requireElement("unaryExpression", tokens);
3478
+ } finally {
3479
+ tokens.popFollow();
3480
+ }
3481
+ } else {
3482
+ var from = parser.requireElement("implicitMeTarget", tokens);
3483
+ }
3484
+
3485
+ var inSearch = false;
3486
+ var withinElt;
3487
+ if (tokens.matchToken("in")) {
3488
+ inSearch = true;
3489
+ var inElt = parser.requireElement("unaryExpression", tokens);
3490
+ } else if (tokens.matchToken("within")) {
3491
+ withinElt = parser.requireElement("unaryExpression", tokens);
3492
+ } else {
3493
+ withinElt = document.body;
3494
+ }
3495
+
3496
+ var wrapping = false;
3497
+ if (tokens.matchToken("with")) {
3498
+ tokens.requireToken("wrapping")
3499
+ wrapping = true;
3500
+ }
3501
+
3502
+ return {
3503
+ type: "relativePositionalExpression",
3504
+ from: from,
3505
+ forwardSearch: forwardSearch,
3506
+ inSearch: inSearch,
3507
+ wrapping: wrapping,
3508
+ inElt: inElt,
3509
+ withinElt: withinElt,
3510
+ operator: op.value,
3511
+ args: [thing, from, inElt, withinElt],
3512
+ op: function (context, thing, from, inElt, withinElt) {
3513
+
3514
+ var css = thing.css;
3515
+ if (css == null) {
3516
+ throw "Expected a CSS value";
3517
+ }
3518
+
3519
+ if(inSearch) {
3520
+ if (inElt) {
3521
+ if (forwardSearch) {
3522
+ return scanForwardArray(from, inElt, css, wrapping);
3523
+ } else {
3524
+ return scanBackwardsArray(from, inElt, css, wrapping);
3525
+ }
3526
+ }
3527
+ } else {
3528
+ if (withinElt) {
3529
+ if (forwardSearch) {
3530
+ return scanForwardQuery(from, withinElt, css, wrapping);
3531
+ } else {
3532
+ return scanBackwardsQuery(from, withinElt, css, wrapping);
3533
+ }
3534
+ }
3535
+ }
3536
+ },
3537
+ evaluate: function (context) {
3538
+ return runtime.unifiedEval(this, context);
3539
+ },
3540
+ }
3541
+
3542
+ });
3543
+
3544
+ parser.addGrammarElement("positionalExpression", function (parser, runtime, tokens) {
3545
+ var op = tokens.matchAnyToken("first", "last", "random");
3546
+ if (!op) return;
3547
+ tokens.matchAnyToken("in", "from", "of");
3548
+ var rhs = parser.requireElement("unaryExpression", tokens);
3549
+ const operator = op.value;
3550
+ return {
3551
+ type: "positionalExpression",
3552
+ rhs: rhs,
3553
+ operator: op.value,
3554
+ args: [rhs],
3555
+ op: function (context, rhsVal) {
3556
+ if (rhsVal && !Array.isArray(rhsVal)) {
3557
+ if (rhsVal.children) {
3558
+ rhsVal = rhsVal.children;
3559
+ } else {
3560
+ rhsVal = Array.from(rhsVal);
3561
+ }
3562
+ }
3563
+ if (rhsVal) {
3564
+ if (operator === "first") {
3565
+ return rhsVal[0];
3566
+ } else if (operator === "last") {
3567
+ return rhsVal[rhsVal.length - 1];
3568
+ } else if (operator === "random") {
3569
+ return rhsVal[Math.floor(Math.random() * rhsVal.length)];
3570
+ }
3571
+ }
3572
+ },
3573
+ evaluate: function (context) {
3574
+ return runtime.unifiedEval(this, context);
3575
+ },
3576
+ };
3577
+ });
3578
+
3579
+ parser.addGrammarElement("mathOperator", function (parser, runtime, tokens) {
3580
+ var expr = parser.parseElement("unaryExpression", tokens);
3581
+ var mathOp,
3582
+ initialMathOp = null;
3583
+ mathOp = tokens.matchAnyOpToken("+", "-", "*", "/", "%");
3584
+ while (mathOp) {
3585
+ initialMathOp = initialMathOp || mathOp;
3586
+ var operator = mathOp.value;
3587
+ if (initialMathOp.value !== operator) {
3588
+ parser.raiseParseError(tokens, "You must parenthesize math operations with different operators");
3589
+ }
3590
+ var rhs = parser.parseElement("unaryExpression", tokens);
3591
+ expr = {
3592
+ type: "mathOperator",
3593
+ lhs: expr,
3594
+ rhs: rhs,
3595
+ operator: operator,
3596
+ args: [expr, rhs],
3597
+ op: function (context, lhsVal, rhsVal) {
3598
+ if (operator === "+") {
3599
+ return lhsVal + rhsVal;
3600
+ } else if (operator === "-") {
3601
+ return lhsVal - rhsVal;
3602
+ } else if (operator === "*") {
3603
+ return lhsVal * rhsVal;
3604
+ } else if (operator === "/") {
3605
+ return lhsVal / rhsVal;
3606
+ } else if (operator === "%") {
3607
+ return lhsVal % rhsVal;
3608
+ }
3609
+ },
3610
+ evaluate: function (context) {
3611
+ return runtime.unifiedEval(this, context);
3612
+ },
3613
+ };
3614
+ mathOp = tokens.matchAnyOpToken("+", "-", "*", "/", "%");
3615
+ }
3616
+ return expr;
3617
+ });
3618
+
3619
+ parser.addGrammarElement("mathExpression", function (parser, runtime, tokens) {
3620
+ return parser.parseAnyOf(["mathOperator", "unaryExpression"], tokens);
3621
+ });
3622
+
3623
+ function sloppyContains(src, container, value){
3624
+ if (container['contains']) {
3625
+ return container.contains(value);
3626
+ } else if (container['includes']) {
3627
+ return container.includes(value);
3628
+ } else {
3629
+ throw Error("The value of " + src.sourceFor() + " does not have a contains or includes method on it");
3630
+ }
3631
+ }
3632
+ function sloppyMatches(src, target, toMatch){
3633
+ if (target['match']) {
3634
+ return !!target.match(toMatch);
3635
+ } else if (target['matches']) {
3636
+ return target.matches(toMatch);
3637
+ } else {
3638
+ throw Error("The value of " + src.sourceFor() + " does not have a match or matches method on it");
3639
+ }
3640
+ }
3641
+
3642
+ parser.addGrammarElement("comparisonOperator", function (parser, runtime, tokens) {
3643
+ var expr = parser.parseElement("mathExpression", tokens);
3644
+ var comparisonToken = tokens.matchAnyOpToken("<", ">", "<=", ">=", "==", "===", "!=", "!==");
3645
+ var operator = comparisonToken ? comparisonToken.value : null;
3646
+ var hasRightValue = true; // By default, most comparisons require two values, but there are some exceptions.
3647
+ var typeCheck = false;
3648
+
3649
+ if (operator == null) {
3650
+ if (tokens.matchToken("is") || tokens.matchToken("am")) {
3651
+ if (tokens.matchToken("not")) {
3652
+ if (tokens.matchToken("in")) {
3653
+ operator = "not in";
3654
+ } else if (tokens.matchToken("a")) {
3655
+ operator = "not a";
3656
+ typeCheck = true;
3657
+ } else if (tokens.matchToken("empty")) {
3658
+ operator = "not empty";
3659
+ hasRightValue = false;
3660
+ } else {
3661
+ operator = "!=";
3662
+ }
3663
+ } else if (tokens.matchToken("in")) {
3664
+ operator = "in";
3665
+ } else if (tokens.matchToken("a")) {
3666
+ operator = "a";
3667
+ typeCheck = true;
3668
+ } else if (tokens.matchToken("empty")) {
3669
+ operator = "empty";
3670
+ hasRightValue = false;
3671
+ } else if (tokens.matchToken("less")) {
3672
+ tokens.requireToken("than");
3673
+ if (tokens.matchToken("or")) {
3674
+ tokens.requireToken("equal");
3675
+ tokens.requireToken("to");
3676
+ operator = "<=";
3677
+ } else {
3678
+ operator = "<";
3679
+ }
3680
+ } else if (tokens.matchToken("greater")) {
3681
+ tokens.requireToken("than");
3682
+ if (tokens.matchToken("or")) {
3683
+ tokens.requireToken("equal");
3684
+ tokens.requireToken("to");
3685
+ operator = ">=";
3686
+ } else {
3687
+ operator = ">";
3688
+ }
3689
+ } else {
3690
+ operator = "==";
3691
+ }
3692
+ } else if (tokens.matchToken("exist") || tokens.matchToken("exists")) {
3693
+ operator = "exist";
3694
+ hasRightValue = false;
3695
+ } else if (tokens.matchToken("matches") || tokens.matchToken("match")) {
3696
+ operator = "match";
3697
+ } else if (tokens.matchToken("contains") || tokens.matchToken("contain")) {
3698
+ operator = "contain";
3699
+ } else if (tokens.matchToken("includes") || tokens.matchToken("include")) {
3700
+ operator = "include";
3701
+ } else if (tokens.matchToken("do") || tokens.matchToken("does")) {
3702
+ tokens.requireToken("not");
3703
+ if (tokens.matchToken("matches") || tokens.matchToken("match")) {
3704
+ operator = "not match";
3705
+ } else if (tokens.matchToken("contains") || tokens.matchToken("contain")) {
3706
+ operator = "not contain";
3707
+ } else if (tokens.matchToken("exist") || tokens.matchToken("exist")) {
3708
+ operator = "not exist";
3709
+ hasRightValue = false;
3710
+ } else if (tokens.matchToken("include")) {
3711
+ operator = "not include";
3712
+ } else {
3713
+ parser.raiseParseError(tokens, "Expected matches or contains");
3714
+ }
3715
+ }
3716
+ }
3717
+
3718
+ if (operator) {
3719
+ // Do not allow chained comparisons, which is dumb
3720
+ if (typeCheck) {
3721
+ var typeName = tokens.requireTokenType("IDENTIFIER");
3722
+ var nullOk = !tokens.matchOpToken("!");
3723
+ } else if (hasRightValue) {
3724
+ var rhs = parser.requireElement("mathExpression", tokens);
3725
+ if (operator === "match" || operator === "not match") {
3726
+ rhs = rhs.css ? rhs.css : rhs;
3727
+ }
3728
+ }
3729
+ var lhs = expr;
3730
+ expr = {
3731
+ type: "comparisonOperator",
3732
+ operator: operator,
3733
+ typeName: typeName,
3734
+ nullOk: nullOk,
3735
+ lhs: expr,
3736
+ rhs: rhs,
3737
+ args: [expr, rhs],
3738
+ op: function (context, lhsVal, rhsVal) {
3739
+ if (operator === "==") {
3740
+ return lhsVal == rhsVal;
3741
+ } else if (operator === "!=") {
3742
+ return lhsVal != rhsVal;
3743
+ }
3744
+ if (operator === "match") {
3745
+ return lhsVal != null && sloppyMatches(lhs, lhsVal, rhsVal);
3746
+ }
3747
+ if (operator === "not match") {
3748
+ return lhsVal == null || !sloppyMatches(lhs, lhsVal, rhsVal);
3749
+ }
3750
+ if (operator === "in") {
3751
+ return rhsVal != null && sloppyContains(rhs, rhsVal, lhsVal);
3752
+ }
3753
+ if (operator === "not in") {
3754
+ return rhsVal == null || !sloppyContains(rhs, rhsVal, lhsVal);
3755
+ }
3756
+ if (operator === "contain") {
3757
+ return lhsVal != null && sloppyContains(lhs, lhsVal, rhsVal);
3758
+ }
3759
+ if (operator === "not contain") {
3760
+ return lhsVal == null || !sloppyContains(lhs, lhsVal, rhsVal);
3761
+ }
3762
+ if (operator === "include") {
3763
+ return lhsVal != null && sloppyContains(lhs, lhsVal, rhsVal);
3764
+ }
3765
+ if (operator === "not include") {
3766
+ return lhsVal == null || !sloppyContains(lhs, lhsVal, rhsVal);
3767
+ }
3768
+ if (operator === "===") {
3769
+ return lhsVal === rhsVal;
3770
+ } else if (operator === "!==") {
3771
+ return lhsVal !== rhsVal;
3772
+ } else if (operator === "<") {
3773
+ return lhsVal < rhsVal;
3774
+ } else if (operator === ">") {
3775
+ return lhsVal > rhsVal;
3776
+ } else if (operator === "<=") {
3777
+ return lhsVal <= rhsVal;
3778
+ } else if (operator === ">=") {
3779
+ return lhsVal >= rhsVal;
3780
+ } else if (operator === "empty") {
3781
+ return runtime.isEmpty(lhsVal);
3782
+ } else if (operator === "not empty") {
3783
+ return !runtime.isEmpty(lhsVal);
3784
+ } else if (operator === "exist") {
3785
+ return runtime.doesExist(lhsVal);
3786
+ } else if (operator === "not exist") {
3787
+ return !runtime.doesExist(lhsVal);
3788
+ } else if (operator === "a") {
3789
+ return runtime.typeCheck(lhsVal, typeName.value, nullOk);
3790
+ } else if (operator === "not a") {
3791
+ return !runtime.typeCheck(lhsVal, typeName.value, nullOk);
3792
+ } else {
3793
+ throw "Unknown comparison : " + operator;
3794
+ }
3795
+ },
3796
+ evaluate: function (context) {
3797
+ return runtime.unifiedEval(this, context);
3798
+ },
3799
+ };
3800
+ }
3801
+ return expr;
3802
+ });
3803
+
3804
+ parser.addGrammarElement("comparisonExpression", function (parser, runtime, tokens) {
3805
+ return parser.parseAnyOf(["comparisonOperator", "mathExpression"], tokens);
3806
+ });
3807
+
3808
+ parser.addGrammarElement("logicalOperator", function (parser, runtime, tokens) {
3809
+ var expr = parser.parseElement("comparisonExpression", tokens);
3810
+ var logicalOp,
3811
+ initialLogicalOp = null;
3812
+ logicalOp = tokens.matchToken("and") || tokens.matchToken("or");
3813
+ while (logicalOp) {
3814
+ initialLogicalOp = initialLogicalOp || logicalOp;
3815
+ if (initialLogicalOp.value !== logicalOp.value) {
3816
+ parser.raiseParseError(tokens, "You must parenthesize logical operations with different operators");
3817
+ }
3818
+ var rhs = parser.requireElement("comparisonExpression", tokens);
3819
+ const operator = logicalOp.value;
3820
+ expr = {
3821
+ type: "logicalOperator",
3822
+ operator: operator,
3823
+ lhs: expr,
3824
+ rhs: rhs,
3825
+ args: [expr, rhs],
3826
+ op: function (context, lhsVal, rhsVal) {
3827
+ if (operator === "and") {
3828
+ return lhsVal && rhsVal;
3829
+ } else {
3830
+ return lhsVal || rhsVal;
3831
+ }
3832
+ },
3833
+ evaluate: function (context) {
3834
+ return runtime.unifiedEval(this, context);
3835
+ },
3836
+ };
3837
+ logicalOp = tokens.matchToken("and") || tokens.matchToken("or");
3838
+ }
3839
+ return expr;
3840
+ });
3841
+
3842
+ parser.addGrammarElement("logicalExpression", function (parser, runtime, tokens) {
3843
+ return parser.parseAnyOf(["logicalOperator", "mathExpression"], tokens);
3844
+ });
3845
+
3846
+ parser.addGrammarElement("asyncExpression", function (parser, runtime, tokens) {
3847
+ if (tokens.matchToken("async")) {
3848
+ var value = parser.requireElement("logicalExpression", tokens);
3849
+ var expr = {
3850
+ type: "asyncExpression",
3851
+ value: value,
3852
+ evaluate: function (context) {
3853
+ return {
3854
+ asyncWrapper: true,
3855
+ value: this.value.evaluate(context), //OK
3856
+ };
3857
+ },
3858
+ };
3859
+ return expr;
3860
+ } else {
3861
+ return parser.parseElement("logicalExpression", tokens);
3862
+ }
3863
+ });
3864
+
3865
+ parser.addGrammarElement("expression", function (parser, runtime, tokens) {
3866
+ tokens.matchToken("the"); // optional the
3867
+ return parser.parseElement("asyncExpression", tokens);
3868
+ });
3869
+
3870
+ parser.addGrammarElement("assignableExpression", function (parser, runtime, tokens) {
3871
+ tokens.matchToken("the"); // optional the
3872
+
3873
+ // TODO obviously we need to generalize this as a left hand side / targetable concept
3874
+ var expr = parser.parseElement("primaryExpression", tokens);
3875
+ if (expr && (
3876
+ expr.type === "symbol" ||
3877
+ expr.type === "ofExpression" ||
3878
+ expr.type === "propertyAccess" ||
3879
+ expr.type === "attributeRefAccess" ||
3880
+ expr.type === "attributeRef" ||
3881
+ expr.type === "styleRef" ||
3882
+ expr.type === "arrayIndex" ||
3883
+ expr.type === "possessive")
3884
+ ) {
3885
+ return expr;
3886
+ } else {
3887
+ parser.raiseParseError(
3888
+ tokens,
3889
+ "A target expression must be writable. The expression type '" + (expr && expr.type) + "' is not."
3890
+ );
3891
+ }
3892
+ return expr;
3893
+ });
3894
+
3895
+ parser.addGrammarElement("hyperscript", function (parser, runtime, tokens) {
3896
+ var features = [];
3897
+
3898
+ if (tokens.hasMore()) {
3899
+ while (parser.featureStart(tokens.currentToken()) || tokens.currentToken().value === "(") {
3900
+ var feature = parser.requireElement("feature", tokens);
3901
+ features.push(feature);
3902
+ tokens.matchToken("end"); // optional end
3903
+ }
3904
+ }
3905
+ return {
3906
+ type: "hyperscript",
3907
+ features: features,
3908
+ apply: function (target, source, args) {
3909
+ // no op
3910
+ for (const feature of features) {
3911
+ feature.install(target, source, args);
3912
+ }
3913
+ },
3914
+ };
3915
+ });
3916
+
3917
+ var parseEventArgs = function (tokens) {
3918
+ var args = [];
3919
+ // handle argument list (look ahead 3)
3920
+ if (
3921
+ tokens.token(0).value === "(" &&
3922
+ (tokens.token(1).value === ")" || tokens.token(2).value === "," || tokens.token(2).value === ")")
3923
+ ) {
3924
+ tokens.matchOpToken("(");
3925
+ do {
3926
+ args.push(tokens.requireTokenType("IDENTIFIER"));
3927
+ } while (tokens.matchOpToken(","));
3928
+ tokens.requireOpToken(")");
3929
+ }
3930
+ return args;
3931
+ };
3932
+
3933
+ parser.addFeature("on", function (parser, runtime, tokens) {
3934
+ if (!tokens.matchToken("on")) return;
3935
+ var every = false;
3936
+ if (tokens.matchToken("every")) {
3937
+ every = true;
3938
+ }
3939
+ var events = [];
3940
+ var displayName = null;
3941
+ do {
3942
+ var on = parser.requireElement("eventName", tokens, "Expected event name");
3943
+
3944
+ var eventName = on.evaluate(); // OK No Promise
3945
+
3946
+ if (displayName) {
3947
+ displayName = displayName + " or " + eventName;
3948
+ } else {
3949
+ displayName = "on " + eventName;
3950
+ }
3951
+ var args = parseEventArgs(tokens);
3952
+
3953
+ var filter = null;
3954
+ if (tokens.matchOpToken("[")) {
3955
+ filter = parser.requireElement("expression", tokens);
3956
+ tokens.requireOpToken("]");
3957
+ }
3958
+
3959
+ if (tokens.currentToken().type === "NUMBER") {
3960
+ var startCountToken = tokens.consumeToken();
3961
+ var startCount = parseInt(startCountToken.value);
3962
+ if (tokens.matchToken("to")) {
3963
+ var endCountToken = tokens.consumeToken();
3964
+ var endCount = parseInt(endCountToken.value);
3965
+ } else if (tokens.matchToken("and")) {
3966
+ var unbounded = true;
3967
+ tokens.requireToken("on");
3968
+ }
3969
+ }
3970
+
3971
+ if (eventName === "intersection") {
3972
+ var intersectionSpec = {};
3973
+ if (tokens.matchToken("with")) {
3974
+ intersectionSpec["with"] = parser.requireElement("expression", tokens).evaluate();
3975
+ }
3976
+ if (tokens.matchToken("having")) {
3977
+ do {
3978
+ if (tokens.matchToken("margin")) {
3979
+ intersectionSpec["rootMargin"] = parser.requireElement("stringLike", tokens).evaluate();
3980
+ } else if (tokens.matchToken("threshold")) {
3981
+ intersectionSpec["threshold"] = parser.requireElement("expression", tokens).evaluate();
3982
+ } else {
3983
+ parser.raiseParseError(tokens, "Unknown intersection config specification");
3984
+ }
3985
+ } while (tokens.matchToken("and"));
3986
+ }
3987
+ } else if (eventName === "mutation") {
3988
+ var mutationSpec = {};
3989
+ if (tokens.matchToken("of")) {
3990
+ do {
3991
+ if (tokens.matchToken("anything")) {
3992
+ mutationSpec["attributes"] = true;
3993
+ mutationSpec["subtree"] = true;
3994
+ mutationSpec["characterData"] = true;
3995
+ mutationSpec["childList"] = true;
3996
+ } else if (tokens.matchToken("childList")) {
3997
+ mutationSpec["childList"] = true;
3998
+ } else if (tokens.matchToken("attributes")) {
3999
+ mutationSpec["attributes"] = true;
4000
+ mutationSpec["attributeOldValue"] = true;
4001
+ } else if (tokens.matchToken("subtree")) {
4002
+ mutationSpec["subtree"] = true;
4003
+ } else if (tokens.matchToken("characterData")) {
4004
+ mutationSpec["characterData"] = true;
4005
+ mutationSpec["characterDataOldValue"] = true;
4006
+ } else if (tokens.currentToken().type === "ATTRIBUTE_REF") {
4007
+ var attribute = tokens.consumeToken();
4008
+ if (mutationSpec["attributeFilter"] == null) {
4009
+ mutationSpec["attributeFilter"] = [];
4010
+ }
4011
+ if (attribute.value.indexOf("@") == 0) {
4012
+ mutationSpec["attributeFilter"].push(attribute.value.substring(1));
4013
+ } else {
4014
+ parser.raiseParseError(
4015
+ tokens,
4016
+ "Only shorthand attribute references are allowed here"
4017
+ );
4018
+ }
4019
+ } else {
4020
+ parser.raiseParseError(tokens, "Unknown mutation config specification");
4021
+ }
4022
+ } while (tokens.matchToken("or"));
4023
+ } else {
4024
+ mutationSpec["attributes"] = true;
4025
+ mutationSpec["characterData"] = true;
4026
+ mutationSpec["childList"] = true;
4027
+ }
4028
+ }
4029
+
4030
+ var from = null;
4031
+ var elsewhere = false;
4032
+ if (tokens.matchToken("from")) {
4033
+ if (tokens.matchToken("elsewhere")) {
4034
+ elsewhere = true;
4035
+ } else {
4036
+ from = parser.parseElement("expression", tokens);
4037
+ if (!from) {
4038
+ parser.raiseParseError(tokens, 'Expected either target value or "elsewhere".');
4039
+ }
4040
+ }
4041
+ }
4042
+ // support both "elsewhere" and "from elsewhere"
4043
+ if (from === null && elsewhere === false && tokens.matchToken("elsewhere")) {
4044
+ elsewhere = true;
4045
+ }
4046
+
4047
+ if (tokens.matchToken("in")) {
4048
+ var inExpr = parser.parseElement('unaryExpression', tokens);
4049
+ }
4050
+
4051
+ if (tokens.matchToken("debounced")) {
4052
+ tokens.requireToken("at");
4053
+ var timeExpr = parser.requireElement("expression", tokens);
4054
+ // @ts-ignore
4055
+ var debounceTime = timeExpr.evaluate({}); // OK No promise TODO make a literal time expr
4056
+ } else if (tokens.matchToken("throttled")) {
4057
+ tokens.requireToken("at");
4058
+ var timeExpr = parser.requireElement("expression", tokens);
4059
+ // @ts-ignore
4060
+ var throttleTime = timeExpr.evaluate({}); // OK No promise TODO make a literal time expr
4061
+ }
4062
+
4063
+ events.push({
4064
+ execCount: 0,
4065
+ every: every,
4066
+ on: eventName,
4067
+ args: args,
4068
+ filter: filter,
4069
+ from: from,
4070
+ inExpr: inExpr,
4071
+ elsewhere: elsewhere,
4072
+ startCount: startCount,
4073
+ endCount: endCount,
4074
+ unbounded: unbounded,
4075
+ debounceTime: debounceTime,
4076
+ throttleTime: throttleTime,
4077
+ mutationSpec: mutationSpec,
4078
+ intersectionSpec: intersectionSpec,
4079
+ debounced: undefined,
4080
+ lastExec: undefined,
4081
+ });
4082
+ } while (tokens.matchToken("or"));
4083
+
4084
+ var queueLast = true;
4085
+ if (!every) {
4086
+ if (tokens.matchToken("queue")) {
4087
+ if (tokens.matchToken("all")) {
4088
+ var queueAll = true;
4089
+ var queueLast = false;
4090
+ } else if (tokens.matchToken("first")) {
4091
+ var queueFirst = true;
4092
+ } else if (tokens.matchToken("none")) {
4093
+ var queueNone = true;
4094
+ } else {
4095
+ tokens.requireToken("last");
4096
+ }
4097
+ }
4098
+ }
4099
+
4100
+ var start = parser.requireElement("commandList", tokens);
4101
+ parser.ensureTerminated(start);
4102
+
4103
+ if (tokens.matchToken("catch")) {
4104
+ var errorSymbol = tokens.requireTokenType("IDENTIFIER").value;
4105
+ var errorHandler = parser.requireElement("commandList", tokens);
4106
+ parser.ensureTerminated(errorHandler);
4107
+ }
4108
+
4109
+ if (tokens.matchToken("finally")) {
4110
+ var finallyHandler = parser.requireElement("commandList", tokens);
4111
+ parser.ensureTerminated(finallyHandler);
4112
+ }
4113
+
4114
+ var onFeature = {
4115
+ displayName: displayName,
4116
+ events: events,
4117
+ start: start,
4118
+ every: every,
4119
+ execCount: 0,
4120
+ errorHandler: errorHandler,
4121
+ errorSymbol: errorSymbol,
4122
+ execute: function (/** @type {Context} */ ctx) {
4123
+ let eventQueueInfo = runtime.getEventQueueFor(ctx.me, onFeature);
4124
+ if (eventQueueInfo.executing && every === false) {
4125
+ if (queueNone || (queueFirst && eventQueueInfo.queue.length > 0)) {
4126
+ return;
4127
+ }
4128
+ if (queueLast) {
4129
+ eventQueueInfo.queue.length = 0;
4130
+ }
4131
+ eventQueueInfo.queue.push(ctx);
4132
+ return;
4133
+ }
4134
+ onFeature.execCount++;
4135
+ eventQueueInfo.executing = true;
4136
+ ctx.meta.onHalt = function () {
4137
+ eventQueueInfo.executing = false;
4138
+ var queued = eventQueueInfo.queue.shift();
4139
+ if (queued) {
4140
+ setTimeout(function () {
4141
+ onFeature.execute(queued);
4142
+ }, 1);
4143
+ }
4144
+ };
4145
+ ctx.meta.reject = function (err) {
4146
+ console.error(err.message ? err.message : err);
4147
+ var hypertrace = runtime.getHyperTrace(ctx, err);
4148
+ if (hypertrace) {
4149
+ hypertrace.print();
4150
+ }
4151
+ runtime.triggerEvent(ctx.me, "exception", {
4152
+ error: err,
4153
+ });
4154
+ };
4155
+ start.execute(ctx);
4156
+ },
4157
+ install: function (elt, source) {
4158
+ for (const eventSpec of onFeature.events) {
4159
+ var targets;
4160
+ if (eventSpec.elsewhere) {
4161
+ targets = [document];
4162
+ } else if (eventSpec.from) {
4163
+ targets = eventSpec.from.evaluate(runtime.makeContext(elt, onFeature, elt, null));
4164
+ } else {
4165
+ targets = [elt];
4166
+ }
4167
+ runtime.implicitLoop(targets, function (target) {
4168
+ // OK NO PROMISE
4169
+
4170
+ var eventName = eventSpec.on;
4171
+ if (eventSpec.mutationSpec) {
4172
+ eventName = "hyperscript:mutation";
4173
+ const observer = new MutationObserver(function (mutationList, observer) {
4174
+ if (!onFeature.executing) {
4175
+ runtime.triggerEvent(target, eventName, {
4176
+ mutationList: mutationList,
4177
+ observer: observer,
4178
+ });
4179
+ }
4180
+ });
4181
+ observer.observe(target, eventSpec.mutationSpec);
4182
+ }
4183
+
4184
+ if (eventSpec.intersectionSpec) {
4185
+ eventName = "hyperscript:insersection";
4186
+ const observer = new IntersectionObserver(function (entries) {
4187
+ for (const entry of entries) {
4188
+ var detail = {
4189
+ observer: observer,
4190
+ };
4191
+ detail = Object.assign(detail, entry);
4192
+ detail["intersecting"] = entry.isIntersecting;
4193
+ runtime.triggerEvent(target, eventName, detail);
4194
+ }
4195
+ }, eventSpec.intersectionSpec);
4196
+ observer.observe(target);
4197
+ }
4198
+
4199
+ var addEventListener = target.addEventListener || target.on;
4200
+ addEventListener.call(target, eventName, function listener(evt) {
4201
+ // OK NO PROMISE
4202
+ if (typeof Node !== 'undefined' && elt instanceof Node && target !== elt && !elt.isConnected) {
4203
+ target.removeEventListener(eventName, listener);
4204
+ return;
4205
+ }
4206
+
4207
+ var ctx = runtime.makeContext(elt, onFeature, elt, evt);
4208
+ if (eventSpec.elsewhere && elt.contains(evt.target)) {
4209
+ return;
4210
+ }
4211
+ if (eventSpec.from) {
4212
+ ctx.result = target;
4213
+ }
4214
+
4215
+ // establish context
4216
+ for (const arg of eventSpec.args) {
4217
+ let eventValue = ctx.event[arg.value];
4218
+ if (eventValue !== undefined) {
4219
+ ctx.locals[arg.value] = eventValue;
4220
+ } else if ('detail' in ctx.event) {
4221
+ ctx.locals[arg.value] = ctx.event['detail'][arg.value];
4222
+ }
4223
+ }
4224
+
4225
+ // install error handler if any
4226
+ ctx.meta.errorHandler = errorHandler;
4227
+ ctx.meta.errorSymbol = errorSymbol;
4228
+ ctx.meta.finallyHandler = finallyHandler;
4229
+
4230
+ // apply filter
4231
+ if (eventSpec.filter) {
4232
+ var initialCtx = ctx.meta.context;
4233
+ ctx.meta.context = ctx.event;
4234
+ try {
4235
+ var value = eventSpec.filter.evaluate(ctx); //OK NO PROMISE
4236
+ if (value) {
4237
+ // match the javascript semantics for if statements
4238
+ } else {
4239
+ return;
4240
+ }
4241
+ } finally {
4242
+ ctx.meta.context = initialCtx;
4243
+ }
4244
+ }
4245
+
4246
+ if (eventSpec.inExpr) {
4247
+ var inElement = evt.target;
4248
+ while (true) {
4249
+ if (inElement.matches && inElement.matches(eventSpec.inExpr.css)) {
4250
+ ctx.result = inElement;
4251
+ break;
4252
+ } else {
4253
+ inElement = inElement.parentElement;
4254
+ if (inElement == null) {
4255
+ return; // no match found
4256
+ }
4257
+ }
4258
+ }
4259
+ }
4260
+
4261
+ // verify counts
4262
+ eventSpec.execCount++;
4263
+ if (eventSpec.startCount) {
4264
+ if (eventSpec.endCount) {
4265
+ if (
4266
+ eventSpec.execCount < eventSpec.startCount ||
4267
+ eventSpec.execCount > eventSpec.endCount
4268
+ ) {
4269
+ return;
4270
+ }
4271
+ } else if (eventSpec.unbounded) {
4272
+ if (eventSpec.execCount < eventSpec.startCount) {
4273
+ return;
4274
+ }
4275
+ } else if (eventSpec.execCount !== eventSpec.startCount) {
4276
+ return;
4277
+ }
4278
+ }
4279
+
4280
+ //debounce
4281
+ if (eventSpec.debounceTime) {
4282
+ if (eventSpec.debounced) {
4283
+ clearTimeout(eventSpec.debounced);
4284
+ }
4285
+ eventSpec.debounced = setTimeout(function () {
4286
+ onFeature.execute(ctx);
4287
+ }, eventSpec.debounceTime);
4288
+ return;
4289
+ }
4290
+
4291
+ // throttle
4292
+ if (eventSpec.throttleTime) {
4293
+ if (
4294
+ eventSpec.lastExec &&
4295
+ Date.now() < eventSpec.lastExec + eventSpec.throttleTime
4296
+ ) {
4297
+ return;
4298
+ } else {
4299
+ eventSpec.lastExec = Date.now();
4300
+ }
4301
+ }
4302
+
4303
+ // apply execute
4304
+ onFeature.execute(ctx);
4305
+ });
4306
+ });
4307
+ }
4308
+ },
4309
+ };
4310
+ parser.setParent(start, onFeature);
4311
+ return onFeature;
4312
+ });
4313
+
4314
+ parser.addFeature("def", function (parser, runtime, tokens) {
4315
+ if (!tokens.matchToken("def")) return;
4316
+ var functionName = parser.requireElement("dotOrColonPath", tokens);
4317
+ var nameVal = functionName.evaluate(); // OK
4318
+ var nameSpace = nameVal.split(".");
4319
+ var funcName = nameSpace.pop();
4320
+
4321
+ var args = [];
4322
+ if (tokens.matchOpToken("(")) {
4323
+ if (tokens.matchOpToken(")")) {
4324
+ // emtpy args list
4325
+ } else {
4326
+ do {
4327
+ args.push(tokens.requireTokenType("IDENTIFIER"));
4328
+ } while (tokens.matchOpToken(","));
4329
+ tokens.requireOpToken(")");
4330
+ }
4331
+ }
4332
+
4333
+ var start = parser.requireElement("commandList", tokens);
4334
+
4335
+ if (tokens.matchToken("catch")) {
4336
+ var errorSymbol = tokens.requireTokenType("IDENTIFIER").value;
4337
+ var errorHandler = parser.parseElement("commandList", tokens);
4338
+ }
4339
+
4340
+ if (tokens.matchToken("finally")) {
4341
+ var finallyHandler = parser.requireElement("commandList", tokens);
4342
+ parser.ensureTerminated(finallyHandler);
4343
+ }
4344
+
4345
+ var functionFeature = {
4346
+ displayName:
4347
+ funcName +
4348
+ "(" +
4349
+ args
4350
+ .map(function (arg) {
4351
+ return arg.value;
4352
+ })
4353
+ .join(", ") +
4354
+ ")",
4355
+ name: funcName,
4356
+ args: args,
4357
+ start: start,
4358
+ errorHandler: errorHandler,
4359
+ errorSymbol: errorSymbol,
4360
+ finallyHandler: finallyHandler,
4361
+ install: function (target, source) {
4362
+ var func = function () {
4363
+ // null, worker
4364
+ var ctx = runtime.makeContext(source, functionFeature, target, null);
4365
+
4366
+ // install error handler if any
4367
+ ctx.meta.errorHandler = errorHandler;
4368
+ ctx.meta.errorSymbol = errorSymbol;
4369
+ ctx.meta.finallyHandler = finallyHandler;
4370
+
4371
+ for (var i = 0; i < args.length; i++) {
4372
+ var name = args[i];
4373
+ var argumentVal = arguments[i];
4374
+ if (name) {
4375
+ ctx.locals[name.value] = argumentVal;
4376
+ }
4377
+ }
4378
+ ctx.meta.caller = arguments[args.length];
4379
+ if (ctx.meta.caller) {
4380
+ ctx.meta.callingCommand = ctx.meta.caller.meta.command;
4381
+ }
4382
+ var resolve,
4383
+ reject = null;
4384
+ var promise = new Promise(function (theResolve, theReject) {
4385
+ resolve = theResolve;
4386
+ reject = theReject;
4387
+ });
4388
+ start.execute(ctx);
4389
+ if (ctx.meta.returned) {
4390
+ return ctx.meta.returnValue;
4391
+ } else {
4392
+ ctx.meta.resolve = resolve;
4393
+ ctx.meta.reject = reject;
4394
+ return promise;
4395
+ }
4396
+ };
4397
+ func.hyperfunc = true;
4398
+ func.hypername = nameVal;
4399
+ runtime.assignToNamespace(target, nameSpace, funcName, func);
4400
+ },
4401
+ };
4402
+
4403
+ parser.ensureTerminated(start);
4404
+
4405
+ // terminate error handler if any
4406
+ if (errorHandler) {
4407
+ parser.ensureTerminated(errorHandler);
4408
+ }
4409
+
4410
+ parser.setParent(start, functionFeature);
4411
+ return functionFeature;
4412
+ });
4413
+
4414
+ parser.addFeature("set", function (parser, runtime, tokens) {
4415
+ let setCmd = parser.parseElement("setCommand", tokens);
4416
+ if (setCmd) {
4417
+ if (setCmd.target.scope !== "element") {
4418
+ parser.raiseParseError(tokens, "variables declared at the feature level must be element scoped.");
4419
+ }
4420
+ let setFeature = {
4421
+ start: setCmd,
4422
+ install: function (target, source) {
4423
+ setCmd && setCmd.execute(runtime.makeContext(target, setFeature, target, null));
4424
+ },
4425
+ };
4426
+ parser.ensureTerminated(setCmd);
4427
+ return setFeature;
4428
+ }
4429
+ });
4430
+
4431
+ parser.addFeature("init", function (parser, runtime, tokens) {
4432
+ if (!tokens.matchToken("init")) return;
4433
+
4434
+ var immediately = tokens.matchToken("immediately");
4435
+
4436
+ var start = parser.requireElement("commandList", tokens);
4437
+ var initFeature = {
4438
+ start: start,
4439
+ install: function (target, source) {
4440
+ let handler = function () {
4441
+ start && start.execute(runtime.makeContext(target, initFeature, target, null));
4442
+ };
4443
+ if (immediately) {
4444
+ handler();
4445
+ } else {
4446
+ setTimeout(handler, 0);
4447
+ }
4448
+ },
4449
+ };
4450
+
4451
+ // terminate body
4452
+ parser.ensureTerminated(start);
4453
+ parser.setParent(start, initFeature);
4454
+ return initFeature;
4455
+ });
4456
+
4457
+ parser.addFeature("worker", function (parser, runtime, tokens) {
4458
+ if (tokens.matchToken("worker")) {
4459
+ parser.raiseParseError(
4460
+ tokens,
4461
+ "In order to use the 'worker' feature, include " +
4462
+ "the _hyperscript worker plugin. See " +
4463
+ "https://hyperscript.org/features/worker/ for " +
4464
+ "more info."
4465
+ );
4466
+ return undefined
4467
+ }
4468
+ });
4469
+
4470
+ parser.addFeature("behavior", function (parser, runtime, tokens) {
4471
+ if (!tokens.matchToken("behavior")) return;
4472
+ var path = parser.requireElement("dotOrColonPath", tokens).evaluate();
4473
+ var nameSpace = path.split(".");
4474
+ var name = nameSpace.pop();
4475
+
4476
+ var formalParams = [];
4477
+ if (tokens.matchOpToken("(") && !tokens.matchOpToken(")")) {
4478
+ do {
4479
+ formalParams.push(tokens.requireTokenType("IDENTIFIER").value);
4480
+ } while (tokens.matchOpToken(","));
4481
+ tokens.requireOpToken(")");
4482
+ }
4483
+ var hs = parser.requireElement("hyperscript", tokens);
4484
+ for (var i = 0; i < hs.features.length; i++) {
4485
+ var feature = hs.features[i];
4486
+ feature.behavior = path;
4487
+ }
4488
+
4489
+ return {
4490
+ install: function (target, source) {
4491
+ runtime.assignToNamespace(
4492
+ globalScope.document && globalScope.document.body,
4493
+ nameSpace,
4494
+ name,
4495
+ function (target, source, innerArgs) {
4496
+ var internalData = runtime.getInternalData(target);
4497
+ var elementScope = getOrInitObject(internalData, path + "Scope");
4498
+ for (var i = 0; i < formalParams.length; i++) {
4499
+ elementScope[formalParams[i]] = innerArgs[formalParams[i]];
4500
+ }
4501
+ hs.apply(target, source);
4502
+ }
4503
+ );
4504
+ },
4505
+ };
4506
+ });
4507
+
4508
+ parser.addFeature("install", function (parser, runtime, tokens) {
4509
+ if (!tokens.matchToken("install")) return;
4510
+ var behaviorPath = parser.requireElement("dotOrColonPath", tokens).evaluate();
4511
+ var behaviorNamespace = behaviorPath.split(".");
4512
+ var args = parser.parseElement("namedArgumentList", tokens);
4513
+
4514
+ var installFeature;
4515
+ return (installFeature = {
4516
+ install: function (target, source) {
4517
+ runtime.unifiedEval(
4518
+ {
4519
+ args: [args],
4520
+ op: function (ctx, args) {
4521
+ var behavior = globalScope;
4522
+ for (var i = 0; i < behaviorNamespace.length; i++) {
4523
+ behavior = behavior[behaviorNamespace[i]];
4524
+ if (typeof behavior !== "object" && typeof behavior !== "function")
4525
+ throw new Error("No such behavior defined as " + behaviorPath);
4526
+ }
4527
+
4528
+ if (!(behavior instanceof Function))
4529
+ throw new Error(behaviorPath + " is not a behavior");
4530
+
4531
+ behavior(target, source, args);
4532
+ },
4533
+ },
4534
+ runtime.makeContext(target, installFeature, target)
4535
+ );
4536
+ },
4537
+ });
4538
+ });
4539
+
4540
+ parser.addGrammarElement("jsBody", function (parser, runtime, tokens) {
4541
+ var jsSourceStart = tokens.currentToken().start;
4542
+ var jsLastToken = tokens.currentToken();
4543
+
4544
+ var funcNames = [];
4545
+ var funcName = "";
4546
+ var expectFunctionDeclaration = false;
4547
+ while (tokens.hasMore()) {
4548
+ jsLastToken = tokens.consumeToken();
4549
+ var peek = tokens.token(0, true);
4550
+ if (peek.type === "IDENTIFIER" && peek.value === "end") {
4551
+ break;
4552
+ }
4553
+ if (expectFunctionDeclaration) {
4554
+ if (jsLastToken.type === "IDENTIFIER" || jsLastToken.type === "NUMBER") {
4555
+ funcName += jsLastToken.value;
4556
+ } else {
4557
+ if (funcName !== "") funcNames.push(funcName);
4558
+ funcName = "";
4559
+ expectFunctionDeclaration = false;
4560
+ }
4561
+ } else if (jsLastToken.type === "IDENTIFIER" && jsLastToken.value === "function") {
4562
+ expectFunctionDeclaration = true;
4563
+ }
4564
+ }
4565
+ var jsSourceEnd = jsLastToken.end + 1;
4566
+
4567
+ return {
4568
+ type: "jsBody",
4569
+ exposedFunctionNames: funcNames,
4570
+ jsSource: tokens.source.substring(jsSourceStart, jsSourceEnd),
4571
+ };
4572
+ });
4573
+
4574
+ parser.addFeature("js", function (parser, runtime, tokens) {
4575
+ if (!tokens.matchToken("js")) return;
4576
+ var jsBody = parser.requireElement("jsBody", tokens);
4577
+
4578
+ var jsSource =
4579
+ jsBody.jsSource +
4580
+ "\nreturn { " +
4581
+ jsBody.exposedFunctionNames
4582
+ .map(function (name) {
4583
+ return name + ":" + name;
4584
+ })
4585
+ .join(",") +
4586
+ " } ";
4587
+ var func = new Function(jsSource);
4588
+
4589
+ return {
4590
+ jsSource: jsSource,
4591
+ function: func,
4592
+ exposedFunctionNames: jsBody.exposedFunctionNames,
4593
+ install: function () {
4594
+ Object.assign(globalScope, func());
4595
+ },
4596
+ };
4597
+ });
4598
+
4599
+ parser.addCommand("js", function (parser, runtime, tokens) {
4600
+ if (!tokens.matchToken("js")) return;
4601
+ // Parse inputs
4602
+ var inputs = [];
4603
+ if (tokens.matchOpToken("(")) {
4604
+ if (tokens.matchOpToken(")")) {
4605
+ // empty input list
4606
+ } else {
4607
+ do {
4608
+ var inp = tokens.requireTokenType("IDENTIFIER");
4609
+ inputs.push(inp.value);
4610
+ } while (tokens.matchOpToken(","));
4611
+ tokens.requireOpToken(")");
4612
+ }
4613
+ }
4614
+
4615
+ var jsBody = parser.requireElement("jsBody", tokens);
4616
+ tokens.matchToken("end");
4617
+
4618
+ var func = varargConstructor(Function, inputs.concat([jsBody.jsSource]));
4619
+
4620
+ var command = {
4621
+ jsSource: jsBody.jsSource,
4622
+ function: func,
4623
+ inputs: inputs,
4624
+ op: function (context) {
4625
+ var args = [];
4626
+ inputs.forEach(function (input) {
4627
+ args.push(runtime.resolveSymbol(input, context, 'default'));
4628
+ });
4629
+ var result = func.apply(globalScope, args);
4630
+ if (result && typeof result.then === "function") {
4631
+ return new Promise(function (resolve) {
4632
+ result.then(function (actualResult) {
4633
+ context.result = actualResult;
4634
+ resolve(runtime.findNext(this, context));
4635
+ });
4636
+ });
4637
+ } else {
4638
+ context.result = result;
4639
+ return runtime.findNext(this, context);
4640
+ }
4641
+ },
4642
+ };
4643
+ return command;
4644
+ });
4645
+
4646
+ parser.addCommand("async", function (parser, runtime, tokens) {
4647
+ if (!tokens.matchToken("async")) return;
4648
+ if (tokens.matchToken("do")) {
4649
+ var body = parser.requireElement("commandList", tokens);
4650
+
4651
+ // Append halt
4652
+ var end = body;
4653
+ while (end.next) end = end.next;
4654
+ end.next = runtime.HALT;
4655
+
4656
+ tokens.requireToken("end");
4657
+ } else {
4658
+ var body = parser.requireElement("command", tokens);
4659
+ }
4660
+ var command = {
4661
+ body: body,
4662
+ op: function (context) {
4663
+ setTimeout(function () {
4664
+ body.execute(context);
4665
+ });
4666
+ return runtime.findNext(this, context);
4667
+ },
4668
+ };
4669
+ parser.setParent(body, command);
4670
+ return command;
4671
+ });
4672
+
4673
+ parser.addCommand("tell", function (parser, runtime, tokens) {
4674
+ var startToken = tokens.currentToken();
4675
+ if (!tokens.matchToken("tell")) return;
4676
+ var value = parser.requireElement("expression", tokens);
4677
+ var body = parser.requireElement("commandList", tokens);
4678
+ if (tokens.hasMore() && !parser.featureStart(tokens.currentToken())) {
4679
+ tokens.requireToken("end");
4680
+ }
4681
+ var slot = "tell_" + startToken.start;
4682
+ var tellCmd = {
4683
+ value: value,
4684
+ body: body,
4685
+ args: [value],
4686
+ resolveNext: function (context) {
4687
+ var iterator = context.meta.iterators[slot];
4688
+ if (iterator.index < iterator.value.length) {
4689
+ context.you = iterator.value[iterator.index++];
4690
+ return body;
4691
+ } else {
4692
+ // restore original me
4693
+ context.you = iterator.originalYou;
4694
+ if (this.next) {
4695
+ return this.next;
4696
+ } else {
4697
+ return runtime.findNext(this.parent, context);
4698
+ }
4699
+ }
4700
+ },
4701
+ op: function (context, value) {
4702
+ if (value == null) {
4703
+ value = [];
4704
+ } else if (!(Array.isArray(value) || value instanceof NodeList)) {
4705
+ value = [value];
4706
+ }
4707
+ context.meta.iterators[slot] = {
4708
+ originalYou: context.you,
4709
+ index: 0,
4710
+ value: value,
4711
+ };
4712
+ return this.resolveNext(context);
4713
+ },
4714
+ };
4715
+ parser.setParent(body, tellCmd);
4716
+ return tellCmd;
4717
+ });
4718
+
4719
+ parser.addCommand("wait", function (parser, runtime, tokens) {
4720
+ if (!tokens.matchToken("wait")) return;
4721
+ var command;
4722
+
4723
+ // wait on event
4724
+ if (tokens.matchToken("for")) {
4725
+ tokens.matchToken("a"); // optional "a"
4726
+ var events = [];
4727
+ do {
4728
+ var lookahead = tokens.token(0);
4729
+ if (lookahead.type === 'NUMBER' || lookahead.type === 'L_PAREN') {
4730
+ events.push({
4731
+ time: parser.requireElement('expression', tokens).evaluate() // TODO: do we want to allow async here?
4732
+ })
4733
+ } else {
4734
+ events.push({
4735
+ name: parser.requireElement("dotOrColonPath", tokens, "Expected event name").evaluate(),
4736
+ args: parseEventArgs(tokens),
4737
+ });
4738
+ }
4739
+ } while (tokens.matchToken("or"));
4740
+
4741
+ if (tokens.matchToken("from")) {
4742
+ var on = parser.requireElement("expression", tokens);
4743
+ }
4744
+
4745
+ // wait on event
4746
+ command = {
4747
+ event: events,
4748
+ on: on,
4749
+ args: [on],
4750
+ op: function (context, on) {
4751
+ var target = on ? on : context.me;
4752
+ if (!(target instanceof EventTarget))
4753
+ throw new Error("Not a valid event target: " + this.on.sourceFor());
4754
+ return new Promise((resolve) => {
4755
+ var resolved = false;
4756
+ for (const eventInfo of events) {
4757
+ var listener = (event) => {
4758
+ context.result = event;
4759
+ if (eventInfo.args) {
4760
+ for (const arg of eventInfo.args) {
4761
+ context.locals[arg.value] =
4762
+ event[arg.value] || (event.detail ? event.detail[arg.value] : null);
4763
+ }
4764
+ }
4765
+ if (!resolved) {
4766
+ resolved = true;
4767
+ resolve(runtime.findNext(this, context));
4768
+ }
4769
+ };
4770
+ if (eventInfo.name){
4771
+ target.addEventListener(eventInfo.name, listener, {once: true});
4772
+ } else if (eventInfo.time != null) {
4773
+ setTimeout(listener, eventInfo.time, eventInfo.time)
4774
+ }
4775
+ }
4776
+ });
4777
+ },
4778
+ };
4779
+ return command;
4780
+ } else {
4781
+ var time;
4782
+ if (tokens.matchToken("a")) {
4783
+ tokens.requireToken("tick");
4784
+ time = 0;
4785
+ } else {
4786
+ time = parser.requireElement("expression", tokens);
4787
+ }
4788
+
4789
+ command = {
4790
+ type: "waitCmd",
4791
+ time: time,
4792
+ args: [time],
4793
+ op: function (context, timeValue) {
4794
+ return new Promise((resolve) => {
4795
+ setTimeout(() => {
4796
+ resolve(runtime.findNext(this, context));
4797
+ }, timeValue);
4798
+ });
4799
+ },
4800
+ execute: function (context) {
4801
+ return runtime.unifiedExec(this, context);
4802
+ },
4803
+ };
4804
+ return command;
4805
+ }
4806
+ });
4807
+
4808
+ // TODO - colon path needs to eventually become part of ruby-style symbols
4809
+ parser.addGrammarElement("dotOrColonPath", function (parser, runtime, tokens) {
4810
+ var root = tokens.matchTokenType("IDENTIFIER");
4811
+ if (root) {
4812
+ var path = [root.value];
4813
+
4814
+ var separator = tokens.matchOpToken(".") || tokens.matchOpToken(":");
4815
+ if (separator) {
4816
+ do {
4817
+ path.push(tokens.requireTokenType("IDENTIFIER", "NUMBER").value);
4818
+ } while (tokens.matchOpToken(separator.value));
4819
+ }
4820
+
4821
+ return {
4822
+ type: "dotOrColonPath",
4823
+ path: path,
4824
+ evaluate: function () {
4825
+ return path.join(separator ? separator.value : "");
4826
+ },
4827
+ };
4828
+ }
4829
+ });
4830
+
4831
+
4832
+ parser.addGrammarElement("eventName", function (parser, runtime, tokens) {
4833
+ var token;
4834
+ if ((token = tokens.matchTokenType("STRING"))) {
4835
+ return {
4836
+ evaluate: function() {
4837
+ return token.value;
4838
+ },
4839
+ };
4840
+ }
4841
+
4842
+ return parser.parseElement("dotOrColonPath", tokens);
4843
+ });
4844
+
4845
+ function parseSendCmd(cmdType, parser, runtime, tokens) {
4846
+ var eventName = parser.requireElement("eventName", tokens);
4847
+
4848
+ var details = parser.parseElement("namedArgumentList", tokens);
4849
+ if ((cmdType === "send" && tokens.matchToken("to")) ||
4850
+ (cmdType === "trigger" && tokens.matchToken("on"))) {
4851
+ var toExpr = parser.requireElement("expression", tokens);
4852
+ } else {
4853
+ var toExpr = parser.requireElement("implicitMeTarget", tokens);
4854
+ }
4855
+
4856
+ var sendCmd = {
4857
+ eventName: eventName,
4858
+ details: details,
4859
+ to: toExpr,
4860
+ args: [toExpr, eventName, details],
4861
+ op: function (context, to, eventName, details) {
4862
+ runtime.nullCheck(to, toExpr);
4863
+ runtime.forEach(to, function (target) {
4864
+ runtime.triggerEvent(target, eventName, details, context.me);
4865
+ });
4866
+ return runtime.findNext(sendCmd, context);
4867
+ },
4868
+ };
4869
+ return sendCmd;
4870
+ }
4871
+
4872
+ parser.addCommand("trigger", function (parser, runtime, tokens) {
4873
+ if (tokens.matchToken("trigger")) {
4874
+ return parseSendCmd("trigger", parser, runtime, tokens);
4875
+ }
4876
+ });
4877
+
4878
+ parser.addCommand("send", function (parser, runtime, tokens) {
4879
+ if (tokens.matchToken("send")) {
4880
+ return parseSendCmd("send", parser, runtime, tokens);
4881
+ }
4882
+ });
4883
+
4884
+ var parseReturnFunction = function (parser, runtime, tokens, returnAValue) {
4885
+ if (returnAValue) {
4886
+ if (parser.commandBoundary(tokens.currentToken())) {
4887
+ parser.raiseParseError(tokens, "'return' commands must return a value. If you do not wish to return a value, use 'exit' instead.");
4888
+ } else {
4889
+ var value = parser.requireElement("expression", tokens);
4890
+ }
4891
+ }
4892
+
4893
+ var returnCmd = {
4894
+ value: value,
4895
+ args: [value],
4896
+ op: function (context, value) {
4897
+ var resolve = context.meta.resolve;
4898
+ context.meta.returned = true;
4899
+ context.meta.returnValue = value;
4900
+ if (resolve) {
4901
+ if (value) {
4902
+ resolve(value);
4903
+ } else {
4904
+ resolve();
4905
+ }
4906
+ }
4907
+ return runtime.HALT;
4908
+ },
4909
+ };
4910
+ return returnCmd;
4911
+ };
4912
+
4913
+ parser.addCommand("return", function (parser, runtime, tokens) {
4914
+ if (tokens.matchToken("return")) {
4915
+ return parseReturnFunction(parser, runtime, tokens, true);
4916
+ }
4917
+ });
4918
+
4919
+ parser.addCommand("exit", function (parser, runtime, tokens) {
4920
+ if (tokens.matchToken("exit")) {
4921
+ return parseReturnFunction(parser, runtime, tokens, false);
4922
+ }
4923
+ });
4924
+
4925
+ parser.addCommand("halt", function (parser, runtime, tokens) {
4926
+ if (tokens.matchToken("halt")) {
4927
+ if (tokens.matchToken("the")) {
4928
+ tokens.requireToken("event");
4929
+ // optional possessive
4930
+ if (tokens.matchOpToken("'")) {
4931
+ tokens.requireToken("s");
4932
+ }
4933
+ var keepExecuting = true;
4934
+ }
4935
+ if (tokens.matchToken("bubbling")) {
4936
+ var bubbling = true;
4937
+ } else if (tokens.matchToken("default")) {
4938
+ var haltDefault = true;
4939
+ }
4940
+ var exit = parseReturnFunction(parser, runtime, tokens, false);
4941
+
4942
+ var haltCmd = {
4943
+ keepExecuting: true,
4944
+ bubbling: bubbling,
4945
+ haltDefault: haltDefault,
4946
+ exit: exit,
4947
+ op: function (ctx) {
4948
+ if (ctx.event) {
4949
+ if (bubbling) {
4950
+ ctx.event.stopPropagation();
4951
+ } else if (haltDefault) {
4952
+ ctx.event.preventDefault();
4953
+ } else {
4954
+ ctx.event.stopPropagation();
4955
+ ctx.event.preventDefault();
4956
+ }
4957
+ if (keepExecuting) {
4958
+ return runtime.findNext(this, ctx);
4959
+ } else {
4960
+ return exit;
4961
+ }
4962
+ }
4963
+ },
4964
+ };
4965
+ return haltCmd;
4966
+ }
4967
+ });
4968
+
4969
+ parser.addCommand("log", function (parser, runtime, tokens) {
4970
+ if (!tokens.matchToken("log")) return;
4971
+ var exprs = [parser.parseElement("expression", tokens)];
4972
+ while (tokens.matchOpToken(",")) {
4973
+ exprs.push(parser.requireElement("expression", tokens));
4974
+ }
4975
+ if (tokens.matchToken("with")) {
4976
+ var withExpr = parser.requireElement("expression", tokens);
4977
+ }
4978
+ var logCmd = {
4979
+ exprs: exprs,
4980
+ withExpr: withExpr,
4981
+ args: [withExpr, exprs],
4982
+ op: function (ctx, withExpr, values) {
4983
+ if (withExpr) {
4984
+ withExpr.apply(null, values);
4985
+ } else {
4986
+ console.log.apply(null, values);
4987
+ }
4988
+ return runtime.findNext(this, ctx);
4989
+ },
4990
+ };
4991
+ return logCmd;
4992
+ });
4993
+
4994
+ parser.addCommand("throw", function (parser, runtime, tokens) {
4995
+ if (!tokens.matchToken("throw")) return;
4996
+ var expr = parser.requireElement("expression", tokens);
4997
+ var throwCmd = {
4998
+ expr: expr,
4999
+ args: [expr],
5000
+ op: function (ctx, expr) {
5001
+ runtime.registerHyperTrace(ctx, expr);
5002
+ throw expr;
5003
+ },
5004
+ };
5005
+ return throwCmd;
5006
+ });
5007
+
5008
+ var parseCallOrGet = function (parser, runtime, tokens) {
5009
+ var expr = parser.requireElement("expression", tokens);
5010
+ var callCmd = {
5011
+ expr: expr,
5012
+ args: [expr],
5013
+ op: function (context, result) {
5014
+ context.result = result;
5015
+ return runtime.findNext(callCmd, context);
5016
+ },
5017
+ };
5018
+ return callCmd;
5019
+ };
5020
+ parser.addCommand("call", function (parser, runtime, tokens) {
5021
+ if (!tokens.matchToken("call")) return;
5022
+ var call = parseCallOrGet(parser, runtime, tokens);
5023
+ if (call.expr && call.expr.type !== "functionCall") {
5024
+ parser.raiseParseError(tokens, "Must be a function invocation");
5025
+ }
5026
+ return call;
5027
+ });
5028
+ parser.addCommand("get", function (parser, runtime, tokens) {
5029
+ if (tokens.matchToken("get")) {
5030
+ return parseCallOrGet(parser, runtime, tokens);
5031
+ }
5032
+ });
5033
+
5034
+ parser.addCommand("make", function (parser, runtime, tokens) {
5035
+ if (!tokens.matchToken("make")) return;
5036
+ tokens.matchToken("a") || tokens.matchToken("an");
5037
+
5038
+ var expr = parser.requireElement("expression", tokens);
5039
+
5040
+ var args = [];
5041
+ if (expr.type !== "queryRef" && tokens.matchToken("from")) {
5042
+ do {
5043
+ args.push(parser.requireElement("expression", tokens));
5044
+ } while (tokens.matchOpToken(","));
5045
+ }
5046
+
5047
+ if (tokens.matchToken("called")) {
5048
+ var target = parser.requireElement("symbol", tokens);
5049
+ }
5050
+
5051
+ var command;
5052
+ if (expr.type === "queryRef") {
5053
+ command = {
5054
+ op: function (ctx) {
5055
+ var match,
5056
+ tagname = "div",
5057
+ id,
5058
+ classes = [];
5059
+ var re = /(?:(^|#|\.)([^#\. ]+))/g;
5060
+ while ((match = re.exec(expr.css))) {
5061
+ if (match[1] === "") tagname = match[2].trim();
5062
+ else if (match[1] === "#") id = match[2].trim();
5063
+ else classes.push(match[2].trim());
5064
+ }
5065
+
5066
+ var result = document.createElement(tagname);
5067
+ if (id !== undefined) result.id = id;
5068
+ for (var i = 0; i < classes.length; i++) {
5069
+ var cls = classes[i];
5070
+ result.classList.add(cls)
5071
+ }
5072
+
5073
+ ctx.result = result;
5074
+ if (target){
5075
+ runtime.setSymbol(target.name, ctx, target.scope, result);
5076
+ }
5077
+
5078
+ return runtime.findNext(this, ctx);
5079
+ },
5080
+ };
5081
+ return command;
5082
+ } else {
5083
+ command = {
5084
+ args: [expr, args],
5085
+ op: function (ctx, expr, args) {
5086
+ ctx.result = varargConstructor(expr, args);
5087
+ if (target){
5088
+ runtime.setSymbol(target.name, ctx, target.scope, ctx.result);
5089
+ }
5090
+
5091
+ return runtime.findNext(this, ctx);
5092
+ },
5093
+ };
5094
+ return command;
5095
+ }
5096
+ });
5097
+
5098
+ parser.addGrammarElement("pseudoCommand", function (parser, runtime, tokens) {
5099
+
5100
+ let lookAhead = tokens.token(1);
5101
+ if (!(lookAhead && lookAhead.op && (lookAhead.value === '.' || lookAhead.value === "("))) {
5102
+ return null;
5103
+ }
5104
+
5105
+ var expr = parser.requireElement("primaryExpression", tokens);
5106
+
5107
+ var rootRoot = expr.root;
5108
+ var root = expr;
5109
+ while (rootRoot.root != null) {
5110
+ root = root.root;
5111
+ rootRoot = rootRoot.root;
5112
+ }
5113
+
5114
+ if (expr.type !== "functionCall") {
5115
+ parser.raiseParseError(tokens, "Pseudo-commands must be function calls");
5116
+ }
5117
+
5118
+ if (root.type === "functionCall" && root.root.root == null) {
5119
+ if (tokens.matchAnyToken("the", "to", "on", "with", "into", "from", "at")) {
5120
+ var realRoot = parser.requireElement("expression", tokens);
5121
+ } else if (tokens.matchToken("me")) {
5122
+ var realRoot = parser.requireElement("implicitMeTarget", tokens);
5123
+ }
5124
+ }
5125
+
5126
+ /** @type {ASTNode} */
5127
+
5128
+ var pseudoCommand
5129
+ if(realRoot){
5130
+ pseudoCommand = {
5131
+ type: "pseudoCommand",
5132
+ root: realRoot,
5133
+ argExressions: root.argExressions,
5134
+ args: [realRoot, root.argExressions],
5135
+ op: function (context, rootRoot, args) {
5136
+ runtime.nullCheck(rootRoot, realRoot);
5137
+ var func = rootRoot[root.root.name];
5138
+ runtime.nullCheck(func, root);
5139
+ if (func.hyperfunc) {
5140
+ args.push(context);
5141
+ }
5142
+ context.result = func.apply(rootRoot, args);
5143
+ return runtime.findNext(pseudoCommand, context);
5144
+ },
5145
+ execute: function (context) {
5146
+ return runtime.unifiedExec(this, context);
5147
+ },
5148
+ }
5149
+ } else {
5150
+ pseudoCommand = {
5151
+ type: "pseudoCommand",
5152
+ expr: expr,
5153
+ args: [expr],
5154
+ op: function (context, result) {
5155
+ context.result = result;
5156
+ return runtime.findNext(pseudoCommand, context);
5157
+ },
5158
+ execute: function (context) {
5159
+ return runtime.unifiedExec(this, context);
5160
+ },
5161
+ };
5162
+ }
5163
+
5164
+ return pseudoCommand;
5165
+ });
5166
+
5167
+ /**
5168
+ * @param {Parser} parser
5169
+ * @param {Runtime} runtime
5170
+ * @param {Tokens} tokens
5171
+ * @param {*} target
5172
+ * @param {*} value
5173
+ * @returns
5174
+ */
5175
+ var makeSetter = function (parser, runtime, tokens, target, value) {
5176
+
5177
+ var symbolWrite = target.type === "symbol";
5178
+ var attributeWrite = target.type === "attributeRef";
5179
+ var styleWrite = target.type === "styleRef";
5180
+ var arrayWrite = target.type === "arrayIndex";
5181
+
5182
+ if (!(attributeWrite || styleWrite || symbolWrite) && target.root == null) {
5183
+ parser.raiseParseError(tokens, "Can only put directly into symbols, not references");
5184
+ }
5185
+
5186
+ var rootElt = null;
5187
+ var prop = null;
5188
+ if (symbolWrite) {
5189
+ // rootElt is null
5190
+ } else if (attributeWrite || styleWrite) {
5191
+ rootElt = parser.requireElement("implicitMeTarget", tokens);
5192
+ var attribute = target;
5193
+ } else if(arrayWrite) {
5194
+ prop = target.firstIndex;
5195
+ rootElt = target.root;
5196
+ } else {
5197
+ prop = target.prop ? target.prop.value : null;
5198
+ var attribute = target.attribute;
5199
+ rootElt = target.root;
5200
+ }
5201
+
5202
+ /** @type {ASTNode} */
5203
+ var setCmd = {
5204
+ target: target,
5205
+ symbolWrite: symbolWrite,
5206
+ value: value,
5207
+ args: [rootElt, prop, value],
5208
+ op: function (context, root, prop, valueToSet) {
5209
+ if (symbolWrite) {
5210
+ runtime.setSymbol(target.name, context, target.scope, valueToSet);
5211
+ } else {
5212
+ runtime.nullCheck(root, rootElt);
5213
+ if (arrayWrite) {
5214
+ root[prop] = valueToSet;
5215
+ } else {
5216
+ runtime.implicitLoop(root, function (elt) {
5217
+ if (attribute) {
5218
+ if (attribute.type === "attributeRef") {
5219
+ if (valueToSet == null) {
5220
+ elt.removeAttribute(attribute.name);
5221
+ } else {
5222
+ elt.setAttribute(attribute.name, valueToSet);
5223
+ }
5224
+ } else {
5225
+ elt.style[attribute.name] = valueToSet;
5226
+ }
5227
+ } else {
5228
+ elt[prop] = valueToSet;
5229
+ }
5230
+ });
5231
+ }
5232
+ }
5233
+ return runtime.findNext(this, context);
5234
+ },
5235
+ };
5236
+ return setCmd;
5237
+ };
5238
+
5239
+ parser.addCommand("default", function (parser, runtime, tokens) {
5240
+ if (!tokens.matchToken("default")) return;
5241
+ var target = parser.requireElement("assignableExpression", tokens);
5242
+ tokens.requireToken("to");
5243
+
5244
+ var value = parser.requireElement("expression", tokens);
5245
+
5246
+ /** @type {ASTNode} */
5247
+ var setter = makeSetter(parser, runtime, tokens, target, value);
5248
+ var defaultCmd = {
5249
+ target: target,
5250
+ value: value,
5251
+ setter: setter,
5252
+ args: [target],
5253
+ op: function (context, target) {
5254
+ if (target) {
5255
+ return runtime.findNext(this, context);
5256
+ } else {
5257
+ return setter;
5258
+ }
5259
+ },
5260
+ };
5261
+ setter.parent = defaultCmd;
5262
+ return defaultCmd;
5263
+ });
5264
+
5265
+ parser.addCommand("set", function (parser, runtime, tokens) {
5266
+ if (!tokens.matchToken("set")) return;
5267
+ if (tokens.currentToken().type === "L_BRACE") {
5268
+ var obj = parser.requireElement("objectLiteral", tokens);
5269
+ tokens.requireToken("on");
5270
+ var target = parser.requireElement("expression", tokens);
5271
+
5272
+ var command = {
5273
+ objectLiteral: obj,
5274
+ target: target,
5275
+ args: [obj, target],
5276
+ op: function (ctx, obj, target) {
5277
+ Object.assign(target, obj);
5278
+ return runtime.findNext(this, ctx);
5279
+ },
5280
+ };
5281
+ return command;
5282
+ }
5283
+
5284
+ try {
5285
+ tokens.pushFollow("to");
5286
+ var target = parser.requireElement("assignableExpression", tokens);
5287
+ } finally {
5288
+ tokens.popFollow();
5289
+ }
5290
+ tokens.requireToken("to");
5291
+ var value = parser.requireElement("expression", tokens);
5292
+ return makeSetter(parser, runtime, tokens, target, value);
5293
+ });
5294
+
5295
+ parser.addCommand("if", function (parser, runtime, tokens) {
5296
+ if (!tokens.matchToken("if")) return;
5297
+ var expr = parser.requireElement("expression", tokens);
5298
+ tokens.matchToken("then"); // optional 'then'
5299
+ var trueBranch = parser.parseElement("commandList", tokens);
5300
+ if (tokens.matchToken("else") || tokens.matchToken("otherwise")) {
5301
+ var falseBranch = parser.parseElement("commandList", tokens);
5302
+ }
5303
+ if (tokens.hasMore()) {
5304
+ tokens.requireToken("end");
5305
+ }
5306
+
5307
+ /** @type {ASTNode} */
5308
+ var ifCmd = {
5309
+ expr: expr,
5310
+ trueBranch: trueBranch,
5311
+ falseBranch: falseBranch,
5312
+ args: [expr],
5313
+ op: function (context, exprValue) {
5314
+ if (exprValue) {
5315
+ return trueBranch;
5316
+ } else if (falseBranch) {
5317
+ return falseBranch;
5318
+ } else {
5319
+ return runtime.findNext(this, context);
5320
+ }
5321
+ },
5322
+ };
5323
+ parser.setParent(trueBranch, ifCmd);
5324
+ parser.setParent(falseBranch, ifCmd);
5325
+ return ifCmd;
5326
+ });
5327
+
5328
+ var parseRepeatExpression = function (parser, tokens, runtime, startedWithForToken) {
5329
+ var innerStartToken = tokens.currentToken();
5330
+ var identifier;
5331
+ if (tokens.matchToken("for") || startedWithForToken) {
5332
+ var identifierToken = tokens.requireTokenType("IDENTIFIER");
5333
+ identifier = identifierToken.value;
5334
+ tokens.requireToken("in");
5335
+ var expression = parser.requireElement("expression", tokens);
5336
+ } else if (tokens.matchToken("in")) {
5337
+ identifier = "it";
5338
+ var expression = parser.requireElement("expression", tokens);
5339
+ } else if (tokens.matchToken("while")) {
5340
+ var whileExpr = parser.requireElement("expression", tokens);
5341
+ } else if (tokens.matchToken("until")) {
5342
+ var isUntil = true;
5343
+ if (tokens.matchToken("event")) {
5344
+ var evt = parser.requireElement("dotOrColonPath", tokens, "Expected event name");
5345
+ if (tokens.matchToken("from")) {
5346
+ var on = parser.requireElement("expression", tokens);
5347
+ }
5348
+ } else {
5349
+ var whileExpr = parser.requireElement("expression", tokens);
5350
+ }
5351
+ } else {
5352
+ if (!parser.commandBoundary(tokens.currentToken()) &&
5353
+ tokens.currentToken().value !== 'forever') {
5354
+ var times = parser.requireElement("expression", tokens);
5355
+ tokens.requireToken("times");
5356
+ } else {
5357
+ tokens.matchToken("forever"); // consume optional forever
5358
+ var forever = true;
5359
+ }
5360
+ }
5361
+
5362
+ if (tokens.matchToken("index")) {
5363
+ var identifierToken = tokens.requireTokenType("IDENTIFIER");
5364
+ var indexIdentifier = identifierToken.value;
5365
+ }
5366
+
5367
+ var loop = parser.parseElement("commandList", tokens);
5368
+ if (loop && evt) {
5369
+ // if this is an event based loop, wait a tick at the end of the loop so that
5370
+ // events have a chance to trigger in the loop condition o_O)))
5371
+ var last = loop;
5372
+ while (last.next) {
5373
+ last = last.next;
5374
+ }
5375
+ var waitATick = {
5376
+ type: "waitATick",
5377
+ op: function () {
5378
+ return new Promise(function (resolve) {
5379
+ setTimeout(function () {
5380
+ resolve(runtime.findNext(waitATick));
5381
+ }, 0);
5382
+ });
5383
+ },
5384
+ };
5385
+ last.next = waitATick;
5386
+ }
5387
+ if (tokens.hasMore()) {
5388
+ tokens.requireToken("end");
5389
+ }
5390
+
5391
+ if (identifier == null) {
5392
+ identifier = "_implicit_repeat_" + innerStartToken.start;
5393
+ var slot = identifier;
5394
+ } else {
5395
+ var slot = identifier + "_" + innerStartToken.start;
5396
+ }
5397
+
5398
+ var repeatCmd = {
5399
+ identifier: identifier,
5400
+ indexIdentifier: indexIdentifier,
5401
+ slot: slot,
5402
+ expression: expression,
5403
+ forever: forever,
5404
+ times: times,
5405
+ until: isUntil,
5406
+ event: evt,
5407
+ on: on,
5408
+ whileExpr: whileExpr,
5409
+ resolveNext: function () {
5410
+ return this;
5411
+ },
5412
+ loop: loop,
5413
+ args: [whileExpr, times],
5414
+ op: function (context, whileValue, times) {
5415
+ var iteratorInfo = context.meta.iterators[slot];
5416
+ var keepLooping = false;
5417
+ var loopVal = null;
5418
+ if (this.forever) {
5419
+ keepLooping = true;
5420
+ } else if (this.until) {
5421
+ if (evt) {
5422
+ keepLooping = context.meta.iterators[slot].eventFired === false;
5423
+ } else {
5424
+ keepLooping = whileValue !== true;
5425
+ }
5426
+ } else if (whileExpr) {
5427
+ keepLooping = whileValue;
5428
+ } else if (times) {
5429
+ keepLooping = iteratorInfo.index < times;
5430
+ } else {
5431
+ var nextValFromIterator = iteratorInfo.iterator.next();
5432
+ keepLooping = !nextValFromIterator.done;
5433
+ loopVal = nextValFromIterator.value;
5434
+ }
5435
+
5436
+ if (keepLooping) {
5437
+ if (iteratorInfo.value) {
5438
+ context.result = context.locals[identifier] = loopVal;
5439
+ } else {
5440
+ context.result = iteratorInfo.index;
5441
+ }
5442
+ if (indexIdentifier) {
5443
+ context.locals[indexIdentifier] = iteratorInfo.index;
5444
+ }
5445
+ iteratorInfo.index++;
5446
+ return loop;
5447
+ } else {
5448
+ context.meta.iterators[slot] = null;
5449
+ return runtime.findNext(this.parent, context);
5450
+ }
5451
+ },
5452
+ };
5453
+ parser.setParent(loop, repeatCmd);
5454
+ var repeatInit = {
5455
+ name: "repeatInit",
5456
+ args: [expression, evt, on],
5457
+ op: function (context, value, event, on) {
5458
+ var iteratorInfo = {
5459
+ index: 0,
5460
+ value: value,
5461
+ eventFired: false,
5462
+ };
5463
+ context.meta.iterators[slot] = iteratorInfo;
5464
+ if (value && value[Symbol.iterator]) {
5465
+ iteratorInfo.iterator = value[Symbol.iterator]();
5466
+ }
5467
+ if (evt) {
5468
+ var target = on || context.me;
5469
+ target.addEventListener(
5470
+ event,
5471
+ function (e) {
5472
+ context.meta.iterators[slot].eventFired = true;
5473
+ },
5474
+ { once: true }
5475
+ );
5476
+ }
5477
+ return repeatCmd; // continue to loop
5478
+ },
5479
+ execute: function (context) {
5480
+ return runtime.unifiedExec(this, context);
5481
+ },
5482
+ };
5483
+ parser.setParent(repeatCmd, repeatInit);
5484
+ return repeatInit;
5485
+ };
5486
+
5487
+ parser.addCommand("repeat", function (parser, runtime, tokens) {
5488
+ if (tokens.matchToken("repeat")) {
5489
+ return parseRepeatExpression(parser, tokens, runtime, false);
5490
+ }
5491
+ });
5492
+
5493
+ parser.addCommand("for", function (parser, runtime, tokens) {
5494
+ if (tokens.matchToken("for")) {
5495
+ return parseRepeatExpression(parser, tokens, runtime, true);
5496
+ }
5497
+ });
5498
+
5499
+ parser.addCommand("continue", function (parser, runtime, tokens) {
5500
+
5501
+ if (!tokens.matchToken("continue")) return;
5502
+
5503
+ var command = {
5504
+ op: function (context) {
5505
+
5506
+ // scan for the closest repeat statement
5507
+ for (var parent = this.parent ; true ; parent = parent.parent) {
5508
+
5509
+ if (parent == undefined) {
5510
+ parser.raiseParseError(tokens, "Command `continue` cannot be used outside of a `repeat` loop.")
5511
+ }
5512
+ if (parent.loop != undefined) {
5513
+ return parent.resolveNext(context)
5514
+ }
5515
+ }
5516
+ }
5517
+ };
5518
+ return command;
5519
+ });
5520
+
5521
+ parser.addCommand("break", function (parser, runtime, tokens) {
5522
+
5523
+ if (!tokens.matchToken("break")) return;
5524
+
5525
+ var command = {
5526
+ op: function (context) {
5527
+
5528
+ // scan for the closest repeat statement
5529
+ for (var parent = this.parent ; true ; parent = parent.parent) {
5530
+
5531
+ if (parent == undefined) {
5532
+ parser.raiseParseError(tokens, "Command `continue` cannot be used outside of a `repeat` loop.")
5533
+ }
5534
+ if (parent.loop != undefined) {
5535
+ return runtime.findNext(parent.parent, context);
5536
+ }
5537
+ }
5538
+ }
5539
+ };
5540
+ return command;
5541
+ });
5542
+
5543
+ parser.addGrammarElement("stringLike", function (parser, runtime, tokens) {
5544
+ return parser.parseAnyOf(["string", "nakedString"], tokens);
5545
+ });
5546
+
5547
+ parser.addCommand("append", function (parser, runtime, tokens) {
5548
+ if (!tokens.matchToken("append")) return;
5549
+ var targetExpr = null;
5550
+
5551
+ var value = parser.requireElement("expression", tokens);
5552
+
5553
+ /** @type {ASTNode} */
5554
+ var implicitResultSymbol = {
5555
+ type: "symbol",
5556
+ evaluate: function (context) {
5557
+ return runtime.resolveSymbol("result", context);
5558
+ },
5559
+ };
5560
+
5561
+ if (tokens.matchToken("to")) {
5562
+ targetExpr = parser.requireElement("expression", tokens);
5563
+ } else {
5564
+ targetExpr = implicitResultSymbol;
5565
+ }
5566
+
5567
+ var setter = null;
5568
+ if (targetExpr.type === "symbol" || targetExpr.type === "attributeRef" || targetExpr.root != null) {
5569
+ setter = makeSetter(parser, runtime, tokens, targetExpr, implicitResultSymbol);
5570
+ }
5571
+
5572
+ var command = {
5573
+ value: value,
5574
+ target: targetExpr,
5575
+ args: [targetExpr, value],
5576
+ op: function (context, target, value) {
5577
+ if (Array.isArray(target)) {
5578
+ target.push(value);
5579
+ return runtime.findNext(this, context);
5580
+ } else if (target instanceof Element) {
5581
+ target.innerHTML += value;
5582
+ return runtime.findNext(this, context);
5583
+ } else if(setter) {
5584
+ context.result = (target || "") + value;
5585
+ return setter;
5586
+ } else {
5587
+ throw Error("Unable to append a value!")
5588
+ }
5589
+ },
5590
+ execute: function (context) {
5591
+ return runtime.unifiedExec(this, context/*, value, target*/);
5592
+ },
5593
+ };
5594
+
5595
+ if (setter != null) {
5596
+ setter.parent = command;
5597
+ }
5598
+
5599
+ return command;
5600
+ });
5601
+
5602
+ function parsePickRange(parser, runtime, tokens) {
5603
+ tokens.matchToken("at") || tokens.matchToken("from");
5604
+ const rv = { includeStart: true, includeEnd: false }
5605
+
5606
+ rv.from = tokens.matchToken("start") ? 0 : parser.requireElement("expression", tokens)
5607
+
5608
+ if (tokens.matchToken("to") || tokens.matchOpToken("..")) {
5609
+ if (tokens.matchToken("end")) {
5610
+ rv.toEnd = true;
5611
+ } else {
5612
+ rv.to = parser.requireElement("expression", tokens);
5613
+ }
5614
+ }
5615
+
5616
+ if (tokens.matchToken("inclusive")) rv.includeEnd = true;
5617
+ else if (tokens.matchToken("exclusive")) rv.includeStart = false;
5618
+
5619
+ return rv;
5620
+ }
5621
+
5622
+ class RegExpIterator {
5623
+ constructor(re, str) {
5624
+ this.re = re;
5625
+ this.str = str;
5626
+ }
5627
+
5628
+ next() {
5629
+ const match = this.re.exec(this.str);
5630
+ if (match === null) return { done: true };
5631
+ else return { value: match };
5632
+ }
5633
+ }
5634
+
5635
+ class RegExpIterable {
5636
+ constructor(re, flags, str) {
5637
+ this.re = re;
5638
+ this.flags = flags;
5639
+ this.str = str;
5640
+ }
5641
+
5642
+ [Symbol.iterator]() {
5643
+ return new RegExpIterator(new RegExp(this.re, this.flags), this.str);
5644
+ }
5645
+ }
5646
+
5647
+ parser.addCommand("pick", (parser, runtime, tokens) => {
5648
+ if (!tokens.matchToken("pick")) return;
5649
+
5650
+ tokens.matchToken("the");
5651
+
5652
+ if (tokens.matchToken("item") || tokens.matchToken("items")
5653
+ || tokens.matchToken("character") || tokens.matchToken("characters")) {
5654
+ const range = parsePickRange(parser, runtime, tokens);
5655
+
5656
+ tokens.requireToken("from");
5657
+ const root = parser.requireElement("expression", tokens);
5658
+
5659
+ return {
5660
+ args: [root, range.from, range.to],
5661
+ op(ctx, root, from, to) {
5662
+ if (range.toEnd) to = root.length;
5663
+ if (!range.includeStart) from++;
5664
+ if (range.includeEnd) to++;
5665
+ if (to == null || to == undefined) to = from + 1;
5666
+ ctx.result = root.slice(from, to);
5667
+ return runtime.findNext(this, ctx);
5668
+ }
5669
+ }
5670
+ }
5671
+
5672
+ if (tokens.matchToken("match")) {
5673
+ tokens.matchToken("of");
5674
+ const re = parser.parseElement("expression", tokens);
5675
+ let flags = ""
5676
+ if (tokens.matchOpToken("|")) {
5677
+ flags = tokens.requireToken("identifier").value;
5678
+ }
5679
+
5680
+ tokens.requireToken("from");
5681
+ const root = parser.parseElement("expression", tokens);
5682
+
5683
+ return {
5684
+ args: [root, re],
5685
+ op(ctx, root, re) {
5686
+ ctx.result = new RegExp(re, flags).exec(root);
5687
+ return runtime.findNext(this, ctx);
5688
+ }
5689
+ }
5690
+ }
5691
+
5692
+ if (tokens.matchToken("matches")) {
5693
+ tokens.matchToken("of");
5694
+ const re = parser.parseElement("expression", tokens);
5695
+ let flags = "gu"
5696
+ if (tokens.matchOpToken("|")) {
5697
+ flags = 'g' + tokens.requireToken("identifier").value.replace('g', '');
5698
+ }
5699
+ console.log('flags', flags)
5700
+
5701
+ tokens.requireToken("from");
5702
+ const root = parser.parseElement("expression", tokens);
5703
+
5704
+ return {
5705
+ args: [root, re],
5706
+ op(ctx, root, re) {
5707
+ ctx.result = new RegExpIterable(re, flags, root);
5708
+ return runtime.findNext(this, ctx);
5709
+ }
5710
+ }
5711
+ }
5712
+ });
5713
+
5714
+ parser.addCommand("increment", function (parser, runtime, tokens) {
5715
+ if (!tokens.matchToken("increment")) return;
5716
+ var amountExpr;
5717
+
5718
+ // This is optional. Defaults to "result"
5719
+ var target = parser.parseElement("assignableExpression", tokens);
5720
+
5721
+ // This is optional. Defaults to 1.
5722
+ if (tokens.matchToken("by")) {
5723
+ amountExpr = parser.requireElement("expression", tokens);
5724
+ }
5725
+
5726
+ var implicitIncrementOp = {
5727
+ type: "implicitIncrementOp",
5728
+ target: target,
5729
+ args: [target, amountExpr],
5730
+ op: function (context, targetValue, amount) {
5731
+ targetValue = targetValue ? parseFloat(targetValue) : 0;
5732
+ amount = amountExpr ? parseFloat(amount) : 1;
5733
+ var newValue = targetValue + amount;
5734
+ context.result = newValue;
5735
+ return newValue;
5736
+ },
5737
+ evaluate: function (context) {
5738
+ return runtime.unifiedEval(this, context);
5739
+ }
5740
+ };
5741
+
5742
+ return makeSetter(parser, runtime, tokens, target, implicitIncrementOp);
5743
+ });
5744
+
5745
+ parser.addCommand("decrement", function (parser, runtime, tokens) {
5746
+ if (!tokens.matchToken("decrement")) return;
5747
+ var amountExpr;
5748
+
5749
+ // This is optional. Defaults to "result"
5750
+ var target = parser.parseElement("assignableExpression", tokens);
5751
+
5752
+ // This is optional. Defaults to 1.
5753
+ if (tokens.matchToken("by")) {
5754
+ amountExpr = parser.requireElement("expression", tokens);
5755
+ }
5756
+
5757
+ var implicitDecrementOp = {
5758
+ type: "implicitDecrementOp",
5759
+ target: target,
5760
+ args: [target, amountExpr],
5761
+ op: function (context, targetValue, amount) {
5762
+ targetValue = targetValue ? parseFloat(targetValue) : 0;
5763
+ amount = amountExpr ? parseFloat(amount) : 1;
5764
+ var newValue = targetValue - amount;
5765
+ context.result = newValue;
5766
+ return newValue;
5767
+ },
5768
+ evaluate: function (context) {
5769
+ return runtime.unifiedEval(this, context);
5770
+ }
5771
+ };
5772
+
5773
+ return makeSetter(parser, runtime, tokens, target, implicitDecrementOp);
5774
+ });
5775
+
5776
+ function parseConversionInfo(tokens, parser) {
5777
+ var type = "text";
5778
+ var conversion;
5779
+ tokens.matchToken("a") || tokens.matchToken("an");
5780
+ if (tokens.matchToken("json") || tokens.matchToken("Object")) {
5781
+ type = "json";
5782
+ } else if (tokens.matchToken("response")) {
5783
+ type = "response";
5784
+ } else if (tokens.matchToken("html")) {
5785
+ type = "html";
5786
+ } else if (tokens.matchToken("text")) {
5787
+ // default, ignore
5788
+ } else {
5789
+ conversion = parser.requireElement("dotOrColonPath", tokens).evaluate();
5790
+ }
5791
+ return {type, conversion};
5792
+ }
5793
+
5794
+ parser.addCommand("fetch", function (parser, runtime, tokens) {
5795
+ if (!tokens.matchToken("fetch")) return;
5796
+ var url = parser.requireElement("stringLike", tokens);
5797
+
5798
+ if (tokens.matchToken("as")) {
5799
+ var conversionInfo = parseConversionInfo(tokens, parser);
5800
+ }
5801
+
5802
+ if (tokens.matchToken("with") && tokens.currentToken().value !== "{") {
5803
+ var args = parser.parseElement("nakedNamedArgumentList", tokens);
5804
+ } else {
5805
+ var args = parser.parseElement("objectLiteral", tokens);
5806
+ }
5807
+
5808
+ if (conversionInfo == null && tokens.matchToken("as")) {
5809
+ conversionInfo = parseConversionInfo(tokens, parser);
5810
+ }
5811
+
5812
+ var type = conversionInfo ? conversionInfo.type : "text";
5813
+ var conversion = conversionInfo ? conversionInfo.conversion : null
5814
+
5815
+ /** @type {ASTNode} */
5816
+ var fetchCmd = {
5817
+ url: url,
5818
+ argExpressions: args,
5819
+ args: [url, args],
5820
+ op: function (context, url, args) {
5821
+ var detail = args || {};
5822
+ detail["sender"] = context.me;
5823
+ detail["headers"] = detail["headers"] || {}
5824
+ var abortController = new AbortController();
5825
+ let abortListener = context.me.addEventListener('fetch:abort', function(){
5826
+ abortController.abort();
5827
+ }, {once: true});
5828
+ detail['signal'] = abortController.signal;
5829
+ runtime.triggerEvent(context.me, "hyperscript:beforeFetch", detail);
5830
+ runtime.triggerEvent(context.me, "fetch:beforeRequest", detail);
5831
+ args = detail;
5832
+ var finished = false;
5833
+ if (args.timeout) {
5834
+ setTimeout(function () {
5835
+ if (!finished) {
5836
+ abortController.abort();
5837
+ }
5838
+ }, args.timeout);
5839
+ }
5840
+ return fetch(url, args)
5841
+ .then(function (resp) {
5842
+ let resultDetails = {response:resp};
5843
+ runtime.triggerEvent(context.me, "fetch:afterResponse", resultDetails);
5844
+ resp = resultDetails.response;
5845
+
5846
+ if (type === "response") {
5847
+ context.result = resp;
5848
+ runtime.triggerEvent(context.me, "fetch:afterRequest", {result:resp});
5849
+ finished = true;
5850
+ return runtime.findNext(fetchCmd, context);
5851
+ }
5852
+ if (type === "json") {
5853
+ return resp.json().then(function (result) {
5854
+ context.result = result;
5855
+ runtime.triggerEvent(context.me, "fetch:afterRequest", {result});
5856
+ finished = true;
5857
+ return runtime.findNext(fetchCmd, context);
5858
+ });
5859
+ }
5860
+ return resp.text().then(function (result) {
5861
+ if (conversion) result = runtime.convertValue(result, conversion);
5862
+
5863
+ if (type === "html") result = runtime.convertValue(result, "Fragment");
5864
+
5865
+ context.result = result;
5866
+ runtime.triggerEvent(context.me, "fetch:afterRequest", {result});
5867
+ finished = true;
5868
+ return runtime.findNext(fetchCmd, context);
5869
+ });
5870
+ })
5871
+ .catch(function (reason) {
5872
+ runtime.triggerEvent(context.me, "fetch:error", {
5873
+ reason: reason,
5874
+ });
5875
+ throw reason;
5876
+ }).finally(function(){
5877
+ context.me.removeEventListener('fetch:abort', abortListener);
5878
+ });
5879
+ },
5880
+ };
5881
+ return fetchCmd;
5882
+ });
5883
+ }
5884
+
5885
+ function hyperscriptWebGrammar(parser) {
5886
+ parser.addCommand("settle", function (parser, runtime, tokens) {
5887
+ if (tokens.matchToken("settle")) {
5888
+ if (!parser.commandBoundary(tokens.currentToken())) {
5889
+ var onExpr = parser.requireElement("expression", tokens);
5890
+ } else {
5891
+ var onExpr = parser.requireElement("implicitMeTarget", tokens);
5892
+ }
5893
+
5894
+ var settleCommand = {
5895
+ type: "settleCmd",
5896
+ args: [onExpr],
5897
+ op: function (context, on) {
5898
+ runtime.nullCheck(on, onExpr);
5899
+ var resolve = null;
5900
+ var resolved = false;
5901
+ var transitionStarted = false;
5902
+
5903
+ var promise = new Promise(function (r) {
5904
+ resolve = r;
5905
+ });
5906
+
5907
+ // listen for a transition begin
5908
+ on.addEventListener(
5909
+ "transitionstart",
5910
+ function () {
5911
+ transitionStarted = true;
5912
+ },
5913
+ { once: true }
5914
+ );
5915
+
5916
+ // if no transition begins in 500ms, cancel
5917
+ setTimeout(function () {
5918
+ if (!transitionStarted && !resolved) {
5919
+ resolve(runtime.findNext(settleCommand, context));
5920
+ }
5921
+ }, 500);
5922
+
5923
+ // continue on a transition emd
5924
+ on.addEventListener(
5925
+ "transitionend",
5926
+ function () {
5927
+ if (!resolved) {
5928
+ resolve(runtime.findNext(settleCommand, context));
5929
+ }
5930
+ },
5931
+ { once: true }
5932
+ );
5933
+ return promise;
5934
+ },
5935
+ execute: function (context) {
5936
+ return runtime.unifiedExec(this, context);
5937
+ },
5938
+ };
5939
+ return settleCommand;
5940
+ }
5941
+ });
5942
+
5943
+ parser.addCommand("add", function (parser, runtime, tokens) {
5944
+ if (tokens.matchToken("add")) {
5945
+ var classRef = parser.parseElement("classRef", tokens);
5946
+ var attributeRef = null;
5947
+ var cssDeclaration = null;
5948
+ if (classRef == null) {
5949
+ attributeRef = parser.parseElement("attributeRef", tokens);
5950
+ if (attributeRef == null) {
5951
+ cssDeclaration = parser.parseElement("styleLiteral", tokens);
5952
+ if (cssDeclaration == null) {
5953
+ parser.raiseParseError(tokens, "Expected either a class reference or attribute expression");
5954
+ }
5955
+ }
5956
+ } else {
5957
+ var classRefs = [classRef];
5958
+ while ((classRef = parser.parseElement("classRef", tokens))) {
5959
+ classRefs.push(classRef);
5960
+ }
5961
+ }
5962
+
5963
+ if (tokens.matchToken("to")) {
5964
+ var toExpr = parser.requireElement("expression", tokens);
5965
+ } else {
5966
+ var toExpr = parser.requireElement("implicitMeTarget", tokens);
5967
+ }
5968
+
5969
+ if (tokens.matchToken("when")) {
5970
+ if (cssDeclaration) {
5971
+ parser.raiseParseError(tokens, "Only class and properties are supported with a when clause")
5972
+ }
5973
+ var when = parser.requireElement("expression", tokens);
5974
+ }
5975
+
5976
+ if (classRefs) {
5977
+ return {
5978
+ classRefs: classRefs,
5979
+ to: toExpr,
5980
+ args: [toExpr, classRefs],
5981
+ op: function (context, to, classRefs) {
5982
+ runtime.nullCheck(to, toExpr);
5983
+ runtime.forEach(classRefs, function (classRef) {
5984
+ runtime.implicitLoop(to, function (target) {
5985
+ if (when) {
5986
+ context.result = target;
5987
+ let whenResult = runtime.evaluateNoPromise(when, context);
5988
+ if (whenResult) {
5989
+ if (target instanceof Element) target.classList.add(classRef.className);
5990
+ } else {
5991
+ if (target instanceof Element) target.classList.remove(classRef.className);
5992
+ }
5993
+ context.result = null;
5994
+ } else {
5995
+ if (target instanceof Element) target.classList.add(classRef.className);
5996
+ }
5997
+ });
5998
+ });
5999
+ return runtime.findNext(this, context);
6000
+ },
6001
+ };
6002
+ } else if (attributeRef) {
6003
+ return {
6004
+ type: "addCmd",
6005
+ attributeRef: attributeRef,
6006
+ to: toExpr,
6007
+ args: [toExpr],
6008
+ op: function (context, to, attrRef) {
6009
+ runtime.nullCheck(to, toExpr);
6010
+ runtime.implicitLoop(to, function (target) {
6011
+ if (when) {
6012
+ context.result = target;
6013
+ let whenResult = runtime.evaluateNoPromise(when, context);
6014
+ if (whenResult) {
6015
+ target.setAttribute(attributeRef.name, attributeRef.value);
6016
+ } else {
6017
+ target.removeAttribute(attributeRef.name);
6018
+ }
6019
+ context.result = null;
6020
+ } else {
6021
+ target.setAttribute(attributeRef.name, attributeRef.value);
6022
+ }
6023
+ });
6024
+ return runtime.findNext(this, context);
6025
+ },
6026
+ execute: function (ctx) {
6027
+ return runtime.unifiedExec(this, ctx);
6028
+ },
6029
+ };
6030
+ } else {
6031
+ return {
6032
+ type: "addCmd",
6033
+ cssDeclaration: cssDeclaration,
6034
+ to: toExpr,
6035
+ args: [toExpr, cssDeclaration],
6036
+ op: function (context, to, css) {
6037
+ runtime.nullCheck(to, toExpr);
6038
+ runtime.implicitLoop(to, function (target) {
6039
+ target.style.cssText += css;
6040
+ });
6041
+ return runtime.findNext(this, context);
6042
+ },
6043
+ execute: function (ctx) {
6044
+ return runtime.unifiedExec(this, ctx);
6045
+ },
6046
+ };
6047
+ }
6048
+ }
6049
+ });
6050
+
6051
+ parser.addGrammarElement("styleLiteral", function (parser, runtime, tokens) {
6052
+ if (!tokens.matchOpToken("{")) return;
6053
+
6054
+ var stringParts = [""]
6055
+ var exprs = []
6056
+
6057
+ while (tokens.hasMore()) {
6058
+ if (tokens.matchOpToken("\\")) {
6059
+ tokens.consumeToken();
6060
+ } else if (tokens.matchOpToken("}")) {
6061
+ break;
6062
+ } else if (tokens.matchToken("$")) {
6063
+ var opencurly = tokens.matchOpToken("{");
6064
+ var expr = parser.parseElement("expression", tokens);
6065
+ if (opencurly) tokens.requireOpToken("}");
6066
+
6067
+ exprs.push(expr)
6068
+ stringParts.push("")
6069
+ } else {
6070
+ var tok = tokens.consumeToken();
6071
+ stringParts[stringParts.length-1] += tokens.source.substring(tok.start, tok.end);
6072
+ }
6073
+
6074
+ stringParts[stringParts.length-1] += tokens.lastWhitespace();
6075
+ }
6076
+
6077
+ return {
6078
+ type: "styleLiteral",
6079
+ args: [exprs],
6080
+ op: function (ctx, exprs) {
6081
+ var rv = "";
6082
+
6083
+ stringParts.forEach(function (part, idx) {
6084
+ rv += part;
6085
+ if (idx in exprs) rv += exprs[idx];
6086
+ });
6087
+
6088
+ return rv;
6089
+ },
6090
+ evaluate: function(ctx) {
6091
+ return runtime.unifiedEval(this, ctx);
6092
+ }
6093
+ }
6094
+ })
6095
+
6096
+ parser.addCommand("remove", function (parser, runtime, tokens) {
6097
+ if (tokens.matchToken("remove")) {
6098
+ var classRef = parser.parseElement("classRef", tokens);
6099
+ var attributeRef = null;
6100
+ var elementExpr = null;
6101
+ if (classRef == null) {
6102
+ attributeRef = parser.parseElement("attributeRef", tokens);
6103
+ if (attributeRef == null) {
6104
+ elementExpr = parser.parseElement("expression", tokens);
6105
+ if (elementExpr == null) {
6106
+ parser.raiseParseError(
6107
+ tokens,
6108
+ "Expected either a class reference, attribute expression or value expression"
6109
+ );
6110
+ }
6111
+ }
6112
+ } else {
6113
+ var classRefs = [classRef];
6114
+ while ((classRef = parser.parseElement("classRef", tokens))) {
6115
+ classRefs.push(classRef);
6116
+ }
6117
+ }
6118
+
6119
+ if (tokens.matchToken("from")) {
6120
+ var fromExpr = parser.requireElement("expression", tokens);
6121
+ } else {
6122
+ if (elementExpr == null) {
6123
+ var fromExpr = parser.requireElement("implicitMeTarget", tokens);
6124
+ }
6125
+ }
6126
+
6127
+ if (elementExpr) {
6128
+ return {
6129
+ elementExpr: elementExpr,
6130
+ from: fromExpr,
6131
+ args: [elementExpr, fromExpr],
6132
+ op: function (context, element, from) {
6133
+ runtime.nullCheck(element, elementExpr);
6134
+ runtime.implicitLoop(element, function (target) {
6135
+ if (target.parentElement && (from == null || from.contains(target))) {
6136
+ target.parentElement.removeChild(target);
6137
+ }
6138
+ });
6139
+ return runtime.findNext(this, context);
6140
+ },
6141
+ };
6142
+ } else {
6143
+ return {
6144
+ classRefs: classRefs,
6145
+ attributeRef: attributeRef,
6146
+ elementExpr: elementExpr,
6147
+ from: fromExpr,
6148
+ args: [classRefs, fromExpr],
6149
+ op: function (context, classRefs, from) {
6150
+ runtime.nullCheck(from, fromExpr);
6151
+ if (classRefs) {
6152
+ runtime.forEach(classRefs, function (classRef) {
6153
+ runtime.implicitLoop(from, function (target) {
6154
+ target.classList.remove(classRef.className);
6155
+ });
6156
+ });
6157
+ } else {
6158
+ runtime.implicitLoop(from, function (target) {
6159
+ target.removeAttribute(attributeRef.name);
6160
+ });
6161
+ }
6162
+ return runtime.findNext(this, context);
6163
+ },
6164
+ };
6165
+ }
6166
+ }
6167
+ });
6168
+
6169
+ parser.addCommand("toggle", function (parser, runtime, tokens) {
6170
+ if (tokens.matchToken("toggle")) {
6171
+ tokens.matchAnyToken("the", "my");
6172
+ if (tokens.currentToken().type === "STYLE_REF") {
6173
+ let styleRef = tokens.consumeToken();
6174
+ var name = styleRef.value.substr(1);
6175
+ var visibility = true;
6176
+ var hideShowStrategy = resolveStrategy(parser, tokens, name);
6177
+ if (tokens.matchToken("of")) {
6178
+ tokens.pushFollow("with");
6179
+ try {
6180
+ var onExpr = parser.requireElement("expression", tokens);
6181
+ } finally {
6182
+ tokens.popFollow();
6183
+ }
6184
+ } else {
6185
+ var onExpr = parser.requireElement("implicitMeTarget", tokens);
6186
+ }
6187
+ } else if (tokens.matchToken("between")) {
6188
+ var between = true;
6189
+ var classRef = parser.parseElement("classRef", tokens);
6190
+ tokens.requireToken("and");
6191
+ var classRef2 = parser.requireElement("classRef", tokens);
6192
+ } else {
6193
+ var classRef = parser.parseElement("classRef", tokens);
6194
+ var attributeRef = null;
6195
+ if (classRef == null) {
6196
+ attributeRef = parser.parseElement("attributeRef", tokens);
6197
+ if (attributeRef == null) {
6198
+ parser.raiseParseError(tokens, "Expected either a class reference or attribute expression");
6199
+ }
6200
+ } else {
6201
+ var classRefs = [classRef];
6202
+ while ((classRef = parser.parseElement("classRef", tokens))) {
6203
+ classRefs.push(classRef);
6204
+ }
6205
+ }
6206
+ }
6207
+
6208
+ if (visibility !== true) {
6209
+ if (tokens.matchToken("on")) {
6210
+ var onExpr = parser.requireElement("expression", tokens);
6211
+ } else {
6212
+ var onExpr = parser.requireElement("implicitMeTarget", tokens);
6213
+ }
6214
+ }
6215
+
6216
+ if (tokens.matchToken("for")) {
6217
+ var time = parser.requireElement("expression", tokens);
6218
+ } else if (tokens.matchToken("until")) {
6219
+ var evt = parser.requireElement("dotOrColonPath", tokens, "Expected event name");
6220
+ if (tokens.matchToken("from")) {
6221
+ var from = parser.requireElement("expression", tokens);
6222
+ }
6223
+ }
6224
+
6225
+ var toggleCmd = {
6226
+ classRef: classRef,
6227
+ classRef2: classRef2,
6228
+ classRefs: classRefs,
6229
+ attributeRef: attributeRef,
6230
+ on: onExpr,
6231
+ time: time,
6232
+ evt: evt,
6233
+ from: from,
6234
+ toggle: function (on, classRef, classRef2, classRefs) {
6235
+ runtime.nullCheck(on, onExpr);
6236
+ if (visibility) {
6237
+ runtime.implicitLoop(on, function (target) {
6238
+ hideShowStrategy("toggle", target);
6239
+ });
6240
+ } else if (between) {
6241
+ runtime.implicitLoop(on, function (target) {
6242
+ if (target.classList.contains(classRef.className)) {
6243
+ target.classList.remove(classRef.className);
6244
+ target.classList.add(classRef2.className);
6245
+ } else {
6246
+ target.classList.add(classRef.className);
6247
+ target.classList.remove(classRef2.className);
6248
+ }
6249
+ });
6250
+ } else if (classRefs) {
6251
+ runtime.forEach(classRefs, function (classRef) {
6252
+ runtime.implicitLoop(on, function (target) {
6253
+ target.classList.toggle(classRef.className);
6254
+ });
6255
+ });
6256
+ } else {
6257
+ runtime.forEach(on, function (target) {
6258
+ if (target.hasAttribute(attributeRef.name)) {
6259
+ target.removeAttribute(attributeRef.name);
6260
+ } else {
6261
+ target.setAttribute(attributeRef.name, attributeRef.value);
6262
+ }
6263
+ });
6264
+ }
6265
+ },
6266
+ args: [onExpr, time, evt, from, classRef, classRef2, classRefs],
6267
+ op: function (context, on, time, evt, from, classRef, classRef2, classRefs) {
6268
+ if (time) {
6269
+ return new Promise(function (resolve) {
6270
+ toggleCmd.toggle(on, classRef, classRef2, classRefs);
6271
+ setTimeout(function () {
6272
+ toggleCmd.toggle(on, classRef, classRef2, classRefs);
6273
+ resolve(runtime.findNext(toggleCmd, context));
6274
+ }, time);
6275
+ });
6276
+ } else if (evt) {
6277
+ return new Promise(function (resolve) {
6278
+ var target = from || context.me;
6279
+ target.addEventListener(
6280
+ evt,
6281
+ function () {
6282
+ toggleCmd.toggle(on, classRef, classRef2, classRefs);
6283
+ resolve(runtime.findNext(toggleCmd, context));
6284
+ },
6285
+ { once: true }
6286
+ );
6287
+ toggleCmd.toggle(on, classRef, classRef2, classRefs);
6288
+ });
6289
+ } else {
6290
+ this.toggle(on, classRef, classRef2, classRefs);
6291
+ return runtime.findNext(toggleCmd, context);
6292
+ }
6293
+ },
6294
+ };
6295
+ return toggleCmd;
6296
+ }
6297
+ });
6298
+
6299
+ var HIDE_SHOW_STRATEGIES = {
6300
+ display: function (op, element, arg) {
6301
+ if (arg) {
6302
+ element.style.display = arg;
6303
+ } else if (op === "toggle") {
6304
+ if (getComputedStyle(element).display === "none") {
6305
+ HIDE_SHOW_STRATEGIES.display("show", element, arg);
6306
+ } else {
6307
+ HIDE_SHOW_STRATEGIES.display("hide", element, arg);
6308
+ }
6309
+ } else if (op === "hide") {
6310
+ const internalData = parser.runtime.getInternalData(element);
6311
+ if (internalData.originalDisplay == null) {
6312
+ internalData.originalDisplay = element.style.display;
6313
+ }
6314
+ element.style.display = "none";
6315
+ } else {
6316
+ const internalData = parser.runtime.getInternalData(element);
6317
+ if (internalData.originalDisplay && internalData.originalDisplay !== 'none') {
6318
+ element.style.display = internalData.originalDisplay;
6319
+ } else {
6320
+ element.style.removeProperty('display');
6321
+ }
6322
+ }
6323
+ },
6324
+ visibility: function (op, element, arg) {
6325
+ if (arg) {
6326
+ element.style.visibility = arg;
6327
+ } else if (op === "toggle") {
6328
+ if (getComputedStyle(element).visibility === "hidden") {
6329
+ HIDE_SHOW_STRATEGIES.visibility("show", element, arg);
6330
+ } else {
6331
+ HIDE_SHOW_STRATEGIES.visibility("hide", element, arg);
6332
+ }
6333
+ } else if (op === "hide") {
6334
+ element.style.visibility = "hidden";
6335
+ } else {
6336
+ element.style.visibility = "visible";
6337
+ }
6338
+ },
6339
+ opacity: function (op, element, arg) {
6340
+ if (arg) {
6341
+ element.style.opacity = arg;
6342
+ } else if (op === "toggle") {
6343
+ if (getComputedStyle(element).opacity === "0") {
6344
+ HIDE_SHOW_STRATEGIES.opacity("show", element, arg);
6345
+ } else {
6346
+ HIDE_SHOW_STRATEGIES.opacity("hide", element, arg);
6347
+ }
6348
+ } else if (op === "hide") {
6349
+ element.style.opacity = "0";
6350
+ } else {
6351
+ element.style.opacity = "1";
6352
+ }
6353
+ },
6354
+ };
6355
+
6356
+ var parseShowHideTarget = function (parser, runtime, tokens) {
6357
+ var target;
6358
+ var currentTokenValue = tokens.currentToken();
6359
+ if (currentTokenValue.value === "when" || currentTokenValue.value === "with" || parser.commandBoundary(currentTokenValue)) {
6360
+ target = parser.parseElement("implicitMeTarget", tokens);
6361
+ } else {
6362
+ target = parser.parseElement("expression", tokens);
6363
+ }
6364
+ return target;
6365
+ };
6366
+
6367
+ var resolveStrategy = function (parser, tokens, name) {
6368
+ var configDefault = config.defaultHideShowStrategy;
6369
+ var strategies = HIDE_SHOW_STRATEGIES;
6370
+ if (config.hideShowStrategies) {
6371
+ strategies = Object.assign(strategies, config.hideShowStrategies); // merge in user provided strategies
6372
+ }
6373
+ name = name || configDefault || "display";
6374
+ var value = strategies[name];
6375
+ if (value == null) {
6376
+ parser.raiseParseError(tokens, "Unknown show/hide strategy : " + name);
6377
+ }
6378
+ return value;
6379
+ };
6380
+
6381
+ parser.addCommand("hide", function (parser, runtime, tokens) {
6382
+ if (tokens.matchToken("hide")) {
6383
+ var targetExpr = parseShowHideTarget(parser, runtime, tokens);
6384
+
6385
+ var name = null;
6386
+ if (tokens.matchToken("with")) {
6387
+ name = tokens.requireTokenType("IDENTIFIER", "STYLE_REF").value;
6388
+ if (name.indexOf("*") === 0) {
6389
+ name = name.substr(1);
6390
+ }
6391
+ }
6392
+ var hideShowStrategy = resolveStrategy(parser, tokens, name);
6393
+
6394
+ return {
6395
+ target: targetExpr,
6396
+ args: [targetExpr],
6397
+ op: function (ctx, target) {
6398
+ runtime.nullCheck(target, targetExpr);
6399
+ runtime.implicitLoop(target, function (elt) {
6400
+ hideShowStrategy("hide", elt);
6401
+ });
6402
+ return runtime.findNext(this, ctx);
6403
+ },
6404
+ };
6405
+ }
6406
+ });
6407
+
6408
+ parser.addCommand("show", function (parser, runtime, tokens) {
6409
+ if (tokens.matchToken("show")) {
6410
+ var targetExpr = parseShowHideTarget(parser, runtime, tokens);
6411
+
6412
+ var name = null;
6413
+ if (tokens.matchToken("with")) {
6414
+ name = tokens.requireTokenType("IDENTIFIER", "STYLE_REF").value;
6415
+ if (name.indexOf("*") === 0) {
6416
+ name = name.substr(1);
6417
+ }
6418
+ }
6419
+ var arg = null;
6420
+ if (tokens.matchOpToken(":")) {
6421
+ var tokenArr = tokens.consumeUntilWhitespace();
6422
+ tokens.matchTokenType("WHITESPACE");
6423
+ arg = tokenArr
6424
+ .map(function (t) {
6425
+ return t.value;
6426
+ })
6427
+ .join("");
6428
+ }
6429
+
6430
+ if (tokens.matchToken("when")) {
6431
+ var when = parser.requireElement("expression", tokens);
6432
+ }
6433
+
6434
+ var hideShowStrategy = resolveStrategy(parser, tokens, name);
6435
+
6436
+ return {
6437
+ target: targetExpr,
6438
+ when: when,
6439
+ args: [targetExpr],
6440
+ op: function (ctx, target) {
6441
+ runtime.nullCheck(target, targetExpr);
6442
+ runtime.implicitLoop(target, function (elt) {
6443
+ if (when) {
6444
+ ctx.result = elt;
6445
+ let whenResult = runtime.evaluateNoPromise(when, ctx);
6446
+ if (whenResult) {
6447
+ hideShowStrategy("show", elt, arg);
6448
+ } else {
6449
+ hideShowStrategy("hide", elt);
6450
+ }
6451
+ ctx.result = null;
6452
+ } else {
6453
+ hideShowStrategy("show", elt, arg);
6454
+ }
6455
+ });
6456
+ return runtime.findNext(this, ctx);
6457
+ },
6458
+ };
6459
+ }
6460
+ });
6461
+
6462
+ parser.addCommand("take", function (parser, runtime, tokens) {
6463
+ if (tokens.matchToken("take")) {
6464
+ var classRef = parser.requireElement("classRef", tokens);
6465
+
6466
+ if (tokens.matchToken("from")) {
6467
+ var fromExpr = parser.requireElement("expression", tokens);
6468
+ } else {
6469
+ var fromExpr = classRef;
6470
+ }
6471
+
6472
+ if (tokens.matchToken("for")) {
6473
+ var forExpr = parser.requireElement("expression", tokens);
6474
+ } else {
6475
+ var forExpr = parser.requireElement("implicitMeTarget", tokens);
6476
+ }
6477
+
6478
+ var takeCmd = {
6479
+ classRef: classRef,
6480
+ from: fromExpr,
6481
+ forElt: forExpr,
6482
+ args: [classRef, fromExpr, forExpr],
6483
+ op: function (context, eltColl, from, forElt) {
6484
+ runtime.nullCheck(from, fromExpr);
6485
+ runtime.nullCheck(forElt, forExpr);
6486
+ var clazz = eltColl.className;
6487
+ runtime.implicitLoop(from, function (target) {
6488
+ target.classList.remove(clazz);
6489
+ });
6490
+ runtime.implicitLoop(forElt, function (target) {
6491
+ target.classList.add(clazz);
6492
+ });
6493
+ return runtime.findNext(this, context);
6494
+ },
6495
+ };
6496
+ return takeCmd;
6497
+ }
6498
+ });
6499
+
6500
+ function putInto(runtime, context, prop, valueToPut) {
6501
+ if (prop != null) {
6502
+ var value = runtime.resolveSymbol(prop, context);
6503
+ } else {
6504
+ var value = context;
6505
+ }
6506
+ if (value instanceof Element || value instanceof HTMLDocument) {
6507
+ while (value.firstChild) value.removeChild(value.firstChild);
6508
+ value.append(parser.runtime.convertValue(valueToPut, "Fragment"));
6509
+ runtime.processNode(value);
6510
+ } else {
6511
+ if (prop != null) {
6512
+ runtime.setSymbol(prop, context, null, valueToPut);
6513
+ } else {
6514
+ throw "Don't know how to put a value into " + typeof context;
6515
+ }
6516
+ }
6517
+ }
6518
+
6519
+ parser.addCommand("put", function (parser, runtime, tokens) {
6520
+ if (tokens.matchToken("put")) {
6521
+ var value = parser.requireElement("expression", tokens);
6522
+
6523
+ var operationToken = tokens.matchAnyToken("into", "before", "after");
6524
+
6525
+ if (operationToken == null && tokens.matchToken("at")) {
6526
+ tokens.matchToken("the"); // optional "the"
6527
+ operationToken = tokens.matchAnyToken("start", "end");
6528
+ tokens.requireToken("of");
6529
+ }
6530
+
6531
+ if (operationToken == null) {
6532
+ parser.raiseParseError(tokens, "Expected one of 'into', 'before', 'at start of', 'at end of', 'after'");
6533
+ }
6534
+ var target = parser.requireElement("expression", tokens);
6535
+
6536
+ var operation = operationToken.value;
6537
+
6538
+ var arrayIndex = false;
6539
+ var symbolWrite = false;
6540
+ var rootExpr = null;
6541
+ var prop = null;
6542
+
6543
+ if (target.type === "arrayIndex" && operation === "into") {
6544
+ arrayIndex = true;
6545
+ prop = target.prop;
6546
+ rootExpr = target.root;
6547
+ } else if (target.prop && target.root && operation === "into") {
6548
+ prop = target.prop.value;
6549
+ rootExpr = target.root;
6550
+ } else if (target.type === "symbol" && operation === "into") {
6551
+ symbolWrite = true;
6552
+ prop = target.name;
6553
+ } else if (target.type === "attributeRef" && operation === "into") {
6554
+ var attributeWrite = true;
6555
+ prop = target.name;
6556
+ rootExpr = parser.requireElement("implicitMeTarget", tokens);
6557
+ } else if (target.type === "styleRef" && operation === "into") {
6558
+ var styleWrite = true;
6559
+ prop = target.name;
6560
+ rootExpr = parser.requireElement("implicitMeTarget", tokens);
6561
+ } else if (target.attribute && operation === "into") {
6562
+ var attributeWrite = target.attribute.type === "attributeRef";
6563
+ var styleWrite = target.attribute.type === "styleRef";
6564
+ prop = target.attribute.name;
6565
+ rootExpr = target.root;
6566
+ } else {
6567
+ rootExpr = target;
6568
+ }
6569
+
6570
+ var putCmd = {
6571
+ target: target,
6572
+ operation: operation,
6573
+ symbolWrite: symbolWrite,
6574
+ value: value,
6575
+ args: [rootExpr, prop, value],
6576
+ op: function (context, root, prop, valueToPut) {
6577
+ if (symbolWrite) {
6578
+ putInto(runtime, context, prop, valueToPut);
6579
+ } else {
6580
+ runtime.nullCheck(root, rootExpr);
6581
+ if (operation === "into") {
6582
+ if (attributeWrite) {
6583
+ runtime.implicitLoop(root, function (elt) {
6584
+ elt.setAttribute(prop, valueToPut);
6585
+ });
6586
+ } else if (styleWrite) {
6587
+ runtime.implicitLoop(root, function (elt) {
6588
+ elt.style[prop] = valueToPut;
6589
+ });
6590
+ } else if (arrayIndex) {
6591
+ root[prop] = valueToPut;
6592
+ } else {
6593
+ runtime.implicitLoop(root, function (elt) {
6594
+ putInto(runtime, elt, prop, valueToPut);
6595
+ });
6596
+ }
6597
+ } else {
6598
+ var op =
6599
+ operation === "before"
6600
+ ? Element.prototype.before
6601
+ : operation === "after"
6602
+ ? Element.prototype.after
6603
+ : operation === "start"
6604
+ ? Element.prototype.prepend
6605
+ : operation === "end"
6606
+ ? Element.prototype.append
6607
+ : Element.prototype.append; // unreachable
6608
+
6609
+ runtime.implicitLoop(root, function (elt) {
6610
+ op.call(
6611
+ elt,
6612
+ valueToPut instanceof Node
6613
+ ? valueToPut
6614
+ : runtime.convertValue(valueToPut, "Fragment")
6615
+ );
6616
+ // process any new content
6617
+ if (elt.parentElement) {
6618
+ runtime.processNode(elt.parentElement);
6619
+ } else {
6620
+ runtime.processNode(elt);
6621
+ }
6622
+ });
6623
+ }
6624
+ }
6625
+ return runtime.findNext(this, context);
6626
+ },
6627
+ };
6628
+ return putCmd;
6629
+ }
6630
+ });
6631
+
6632
+ function parsePseudopossessiveTarget(parser, runtime, tokens) {
6633
+ var targets;
6634
+ if (
6635
+ tokens.matchToken("the") ||
6636
+ tokens.matchToken("element") ||
6637
+ tokens.matchToken("elements") ||
6638
+ tokens.currentToken().type === "CLASS_REF" ||
6639
+ tokens.currentToken().type === "ID_REF" ||
6640
+ (tokens.currentToken().op && tokens.currentToken().value === "<")
6641
+ ) {
6642
+ parser.possessivesDisabled = true;
6643
+ try {
6644
+ targets = parser.parseElement("expression", tokens);
6645
+ } finally {
6646
+ delete parser.possessivesDisabled;
6647
+ }
6648
+ // optional possessive
6649
+ if (tokens.matchOpToken("'")) {
6650
+ tokens.requireToken("s");
6651
+ }
6652
+ } else if (tokens.currentToken().type === "IDENTIFIER" && tokens.currentToken().value === "its") {
6653
+ var identifier = tokens.matchToken("its");
6654
+ targets = {
6655
+ type: "pseudopossessiveIts",
6656
+ token: identifier,
6657
+ name: identifier.value,
6658
+ evaluate: function (context) {
6659
+ return runtime.resolveSymbol("it", context);
6660
+ },
6661
+ };
6662
+ } else {
6663
+ tokens.matchToken("my") || tokens.matchToken("me"); // consume optional 'my'
6664
+ targets = parser.parseElement("implicitMeTarget", tokens);
6665
+ }
6666
+ return targets;
6667
+ }
6668
+
6669
+ parser.addCommand("transition", function (parser, runtime, tokens) {
6670
+ if (tokens.matchToken("transition")) {
6671
+ var targetsExpr = parsePseudopossessiveTarget(parser, runtime, tokens);
6672
+
6673
+ var properties = [];
6674
+ var from = [];
6675
+ var to = [];
6676
+ var currentToken = tokens.currentToken();
6677
+ while (
6678
+ !parser.commandBoundary(currentToken) &&
6679
+ currentToken.value !== "over" &&
6680
+ currentToken.value !== "using"
6681
+ ) {
6682
+ if (tokens.currentToken().type === "STYLE_REF") {
6683
+ let styleRef = tokens.consumeToken();
6684
+ let styleProp = styleRef.value.substr(1);
6685
+ properties.push({
6686
+ type: "styleRefValue",
6687
+ evaluate: function () {
6688
+ return styleProp;
6689
+ },
6690
+ });
6691
+ } else {
6692
+ properties.push(parser.requireElement("stringLike", tokens));
6693
+ }
6694
+
6695
+ if (tokens.matchToken("from")) {
6696
+ from.push(parser.requireElement("expression", tokens));
6697
+ } else {
6698
+ from.push(null);
6699
+ }
6700
+ tokens.requireToken("to");
6701
+ if (tokens.matchToken("initial")) {
6702
+ to.push({
6703
+ type: "initial_literal",
6704
+ evaluate : function(){
6705
+ return "initial";
6706
+ }
6707
+ });
6708
+ } else {
6709
+ to.push(parser.requireElement("expression", tokens));
6710
+ }
6711
+ currentToken = tokens.currentToken();
6712
+ }
6713
+ if (tokens.matchToken("over")) {
6714
+ var over = parser.requireElement("expression", tokens);
6715
+ } else if (tokens.matchToken("using")) {
6716
+ var using = parser.requireElement("expression", tokens);
6717
+ }
6718
+
6719
+ var transition = {
6720
+ to: to,
6721
+ args: [targetsExpr, properties, from, to, using, over],
6722
+ op: function (context, targets, properties, from, to, using, over) {
6723
+ runtime.nullCheck(targets, targetsExpr);
6724
+ var promises = [];
6725
+ runtime.implicitLoop(targets, function (target) {
6726
+ var promise = new Promise(function (resolve, reject) {
6727
+ var initialTransition = target.style.transition;
6728
+ if (over) {
6729
+ target.style.transition = "all " + over + "ms ease-in";
6730
+ } else if (using) {
6731
+ target.style.transition = using;
6732
+ } else {
6733
+ target.style.transition = config.defaultTransition;
6734
+ }
6735
+ var internalData = runtime.getInternalData(target);
6736
+ var computedStyles = getComputedStyle(target);
6737
+
6738
+ var initialStyles = {};
6739
+ for (var i = 0; i < computedStyles.length; i++) {
6740
+ var name = computedStyles[i];
6741
+ var initialValue = computedStyles[name];
6742
+ initialStyles[name] = initialValue;
6743
+ }
6744
+
6745
+ // store intitial values
6746
+ if (!internalData.initalStyles) {
6747
+ internalData.initalStyles = initialStyles;
6748
+ }
6749
+
6750
+ for (var i = 0; i < properties.length; i++) {
6751
+ var property = properties[i];
6752
+ var fromVal = from[i];
6753
+ if (fromVal === "computed" || fromVal == null) {
6754
+ target.style[property] = initialStyles[property];
6755
+ } else {
6756
+ target.style[property] = fromVal;
6757
+ }
6758
+ }
6759
+ //console.log("transition started", transition);
6760
+
6761
+ var transitionStarted = false;
6762
+ var resolved = false;
6763
+
6764
+ target.addEventListener(
6765
+ "transitionend",
6766
+ function () {
6767
+ if (!resolved) {
6768
+ //console.log("transition ended", transition);
6769
+ target.style.transition = initialTransition;
6770
+ resolved = true;
6771
+ resolve();
6772
+ }
6773
+ },
6774
+ { once: true }
6775
+ );
6776
+
6777
+ target.addEventListener(
6778
+ "transitionstart",
6779
+ function () {
6780
+ transitionStarted = true;
6781
+ },
6782
+ { once: true }
6783
+ );
6784
+
6785
+ // it no transition has started in 100ms, continue
6786
+ setTimeout(function () {
6787
+ if (!resolved && !transitionStarted) {
6788
+ //console.log("transition ended", transition);
6789
+ target.style.transition = initialTransition;
6790
+ resolved = true;
6791
+ resolve();
6792
+ }
6793
+ }, 100);
6794
+
6795
+ setTimeout(function () {
6796
+ var autoProps = [];
6797
+ for (var i = 0; i < properties.length; i++) {
6798
+ var property = properties[i];
6799
+ var toVal = to[i];
6800
+ if (toVal === "initial") {
6801
+ var propertyValue = internalData.initalStyles[property];
6802
+ target.style[property] = propertyValue;
6803
+ } else {
6804
+ target.style[property] = toVal;
6805
+ }
6806
+ //console.log("set", property, "to", target.style[property], "on", target, "value passed in : ", toVal);
6807
+ }
6808
+ }, 0);
6809
+ });
6810
+ promises.push(promise);
6811
+ });
6812
+ return Promise.all(promises).then(function () {
6813
+ return runtime.findNext(transition, context);
6814
+ });
6815
+ },
6816
+ };
6817
+ return transition;
6818
+ }
6819
+ });
6820
+
6821
+ parser.addCommand("measure", function (parser, runtime, tokens) {
6822
+ if (!tokens.matchToken("measure")) return;
6823
+
6824
+ var targetExpr = parsePseudopossessiveTarget(parser, runtime, tokens);
6825
+
6826
+ var propsToMeasure = [];
6827
+ if (!parser.commandBoundary(tokens.currentToken()))
6828
+ do {
6829
+ propsToMeasure.push(tokens.matchTokenType("IDENTIFIER").value);
6830
+ } while (tokens.matchOpToken(","));
6831
+
6832
+ return {
6833
+ properties: propsToMeasure,
6834
+ args: [targetExpr],
6835
+ op: function (ctx, target) {
6836
+ runtime.nullCheck(target, targetExpr);
6837
+ if (0 in target) target = target[0]; // not measuring multiple elts
6838
+ var rect = target.getBoundingClientRect();
6839
+ var scroll = {
6840
+ top: target.scrollTop,
6841
+ left: target.scrollLeft,
6842
+ topMax: target.scrollTopMax,
6843
+ leftMax: target.scrollLeftMax,
6844
+ height: target.scrollHeight,
6845
+ width: target.scrollWidth,
6846
+ };
6847
+
6848
+ ctx.result = {
6849
+ x: rect.x,
6850
+ y: rect.y,
6851
+ left: rect.left,
6852
+ top: rect.top,
6853
+ right: rect.right,
6854
+ bottom: rect.bottom,
6855
+ width: rect.width,
6856
+ height: rect.height,
6857
+ bounds: rect,
6858
+
6859
+ scrollLeft: scroll.left,
6860
+ scrollTop: scroll.top,
6861
+ scrollLeftMax: scroll.leftMax,
6862
+ scrollTopMax: scroll.topMax,
6863
+ scrollWidth: scroll.width,
6864
+ scrollHeight: scroll.height,
6865
+ scroll: scroll,
6866
+ };
6867
+
6868
+ runtime.forEach(propsToMeasure, function (prop) {
6869
+ if (prop in ctx.result) ctx.locals[prop] = ctx.result[prop];
6870
+ else throw "No such measurement as " + prop;
6871
+ });
6872
+
6873
+ return runtime.findNext(this, ctx);
6874
+ },
6875
+ };
6876
+ });
6877
+
6878
+ parser.addLeafExpression("closestExpr", function (parser, runtime, tokens) {
6879
+ if (tokens.matchToken("closest")) {
6880
+ if (tokens.matchToken("parent")) {
6881
+ var parentSearch = true;
6882
+ }
6883
+
6884
+ var css = null;
6885
+ if (tokens.currentToken().type === "ATTRIBUTE_REF") {
6886
+ var attributeRef = parser.requireElement("attributeRefAccess", tokens, null);
6887
+ css = "[" + attributeRef.attribute.name + "]";
6888
+ }
6889
+
6890
+ if (css == null) {
6891
+ var expr = parser.requireElement("expression", tokens);
6892
+ if (expr.css == null) {
6893
+ parser.raiseParseError(tokens, "Expected a CSS expression");
6894
+ } else {
6895
+ css = expr.css;
6896
+ }
6897
+ }
6898
+
6899
+ if (tokens.matchToken("to")) {
6900
+ var to = parser.parseElement("expression", tokens);
6901
+ } else {
6902
+ var to = parser.parseElement("implicitMeTarget", tokens);
6903
+ }
6904
+
6905
+ var closestExpr = {
6906
+ type: "closestExpr",
6907
+ parentSearch: parentSearch,
6908
+ expr: expr,
6909
+ css: css,
6910
+ to: to,
6911
+ args: [to],
6912
+ op: function (ctx, to) {
6913
+ if (to == null) {
6914
+ return null;
6915
+ } else {
6916
+ let result = [];
6917
+ runtime.implicitLoop(to, function(to){
6918
+ if (parentSearch) {
6919
+ result.push(to.parentElement ? to.parentElement.closest(css) : null);
6920
+ } else {
6921
+ result.push(to.closest(css));
6922
+ }
6923
+ })
6924
+ if (runtime.shouldAutoIterate(to)) {
6925
+ return result;
6926
+ } else {
6927
+ return result[0];
6928
+ }
6929
+ }
6930
+ },
6931
+ evaluate: function (context) {
6932
+ return runtime.unifiedEval(this, context);
6933
+ },
6934
+ };
6935
+
6936
+ if (attributeRef) {
6937
+ attributeRef.root = closestExpr;
6938
+ attributeRef.args = [closestExpr];
6939
+ return attributeRef;
6940
+ } else {
6941
+ return closestExpr;
6942
+ }
6943
+ }
6944
+ });
6945
+
6946
+ parser.addCommand("go", function (parser, runtime, tokens) {
6947
+ if (tokens.matchToken("go")) {
6948
+ if (tokens.matchToken("back")) {
6949
+ var back = true;
6950
+ } else {
6951
+ tokens.matchToken("to");
6952
+ if (tokens.matchToken("url")) {
6953
+ var target = parser.requireElement("stringLike", tokens);
6954
+ var url = true;
6955
+ if (tokens.matchToken("in")) {
6956
+ tokens.requireToken("new");
6957
+ tokens.requireToken("window");
6958
+ var newWindow = true;
6959
+ }
6960
+ } else {
6961
+ tokens.matchToken("the"); // optional the
6962
+ var verticalPosition = tokens.matchAnyToken("top", "middle", "bottom");
6963
+ var horizontalPosition = tokens.matchAnyToken("left", "center", "right");
6964
+ if (verticalPosition || horizontalPosition) {
6965
+ tokens.requireToken("of");
6966
+ }
6967
+ var target = parser.requireElement("unaryExpression", tokens);
6968
+
6969
+ var plusOrMinus = tokens.matchAnyOpToken("+", "-");
6970
+ if (plusOrMinus) {
6971
+ tokens.pushFollow("px");
6972
+ try {
6973
+ var offset = parser.requireElement("expression", tokens);
6974
+ } finally {
6975
+ tokens.popFollow();
6976
+ }
6977
+ }
6978
+ tokens.matchToken("px"); // optional px
6979
+
6980
+ var smoothness = tokens.matchAnyToken("smoothly", "instantly");
6981
+
6982
+ var scrollOptions = {};
6983
+ if (verticalPosition) {
6984
+ if (verticalPosition.value === "top") {
6985
+ scrollOptions.block = "start";
6986
+ } else if (verticalPosition.value === "bottom") {
6987
+ scrollOptions.block = "end";
6988
+ } else if (verticalPosition.value === "middle") {
6989
+ scrollOptions.block = "center";
6990
+ }
6991
+ }
6992
+
6993
+ if (horizontalPosition) {
6994
+ if (horizontalPosition.value === "left") {
6995
+ scrollOptions.inline = "start";
6996
+ } else if (horizontalPosition.value === "center") {
6997
+ scrollOptions.inline = "center";
6998
+ } else if (horizontalPosition.value === "right") {
6999
+ scrollOptions.inline = "end";
7000
+ }
7001
+ }
7002
+
7003
+ if (smoothness) {
7004
+ if (smoothness.value === "smoothly") {
7005
+ scrollOptions.behavior = "smooth";
7006
+ } else if (smoothness.value === "instantly") {
7007
+ scrollOptions.behavior = "instant";
7008
+ }
7009
+ }
7010
+ }
7011
+ }
7012
+
7013
+ var goCmd = {
7014
+ target: target,
7015
+ args: [target, offset],
7016
+ op: function (ctx, to, offset) {
7017
+ if (back) {
7018
+ window.history.back();
7019
+ } else if (url) {
7020
+ if (to) {
7021
+ if (newWindow) {
7022
+ window.open(to);
7023
+ } else {
7024
+ window.location.href = to;
7025
+ }
7026
+ }
7027
+ } else {
7028
+ runtime.implicitLoop(to, function (target) {
7029
+
7030
+ if (target === window) {
7031
+ target = document.body;
7032
+ }
7033
+
7034
+ if(plusOrMinus) {
7035
+ // a top scroll w/ an offset of some sort
7036
+ var boundingRect = target.getBoundingClientRect();
7037
+ let scrollShim = document.createElement('div');
7038
+
7039
+ if (plusOrMinus.value === "-") {
7040
+ var finalOffset = -offset;
7041
+ } else {
7042
+ var finalOffset = - -offset;
7043
+ }
7044
+
7045
+ scrollShim.style.position = 'absolute';
7046
+ scrollShim.style.top = (boundingRect.x + finalOffset) + "px";
7047
+ scrollShim.style.left = (boundingRect.y + finalOffset) + "px";
7048
+ scrollShim.style.height = (boundingRect.height + (2 * finalOffset)) + "px";
7049
+ scrollShim.style.width = (boundingRect.width + (2 * finalOffset)) + "px";
7050
+ scrollShim.style.zIndex = "" + Number.MIN_SAFE_INTEGER;
7051
+ scrollShim.style.opacity = "0";
7052
+
7053
+ document.body.appendChild(scrollShim);
7054
+ setTimeout(function () {
7055
+ document.body.removeChild(scrollShim);
7056
+ }, 100);
7057
+
7058
+ target = scrollShim;
7059
+ }
7060
+
7061
+ target.scrollIntoView(scrollOptions);
7062
+ });
7063
+ }
7064
+ return runtime.findNext(goCmd, ctx);
7065
+ },
7066
+ };
7067
+ return goCmd;
7068
+ }
7069
+ });
7070
+
7071
+ config.conversions.dynamicResolvers.push(function (str, node) {
7072
+ if (!(str === "Values" || str.indexOf("Values:") === 0)) {
7073
+ return;
7074
+ }
7075
+ var conversion = str.split(":")[1];
7076
+ /** @type Object<string,string | string[]> */
7077
+ var result = {};
7078
+
7079
+ var implicitLoop = parser.runtime.implicitLoop.bind(parser.runtime);
7080
+
7081
+ implicitLoop(node, function (/** @type HTMLInputElement */ node) {
7082
+ // Try to get a value directly from this node
7083
+ var input = getInputInfo(node);
7084
+
7085
+ if (input !== undefined) {
7086
+ result[input.name] = input.value;
7087
+ return;
7088
+ }
7089
+
7090
+ // Otherwise, try to query all child elements of this node that *should* contain values.
7091
+ if (node.querySelectorAll != undefined) {
7092
+ /** @type {NodeListOf<HTMLInputElement>} */
7093
+ var children = node.querySelectorAll("input,select,textarea");
7094
+ children.forEach(appendValue);
7095
+ }
7096
+ });
7097
+
7098
+ if (conversion) {
7099
+ if (conversion === "JSON") {
7100
+ return JSON.stringify(result);
7101
+ } else if (conversion === "Form") {
7102
+ /** @ts-ignore */
7103
+ // TODO: does this work with multiple inputs of the same name?
7104
+ return new URLSearchParams(result).toString();
7105
+ } else {
7106
+ throw "Unknown conversion: " + conversion;
7107
+ }
7108
+ } else {
7109
+ return result;
7110
+ }
7111
+
7112
+ /**
7113
+ * @param {HTMLInputElement} node
7114
+ */
7115
+ function appendValue(node) {
7116
+ var info = getInputInfo(node);
7117
+
7118
+ if (info == undefined) {
7119
+ return;
7120
+ }
7121
+
7122
+ // If there is no value already stored in this space.
7123
+ if (result[info.name] == undefined) {
7124
+ result[info.name] = info.value;
7125
+ return;
7126
+ }
7127
+
7128
+ if (Array.isArray(result[info.name]) && Array.isArray(info.value)) {
7129
+ result[info.name] = [].concat(result[info.name], info.value);
7130
+ return;
7131
+ }
7132
+ }
7133
+
7134
+ /**
7135
+ * @param {HTMLInputElement} node
7136
+ * @returns {{name:string, value:string | string[]} | undefined}
7137
+ */
7138
+ function getInputInfo(node) {
7139
+ try {
7140
+ /** @type {{name: string, value: string | string[]}}*/
7141
+ var result = {
7142
+ name: node.name,
7143
+ value: node.value,
7144
+ };
7145
+
7146
+ if (result.name == undefined || result.value == undefined) {
7147
+ return undefined;
7148
+ }
7149
+
7150
+ if (node.type == "radio" && node.checked == false) {
7151
+ return undefined;
7152
+ }
7153
+
7154
+ if (node.type == "checkbox") {
7155
+ if (node.checked == false) {
7156
+ result.value = undefined;
7157
+ } else if (typeof result.value === "string") {
7158
+ result.value = [result.value];
7159
+ }
7160
+ }
7161
+
7162
+ if (node.type == "select-multiple") {
7163
+ /** @type {NodeListOf<HTMLSelectElement>} */
7164
+ var selected = node.querySelectorAll("option[selected]");
7165
+
7166
+ result.value = [];
7167
+ for (var index = 0; index < selected.length; index++) {
7168
+ result.value.push(selected[index].value);
7169
+ }
7170
+ }
7171
+ return result;
7172
+ } catch (e) {
7173
+ return undefined;
7174
+ }
7175
+ }
7176
+ });
7177
+
7178
+ config.conversions["HTML"] = function (value) {
7179
+ var toHTML = /** @returns {string}*/ function (/** @type any*/ value) {
7180
+ if (value instanceof Array) {
7181
+ return value
7182
+ .map(function (item) {
7183
+ return toHTML(item);
7184
+ })
7185
+ .join("");
7186
+ }
7187
+
7188
+ if (value instanceof HTMLElement) {
7189
+ return value.outerHTML;
7190
+ }
7191
+
7192
+ if (value instanceof NodeList) {
7193
+ var result = "";
7194
+ for (var i = 0; i < value.length; i++) {
7195
+ var node = value[i];
7196
+ if (node instanceof HTMLElement) {
7197
+ result += node.outerHTML;
7198
+ }
7199
+ }
7200
+ return result;
7201
+ }
7202
+
7203
+ if (value.toString) {
7204
+ return value.toString();
7205
+ }
7206
+
7207
+ return "";
7208
+ };
7209
+
7210
+ return toHTML(value);
7211
+ };
7212
+
7213
+ config.conversions["Fragment"] = function (val) {
7214
+ var frag = document.createDocumentFragment();
7215
+ parser.runtime.implicitLoop(val, function (val) {
7216
+ if (val instanceof Node) frag.append(val);
7217
+ else {
7218
+ var temp = document.createElement("template");
7219
+ temp.innerHTML = val;
7220
+ frag.append(temp.content);
7221
+ }
7222
+ });
7223
+ return frag;
7224
+ };
7225
+ }
7226
+
7227
+
7228
+ // Public API
7229
+
7230
+ const runtime_ = new Runtime(), lexer_ = runtime_.lexer, parser_ = runtime_.parser
7231
+
7232
+ /**
7233
+ *
7234
+ * @param {string} src
7235
+ * @param {Partial<Context>} [ctx]
7236
+ */
7237
+ function run(src, ctx) {
7238
+ return runtime_.evaluate(src, ctx)
7239
+ }
7240
+
7241
+ function browserInit() {
7242
+ /** @type {HTMLScriptElement[]} */
7243
+ var scripts = Array.from(globalScope.document.querySelectorAll("script[type='text/hyperscript'][src]"))
7244
+ Promise.all(
7245
+ scripts.map(function (script) {
7246
+ return fetch(script.src)
7247
+ .then(function (res) {
7248
+ return res.text();
7249
+ });
7250
+ })
7251
+ )
7252
+ .then(script_values => script_values.forEach(sc => _hyperscript(sc)))
7253
+ .then(() => ready(function () {
7254
+ mergeMetaConfig();
7255
+ runtime_.processNode(document.documentElement);
7256
+ globalScope.document.addEventListener("htmx:load", function (/** @type {CustomEvent} */ evt) {
7257
+ runtime_.processNode(evt.detail.elt);
7258
+ });
7259
+ }));
7260
+
7261
+ function ready(fn) {
7262
+ if (document.readyState !== "loading") {
7263
+ setTimeout(fn);
7264
+ } else {
7265
+ document.addEventListener("DOMContentLoaded", fn);
7266
+ }
7267
+ }
7268
+
7269
+ function getMetaConfig() {
7270
+ /** @type {HTMLMetaElement} */
7271
+ var element = document.querySelector('meta[name="htmx-config"]');
7272
+ if (element) {
7273
+ return parseJSON(element.content);
7274
+ } else {
7275
+ return null;
7276
+ }
7277
+ }
7278
+
7279
+ function mergeMetaConfig() {
7280
+ var metaConfig = getMetaConfig();
7281
+ if (metaConfig) {
7282
+ Object.assign(config, metaConfig);
7283
+ }
7284
+ }
7285
+ }
7286
+
7287
+ /**
7288
+ * @typedef {Object} HyperscriptAPI
7289
+ *
7290
+ * @property {Object} config
7291
+ * @property {string} config.attributes
7292
+ * @property {string} config.defaultTransition
7293
+ * @property {string} config.disableSelector
7294
+ * @property {typeof conversions} config.conversions
7295
+ *
7296
+ * @property {Object} internals
7297
+ * @property {Lexer} internals.lexer
7298
+ * @property {typeof Lexer} internals.Lexer
7299
+ * @property {Parser} internals.parser
7300
+ * @property {typeof Parser} internals.Parser
7301
+ * @property {Runtime} internals.runtime
7302
+ * @property {typeof Runtime} internals.Runtime
7303
+ *
7304
+ * @property {typeof ElementCollection} ElementCollection
7305
+ *
7306
+ * @property {(keyword: string, definition: ParseRule) => void} addFeature
7307
+ * @property {(keyword: string, definition: ParseRule) => void} addCommand
7308
+ * @property {(keyword: string, definition: ParseRule) => void} addLeafExpression
7309
+ * @property {(keyword: string, definition: ParseRule) => void} addIndirectExpression
7310
+ *
7311
+ * @property {(src: string, ctx?: Partial<Context>) => any} evaluate
7312
+ * @property {(src: string) => ASTNode} parse
7313
+ * @property {(node: Element) => void} processNode
7314
+ *
7315
+ * @property {() => void} browserInit
7316
+ *
7317
+ *
7318
+ * @typedef {HyperscriptAPI & ((src: string, ctx?: Partial<Context>) => any)} Hyperscript
7319
+ */
7320
+
7321
+ /**
7322
+ * @type {Hyperscript}
7323
+ */
7324
+ const _hyperscript = Object.assign(
7325
+ run,
7326
+ {
7327
+ config,
7328
+
7329
+ use(plugin) { plugin(_hyperscript) },
7330
+
7331
+ internals: {
7332
+ lexer: lexer_, parser: parser_, runtime: runtime_,
7333
+ Lexer, Tokens, Parser, Runtime,
7334
+ },
7335
+ ElementCollection,
7336
+
7337
+ addFeature: parser_.addFeature.bind(parser_),
7338
+ addCommand: parser_.addCommand.bind(parser_),
7339
+ addLeafExpression: parser_.addLeafExpression.bind(parser_),
7340
+ addIndirectExpression: parser_.addIndirectExpression.bind(parser_),
7341
+
7342
+ evaluate: runtime_.evaluate.bind(runtime_),
7343
+ parse: runtime_.parse.bind(runtime_),
7344
+ processNode: runtime_.processNode.bind(runtime_),
7345
+
7346
+ browserInit,
7347
+ }
7348
+ )
7349
+
7350
+ return _hyperscript
7351
+ })
http.go CHANGED
@@ -338,6 +338,7 @@ func Handle(router *mux.Router, method, route string, h interface{}, meta, style
338
338
  c.Link("stylesheet", GetComponentsStylesUrl(), "", "")
339
339
  c.Link("icon", "/assets/favicon.ico", "image/x-icon", "image")
340
340
  c.Script("/gromer/js/htmx@1.7.0.js", false)
341
+ c.Script("/gromer/js/hyperscript@0.9.6.js", false)
341
342
  // c.Script("/gromer/js/alpinejs@3.9.6.js", true)
342
343
  c.Meta(meta)
343
344
  PerformRequest(route, h, c, w, r)