Debian Codegraph @

www/public/test/lib/_hyperscript.js

raw symbols SCIP
1 ///=========================================================================
2 /// This module provides the core runtime and grammar for hyperscript
3 ///=========================================================================
4 //AMD insanity
5
6 /** @var {HyperscriptObject} _hyperscript */
7
8 (function (root, factory) {
9 if (typeof define === "function" && define.amd) {
10 // AMD. Register as an anonymous module.
11 define([], factory);
12 } else {
13 // Browser globals
14 root._hyperscript = factory();
15 }
16 })(typeof self !== "undefined" ? self : this, function () {
17 "use strict";
18
19 //====================================================================
20 // Utilities
21 //====================================================================
22
23 /**
24 * mergeObjects combines the keys from obj2 into obj2, then returns obj1
25 *
26 * @param {object} obj1
27 * @param {object} obj2
28 * @returns object
29 */
30 function mergeObjects(obj1, obj2) {
31 for (var key in obj2) {
32 if (obj2.hasOwnProperty(key)) {
33 obj1[key] = obj2[key];
34 }
35 }
36 return obj1;
37 }
38
39 function getOrInitObject(root, prop) {
40 var value = root[prop];
41 if (value) {
42 return value;
43 } else {
44 var newObj = {};
45 root[prop] = newObj;
46 return newObj;
47 }
48 }
49
50 /**
51 * parseJSON parses a JSON string into a corresponding value. If the
52 * value passed in is not valid JSON, then it logs an error and returns `null`.
53 *
54 * @param {string} jString
55 * @returns any
56 */
57 function parseJSON(jString) {
58 try {
59 return JSON.parse(jString);
60 } catch (error) {
61 logError(error);
62 return null;
63 }
64 }
65
66 /**
67 * logError writes an error message to the Javascript console. It can take any
68 * value, but msg should commonly be a simple string.
69 * @param {*} msg
70 */
71 function logError(msg) {
72 if (console.error) {
73 console.error(msg);
74 } else if (console.log) {
75 console.log("ERROR: ", msg);
76 }
77 }
78
79 // TODO: JSDoc description of what's happening here
80 function varargConstructor(Cls, args) {
81 return new (Cls.bind.apply(Cls, [Cls].concat(args)))();
82 }
83
84 var globalScope = typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this;
85
86 //====================================================================
87 // Lexer
88 //====================================================================
89
90 /** @type LexerObject */
91 var _lexer = (function () {
92 var OP_TABLE = {
93 "+": "PLUS",
94 "-": "MINUS",
95 "*": "MULTIPLY",
96 "/": "DIVIDE",
97 ".": "PERIOD",
98 "..": "ELLIPSIS",
99 "\\": "BACKSLASH",
100 ":": "COLON",
101 "%": "PERCENT",
102 "|": "PIPE",
103 "!": "EXCLAMATION",
104 "?": "QUESTION",
105 "#": "POUND",
106 "&": "AMPERSAND",
107 $: "DOLLAR",
108 ";": "SEMI",
109 ",": "COMMA",
110 "(": "L_PAREN",
111 ")": "R_PAREN",
112 "<": "L_ANG",
113 ">": "R_ANG",
114 "<=": "LTE_ANG",
115 ">=": "GTE_ANG",
116 "==": "EQ",
117 "===": "EQQ",
118 "!=": "NEQ",
119 "!==": "NEQQ",
120 "{": "L_BRACE",
121 "}": "R_BRACE",
122 "[": "L_BRACKET",
123 "]": "R_BRACKET",
124 "=": "EQUALS",
125 };
126
127 /**
128 * isValidCSSClassChar returns `true` if the provided character is valid in a CSS class.
129 * @param {string} c
130 * @returns boolean
131 */
132 function isValidCSSClassChar(c) {
133 return isAlpha(c) || isNumeric(c) || c === "-" || c === "_" || c === ":";
134 }
135
136 /**
137 * isValidCSSIDChar returns `true` if the provided character is valid in a CSS ID
138 * @param {string} c
139 * @returns boolean
140 */
141 function isValidCSSIDChar(c) {
142 return isAlpha(c) || isNumeric(c) || c === "-" || c === "_" || c === ":";
143 }
144
145 /**
146 * isWhitespace returns `true` if the provided character is whitespace.
147 * @param {string} c
148 * @returns boolean
149 */
150 function isWhitespace(c) {
151 return c === " " || c === "\t" || isNewline(c);
152 }
153
154 /**
155 * positionString returns a string representation of a Token's line and column details.
156 * @param {Token} token
157 * @returns string
158 */
159 function positionString(token) {
160 return "[Line: " + token.line + ", Column: " + token.col + "]";
161 }
162
163 /**
164 * isNewline returns `true` if the provided character is a carrage return or newline
165 * @param {string} c
166 * @returns boolean
167 */
168 function isNewline(c) {
169 return c === "\r" || c === "\n";
170 }
171
172 /**
173 * isNumeric returns `true` if the provided character is a number (0-9)
174 * @param {string} c
175 * @returns boolean
176 */
177 function isNumeric(c) {
178 return c >= "0" && c <= "9";
179 }
180
181 /**
182 * isAlpha returns `true` if the provided character is a letter in the alphabet
183 * @param {string} c
184 * @returns boolean
185 */
186 function isAlpha(c) {
187 return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z");
188 }
189
190 /**
191 * @param {string} c
192 * @param {boolean} [dollarIsOp]
193 * @returns boolean
194 */
195 function isIdentifierChar(c) {
196 return c === "_" || c === "$";
197 }
198
199 /**
200 * @param {string} c
201 * @returns boolean
202 */
203 function isReservedChar(c) {
204 return c === "`" || c === "^";
205 }
206
207 /**
208 * @param {Token[]} tokens
209 * @param {Token[]} consumed
210 * @param {string} source
211 * @returns {TokensObject}
212 */
213 function makeTokensObject(tokens, consumed, source) {
214 consumeWhitespace(); // consume initial whitespace
215
216 /** @type Token | null */
217 var _lastConsumed = null;
218
219 function consumeWhitespace() {
220 while (token(0, true).type === "WHITESPACE") {
221 consumed.push(tokens.shift());
222 }
223 }
224
225 /**
226 * @param {Token[]} tokens
227 * @param {*} error
228 */
229 function raiseError(tokens, error) {
230 _parser.raiseParseError(tokens, error);
231 }
232
233 /**
234 * @param {string} value
235 * @returns {Token}
236 */
237 function requireOpToken(value) {
238 var token = matchOpToken(value);
239 if (token) {
240 return token;
241 } else {
242 raiseError(this, "Expected '" + value + "' but found '" + currentToken().value + "'");
243 }
244 }
245
246 /**
247 * @param {string} op1
248 * @param {string} [op2]
249 * @param {string} [op3]
250 * @returns {Token | void}
251 */
252 function matchAnyOpToken(op1, op2, op3) {
253 for (var i = 0; i < arguments.length; i++) {
254 var opToken = arguments[i];
255 var match = matchOpToken(opToken);
256 if (match) {
257 return match;
258 }
259 }
260 }
261
262 /**
263 * @param {string} op1
264 * @param {string} [op2]
265 * @param {string} [op3]
266 * @returns {Token | void}
267 */
268 function matchAnyToken(op1, op2, op3) {
269 for (var i = 0; i < arguments.length; i++) {
270 var opToken = arguments[i];
271 var match = matchToken(opToken);
272 if (match) {
273 return match;
274 }
275 }
276 }
277
278 /**
279 * @param {string} value
280 * @returns {Token | void}
281 */
282 function matchOpToken(value) {
283 if (currentToken() && currentToken().op && currentToken().value === value) {
284 return consumeToken();
285 }
286 }
287
288 /**
289 * @param {string} type1
290 * @param {string} [type2]
291 * @param {string} [type3]
292 * @param {string} [type4]
293 * @returns {Token | void}
294 */
295 function requireTokenType(type1, type2, type3, type4) {
296 var token = matchTokenType(type1, type2, type3, type4);
297 if (token) {
298 return token;
299 } else {
300 raiseError(this, "Expected one of " + JSON.stringify([type1, type2, type3]));
301 }
302 }
303
304 /**
305 * @param {string} type1
306 * @param {string} [type2]
307 * @param {string} [type3]
308 * @param {string} [type4]
309 * @returns {Token | void}
310 */
311 function matchTokenType(type1, type2, type3, type4) {
312 if (
313 currentToken() &&
314 currentToken().type &&
315 [type1, type2, type3, type4].indexOf(currentToken().type) >= 0
316 ) {
317 return consumeToken();
318 }
319 }
320
321 /**
322 * @param {string} value
323 * @param {string} [type]
324 * @returns {Token}
325 */
326 function requireToken(value, type) {
327 var token = matchToken(value, type);
328 if (token) {
329 return token;
330 } else {
331 raiseError(this, "Expected '" + value + "' but found '" + currentToken().value + "'");
332 }
333 }
334
335 /**
336 * @param {string} value
337 * @param {string} [type]
338 * @returns {Token | void}
339 */
340 function matchToken(value, type) {
341 if (follows.indexOf(value) !== -1) {
342 return; // disallowed token here
343 }
344 var type = type || "IDENTIFIER";
345 if (currentToken() && currentToken().value === value && currentToken().type === type) {
346 return consumeToken();
347 }
348 }
349
350 /**
351 * @returns {Token}
352 */
353 function consumeToken() {
354 var match = tokens.shift();
355 consumed.push(match);
356 _lastConsumed = match;
357 consumeWhitespace(); // consume any whitespace
358 return match;
359 }
360
361 /**
362 * @param {string} value
363 * @param {string} [type]
364 * @returns {Token[]}
365 */
366 function consumeUntil(value, type) {
367 /** @type Token[] */
368 var tokenList = [];
369 var currentToken = token(0, true);
370
371 while (
372 (type == null || currentToken.type !== type) &&
373 (value == null || currentToken.value !== value) &&
374 currentToken.type !== "EOF"
375 ) {
376 var match = tokens.shift();
377 consumed.push(match);
378 tokenList.push(currentToken);
379 currentToken = token(0, true);
380 }
381 consumeWhitespace(); // consume any whitespace
382 return tokenList;
383 }
384
385 /**
386 * @returns {string}
387 */
388 function lastWhitespace() {
389 if (consumed[consumed.length - 1] && consumed[consumed.length - 1].type === "WHITESPACE") {
390 return consumed[consumed.length - 1].value;
391 } else {
392 return "";
393 }
394 }
395
396 function consumeUntilWhitespace() {
397 return consumeUntil(null, "WHITESPACE");
398 }
399
400 /**
401 * @returns {boolean}
402 */
403 function hasMore() {
404 return tokens.length > 0;
405 }
406
407 /**
408 * @param {number} n
409 * @param {boolean} [dontIgnoreWhitespace]
410 * @returns {Token}
411 */
412 function token(n, dontIgnoreWhitespace) {
413 var /**@type {Token}*/ token;
414 var i = 0;
415 do {
416 if (!dontIgnoreWhitespace) {
417 while (tokens[i] && tokens[i].type === "WHITESPACE") {
418 i++;
419 }
420 }
421 token = tokens[i];
422 n--;
423 i++;
424 } while (n > -1);
425 if (token) {
426 return token;
427 } else {
428 return {
429 type: "EOF",
430 value: "<<<EOF>>>",
431 };
432 }
433 }
434
435 /**
436 * @returns {Token}
437 */
438 function currentToken() {
439 return token(0);
440 }
441
442 /**
443 * @returns {Token | null}
444 */
445 function lastMatch() {
446 return _lastConsumed;
447 }
448
449 /**
450 * @returns {string}
451 */
452 function sourceFor() {
453 return source.substring(this.startToken.start, this.endToken.end);
454 }
455
456 /**
457 * @returns {string}
458 */
459 function lineFor() {
460 return source.split("\n")[this.startToken.line - 1];
461 }
462
463 var follows = [];
464
465 function pushFollow(str) {
466 follows.push(str);
467 }
468
469 function popFollow() {
470 follows.pop();
471 }
472
473 function clearFollows() {
474 var tmp = follows;
475 follows = [];
476 return tmp;
477 }
478
479 function restoreFollows(f) {
480 follows = f;
481 }
482
483 /** @type {TokensObject} */
484 return {
485 pushFollow: pushFollow,
486 popFollow: popFollow,
487 clearFollow: clearFollows,
488 restoreFollow: restoreFollows,
489 matchAnyToken: matchAnyToken,
490 matchAnyOpToken: matchAnyOpToken,
491 matchOpToken: matchOpToken,
492 requireOpToken: requireOpToken,
493 matchTokenType: matchTokenType,
494 requireTokenType: requireTokenType,
495 consumeToken: consumeToken,
496 matchToken: matchToken,
497 requireToken: requireToken,
498 list: tokens,
499 consumed: consumed,
500 source: source,
501 hasMore: hasMore,
502 currentToken: currentToken,
503 lastMatch: lastMatch,
504 token: token,
505 consumeUntil: consumeUntil,
506 consumeUntilWhitespace: consumeUntilWhitespace,
507 lastWhitespace: lastWhitespace,
508 sourceFor: sourceFor,
509 lineFor: lineFor,
510 };
511 }
512
513 /**
514 * @param {Token[]} tokens
515 * @returns {boolean}
516 */
517 function isValidSingleQuoteStringStart(tokens) {
518 if (tokens.length > 0) {
519 var previousToken = tokens[tokens.length - 1];
520 if (
521 previousToken.type === "IDENTIFIER" ||
522 previousToken.type === "CLASS_REF" ||
523 previousToken.type === "ID_REF"
524 ) {
525 return false;
526 }
527 if (previousToken.op && (previousToken.value === ">" || previousToken.value === ")")) {
528 return false;
529 }
530 }
531 return true;
532 }
533
534 /**
535 * @param {string} string
536 * @param {boolean} [template]
537 * @returns {TokensObject}
538 */
539 function tokenize(string, template) {
540 var tokens = /** @type {Token[]}*/ [];
541 var source = string;
542 var position = 0;
543 var column = 0;
544 var line = 1;
545 var lastToken = "<START>";
546 var templateBraceCount = 0;
547
548 function inTemplate() {
549 return template && templateBraceCount === 0;
550 }
551
552 while (position < source.length) {
553 if (currentChar() === "-" && nextChar() === "-") {
554 consumeComment();
555 } else {
556 if (isWhitespace(currentChar())) {
557 tokens.push(consumeWhitespace());
558 } else if (
559 !possiblePrecedingSymbol() &&
560 currentChar() === "." &&
561 (isAlpha(nextChar()) || nextChar() === "{")
562 ) {
563 tokens.push(consumeClassReference());
564 } else if (
565 !possiblePrecedingSymbol() &&
566 currentChar() === "#" &&
567 (isAlpha(nextChar()) || nextChar() === "{")
568 ) {
569 tokens.push(consumeIdReference());
570 } else if (currentChar() === "[" && nextChar() === "@") {
571 tokens.push(consumeAttributeReference());
572 } else if (currentChar() === "@") {
573 tokens.push(consumeShortAttributeReference());
574 } else if (isAlpha(currentChar()) || (!inTemplate() && isIdentifierChar(currentChar()))) {
575 tokens.push(consumeIdentifier());
576 } else if (isNumeric(currentChar())) {
577 tokens.push(consumeNumber());
578 } else if (!inTemplate() && (currentChar() === '"' || currentChar() === "`")) {
579 tokens.push(consumeString());
580 } else if (!inTemplate() && currentChar() === "'") {
581 if (isValidSingleQuoteStringStart(tokens)) {
582 tokens.push(consumeString());
583 } else {
584 tokens.push(consumeOp());
585 }
586 } else if (OP_TABLE[currentChar()]) {
587 if (lastToken === "$" && currentChar() === "{") {
588 templateBraceCount++;
589 }
590 if (currentChar() === "}") {
591 templateBraceCount--;
592 }
593 tokens.push(consumeOp());
594 } else if (inTemplate() || isReservedChar(currentChar())) {
595 tokens.push(makeToken("RESERVED", consumeChar()));
596 } else {
597 if (position < source.length) {
598 throw Error("Unknown token: " + currentChar() + " ");
599 }
600 }
601 }
602 }
603
604 return makeTokensObject(tokens, [], source);
605
606 /**
607 * @param {string} [type]
608 * @param {string} [value]
609 * @returns {Token}
610 */
611 function makeOpToken(type, value) {
612 var token = makeToken(type, value);
613 token.op = true;
614 return token;
615 }
616
617 /**
618 * @param {string} [type]
619 * @param {string} [value]
620 * @returns {Token}
621 */
622 function makeToken(type, value) {
623 return {
624 type: type,
625 value: value,
626 start: position,
627 end: position + 1,
628 column: column,
629 line: line,
630 };
631 }
632
633 function consumeComment() {
634 while (currentChar() && !isNewline(currentChar())) {
635 consumeChar();
636 }
637 consumeChar();
638 }
639
640 /**
641 * @returns Token
642 */
643 function consumeClassReference() {
644 var classRef = makeToken("CLASS_REF");
645 var value = consumeChar();
646 if (currentChar() === "{") {
647 classRef.template = true;
648 value += consumeChar();
649 while (currentChar() && currentChar() !== "}") {
650 value += consumeChar();
651 }
652 if (currentChar() !== "}") {
653 throw Error("Unterminated class reference");
654 } else {
655 value += consumeChar(); // consume final curly
656 }
657 } else {
658 while (isValidCSSClassChar(currentChar())) {
659 value += consumeChar();
660 }
661 }
662 classRef.value = value;
663 classRef.end = position;
664 return classRef;
665 }
666
667 /**
668 * @returns Token
669 */
670 function consumeAttributeReference() {
671 var attributeRef = makeToken("ATTRIBUTE_REF");
672 var value = consumeChar();
673 while (position < source.length && currentChar() !== "]") {
674 value += consumeChar();
675 }
676 if (currentChar() === "]") {
677 value += consumeChar();
678 }
679 attributeRef.value = value;
680 attributeRef.end = position;
681 return attributeRef;
682 }
683
684 function consumeShortAttributeReference() {
685 var attributeRef = makeToken("ATTRIBUTE_REF");
686 var value = consumeChar();
687 while (isValidCSSIDChar(currentChar())) {
688 value += consumeChar();
689 }
690 attributeRef.value = value;
691 attributeRef.end = position;
692 return attributeRef;
693 }
694
695 /**
696 * @returns Token
697 */
698 function consumeIdReference() {
699 var idRef = makeToken("ID_REF");
700 var value = consumeChar();
701 if (currentChar() === "{") {
702 idRef.template = true;
703 value += consumeChar();
704 while (currentChar() && currentChar() !== "}") {
705 value += consumeChar();
706 }
707 if (currentChar() !== "}") {
708 throw Error("Unterminated id reference");
709 } else {
710 consumeChar(); // consume final quote
711 }
712 } else {
713 while (isValidCSSIDChar(currentChar())) {
714 value += consumeChar();
715 }
716 }
717 idRef.value = value;
718 idRef.end = position;
719 return idRef;
720 }
721
722 /**
723 * @returns Token
724 */
725 function consumeIdentifier() {
726 var identifier = makeToken("IDENTIFIER");
727 var value = consumeChar();
728 while (isAlpha(currentChar()) || isIdentifierChar(currentChar())) {
729 value += consumeChar();
730 }
731 identifier.value = value;
732 identifier.end = position;
733 return identifier;
734 }
735
736 /**
737 * @returns Token
738 */
739 function consumeNumber() {
740 var number = makeToken("NUMBER");
741 var value = consumeChar();
742 while (isNumeric(currentChar())) {
743 value += consumeChar();
744 }
745 if (currentChar() === "." && isNumeric(nextChar())) {
746 value += consumeChar();
747 }
748 while (isNumeric(currentChar())) {
749 value += consumeChar();
750 }
751 number.value = value;
752 number.end = position;
753 return number;
754 }
755
756 /**
757 * @returns Token
758 */
759 function consumeOp() {
760 var op = makeOpToken();
761 var value = consumeChar(); // consume leading char
762 while (currentChar() && OP_TABLE[value + currentChar()]) {
763 value += consumeChar();
764 }
765 op.type = OP_TABLE[value];
766 op.value = value;
767 op.end = position;
768 return op;
769 }
770
771 /**
772 * @returns Token
773 */
774 function consumeString() {
775 var string = makeToken("STRING");
776 var startChar = consumeChar(); // consume leading quote
777 var value = "";
778 while (currentChar() && currentChar() !== startChar) {
779 if (currentChar() === "\\") {
780 consumeChar(); // consume escape char and move on
781 }
782 value += consumeChar();
783 }
784 if (currentChar() !== startChar) {
785 throw Error("Unterminated string at " + positionString(string));
786 } else {
787 consumeChar(); // consume final quote
788 }
789 string.value = value;
790 string.end = position;
791 string.template = startChar === "`";
792 return string;
793 }
794
795 /**
796 * @returns string
797 */
798 function currentChar() {
799 return source.charAt(position);
800 }
801
802 /**
803 * @returns string
804 */
805 function nextChar() {
806 return source.charAt(position + 1);
807 }
808
809 /**
810 * @returns string
811 */
812 function consumeChar() {
813 lastToken = currentChar();
814 position++;
815 column++;
816 return lastToken;
817 }
818
819 /**
820 * @returns boolean
821 */
822 function possiblePrecedingSymbol() {
823 return (
824 isAlpha(lastToken) ||
825 isNumeric(lastToken) ||
826 lastToken === ")" ||
827 lastToken === "}" ||
828 lastToken === "]"
829 );
830 }
831
832 /**
833 * @returns Token
834 */
835 function consumeWhitespace() {
836 var whitespace = makeToken("WHITESPACE");
837 var value = "";
838 while (currentChar() && isWhitespace(currentChar())) {
839 if (isNewline(currentChar())) {
840 column = 0;
841 line++;
842 }
843 value += consumeChar();
844 }
845 whitespace.value = value;
846 whitespace.end = position;
847 return whitespace;
848 }
849 }
850
851 return {
852 tokenize: tokenize,
853 makeTokensObject: makeTokensObject,
854 };
855 })();
856
857 //====================================================================
858 // Parser
859 //====================================================================
860
861 /** @type ParserObject */
862 var _parser = (function () {
863 /** @type {Object<string,GrammarDefinition>} */
864 var GRAMMAR = {};
865
866 /** @type {Object<string,GrammarDefinition>} */
867 var COMMANDS = {};
868
869 /** @type {Object<string,GrammarDefinition>} */
870 var FEATURES = {};
871
872 var LEAF_EXPRESSIONS = [];
873 var INDIRECT_EXPRESSIONS = [];
874
875 /**
876 * @param {*} parseElement
877 * @param {*} start
878 * @param {TokensObject} tokens
879 */
880 function initElt(parseElement, start, tokens) {
881 parseElement.startToken = start;
882 parseElement.sourceFor = tokens.sourceFor;
883 parseElement.lineFor = tokens.lineFor;
884 parseElement.programSource = tokens.source;
885 }
886
887 /**
888 * @param {string} type
889 * @param {TokensObject} tokens
890 * @param {*} root
891 * @returns GrammarElement
892 */
893 function parseElement(type, tokens, root) {
894 var elementDefinition = GRAMMAR[type];
895 if (elementDefinition) {
896 var start = tokens.currentToken();
897 var parseElement = elementDefinition(_parser, _runtime, tokens, root);
898 if (parseElement) {
899 initElt(parseElement, start, tokens);
900 parseElement.endToken = parseElement.endToken || tokens.lastMatch();
901 var root = parseElement.root;
902 while (root != null) {
903 initElt(root, start, tokens);
904 root = root.root;
905 }
906 }
907 return parseElement;
908 }
909 }
910
911 /**
912 * @param {string} type
913 * @param {TokensObject} tokens
914 * @param {string} [message]
915 * @param {*} [root]
916 * @returns {GrammarElement}
917 */
918 function requireElement(type, tokens, message, root) {
919 var result = parseElement(type, tokens, root);
920 return result || raiseParseError(tokens, message || "Expected " + type);
921 }
922
923 /**
924 * @param {string[]} types
925 * @param {TokensObject} tokens
926 * @returns {GrammarElement}
927 */
928 function parseAnyOf(types, tokens) {
929 for (var i = 0; i < types.length; i++) {
930 var type = types[i];
931 var expression = parseElement(type, tokens);
932 if (expression) {
933 return expression;
934 }
935 }
936 }
937
938 /**
939 * @param {string} name
940 * @param {GrammarDefinition} definition
941 */
942 function addGrammarElement(name, definition) {
943 GRAMMAR[name] = definition;
944 }
945
946 /**
947 * @param {string} keyword
948 * @param {GrammarDefinition} definition
949 */
950 function addCommand(keyword, definition) {
951 var commandGrammarType = keyword + "Command";
952 var commandDefinitionWrapper = function (parser, runtime, tokens) {
953 var commandElement = definition(parser, runtime, tokens);
954 if (commandElement) {
955 commandElement.type = commandGrammarType;
956 commandElement.execute = function (context) {
957 context.meta.command = commandElement;
958 return runtime.unifiedExec(this, context);
959 };
960 return commandElement;
961 }
962 };
963 GRAMMAR[commandGrammarType] = commandDefinitionWrapper;
964 COMMANDS[keyword] = commandDefinitionWrapper;
965 }
966
967 /**
968 * @param {string} keyword
969 * @param {GrammarDefinition} definition
970 */
971 function addFeature(keyword, definition) {
972 var featureGrammarType = keyword + "Feature";
973
974 /** @type {GrammarDefinition} */
975 var featureDefinitionWrapper = function (parser, runtime, tokens) {
976 var featureElement = definition(parser, runtime, tokens);
977 if (featureElement) {
978 featureElement.keyword = keyword;
979 featureElement.type = featureGrammarType;
980 return featureElement;
981 }
982 };
983 GRAMMAR[featureGrammarType] = featureDefinitionWrapper;
984 FEATURES[keyword] = featureDefinitionWrapper;
985 }
986
987 /**
988 * @param {string} name
989 * @param {GrammarDefinition} definition
990 */
991 function addLeafExpression(name, definition) {
992 LEAF_EXPRESSIONS.push(name);
993 addGrammarElement(name, definition);
994 }
995
996 /**
997 * @param {string} name
998 * @param {GrammarDefinition} definition
999 */
1000 function addIndirectExpression(name, definition) {
1001 INDIRECT_EXPRESSIONS.push(name);
1002 addGrammarElement(name, definition);
1003 }
1004
1005 /* ============================================================================================ */
1006 /* Core hyperscript Grammar Elements */
1007 /* ============================================================================================ */
1008 addGrammarElement("feature", function (parser, runtime, tokens) {
1009 if (tokens.matchOpToken("(")) {
1010 var featureElement = parser.requireElement("feature", tokens);
1011 tokens.requireOpToken(")");
1012 return featureElement;
1013 }
1014
1015 var featureDefinition = FEATURES[tokens.currentToken().value];
1016 if (featureDefinition) {
1017 return featureDefinition(parser, runtime, tokens);
1018 }
1019 });
1020
1021 addGrammarElement("command", function (parser, runtime, tokens) {
1022 if (tokens.matchOpToken("(")) {
1023 var commandElement = parser.requireElement("command", tokens);
1024 tokens.requireOpToken(")");
1025 return commandElement;
1026 }
1027
1028 var commandDefinition = COMMANDS[tokens.currentToken().value];
1029 if (commandDefinition) {
1030 var commandElement = commandDefinition(parser, runtime, tokens);
1031 } else if (tokens.currentToken().type === "IDENTIFIER" && tokens.token(1).value === "(") {
1032 var commandElement = parser.requireElement("pseudoCommand", tokens);
1033 }
1034 if (commandElement) {
1035 return parser.parseElement("indirectStatement", tokens, commandElement);
1036 }
1037
1038 return commandElement;
1039 });
1040
1041 addGrammarElement("commandList", function (parser, runtime, tokens) {
1042 var cmd = parser.parseElement("command", tokens);
1043 if (cmd) {
1044 tokens.matchToken("then");
1045 cmd.next = parser.parseElement("commandList", tokens);
1046 return cmd;
1047 }
1048 });
1049
1050 addGrammarElement("leaf", function (parser, runtime, tokens) {
1051 var result = parseAnyOf(LEAF_EXPRESSIONS, tokens);
1052 // symbol is last so it doesn't consume any constants
1053 if (result == null) {
1054 return parseElement("symbol", tokens);
1055 }
1056
1057 return result;
1058 });
1059
1060 addGrammarElement("indirectExpression", function (parser, runtime, tokens, root) {
1061 for (var i = 0; i < INDIRECT_EXPRESSIONS.length; i++) {
1062 var indirect = INDIRECT_EXPRESSIONS[i];
1063 root.endToken = tokens.lastMatch();
1064 var result = parser.parseElement(indirect, tokens, root);
1065 if (result) {
1066 return result;
1067 }
1068 }
1069 return root;
1070 });
1071
1072 addGrammarElement("indirectStatement", function (parser, runtime, tokens, root) {
1073 if (tokens.matchToken("unless")) {
1074 root.endToken = tokens.lastMatch();
1075 var conditional = parser.requireElement("expression", tokens);
1076 var unless = {
1077 type: "unlessStatementModifier",
1078 args: [conditional],
1079 op: function (context, conditional) {
1080 if (conditional) {
1081 return this.next;
1082 } else {
1083 return root;
1084 }
1085 },
1086 execute: function (context) {
1087 return runtime.unifiedExec(this, context);
1088 },
1089 };
1090 root.parent = unless;
1091 return unless;
1092 }
1093 return root;
1094 });
1095
1096 addGrammarElement("primaryExpression", function (parser, runtime, tokens) {
1097 var leaf = parser.parseElement("leaf", tokens);
1098 if (leaf) {
1099 return parser.parseElement("indirectExpression", tokens, leaf);
1100 }
1101 parser.raiseParseError(tokens, "Unexpected value: " + tokens.currentToken().value);
1102 });
1103
1104 /* ============================================================================================ */
1105 /* END Core hyperscript Grammar Elements */
1106
1107 /* ============================================================================================ */
1108
1109 /**
1110 *
1111 * @param {TokensObject} tokens
1112 * @returns string
1113 */
1114 function createParserContext(tokens) {
1115 var currentToken = tokens.currentToken();
1116 var source = tokens.source;
1117 var lines = source.split("\n");
1118 var line = currentToken && currentToken.line ? currentToken.line - 1 : lines.length - 1;
1119 var contextLine = lines[line];
1120 var offset = currentToken && currentToken.line ? currentToken.column : contextLine.length - 1;
1121 return contextLine + "\n" + " ".repeat(offset) + "^^\n\n";
1122 }
1123
1124 /**
1125 * @param {TokensObject} tokens
1126 * @param {string} message
1127 */
1128 function raiseParseError(tokens, message) {
1129 message =
1130 (message || "Unexpected Token : " + tokens.currentToken().value) + "\n\n" + createParserContext(tokens);
1131 var error = new Error(message);
1132 error["tokens"] = tokens;
1133 throw error;
1134 }
1135
1136 /**
1137 * @param {TokensObject} tokens
1138 * @returns {GrammarElement}
1139 */
1140 function parseHyperScript(tokens) {
1141 var result = parseElement("hyperscript", tokens);
1142 if (tokens.hasMore()) raiseParseError(tokens);
1143 return result;
1144 }
1145
1146 /**
1147 * @param {GrammarElement} elt
1148 * @param {GrammarElement} parent
1149 */
1150 function setParent(elt, parent) {
1151 if (elt) {
1152 elt.parent = parent;
1153 setParent(elt.next, parent);
1154 }
1155 }
1156
1157 /**
1158 * @param {Token} token
1159 * @returns {GrammarDefinition}
1160 */
1161 function commandStart(token) {
1162 return COMMANDS[token.value];
1163 }
1164
1165 /**
1166 * @param {Token} token
1167 * @returns {GrammarDefinition}
1168 */
1169 function featureStart(token) {
1170 return FEATURES[token.value];
1171 }
1172
1173 /**
1174 * @param {Token} token
1175 * @returns {true | void}
1176 */
1177 function commandBoundary(token) {
1178 if (
1179 token.value == "end" ||
1180 token.value == "then" ||
1181 token.value == "else" ||
1182 token.value == ")" ||
1183 commandStart(token) ||
1184 featureStart(token) ||
1185 token.type == "EOF"
1186 ) {
1187 return true;
1188 }
1189 }
1190
1191 /**
1192 * @param {TokensObject} tokens
1193 * @returns {(string | Token)[]}
1194 */
1195 function parseStringTemplate(tokens) {
1196 /** @type (string | Token)[] */
1197 var returnArr = [""];
1198 do {
1199 returnArr.push(tokens.lastWhitespace());
1200 if (tokens.currentToken().value === "$") {
1201 tokens.consumeToken();
1202 var startingBrace = tokens.matchOpToken("{");
1203 returnArr.push(requireElement("expression", tokens));
1204 if (startingBrace) {
1205 tokens.requireOpToken("}");
1206 }
1207 returnArr.push("");
1208 } else if (tokens.currentToken().value === "\\") {
1209 tokens.consumeToken(); // skip next
1210 tokens.consumeToken();
1211 } else {
1212 var token = tokens.consumeToken();
1213 returnArr[returnArr.length - 1] += token ? token.value : "";
1214 }
1215 } while (tokens.hasMore());
1216 returnArr.push(tokens.lastWhitespace());
1217 return returnArr;
1218 }
1219
1220 // parser API
1221 return {
1222 setParent: setParent,
1223 requireElement: requireElement,
1224 parseElement: parseElement,
1225 featureStart: featureStart,
1226 commandStart: commandStart,
1227 commandBoundary: commandBoundary,
1228 parseAnyOf: parseAnyOf,
1229 parseHyperScript: parseHyperScript,
1230 raiseParseError: raiseParseError,
1231 addGrammarElement: addGrammarElement,
1232 addCommand: addCommand,
1233 addFeature: addFeature,
1234 addLeafExpression: addLeafExpression,
1235 addIndirectExpression: addIndirectExpression,
1236 parseStringTemplate: parseStringTemplate,
1237 };
1238 })();
1239
1240 //====================================================================
1241 // Runtime
1242 //====================================================================
1243
1244 /** @type ConversionMap */
1245 var CONVERSIONS = {
1246 dynamicResolvers: /** @type DynamicConversionFunction[] */ [],
1247 String: function (val) {
1248 if (val.toString) {
1249 return val.toString();
1250 } else {
1251 return "" + val;
1252 }
1253 },
1254 Int: function (val) {
1255 return parseInt(val);
1256 },
1257 Float: function (val) {
1258 return parseFloat(val);
1259 },
1260 Number: function (val) {
1261 console.log(val);
1262 return Number(val);
1263 },
1264 Date: function (val) {
1265 return Date(val);
1266 },
1267 Array: function (val) {
1268 return Array.from(val);
1269 },
1270 JSON: function (val) {
1271 return JSON.stringify(val);
1272 },
1273 Object: function (val) {
1274 if (val instanceof String) {
1275 val = val.toString();
1276 }
1277 if (typeof val === "string") {
1278 return JSON.parse(val);
1279 } else {
1280 return mergeObjects({}, val);
1281 }
1282 },
1283 };
1284
1285 /********************************************
1286 * RUNTIME OBJECT
1287 ********************************************/
1288
1289 /** @type {RuntimeObject} */
1290 var _runtime = (function () {
1291 /**
1292 * @param {HTMLElement} elt
1293 * @param {string} selector
1294 * @returns boolean
1295 */
1296 function matchesSelector(elt, selector) {
1297 // noinspection JSUnresolvedVariable
1298 var matchesFunction =
1299 elt.matches ||
1300 elt.matchesSelector ||
1301 elt.msMatchesSelector ||
1302 elt.mozMatchesSelector ||
1303 elt.webkitMatchesSelector ||
1304 elt.oMatchesSelector;
1305 return matchesFunction && matchesFunction.call(elt, selector);
1306 }
1307
1308 /**
1309 * @param {string} eventName
1310 * @param {Object} [detail]
1311 * @returns {Event}
1312 */
1313 function makeEvent(eventName, detail) {
1314 var evt;
1315 if (window.CustomEvent && typeof window.CustomEvent === "function") {
1316 evt = new CustomEvent(eventName, {
1317 bubbles: true,
1318 cancelable: true,
1319 detail: detail,
1320 });
1321 } else {
1322 evt = document.createEvent("CustomEvent");
1323 evt.initCustomEvent(eventName, true, true, detail);
1324 }
1325 return evt;
1326 }
1327
1328 /**
1329 * @param {HTMLElement} elt
1330 * @param {string} eventName
1331 * @param {Object} [detail]
1332 * @returns {boolean}
1333 */
1334 function triggerEvent(elt, eventName, detail) {
1335 detail = detail || {};
1336 detail["sentBy"] = elt;
1337 var event = makeEvent(eventName, detail);
1338 var eventResult = elt.dispatchEvent(event);
1339 return eventResult;
1340 }
1341
1342 /**
1343 * isArrayLike returns `true` if the provided value is an array or
1344 * a NodeList (which is close enough to being an array for our purposes).
1345 *
1346 * @param {any} value
1347 * @returns {value is Array | NodeList}
1348 */
1349 function isArrayLike(value) {
1350 return Array.isArray(value) || value instanceof NodeList;
1351 }
1352
1353 /**
1354 * forEach executes the provided `func` on every item in the `value` array.
1355 * if `value` is a single item (and not an array) then `func` is simply called
1356 * once. If `value` is null, then no further actions are taken.
1357 *
1358 * @template T
1359 * @param {NodeList | T | T[]} value
1360 * @param {(item:Node | T) => void} func
1361 */
1362 function forEach(value, func) {
1363 if (value == null) {
1364 // do nothing
1365 } else if (isArrayLike(value)) {
1366 for (var i = 0; i < value.length; i++) {
1367 func(value[i]);
1368 }
1369 } else {
1370 func(value);
1371 }
1372 }
1373
1374 var ARRAY_SENTINEL = { array_sentinel: true };
1375
1376 function linearize(args) {
1377 var arr = [];
1378 for (var i = 0; i < args.length; i++) {
1379 var arg = args[i];
1380 if (Array.isArray(arg)) {
1381 arr.push(ARRAY_SENTINEL);
1382 for (var j = 0; j < arg.length; j++) {
1383 arr.push(arg[j]);
1384 }
1385 arr.push(ARRAY_SENTINEL);
1386 } else {
1387 arr.push(arg);
1388 }
1389 }
1390 return arr;
1391 }
1392
1393 function delinearize(values) {
1394 var arr = [];
1395 for (var i = 0; i < values.length; i++) {
1396 var value = values[i];
1397 if (value === ARRAY_SENTINEL) {
1398 value = values[++i];
1399 var valueArray = [];
1400 arr.push(valueArray);
1401 while (value !== ARRAY_SENTINEL) {
1402 valueArray.push(value);
1403 value = values[++i];
1404 }
1405 } else {
1406 arr.push(value);
1407 }
1408 }
1409 return arr;
1410 }
1411
1412 function unwrapAsyncs(values) {
1413 for (var i = 0; i < values.length; i++) {
1414 var value = values[i];
1415 if (value.asyncWrapper) {
1416 values[i] = value.value;
1417 }
1418 if (Array.isArray(value)) {
1419 for (var j = 0; j < value.length; j++) {
1420 var valueElement = value[j];
1421 if (valueElement.asyncWrapper) {
1422 value[j] = valueElement.value;
1423 }
1424 }
1425 }
1426 }
1427 }
1428
1429 var HALT = { halt_flag: true };
1430
1431 /**
1432 * @param {GrammarDefinition} command
1433 * @param {Context} ctx
1434 */
1435 function unifiedExec(command, ctx) {
1436 while (true) {
1437 try {
1438 var next = unifiedEval(command, ctx);
1439 } catch (e) {
1440 _runtime.registerHyperTrace(ctx, e);
1441 if (ctx.meta.errorHandler && !ctx.meta.handlingError) {
1442 ctx.meta.handlingError = true;
1443 ctx[ctx.meta.errorSymmbol] = e;
1444 command = ctx.meta.errorHandler;
1445 continue;
1446 } else if (ctx.meta.reject) {
1447 ctx.meta.reject(e);
1448 next = HALT;
1449 } else {
1450 throw e;
1451 }
1452 }
1453 if (next == null) {
1454 console.error(command, " did not return a next element to execute! context: ", ctx);
1455 return;
1456 } else if (next.then) {
1457 next.then(function (resolvedNext) {
1458 unifiedExec(resolvedNext, ctx);
1459 }).catch(function (reason) {
1460 _runtime.registerHyperTrace(ctx, reason);
1461 if (ctx.meta.errorHandler && !ctx.meta.handlingError) {
1462 ctx.meta.handlingError = true;
1463 ctx[ctx.meta.errorSymmbol] = reason;
1464 unifiedExec(ctx.meta.errorHandler, ctx);
1465 } else if (ctx.meta.reject) {
1466 ctx.meta.reject(reason);
1467 } else {
1468 throw reason;
1469 }
1470 });
1471 return;
1472 } else if (next === HALT) {
1473 // done
1474 return;
1475 } else {
1476 command = next; // move to the next command
1477 }
1478 }
1479 }
1480
1481 /**
1482 * @param {*} parseElement
1483 * @param {Context} ctx
1484 * @returns {*}
1485 */
1486 function unifiedEval(parseElement, ctx) {
1487 /** @type any[] */
1488 var args = [ctx];
1489 var async = false;
1490 var wrappedAsyncs = false;
1491
1492 if (parseElement.args) {
1493 for (var i = 0; i < parseElement.args.length; i++) {
1494 var argument = parseElement.args[i];
1495 if (argument == null) {
1496 args.push(null);
1497 } else if (Array.isArray(argument)) {
1498 var arr = [];
1499 for (var j = 0; j < argument.length; j++) {
1500 var element = argument[j];
1501 var value = element ? element.evaluate(ctx) : null; // OK
1502 if (value) {
1503 if (value.then) {
1504 async = true;
1505 } else if (value.asyncWrapper) {
1506 wrappedAsyncs = true;
1507 }
1508 }
1509 arr.push(value);
1510 }
1511 args.push(arr);
1512 } else if (argument.evaluate) {
1513 var value = argument.evaluate(ctx); // OK
1514 if (value) {
1515 if (value.then) {
1516 async = true;
1517 } else if (value.asyncWrapper) {
1518 wrappedAsyncs = true;
1519 }
1520 }
1521 args.push(value);
1522 } else {
1523 args.push(argument);
1524 }
1525 }
1526 }
1527 if (async) {
1528 return new Promise(function (resolve, reject) {
1529 var linearized = linearize(args);
1530 Promise.all(linearized)
1531 .then(function (values) {
1532 values = delinearize(values);
1533 if (wrappedAsyncs) {
1534 unwrapAsyncs(values);
1535 }
1536 try {
1537 var apply = parseElement.op.apply(parseElement, values);
1538 resolve(apply);
1539 } catch (e) {
1540 reject(e);
1541 }
1542 })
1543 .catch(function (reason) {
1544 if (ctx.meta.errorHandler && !ctx.meta.handlingError) {
1545 ctx.meta.handlingError = true;
1546 ctx[ctx.meta.errorSymmbol] = reason;
1547 unifiedExec(ctx.meta.errorHandler, ctx);
1548 } else if (ctx.meta.reject) {
1549 ctx.meta.reject(reason);
1550 } else {
1551 // TODO: no meta context to reject with, trigger event?
1552 }
1553 });
1554 });
1555 } else {
1556 if (wrappedAsyncs) {
1557 unwrapAsyncs(args);
1558 }
1559 return parseElement.op.apply(parseElement, args);
1560 }
1561 }
1562
1563 var _scriptAttrs = null;
1564
1565 /**
1566 * getAttributes returns the attribute name(s) to use when
1567 * locating hyperscript scripts in a DOM element. If no value
1568 * has been configured, it defaults to _hyperscript.config.attributes
1569 * @returns string[]
1570 */
1571 function getScriptAttributes() {
1572 if (_scriptAttrs == null) {
1573 _scriptAttrs = _hyperscript.config.attributes.replace(/ /g, "").split(",");
1574 }
1575 return _scriptAttrs;
1576 }
1577
1578 /**
1579 * @param {HTMLElement} elt
1580 * @returns {string | null}
1581 */
1582 function getScript(elt) {
1583 for (var i = 0; i < getScriptAttributes().length; i++) {
1584 var scriptAttribute = getScriptAttributes()[i];
1585 if (elt.hasAttribute && elt.hasAttribute(scriptAttribute)) {
1586 return elt.getAttribute(scriptAttribute);
1587 }
1588 }
1589 if (elt["type"] === "text/hyperscript") {
1590 return elt.innerText;
1591 }
1592 return null;
1593 }
1594
1595 /**
1596 * @param {Object} owner
1597 * @param {Context} ctx
1598 */
1599 function addFeatures(owner, ctx) {
1600 if (owner) {
1601 if (owner.hyperscriptFeatures) {
1602 mergeObjects(ctx, owner.hyperscriptFeatures);
1603 }
1604 addFeatures(owner.parentElement, ctx);
1605 }
1606 }
1607
1608 /**
1609 * @param {*} owner
1610 * @param {*} feature
1611 * @param {*} hyperscriptTarget
1612 * @param {*} event
1613 * @returns {Context}
1614 */
1615 function makeContext(owner, feature, hyperscriptTarget, event) {
1616 /** @type {Context} */
1617 var ctx = {
1618 meta: {
1619 parser: _parser,
1620 lexer: _lexer,
1621 runtime: _runtime,
1622 owner: owner,
1623 feature: feature,
1624 iterators: {},
1625 },
1626 me: hyperscriptTarget,
1627 event: event,
1628 target: event ? event.target : null,
1629 detail: event ? event.detail : null,
1630 body: "document" in globalScope ? document.body : null,
1631 };
1632 ctx.meta.ctx = ctx;
1633 addFeatures(owner, ctx);
1634 return ctx;
1635 }
1636
1637 /**
1638 * @returns string
1639 */
1640 function getScriptSelector() {
1641 return getScriptAttributes()
1642 .map(function (attribute) {
1643 return "[" + attribute + "]";
1644 })
1645 .join(", ");
1646 }
1647
1648 /**
1649 * @param {any} value
1650 * @param {string} type
1651 * @returns {any}
1652 */
1653 function convertValue(value, type) {
1654 var dynamicResolvers = CONVERSIONS.dynamicResolvers;
1655 for (var i = 0; i < dynamicResolvers.length; i++) {
1656 var dynamicResolver = dynamicResolvers[i];
1657 var converted = dynamicResolver(type, value);
1658 if (converted !== undefined) {
1659 return converted;
1660 }
1661 }
1662
1663 if (value == null) {
1664 return null;
1665 }
1666 var converter = CONVERSIONS[type];
1667 if (converter) {
1668 return converter(value);
1669 }
1670
1671 throw "Unknown conversion : " + type;
1672 }
1673
1674 // TODO: There do not seem to be any references to this function.
1675 // Is it still in use, or can it be removed?
1676 function isType(o, type) {
1677 return Object.prototype.toString.call(o) === "[object " + type + "]";
1678 }
1679
1680 /**
1681 * @param {string} src
1682 * @returns {GrammarElement}
1683 */
1684 function parse(src) {
1685 var tokens = _lexer.tokenize(src);
1686 if (_parser.commandStart(tokens.currentToken())) {
1687 var commandList = _parser.parseElement("commandList", tokens);
1688 var last = commandList;
1689 while (last.next) {
1690 last = last.next;
1691 }
1692 last.next = {
1693 op: function () {
1694 return HALT;
1695 },
1696 };
1697 return commandList;
1698 } else if (_parser.featureStart(tokens.currentToken())) {
1699 var hyperscript = _parser.parseElement("hyperscript", tokens);
1700 return hyperscript;
1701 } else {
1702 var expression = _parser.parseElement("expression", tokens);
1703 return expression;
1704 }
1705 }
1706
1707 /**
1708 * @param {string} src
1709 * @param {Context} ctx
1710 * @returns {any}
1711 */
1712 function evaluate(src, ctx) {
1713 ctx = mergeObjects(makeContext(document.body, null, document.body, null), ctx || {});
1714 var element = parse(src);
1715 if (element.execute) {
1716 return element.execute(ctx);
1717 } else if (element.apply) {
1718 element.apply(document.body, null);
1719 } else {
1720 return element.evaluate(ctx);
1721 }
1722 }
1723
1724 /**
1725 * @param {HTMLElement} elt
1726 */
1727 function processNode(elt) {
1728 var selector = _runtime.getScriptSelector();
1729 if (matchesSelector(elt, selector)) {
1730 initElement(elt, elt);
1731 }
1732 if (elt["type"] === "text/hyperscript") {
1733 initElement(elt, document.body);
1734 }
1735 if (elt.querySelectorAll) {
1736 forEach(elt.querySelectorAll(selector + ", [type='text/hyperscript']"), function (elt) {
1737 initElement(elt, elt.type === "text/hyperscript" ? document.body : elt);
1738 });
1739 }
1740 }
1741
1742 /**
1743 * @param {HTMLElement} elt
1744 * @param {HTMLElement} [target]
1745 */
1746 function initElement(elt, target) {
1747 if (elt.closest && elt.closest(_hyperscript.config.disableSelector)) {
1748 return;
1749 }
1750 var internalData = getInternalData(elt);
1751 if (!internalData.initialized) {
1752 var src = getScript(elt);
1753 if (src) {
1754 try {
1755 internalData.initialized = true;
1756 internalData.script = src;
1757 var tokens = _lexer.tokenize(src);
1758 var hyperScript = _parser.parseHyperScript(tokens);
1759 hyperScript.apply(target || elt, elt);
1760 setTimeout(function () {
1761 triggerEvent(target || elt, "load", {
1762 hyperscript: true,
1763 });
1764 }, 1);
1765 } catch (e) {
1766 _runtime.triggerEvent(elt, "exception", {
1767 error: e,
1768 });
1769 console.error(
1770 "hyperscript errors were found on the following element:",
1771 elt,
1772 "\n\n",
1773 e.message,
1774 e.stack
1775 );
1776 }
1777 }
1778 }
1779 }
1780
1781 /**
1782 * @param {HTMLElement} elt
1783 * @returns {Object}
1784 */
1785 function getInternalData(elt) {
1786 var dataProp = "hyperscript-internal-data";
1787 var data = elt[dataProp];
1788 if (!data) {
1789 data = elt[dataProp] = {};
1790 }
1791 return data;
1792 }
1793
1794 /**
1795 * @param {any} value
1796 * @param {string} typeString
1797 * @param {boolean} [nullOk]
1798 * @returns {boolean}
1799 */
1800 function typeCheck(value, typeString, nullOk) {
1801 if (value == null && nullOk) {
1802 return true;
1803 }
1804 var typeName = Object.prototype.toString.call(value).slice(8, -1);
1805 return typeName === typeString;
1806 }
1807
1808 function getElementScope(context) {
1809 var elt = context.meta.owner;
1810 if (elt) {
1811 var internalData = getInternalData(elt);
1812 var scopeName = "elementScope";
1813 if (context.meta.feature && context.meta.feature.behavior) {
1814 scopeName = context.meta.feature.behavior + "Scope";
1815 }
1816 var elementScope = getOrInitObject(internalData, scopeName);
1817 return elementScope;
1818 } else {
1819 return {}; // no element, return empty scope
1820 }
1821 }
1822
1823 /**
1824 * @param {string} str
1825 * @param {Context} context
1826 * @returns {any}
1827 */
1828 function resolveSymbol(str, context, type) {
1829 if (str === "me" || str === "my" || str === "I") {
1830 return context["me"];
1831 }
1832 if (str === "it" || str === "its") {
1833 return context["result"];
1834 }
1835 if (str === "you" || str === "your" || str === "yourself") {
1836 return context["beingTold"];
1837 } else {
1838 if (type === "global") {
1839 return globalScope[str];
1840 } else if (type === "element") {
1841 var elementScope = getElementScope(context);
1842 return elementScope[str];
1843 } else if (type === "local") {
1844 return context[str];
1845 } else {
1846 // meta scope (used for event conditionals)
1847 if (context.meta && context.meta.context) {
1848 var fromMetaContext = context.meta.context[str];
1849 if (typeof fromMetaContext !== "undefined") {
1850 return fromMetaContext;
1851 }
1852 }
1853 // local scope
1854 var fromContext = context[str];
1855 if (typeof fromContext !== "undefined") {
1856 return fromContext;
1857 } else {
1858 // element scope
1859 var elementScope = getElementScope(context);
1860 fromContext = elementScope[str];
1861 if (typeof fromContext !== "undefined") {
1862 return fromContext;
1863 } else {
1864 // global scope
1865 return globalScope[str];
1866 }
1867 }
1868 }
1869 }
1870 }
1871
1872 function setSymbol(str, context, type, value) {
1873 if (type === "global") {
1874 globalScope[str] = value;
1875 } else if (type === "element") {
1876 var elementScope = getElementScope(context);
1877 elementScope[str] = value;
1878 } else if (type === "local") {
1879 context[str] = value;
1880 } else {
1881 // local scope
1882 var fromContext = context[str];
1883 if (typeof fromContext !== "undefined") {
1884 context[str] = value;
1885 } else {
1886 // element scope
1887 var elementScope = getElementScope(context);
1888 fromContext = elementScope[str];
1889 if (typeof fromContext !== "undefined") {
1890 elementScope[str] = value;
1891 } else {
1892 // global scope
1893 fromContext = globalScope[str];
1894 if (typeof fromContext !== "undefined") {
1895 globalScope[str] = value;
1896 } else {
1897 context[str] = value;
1898 }
1899 }
1900 }
1901 }
1902 }
1903
1904 /**
1905 * @param {GrammarElement} command
1906 * @param {Context} context
1907 * @returns {undefined | GrammarElement}
1908 */
1909 function findNext(command, context) {
1910 if (command) {
1911 if (command.resolveNext) {
1912 return command.resolveNext(context);
1913 } else if (command.next) {
1914 return command.next;
1915 } else {
1916 return findNext(command.parent, context);
1917 }
1918 }
1919 }
1920
1921 /**
1922 * @param {Object<string,any>} root
1923 * @param {string} property
1924 * @param {boolean} attribute
1925 * @returns {any}
1926 */
1927 function resolveProperty(root, property, attribute) {
1928 if (root != null) {
1929 var val = attribute && root.getAttribute ? root.getAttribute(property) : root[property];
1930 if (typeof val !== "undefined") {
1931 return val;
1932 }
1933
1934 if (isArrayLike(root)) {
1935 // flat map
1936 var result = [];
1937 for (var i = 0; i < root.length; i++) {
1938 var component = root[i];
1939 var componentValue = attribute ? component.getAttribute(property) : component[property];
1940 if (componentValue) {
1941 result.push(componentValue);
1942 }
1943 }
1944 return result;
1945 }
1946 }
1947 }
1948
1949 /**
1950 * @param {Element} elt
1951 * @param {string[]} nameSpace
1952 * @param {string} name
1953 * @param {any} value
1954 */
1955 function assignToNamespace(elt, nameSpace, name, value) {
1956 if (typeof document === "undefined" || elt === document.body) {
1957 var root = globalScope;
1958 } else {
1959 var root = elt["hyperscriptFeatures"];
1960 if (root == null) {
1961 root = {};
1962 elt["hyperscriptFeatures"] = root;
1963 }
1964 }
1965 while (nameSpace.length > 0) {
1966 var propertyName = nameSpace.shift();
1967 var newRoot = root[propertyName];
1968 if (newRoot == null) {
1969 newRoot = {};
1970 root[propertyName] = newRoot;
1971 }
1972 root = newRoot;
1973 }
1974
1975 root[name] = value;
1976 }
1977
1978 function getHyperTrace(ctx, thrown) {
1979 var trace = [];
1980 var root = ctx;
1981 while (root.meta.caller) {
1982 root = root.meta.caller;
1983 }
1984 if (root.meta.traceMap) {
1985 return root.meta.traceMap.get(thrown, trace);
1986 }
1987 }
1988
1989 function registerHyperTrace(ctx, thrown) {
1990 var trace = [];
1991 var root = null;
1992 while (ctx != null) {
1993 trace.push(ctx);
1994 root = ctx;
1995 ctx = ctx.meta.caller;
1996 }
1997 if (root.meta.traceMap == null) {
1998 root.meta.traceMap = new Map(); // TODO - WeakMap?
1999 }
2000 if (!root.meta.traceMap.get(thrown)) {
2001 var traceEntry = {
2002 trace: trace,
2003 print: function (logger) {
2004 logger = logger || console.error;
2005 logger("hypertrace /// ");
2006 var maxLen = 0;
2007 for (var i = 0; i < trace.length; i++) {
2008 maxLen = Math.max(maxLen, trace[i].meta.feature.displayName.length);
2009 }
2010 for (var i = 0; i < trace.length; i++) {
2011 var traceElt = trace[i];
2012 logger(
2013 " ->",
2014 traceElt.meta.feature.displayName.padEnd(maxLen + 2),
2015 "-",
2016 traceElt.meta.owner
2017 );
2018 }
2019 },
2020 };
2021 root.meta.traceMap.set(thrown, traceEntry);
2022 }
2023 }
2024
2025 /**
2026 * @param {string} str
2027 * @returns {string}
2028 */
2029 function escapeSelector(str) {
2030 return str.replace(/:/g, function (str) {
2031 return "\\" + str;
2032 });
2033 }
2034
2035 /**
2036 * @param {any} value
2037 * @param {*} elt
2038 */
2039 function nullCheck(value, elt) {
2040 if (value == null) {
2041 throw new Error(elt.sourceFor() + " is null");
2042 }
2043 }
2044
2045 /**
2046 * @param {any} value
2047 * @returns {boolean}
2048 */
2049 function isEmpty(value) {
2050 return value == undefined || value.length === 0;
2051 }
2052
2053 /** @type string | null */
2054 var hyperscriptUrl = "document" in globalScope ? document.currentScript.src : null;
2055
2056 /** @type {RuntimeObject} */
2057 return {
2058 typeCheck: typeCheck,
2059 forEach: forEach,
2060 triggerEvent: triggerEvent,
2061 matchesSelector: matchesSelector,
2062 getScript: getScript,
2063 processNode: processNode,
2064 evaluate: evaluate,
2065 parse: parse,
2066 getScriptSelector: getScriptSelector,
2067 resolveSymbol: resolveSymbol,
2068 setSymbol: setSymbol,
2069 makeContext: makeContext,
2070 findNext: findNext,
2071 unifiedEval: unifiedEval,
2072 convertValue: convertValue,
2073 unifiedExec: unifiedExec,
2074 resolveProperty: resolveProperty,
2075 assignToNamespace: assignToNamespace,
2076 registerHyperTrace: registerHyperTrace,
2077 getHyperTrace: getHyperTrace,
2078 getInternalData: getInternalData,
2079 escapeSelector: escapeSelector,
2080 nullCheck: nullCheck,
2081 isEmpty: isEmpty,
2082 hyperscriptUrl: hyperscriptUrl,
2083 HALT: HALT,
2084 };
2085 })();
2086
2087 //====================================================================
2088 // Grammar
2089 //====================================================================
2090 {
2091 _parser.addLeafExpression("parenthesized", function (parser, _runtime, tokens) {
2092 if (tokens.matchOpToken("(")) {
2093 var follows = tokens.clearFollow();
2094 try {
2095 var expr = parser.requireElement("expression", tokens);
2096 } finally {
2097 tokens.restoreFollow(follows);
2098 }
2099 tokens.requireOpToken(")");
2100 return expr;
2101 }
2102 });
2103
2104 _parser.addLeafExpression("string", function (parser, runtime, tokens) {
2105 var stringToken = tokens.matchTokenType("STRING");
2106 if (!stringToken) return;
2107 var rawValue = stringToken.value;
2108 if (stringToken.template) {
2109 var innerTokens = _lexer.tokenize(rawValue, true);
2110 var args = parser.parseStringTemplate(innerTokens);
2111 } else {
2112 var args = [];
2113 }
2114 return {
2115 type: "string",
2116 token: stringToken,
2117 args: args,
2118 op: function (context) {
2119 var returnStr = "";
2120 for (var i = 1; i < arguments.length; i++) {
2121 var val = arguments[i];
2122 if (val !== undefined) {
2123 returnStr += val;
2124 }
2125 }
2126 return returnStr;
2127 },
2128 evaluate: function (context) {
2129 if (args.length === 0) {
2130 return rawValue;
2131 } else {
2132 return runtime.unifiedEval(this, context);
2133 }
2134 },
2135 };
2136 });
2137
2138 _parser.addGrammarElement("nakedString", function (parser, runtime, tokens) {
2139 if (tokens.hasMore()) {
2140 var tokenArr = tokens.consumeUntilWhitespace();
2141 tokens.matchTokenType("WHITESPACE");
2142 return {
2143 type: "nakedString",
2144 tokens: tokenArr,
2145 evaluate: function (context) {
2146 return tokenArr
2147 .map(function (t) {
2148 return t.value;
2149 })
2150 .join("");
2151 },
2152 };
2153 }
2154 });
2155
2156 _parser.addLeafExpression("number", function (parser, runtime, tokens) {
2157 var number = tokens.matchTokenType("NUMBER");
2158 if (!number) return;
2159 var numberToken = number;
2160 var value = parseFloat(number.value);
2161 return {
2162 type: "number",
2163 value: value,
2164 numberToken: numberToken,
2165 evaluate: function () {
2166 return value;
2167 },
2168 };
2169 });
2170
2171 _parser.addLeafExpression("idRef", function (parser, runtime, tokens) {
2172 var elementId = tokens.matchTokenType("ID_REF");
2173 if (!elementId) return;
2174 // TODO - unify these two expression types
2175 if (elementId.template) {
2176 var templateValue = elementId.value.substr(2, elementId.value.length - 2);
2177 var innerTokens = _lexer.tokenize(templateValue);
2178 var innerExpression = parser.requireElement("expression", innerTokens);
2179 return {
2180 type: "idRefTemplate",
2181 args: [innerExpression],
2182 op: function (context, arg) {
2183 return context.me.getRootNode().getElementById(arg) || document.getElementById(arg);
2184 },
2185 evaluate: function (context) {
2186 return runtime.unifiedEval(this, context);
2187 },
2188 };
2189 } else {
2190 return {
2191 type: "idRef",
2192 css: elementId.value,
2193 value: elementId.value.substr(1),
2194 evaluate: function (context) {
2195 return (
2196 context.me.getRootNode().getElementById(this.value) || document.getElementById(this.value)
2197 );
2198 },
2199 };
2200 }
2201 });
2202
2203 _parser.addLeafExpression("classRef", function (parser, runtime, tokens) {
2204 var classRef = tokens.matchTokenType("CLASS_REF");
2205
2206 if (!classRef) return;
2207
2208 // TODO - unify these two expression types
2209 if (classRef.template) {
2210 var templateValue = classRef.value.substr(2, classRef.value.length - 2);
2211 var innerTokens = _lexer.tokenize(templateValue);
2212 var innerExpression = parser.requireElement("expression", innerTokens);
2213 return {
2214 type: "classRefTemplate",
2215 args: [innerExpression],
2216 op: function (context, arg) {
2217 return document.querySelectorAll(runtime.escapeSelector("." + arg));
2218 },
2219 evaluate: function (context) {
2220 return runtime.unifiedEval(this, context);
2221 },
2222 };
2223 } else {
2224 return {
2225 type: "classRef",
2226 css: classRef.value,
2227 className: function () {
2228 return this.css.substr(1);
2229 },
2230 evaluate: function (context) {
2231 return context.me.getRootNode().querySelectorAll(runtime.escapeSelector(this.css));
2232 },
2233 };
2234 }
2235 });
2236
2237 _parser.addLeafExpression("queryRef", function (parser, runtime, tokens) {
2238 var queryStart = tokens.matchOpToken("<");
2239 if (!queryStart) return;
2240 var queryTokens = tokens.consumeUntil("/");
2241 tokens.requireOpToken("/");
2242 tokens.requireOpToken(">");
2243 var queryValue = queryTokens
2244 .map(function (t) {
2245 if (t.type === "STRING") {
2246 return '"' + t.value + '"';
2247 } else {
2248 return t.value;
2249 }
2250 })
2251 .join("");
2252
2253 if (queryValue.indexOf("$") >= 0) {
2254 var template = true;
2255 var innerTokens = _lexer.tokenize(queryValue, true);
2256 var args = parser.parseStringTemplate(innerTokens);
2257 }
2258
2259 return {
2260 type: "queryRef",
2261 css: queryValue,
2262 args: args,
2263 op: function (context, args) {
2264 var query = queryValue;
2265 var elements = [];
2266 if (template) {
2267 query = "";
2268 for (var i = 1; i < arguments.length; i++) {
2269 var val = arguments[i];
2270 if (val) {
2271 if (val instanceof Element) {
2272 val.dataset.hsQueryId = elements.length;
2273 query += "[data-hs-query-id='" + elements.length + "']";
2274 elements.push(val);
2275 } else query += val;
2276 }
2277 }
2278 }
2279 var result = context.me.getRootNode().querySelectorAll(query);
2280 runtime.forEach(elements, function (el) { el.removeAttribute("data-hs-query-id") });
2281 return result;
2282 },
2283 evaluate: function (context) {
2284 return runtime.unifiedEval(this, context);
2285 },
2286 };
2287 });
2288
2289 _parser.addLeafExpression("attributeRef", function (parser, runtime, tokens) {
2290 var attributeRef = tokens.matchTokenType("ATTRIBUTE_REF");
2291 if (!attributeRef) return;
2292 var outerVal = attributeRef.value;
2293 if (outerVal.indexOf("[") === 0) {
2294 var innerValue = outerVal.substring(2, outerVal.length - 1);
2295 } else {
2296 var innerValue = outerVal.substring(1);
2297 }
2298 var css = "[" + innerValue + "]";
2299 var split = innerValue.split("=");
2300 var name = split[0];
2301 var value = split[1];
2302 if (value) {
2303 // strip quotes
2304 if (value.indexOf('"') === 0) {
2305 value = value.substring(1, value.length - 1);
2306 }
2307 }
2308 return {
2309 type: "attributeRef",
2310 name: name,
2311 css: css,
2312 value: value,
2313 op: function (context) {
2314 var target = context.beingTold || context.me;
2315 if (target) {
2316 return target.getAttribute(name);
2317 }
2318 },
2319 evaluate: function (context) {
2320 return runtime.unifiedEval(this, context);
2321 },
2322 };
2323 });
2324
2325 _parser.addGrammarElement("objectKey", function (parser, runtime, tokens) {
2326 var token;
2327 if ((token = tokens.matchTokenType("STRING"))) {
2328 return {
2329 type: "objectKey",
2330 key: token.value,
2331 evaluate: function () {
2332 return this.key;
2333 },
2334 };
2335 } else if (tokens.matchOpToken("[")) {
2336 var expr = parser.parseElement("expression", tokens);
2337 tokens.requireOpToken("]");
2338 return {
2339 type: "objectKey",
2340 expr: expr,
2341 args: [expr],
2342 op: function (ctx, expr) {
2343 return expr;
2344 },
2345 evaluate: function (context) {
2346 return runtime.unifiedEval(this, context);
2347 },
2348 };
2349 } else {
2350 var key = "";
2351 do {
2352 token = tokens.matchTokenType("IDENTIFIER") || tokens.matchOpToken("-");
2353 if (token) key += token.value;
2354 } while (token);
2355 return {
2356 type: "objectKey",
2357 key: key,
2358 evaluate: function () {
2359 return this.key;
2360 },
2361 };
2362 }
2363 });
2364
2365 _parser.addLeafExpression("objectLiteral", function (parser, runtime, tokens) {
2366 if (!tokens.matchOpToken("{")) return;
2367 var keyExpressions = [];
2368 var valueExpressions = [];
2369 if (!tokens.matchOpToken("}")) {
2370 do {
2371 var name = parser.requireElement("objectKey", tokens);
2372 tokens.requireOpToken(":");
2373 var value = parser.requireElement("expression", tokens);
2374 valueExpressions.push(value);
2375 keyExpressions.push(name);
2376 } while (tokens.matchOpToken(","));
2377 tokens.requireOpToken("}");
2378 }
2379 return {
2380 type: "objectLiteral",
2381 args: [keyExpressions, valueExpressions],
2382 op: function (context, keys, values) {
2383 var returnVal = {};
2384 for (var i = 0; i < keys.length; i++) {
2385 returnVal[keys[i]] = values[i];
2386 }
2387 return returnVal;
2388 },
2389 evaluate: function (context) {
2390 return runtime.unifiedEval(this, context);
2391 },
2392 };
2393 });
2394
2395 _parser.addGrammarElement("namedArgumentList", function (parser, runtime, tokens) {
2396 if (!tokens.matchOpToken("(")) return;
2397 var fields = [];
2398 var valueExpressions = [];
2399 if (!tokens.matchOpToken(")")) {
2400 do {
2401 var name = tokens.requireTokenType("IDENTIFIER");
2402 tokens.requireOpToken(":");
2403 var value = parser.requireElement("expression", tokens);
2404 valueExpressions.push(value);
2405 fields.push({ name: name, value: value });
2406 } while (tokens.matchOpToken(","));
2407 tokens.requireOpToken(")");
2408 }
2409 return {
2410 type: "namedArgumentList",
2411 fields: fields,
2412 args: [valueExpressions],
2413 op: function (context, values) {
2414 var returnVal = { _namedArgList_: true };
2415 for (var i = 0; i < values.length; i++) {
2416 var field = fields[i];
2417 returnVal[field.name.value] = values[i];
2418 }
2419 return returnVal;
2420 },
2421 evaluate: function (context) {
2422 return runtime.unifiedEval(this, context);
2423 },
2424 };
2425 });
2426
2427 _parser.addGrammarElement("symbol", function (parser, runtime, tokens) {
2428 var type = "default";
2429 if (tokens.matchToken("global")) {
2430 type = "global";
2431 } else if (tokens.matchToken("element")) {
2432 type = "element";
2433 // optional possessive
2434 if (tokens.matchOpToken("'")) {
2435 tokens.requireToken("s");
2436 }
2437 } else if (tokens.matchToken("local")) {
2438 type = "local";
2439 }
2440 var identifier = tokens.matchTokenType("IDENTIFIER");
2441 if (identifier) {
2442 return {
2443 type: "symbol",
2444 symbolType: type,
2445 token: identifier,
2446 name: identifier.value,
2447 evaluate: function (context) {
2448 return runtime.resolveSymbol(identifier.value, context, type);
2449 },
2450 };
2451 }
2452 });
2453
2454 _parser.addGrammarElement("implicitMeTarget", function (parser, runtime, tokens) {
2455 return {
2456 type: "implicitMeTarget",
2457 evaluate: function (context) {
2458 return context.beingTold || context.me;
2459 },
2460 };
2461 });
2462
2463 _parser.addLeafExpression("boolean", function (parser, runtime, tokens) {
2464 var booleanLiteral = tokens.matchToken("true") || tokens.matchToken("false");
2465 if (!booleanLiteral) return;
2466 return {
2467 type: "boolean",
2468 evaluate: function (context) {
2469 return booleanLiteral.value === "true";
2470 },
2471 };
2472 });
2473
2474 _parser.addLeafExpression("null", function (parser, runtime, tokens) {
2475 if (tokens.matchToken("null")) {
2476 return {
2477 type: "null",
2478 evaluate: function (context) {
2479 return null;
2480 },
2481 };
2482 }
2483 });
2484
2485 _parser.addLeafExpression("arrayLiteral", function (parser, runtime, tokens) {
2486 if (!tokens.matchOpToken("[")) return;
2487 var values = [];
2488 if (!tokens.matchOpToken("]")) {
2489 do {
2490 var expr = parser.requireElement("expression", tokens);
2491 values.push(expr);
2492 } while (tokens.matchOpToken(","));
2493 tokens.requireOpToken("]");
2494 }
2495 return {
2496 type: "arrayLiteral",
2497 values: values,
2498 args: [values],
2499 op: function (context, values) {
2500 return values;
2501 },
2502 evaluate: function (context) {
2503 return runtime.unifiedEval(this, context);
2504 },
2505 };
2506 });
2507
2508 _parser.addLeafExpression("blockLiteral", function (parser, runtime, tokens) {
2509 if (!tokens.matchOpToken("\\")) return;
2510 var args = [];
2511 var arg1 = tokens.matchTokenType("IDENTIFIER");
2512 if (arg1) {
2513 args.push(arg1);
2514 while (tokens.matchOpToken(",")) {
2515 args.push(tokens.requireTokenType("IDENTIFIER"));
2516 }
2517 }
2518 // TODO compound op token
2519 tokens.requireOpToken("-");
2520 tokens.requireOpToken(">");
2521 var expr = parser.requireElement("expression", tokens);
2522 return {
2523 type: "blockLiteral",
2524 args: args,
2525 expr: expr,
2526 evaluate: function (ctx) {
2527 var returnFunc = function () {
2528 //TODO - push scope
2529 for (var i = 0; i < args.length; i++) {
2530 ctx[args[i].value] = arguments[i];
2531 }
2532 return expr.evaluate(ctx); //OK
2533 };
2534 return returnFunc;
2535 },
2536 };
2537 });
2538
2539 _parser.addGrammarElement("timeExpression", function (parser, runtime, tokens) {
2540 var time = parser.requireElement("expression", tokens);
2541 var factor = 1;
2542 if (tokens.matchToken("s") || tokens.matchToken("seconds")) {
2543 factor = 1000;
2544 } else if (tokens.matchToken("ms") || tokens.matchToken("milliseconds")) {
2545 // do nothing
2546 }
2547 return {
2548 type: "timeExpression",
2549 time: time,
2550 factor: factor,
2551 args: [time],
2552 op: function (_context, val) {
2553 return val * this.factor;
2554 },
2555 evaluate: function (context) {
2556 return runtime.unifiedEval(this, context);
2557 },
2558 };
2559 });
2560
2561 _parser.addIndirectExpression("propertyAccess", function (parser, runtime, tokens, root) {
2562 if (!tokens.matchOpToken(".")) return;
2563 var prop = tokens.requireTokenType("IDENTIFIER");
2564 var propertyAccess = {
2565 type: "propertyAccess",
2566 root: root,
2567 prop: prop,
2568 args: [root],
2569 op: function (_context, rootVal) {
2570 var value = runtime.resolveProperty(rootVal, prop.value);
2571 return value;
2572 },
2573 evaluate: function (context) {
2574 return runtime.unifiedEval(this, context);
2575 },
2576 };
2577 return parser.parseElement("indirectExpression", tokens, propertyAccess);
2578 });
2579
2580 _parser.addIndirectExpression("of", function (parser, runtime, tokens, root) {
2581 if (!tokens.matchToken("of")) return;
2582 var newRoot = parser.requireElement("expression", tokens);
2583 // find the urroot
2584 var childOfUrRoot = null;
2585 var urRoot = root;
2586 while (urRoot.root) {
2587 childOfUrRoot = urRoot;
2588 urRoot = urRoot.root;
2589 }
2590 if (urRoot.type !== "symbol" && urRoot.type !== "attributeRef") {
2591 parser.raiseParseError(tokens, "Cannot take a property of a non-symbol: " + urRoot.type);
2592 }
2593 var attribute = urRoot.type === "attributeRef";
2594 var prop = urRoot.name;
2595 var propertyAccess = {
2596 type: "ofExpression",
2597 prop: urRoot.token,
2598 root: newRoot,
2599 attribute: attribute,
2600 expression: root,
2601 args: [newRoot],
2602 op: function (context, rootVal) {
2603 return runtime.resolveProperty(rootVal, prop, attribute);
2604 },
2605 evaluate: function (context) {
2606 return runtime.unifiedEval(this, context);
2607 },
2608 };
2609
2610 if (urRoot.type === "attributeRef") {
2611 propertyAccess.attribute = urRoot;
2612 }
2613 if (childOfUrRoot) {
2614 childOfUrRoot.root = propertyAccess;
2615 childOfUrRoot.args = [propertyAccess];
2616 } else {
2617 root = propertyAccess;
2618 }
2619
2620 return parser.parseElement("indirectExpression", tokens, root);
2621 });
2622
2623 _parser.addIndirectExpression("possessive", function (parser, runtime, tokens, root) {
2624 if (parser.possessivesDisabled) {
2625 return;
2626 }
2627 var apostrophe = tokens.matchOpToken("'");
2628 if (
2629 apostrophe ||
2630 (root.type === "symbol" &&
2631 (root.name === "my" || root.name === "its" || root.name === "your") &&
2632 tokens.currentToken().type === "IDENTIFIER")
2633 ) {
2634 if (apostrophe) {
2635 tokens.requireToken("s");
2636 }
2637 var attribute = parser.parseElement("attributeRef", tokens);
2638 if (attribute == null) {
2639 var prop = tokens.requireTokenType("IDENTIFIER");
2640 }
2641 var propertyAccess = {
2642 type: "possessive",
2643 root: root,
2644 attribute: attribute,
2645 prop: prop,
2646 args: [root],
2647 op: function (context, rootVal) {
2648 if (attribute) {
2649 var value = runtime.resolveProperty(rootVal, attribute.name, true);
2650 } else {
2651 var value = runtime.resolveProperty(rootVal, prop.value, false);
2652 }
2653 return value;
2654 },
2655 evaluate: function (context) {
2656 return runtime.unifiedEval(this, context);
2657 },
2658 };
2659 return parser.parseElement("indirectExpression", tokens, propertyAccess);
2660 }
2661 });
2662
2663 _parser.addIndirectExpression("inExpression", function (parser, runtime, tokens, root) {
2664 if (!tokens.matchToken("in")) return;
2665 if ((root.type !== "idRef" && root.type === "queryRef") || root.type === "classRef") {
2666 var query = true;
2667 }
2668 var target = parser.requireElement("expression", tokens);
2669 var propertyAccess = {
2670 type: "inExpression",
2671 root: root,
2672 args: [query ? null : root, target],
2673 op: function (context, rootVal, target) {
2674 var returnArr = [];
2675 if (query) {
2676 runtime.forEach(target, function (targetElt) {
2677 var results = targetElt.querySelectorAll(root.css);
2678 for (var i = 0; i < results.length; i++) {
2679 returnArr.push(results[i]);
2680 }
2681 });
2682 } else {
2683 runtime.forEach(rootVal, function (rootElt) {
2684 runtime.forEach(target, function (targetElt) {
2685 if (rootElt === targetElt) {
2686 returnArr.push(rootElt);
2687 }
2688 });
2689 });
2690 }
2691 if (returnArr.length > 0) {
2692 return returnArr;
2693 } else {
2694 return null;
2695 }
2696 },
2697 evaluate: function (context) {
2698 return runtime.unifiedEval(this, context);
2699 },
2700 };
2701 return parser.parseElement("indirectExpression", tokens, propertyAccess);
2702 });
2703
2704 _parser.addIndirectExpression("asExpression", function (parser, runtime, tokens, root) {
2705 if (!tokens.matchToken("as")) return;
2706 var conversion = parser.requireElement("dotOrColonPath", tokens).evaluate(); // OK No promise
2707 var propertyAccess = {
2708 type: "asExpression",
2709 root: root,
2710 args: [root],
2711 op: function (context, rootVal) {
2712 return runtime.convertValue(rootVal, conversion);
2713 },
2714 evaluate: function (context) {
2715 return runtime.unifiedEval(this, context);
2716 },
2717 };
2718 return parser.parseElement("indirectExpression", tokens, propertyAccess);
2719 });
2720
2721 _parser.addIndirectExpression("functionCall", function (parser, runtime, tokens, root) {
2722 if (!tokens.matchOpToken("(")) return;
2723 var args = [];
2724 if (!tokens.matchOpToken(")")) {
2725 do {
2726 args.push(parser.requireElement("expression", tokens));
2727 } while (tokens.matchOpToken(","));
2728 tokens.requireOpToken(")");
2729 }
2730
2731 if (root.root) {
2732 var functionCall = {
2733 type: "functionCall",
2734 root: root,
2735 argExressions: args,
2736 args: [root.root, args],
2737 op: function (context, rootRoot, args) {
2738 runtime.nullCheck(rootRoot, root.root);
2739 var func = rootRoot[root.prop.value];
2740 runtime.nullCheck(func, root);
2741 if (func.hyperfunc) {
2742 args.push(context);
2743 }
2744 return func.apply(rootRoot, args);
2745 },
2746 evaluate: function (context) {
2747 return runtime.unifiedEval(this, context);
2748 },
2749 };
2750 } else {
2751 var functionCall = {
2752 type: "functionCall",
2753 root: root,
2754 argExressions: args,
2755 args: [root, args],
2756 op: function (context, func, argVals) {
2757 runtime.nullCheck(func, root);
2758 if (func.hyperfunc) {
2759 argVals.push(context);
2760 }
2761 var apply = func.apply(null, argVals);
2762 return apply;
2763 },
2764 evaluate: function (context) {
2765 return runtime.unifiedEval(this, context);
2766 },
2767 };
2768 }
2769 return parser.parseElement("indirectExpression", tokens, functionCall);
2770 });
2771
2772 _parser.addIndirectExpression("attributeRefAccess", function (parser, runtime, tokens, root) {
2773 var attribute = parser.parseElement("attributeRef", tokens);
2774 if (!attribute) return;
2775 var attributeAccess = {
2776 type: "attributeRefAccess",
2777 root: root,
2778 attribute: attribute,
2779 args: [root],
2780 op: function (_ctx, rootVal) {
2781 var value = runtime.resolveProperty(rootVal, attribute.name, true);
2782 return value;
2783 },
2784 evaluate: function (context) {
2785 return _runtime.unifiedEval(this, context);
2786 },
2787 };
2788 return attributeAccess;
2789 });
2790
2791 _parser.addIndirectExpression("arrayIndex", function (parser, runtime, tokens, root) {
2792 if (!tokens.matchOpToken("[")) return;
2793 var andBefore = false;
2794 var andAfter = false;
2795 var firstIndex = null;
2796 var secondIndex = null;
2797
2798 if (tokens.matchOpToken("..")) {
2799 andBefore = true;
2800 firstIndex = parser.requireElement("expression", tokens);
2801 } else {
2802 firstIndex = parser.requireElement("expression", tokens);
2803
2804 if (tokens.matchOpToken("..")) {
2805 andAfter = true;
2806 var current = tokens.currentToken();
2807 if (current.type !== "R_BRACKET") {
2808 secondIndex = parser.parseElement("expression", tokens);
2809 }
2810 }
2811 }
2812 tokens.requireOpToken("]");
2813
2814 var arrayIndex = {
2815 type: "arrayIndex",
2816 root: root,
2817 firstIndex: firstIndex,
2818 secondIndex: secondIndex,
2819 args: [root, firstIndex, secondIndex],
2820 op: function (_ctx, root, firstIndex, secondIndex) {
2821 if (andBefore) {
2822 return root.slice(0, firstIndex + 1); // returns all items from beginning to firstIndex (inclusive)
2823 } else if (andAfter) {
2824 if (secondIndex != null) {
2825 return root.slice(firstIndex, secondIndex + 1); // returns all items from firstIndex to secondIndex (inclusive)
2826 } else {
2827 return root.slice(firstIndex); // returns from firstIndex to end of array
2828 }
2829 } else {
2830 return root[firstIndex];
2831 }
2832 },
2833 evaluate: function (context) {
2834 return _runtime.unifiedEval(this, context);
2835 },
2836 };
2837
2838 return _parser.parseElement("indirectExpression", tokens, arrayIndex);
2839 });
2840
2841 _parser.addGrammarElement("postfixExpression", function (parser, runtime, tokens) {
2842 var root = parser.parseElement("primaryExpression", tokens);
2843 if (tokens.matchOpToken(":")) {
2844 var typeName = tokens.requireTokenType("IDENTIFIER");
2845 var nullOk = !tokens.matchOpToken("!");
2846 return {
2847 type: "typeCheck",
2848 typeName: typeName,
2849 root: root,
2850 nullOk: nullOk,
2851 args: [root],
2852 op: function (context, val) {
2853 var passed = runtime.typeCheck(val, this.typeName.value, this.nullOk);
2854 if (passed) {
2855 return val;
2856 } else {
2857 throw new Error("Typecheck failed! Expected: " + this.typeName.value);
2858 }
2859 },
2860 evaluate: function (context) {
2861 return runtime.unifiedEval(this, context);
2862 },
2863 };
2864 } else {
2865 return root;
2866 }
2867 });
2868
2869 _parser.addGrammarElement("logicalNot", function (parser, runtime, tokens) {
2870 if (!tokens.matchToken("not")) return;
2871 var root = parser.requireElement("unaryExpression", tokens);
2872 return {
2873 type: "logicalNot",
2874 root: root,
2875 args: [root],
2876 op: function (context, val) {
2877 return !val;
2878 },
2879 evaluate: function (context) {
2880 return runtime.unifiedEval(this, context);
2881 },
2882 };
2883 });
2884
2885 _parser.addGrammarElement("noExpression", function (parser, runtime, tokens) {
2886 if (!tokens.matchToken("no")) return;
2887 var root = parser.requireElement("unaryExpression", tokens);
2888 return {
2889 type: "noExpression",
2890 root: root,
2891 args: [root],
2892 op: function (_context, val) {
2893 return runtime.isEmpty(val);
2894 },
2895 evaluate: function (context) {
2896 return runtime.unifiedEval(this, context);
2897 },
2898 };
2899 });
2900
2901 _parser.addGrammarElement("negativeNumber", function (parser, runtime, tokens) {
2902 if (!tokens.matchOpToken("-")) return;
2903 var root = parser.requireElement("unaryExpression", tokens);
2904 return {
2905 type: "negativeNumber",
2906 root: root,
2907 args: [root],
2908 op: function (context, value) {
2909 return -1 * value;
2910 },
2911 evaluate: function (context) {
2912 return runtime.unifiedEval(this, context);
2913 },
2914 };
2915 });
2916
2917 _parser.addGrammarElement("unaryExpression", function (parser, runtime, tokens) {
2918 return parser.parseAnyOf(
2919 ["logicalNot", "positionalExpression", "noExpression", "negativeNumber", "postfixExpression"],
2920 tokens
2921 );
2922 });
2923
2924 _parser.addGrammarElement("positionalExpression", function (parser, runtime, tokens) {
2925 var op = tokens.matchAnyToken("first", "last", "random");
2926 if (!op) return;
2927 tokens.matchAnyToken("in", "from", "of");
2928 var rhs = parser.requireElement("unaryExpression", tokens);
2929 return {
2930 type: "positionalExpression",
2931 rhs: rhs,
2932 operator: op.value,
2933 args: [rhs],
2934 op: function (context, rhsVal) {
2935 if (rhsVal && !Array.isArray(rhsVal)) {
2936 if (rhsVal.children) {
2937 rhsVal = rhsVal.children;
2938 } else {
2939 rhsVal = Array.from(rhsVal);
2940 }
2941 }
2942 if (rhsVal) {
2943 if (this.operator === "first") {
2944 return rhsVal[0];
2945 } else if (this.operator === "last") {
2946 return rhsVal[rhsVal.length - 1];
2947 } else if (this.operator === "random") {
2948 return rhsVal[Math.floor(Math.random() * rhsVal.length)];
2949 }
2950 }
2951 },
2952 evaluate: function (context) {
2953 return runtime.unifiedEval(this, context);
2954 },
2955 };
2956 });
2957
2958 _parser.addGrammarElement("mathOperator", function (parser, runtime, tokens) {
2959 var expr = parser.parseElement("unaryExpression", tokens);
2960 var mathOp,
2961 initialMathOp = null;
2962 mathOp = tokens.matchAnyOpToken("+", "-", "*", "/", "%");
2963 while (mathOp) {
2964 initialMathOp = initialMathOp || mathOp;
2965 var operator = mathOp.value;
2966 if (initialMathOp.value !== operator) {
2967 parser.raiseParseError(tokens, "You must parenthesize math operations with different operators");
2968 }
2969 var rhs = parser.parseElement("unaryExpression", tokens);
2970 expr = {
2971 type: "mathOperator",
2972 lhs: expr,
2973 rhs: rhs,
2974 operator: operator,
2975 args: [expr, rhs],
2976 op: function (context, lhsVal, rhsVal) {
2977 if (this.operator === "+") {
2978 return lhsVal + rhsVal;
2979 } else if (this.operator === "-") {
2980 return lhsVal - rhsVal;
2981 } else if (this.operator === "*") {
2982 return lhsVal * rhsVal;
2983 } else if (this.operator === "/") {
2984 return lhsVal / rhsVal;
2985 } else if (this.operator === "%") {
2986 return lhsVal % rhsVal;
2987 }
2988 },
2989 evaluate: function (context) {
2990 return runtime.unifiedEval(this, context);
2991 },
2992 };
2993 mathOp = tokens.matchAnyOpToken("+", "-", "*", "/", "%");
2994 }
2995 return expr;
2996 });
2997
2998 _parser.addGrammarElement("mathExpression", function (parser, runtime, tokens) {
2999 return parser.parseAnyOf(["mathOperator", "unaryExpression"], tokens);
3000 });
3001
3002 _parser.addGrammarElement("comparisonOperator", function (parser, runtime, tokens) {
3003 var expr = parser.parseElement("mathExpression", tokens);
3004 var comparisonToken = tokens.matchAnyOpToken("<", ">", "<=", ">=", "==", "===", "!=", "!==");
3005 var comparisonStr = comparisonToken ? comparisonToken.value : null;
3006 var hasRightValue = true; // By default, most comparisons require two values, but there are some exceptions.
3007 var typeCheck = false;
3008
3009 if (comparisonStr == null) {
3010 if (tokens.matchToken("is") || tokens.matchToken("am")) {
3011 if (tokens.matchToken("not")) {
3012 if (tokens.matchToken("in")) {
3013 comparisonStr = "not in";
3014 } else if (tokens.matchToken("a")) {
3015 comparisonStr = "not a";
3016 typeCheck = true;
3017 } else if (tokens.matchToken("empty")) {
3018 comparisonStr = "not empty";
3019 hasRightValue = false;
3020 } else {
3021 comparisonStr = "!=";
3022 }
3023 } else if (tokens.matchToken("in")) {
3024 comparisonStr = "in";
3025 } else if (tokens.matchToken("a")) {
3026 comparisonStr = "a";
3027 typeCheck = true;
3028 } else if (tokens.matchToken("empty")) {
3029 comparisonStr = "empty";
3030 hasRightValue = false;
3031 } else {
3032 comparisonStr = "==";
3033 }
3034 } else if (tokens.matchToken("matches") || tokens.matchToken("match")) {
3035 comparisonStr = "match";
3036 } else if (tokens.matchToken("contains") || tokens.matchToken("contain")) {
3037 comparisonStr = "contain";
3038 } else if (tokens.matchToken("do") || tokens.matchToken("does")) {
3039 tokens.requireToken("not");
3040 if (tokens.matchToken("matches") || tokens.matchToken("match")) {
3041 comparisonStr = "not match";
3042 } else if (tokens.matchToken("contains") || tokens.matchToken("contain")) {
3043 comparisonStr = "not contain";
3044 } else {
3045 parser.raiseParseError(tokens, "Expected matches or contains");
3046 }
3047 }
3048 }
3049
3050 if (comparisonStr) {
3051 // Do not allow chained comparisons, which is dumb
3052 if (typeCheck) {
3053 var typeName = tokens.requireTokenType("IDENTIFIER");
3054 var nullOk = !tokens.matchOpToken("!");
3055 } else if (hasRightValue) {
3056 var rhs = parser.requireElement("mathExpression", tokens);
3057 if (comparisonStr === "match" || comparisonStr === "not match") {
3058 rhs = rhs.css ? rhs.css : rhs;
3059 }
3060 }
3061 expr = {
3062 type: "comparisonOperator",
3063 operator: comparisonStr,
3064 typeName: typeName,
3065 nullOk: nullOk,
3066 lhs: expr,
3067 rhs: rhs,
3068 args: [expr, rhs],
3069 op: function (context, lhsVal, rhsVal) {
3070 if (this.operator === "==") {
3071 return lhsVal == rhsVal;
3072 } else if (this.operator === "!=") {
3073 return lhsVal != rhsVal;
3074 }
3075 if (this.operator === "in") {
3076 return rhsVal != null && Array.from(rhsVal).indexOf(lhsVal) >= 0;
3077 }
3078 if (this.operator === "not in") {
3079 return rhsVal == null || Array.from(rhsVal).indexOf(lhsVal) < 0;
3080 }
3081 if (this.operator === "match") {
3082 return lhsVal != null && lhsVal.matches(rhsVal);
3083 }
3084 if (this.operator === "not match") {
3085 return lhsVal == null || !lhsVal.matches(rhsVal);
3086 }
3087 if (this.operator === "contain") {
3088 return lhsVal != null && lhsVal.contains(rhsVal);
3089 }
3090 if (this.operator === "not contain") {
3091 return lhsVal == null || !lhsVal.contains(rhsVal);
3092 }
3093 if (this.operator === "===") {
3094 return lhsVal === rhsVal;
3095 } else if (this.operator === "!==") {
3096 return lhsVal !== rhsVal;
3097 } else if (this.operator === "<") {
3098 return lhsVal < rhsVal;
3099 } else if (this.operator === ">") {
3100 return lhsVal > rhsVal;
3101 } else if (this.operator === "<=") {
3102 return lhsVal <= rhsVal;
3103 } else if (this.operator === ">=") {
3104 return lhsVal >= rhsVal;
3105 } else if (this.operator === "empty") {
3106 return runtime.isEmpty(lhsVal);
3107 } else if (this.operator === "not empty") {
3108 return !runtime.isEmpty(lhsVal);
3109 } else if (this.operator === "a") {
3110 return runtime.typeCheck(lhsVal, this.typeName.value, this.nullOk);
3111 } else if (this.operator === "not a") {
3112 return !runtime.typeCheck(lhsVal, this.typeName.value, this.nullOk);
3113 } else {
3114 throw "Unknown comparison : " + this.operator;
3115 }
3116 },
3117 evaluate: function (context) {
3118 return runtime.unifiedEval(this, context);
3119 },
3120 };
3121 }
3122 return expr;
3123 });
3124
3125 _parser.addGrammarElement("comparisonExpression", function (parser, runtime, tokens) {
3126 return parser.parseAnyOf(["comparisonOperator", "mathExpression"], tokens);
3127 });
3128
3129 _parser.addGrammarElement("logicalOperator", function (parser, runtime, tokens) {
3130 var expr = parser.parseElement("comparisonExpression", tokens);
3131 var logicalOp,
3132 initialLogicalOp = null;
3133 logicalOp = tokens.matchToken("and") || tokens.matchToken("or");
3134 while (logicalOp) {
3135 initialLogicalOp = initialLogicalOp || logicalOp;
3136 if (initialLogicalOp.value !== logicalOp.value) {
3137 parser.raiseParseError(tokens, "You must parenthesize logical operations with different operators");
3138 }
3139 var rhs = parser.requireElement("comparisonExpression", tokens);
3140 expr = {
3141 type: "logicalOperator",
3142 operator: logicalOp.value,
3143 lhs: expr,
3144 rhs: rhs,
3145 args: [expr, rhs],
3146 op: function (context, lhsVal, rhsVal) {
3147 if (this.operator === "and") {
3148 return lhsVal && rhsVal;
3149 } else {
3150 return lhsVal || rhsVal;
3151 }
3152 },
3153 evaluate: function (context) {
3154 return runtime.unifiedEval(this, context);
3155 },
3156 };
3157 logicalOp = tokens.matchToken("and") || tokens.matchToken("or");
3158 }
3159 return expr;
3160 });
3161
3162 _parser.addGrammarElement("logicalExpression", function (parser, runtime, tokens) {
3163 return parser.parseAnyOf(["logicalOperator", "mathExpression"], tokens);
3164 });
3165
3166 _parser.addGrammarElement("asyncExpression", function (parser, runtime, tokens) {
3167 if (tokens.matchToken("async")) {
3168 var value = parser.requireElement("logicalExpression", tokens);
3169 var expr = {
3170 type: "asyncExpression",
3171 value: value,
3172 evaluate: function (context) {
3173 return {
3174 asyncWrapper: true,
3175 value: this.value.evaluate(context), //OK
3176 };
3177 },
3178 };
3179 return expr;
3180 } else {
3181 return parser.parseElement("logicalExpression", tokens);
3182 }
3183 });
3184
3185 _parser.addGrammarElement("expression", function (parser, runtime, tokens) {
3186 tokens.matchToken("the"); // optional the
3187 return parser.parseElement("asyncExpression", tokens);
3188 });
3189
3190 _parser.addGrammarElement("assignableExpression", function (parser, runtime, tokens) {
3191 tokens.matchToken("the"); // optional the
3192
3193 // TODO obviously we need to generalize this as a left hand side / targetable concept
3194 var expr = parser.parseElement("primaryExpression", tokens);
3195 if (
3196 expr.type === "symbol" ||
3197 expr.type === "ofExpression" ||
3198 expr.type === "propertyAccess" ||
3199 expr.type === "attributeRefAccess" ||
3200 expr.type === "attributeRef" ||
3201 expr.type === "possessive"
3202 ) {
3203 return expr;
3204 } else {
3205 _parser.raiseParseError(
3206 tokens,
3207 "A target expression must be writable. The expression type '" + expr.type + "' is not."
3208 );
3209 }
3210 return expr;
3211 });
3212
3213 _parser.addGrammarElement("hyperscript", function (parser, runtime, tokens) {
3214 var features = [];
3215
3216 if (tokens.hasMore()) {
3217 while (parser.featureStart(tokens.currentToken()) || tokens.currentToken().value === "(") {
3218 var feature = parser.requireElement("feature", tokens);
3219 features.push(feature);
3220 tokens.matchToken("end"); // optional end
3221 }
3222 }
3223 return {
3224 type: "hyperscript",
3225 features: features,
3226 apply: function (target, source, args) {
3227 // no op
3228 _runtime.forEach(features, function (feature) {
3229 feature.install(target, source, args);
3230 });
3231 },
3232 };
3233 });
3234
3235 var parseEventArgs = function (tokens) {
3236 var args = [];
3237 // handle argument list (look ahead 3)
3238 if (
3239 tokens.token(0).value === "(" &&
3240 (tokens.token(1).value === ")" || tokens.token(2).value === "," || tokens.token(2).value === ")")
3241 ) {
3242 tokens.matchOpToken("(");
3243 do {
3244 args.push(tokens.requireTokenType("IDENTIFIER"));
3245 } while (tokens.matchOpToken(","));
3246 tokens.requireOpToken(")");
3247 }
3248 return args;
3249 };
3250
3251 _parser.addFeature("on", function (parser, runtime, tokens) {
3252 if (!tokens.matchToken("on")) return;
3253 var every = false;
3254 if (tokens.matchToken("every")) {
3255 every = true;
3256 }
3257 var events = [];
3258 var displayName = null;
3259 do {
3260 var on = parser.requireElement("eventName", tokens, "Expected event name");
3261
3262 var eventName = on.evaluate(); // OK No Promise
3263
3264 if (displayName) {
3265 displayName = displayName + " or " + eventName;
3266 } else {
3267 displayName = "on " + eventName;
3268 }
3269 var args = parseEventArgs(tokens);
3270
3271 var filter = null;
3272 if (tokens.matchOpToken("[")) {
3273 filter = parser.requireElement("expression", tokens);
3274 tokens.requireOpToken("]");
3275 }
3276
3277 if (tokens.currentToken().type === "NUMBER") {
3278 var startCountToken = tokens.consumeToken();
3279 var startCount = parseInt(startCountToken.value);
3280 if (tokens.matchToken("to")) {
3281 var endCountToken = tokens.consumeToken();
3282 var endCount = parseInt(endCountToken.value);
3283 } else if (tokens.matchToken("and")) {
3284 var unbounded = true;
3285 tokens.requireToken("on");
3286 }
3287 }
3288
3289 if (eventName === "intersection") {
3290 var intersectionSpec = {};
3291 if (tokens.matchToken("with")) {
3292 intersectionSpec["with"] = parser.parseElement("expression", tokens).evaluate();
3293 }
3294 if (tokens.matchToken("having")) {
3295 do {
3296 if (tokens.matchToken("margin")) {
3297 intersectionSpec["rootMargin"] = parser.parseElement("stringLike", tokens).evaluate();
3298 } else if (tokens.matchToken("threshold")) {
3299 intersectionSpec["threshold"] = parser.parseElement("expression", tokens).evaluate();
3300 } else {
3301 parser.raiseParseError(tokens, "Unknown intersection config specification");
3302 }
3303 } while (tokens.matchToken("and"));
3304 }
3305 } else if (eventName === "mutation") {
3306 var mutationSpec = {};
3307 if (tokens.matchToken("of")) {
3308 do {
3309 if (tokens.matchToken("anything")) {
3310 mutationSpec["attributes"] = true;
3311 mutationSpec["subtree"] = true;
3312 mutationSpec["characterData"] = true;
3313 mutationSpec["childList"] = true;
3314 } else if (tokens.matchToken("childList")) {
3315 mutationSpec["childList"] = true;
3316 } else if (tokens.matchToken("attributes")) {
3317 mutationSpec["attributes"] = true;
3318 mutationSpec["attributeOldValue"] = true;
3319 } else if (tokens.matchToken("subtree")) {
3320 mutationSpec["subtree"] = true;
3321 } else if (tokens.matchToken("characterData")) {
3322 mutationSpec["characterData"] = true;
3323 mutationSpec["characterDataOldValue"] = true;
3324 } else if (tokens.currentToken().type === "ATTRIBUTE_REF") {
3325 var attribute = tokens.consumeToken();
3326 if (mutationSpec["attributeFilter"] == null) {
3327 mutationSpec["attributeFilter"] = [];
3328 }
3329 if (attribute.value.indexOf("@") == 0) {
3330 mutationSpec["attributeFilter"].push(attribute.value.substring(1));
3331 } else {
3332 parser.raiseParseError(
3333 tokens,
3334 "Only shorthand attribute references are allowed here"
3335 );
3336 }
3337 } else {
3338 parser.raiseParseError(tokens, "Unknown mutation config specification");
3339 }
3340 } while (tokens.matchToken("or"));
3341 } else {
3342 mutationSpec["attributes"] = true;
3343 mutationSpec["characterData"] = true;
3344 mutationSpec["childList"] = true;
3345 }
3346 }
3347
3348 var from = null;
3349 var elsewhere = false;
3350 if (tokens.matchToken("from")) {
3351 if (tokens.matchToken("elsewhere")) {
3352 elsewhere = true;
3353 } else {
3354 from = parser.parseElement("expression", tokens);
3355 if (!from) {
3356 parser.raiseParseError('Expected either target value or "elsewhere".', tokens);
3357 }
3358 }
3359 }
3360 // support both "elsewhere" and "from elsewhere"
3361 if (from === null && elsewhere === false && tokens.matchToken("elsewhere")) {
3362 elsewhere = true;
3363 }
3364
3365 if (tokens.matchToken("in")) {
3366 var inExpr = parser.parseAnyOf(["idRef", "queryRef", "classRef"], tokens);
3367 }
3368
3369 if (tokens.matchToken("debounced")) {
3370 tokens.requireToken("at");
3371 var timeExpr = parser.requireElement("timeExpression", tokens);
3372 var debounceTime = timeExpr.evaluate({}); // OK No promise TODO make a literal time expr
3373 } else if (tokens.matchToken("throttled")) {
3374 tokens.requireToken("at");
3375 var timeExpr = parser.requireElement("timeExpression", tokens);
3376 var throttleTime = timeExpr.evaluate({}); // OK No promise TODO make a literal time expr
3377 }
3378
3379 events.push({
3380 execCount: 0,
3381 every: every,
3382 on: eventName,
3383 args: args,
3384 filter: filter,
3385 from: from,
3386 inExpr: inExpr,
3387 elsewhere: elsewhere,
3388 startCount: startCount,
3389 endCount: endCount,
3390 unbounded: unbounded,
3391 debounceTime: debounceTime,
3392 throttleTime: throttleTime,
3393 mutationSpec: mutationSpec,
3394 intersectionSpec: intersectionSpec,
3395 });
3396 } while (tokens.matchToken("or"));
3397
3398 var queue = [];
3399 var queueLast = true;
3400 if (!every) {
3401 if (tokens.matchToken("queue")) {
3402 if (tokens.matchToken("all")) {
3403 var queueAll = true;
3404 var queueLast = false;
3405 } else if (tokens.matchToken("first")) {
3406 var queueFirst = true;
3407 } else if (tokens.matchToken("none")) {
3408 var queueNone = true;
3409 } else {
3410 tokens.requireToken("last");
3411 }
3412 }
3413 }
3414
3415 var start = parser.requireElement("commandList", tokens);
3416
3417 var implicitReturn = {
3418 type: "implicitReturn",
3419 op: function (context) {
3420 // automatically resolve at the end of an event handler if nothing else does
3421 context.meta.resolve();
3422 return runtime.HALT;
3423 },
3424 execute: function (ctx) {
3425 // do nothing
3426 },
3427 };
3428 if (start) {
3429 var end = start;
3430 while (end.next) {
3431 end = end.next;
3432 }
3433 end.next = implicitReturn;
3434 } else {
3435 start = implicitReturn;
3436 }
3437
3438 var onFeature = {
3439 displayName: displayName,
3440 events: events,
3441 start: start,
3442 every: every,
3443 executing: false,
3444 execCount: 0,
3445 queue: queue,
3446 execute: function (/** @type {Context} */ ctx) {
3447 if (this.executing && this.every === false) {
3448 if (queueNone || (queueFirst && queue.length > 0)) {
3449 return;
3450 }
3451 if (queueLast) {
3452 onFeature.queue.length = 0;
3453 }
3454 onFeature.queue.push(ctx);
3455 return;
3456 }
3457 this.execCount++;
3458 this.executing = true;
3459 ctx.meta.resolve = function () {
3460 onFeature.executing = false;
3461 var queued = onFeature.queue.shift();
3462 if (queued) {
3463 setTimeout(function () {
3464 onFeature.execute(queued);
3465 }, 1);
3466 }
3467 };
3468 ctx.meta.reject = function (err) {
3469 console.error(err.message ? err.message : err);
3470 var hypertrace = runtime.getHyperTrace(ctx, err);
3471 if (hypertrace) {
3472 hypertrace.print();
3473 }
3474 runtime.triggerEvent(ctx.me, "exception", {
3475 error: err,
3476 });
3477 onFeature.executing = false;
3478 var queued = onFeature.queue.shift();
3479 if (queued) {
3480 setTimeout(function () {
3481 onFeature.execute(queued);
3482 }, 1);
3483 }
3484 };
3485 start.execute(ctx);
3486 },
3487 install: function (elt, source) {
3488 runtime.forEach(onFeature.events, function (eventSpec) {
3489 var targets;
3490 if (eventSpec.elsewhere) {
3491 targets = [document];
3492 } else if (eventSpec.from) {
3493 targets = eventSpec.from.evaluate({
3494 me: elt,
3495 });
3496 } else {
3497 targets = [elt];
3498 }
3499 runtime.forEach(targets, function (target) {
3500 // OK NO PROMISE
3501
3502 var eventName = eventSpec.on;
3503 if (eventSpec.mutationSpec) {
3504 eventName = "hyperscript:mutation";
3505 var observer = new MutationObserver(function (mutationList, observer) {
3506 console.log(target, mutationList);
3507 if (!onFeature.executing) {
3508 _runtime.triggerEvent(target, eventName, {
3509 mutationList: mutationList,
3510 observer: observer,
3511 });
3512 }
3513 });
3514 observer.observe(target, eventSpec.mutationSpec);
3515 }
3516
3517 if (eventSpec.intersectionSpec) {
3518 eventName = "hyperscript:insersection";
3519 var observer = new IntersectionObserver(function (entries) {
3520 _runtime.forEach(entries, function (entry) {
3521 var detail = {
3522 observer: observer,
3523 };
3524 detail = mergeObjects(detail, entry);
3525 detail["intersecting"] = entry.isIntersecting;
3526 _runtime.triggerEvent(target, eventName, detail);
3527 });
3528 }, eventSpec.intersectionSpec);
3529 observer.observe(target);
3530 }
3531
3532 target.addEventListener(eventName, function listener(evt) {
3533 // OK NO PROMISE
3534 if (elt instanceof Node && target !== elt && elt.getRootNode() === null) {
3535 target.removeEventListener(eventName, listener);
3536 return;
3537 }
3538
3539 var ctx = runtime.makeContext(elt, onFeature, elt, evt);
3540 if (eventSpec.elsewhere && elt.contains(evt.target)) {
3541 return;
3542 }
3543 if (eventSpec.from) {
3544 ctx.result = target;
3545 }
3546
3547 // establish context
3548 runtime.forEach(eventSpec.args, function (arg) {
3549 ctx[arg.value] =
3550 ctx.event[arg.value] || (ctx.event.detail ? ctx.event.detail[arg.value] : null);
3551 });
3552
3553 // apply filter
3554 if (eventSpec.filter) {
3555 var initialCtx = ctx.meta.context;
3556 ctx.meta.context = ctx.event;
3557 try {
3558 var value = eventSpec.filter.evaluate(ctx); //OK NO PROMISE
3559 if (value) {
3560 // match the javascript semantics for if statements
3561 } else {
3562 return;
3563 }
3564 } finally {
3565 ctx.meta.context = initialCtx;
3566 }
3567 }
3568
3569 if (eventSpec.inExpr) {
3570 var inElement = evt.target;
3571 while (true) {
3572 if (inElement.matches && inElement.matches(eventSpec.inExpr.css)) {
3573 ctx.result = inElement;
3574 break;
3575 } else {
3576 inElement = inElement.parentElement;
3577 if (inElement == null) {
3578 return; // no match found
3579 }
3580 }
3581 }
3582 }
3583
3584 // verify counts
3585 eventSpec.execCount++;
3586 if (eventSpec.startCount) {
3587 if (eventSpec.endCount) {
3588 if (
3589 eventSpec.execCount < eventSpec.startCount ||
3590 eventSpec.execCount > eventSpec.endCount
3591 ) {
3592 return;
3593 }
3594 } else if (eventSpec.unbounded) {
3595 if (eventSpec.execCount < eventSpec.startCount) {
3596 return;
3597 }
3598 } else if (eventSpec.execCount !== eventSpec.startCount) {
3599 return;
3600 }
3601 }
3602
3603 //debounce
3604 if (eventSpec.debounceTime) {
3605 if (eventSpec.debounced) {
3606 clearTimeout(eventSpec.debounced);
3607 }
3608 eventSpec.debounced = setTimeout(function () {
3609 onFeature.execute(ctx);
3610 }, eventSpec.debounceTime);
3611 return;
3612 }
3613
3614 // throttle
3615 if (eventSpec.throttleTime) {
3616 if (
3617 eventSpec.lastExec &&
3618 Date.now() < eventSpec.lastExec + eventSpec.throttleTime
3619 ) {
3620 return;
3621 } else {
3622 eventSpec.lastExec = Date.now();
3623 }
3624 }
3625
3626 // apply execute
3627 onFeature.execute(ctx);
3628 });
3629 });
3630 });
3631 },
3632 };
3633 parser.setParent(start, onFeature);
3634 return onFeature;
3635 });
3636
3637 _parser.addFeature("def", function (parser, runtime, tokens) {
3638 if (!tokens.matchToken("def")) return;
3639 var functionName = parser.requireElement("dotOrColonPath", tokens);
3640 var nameVal = functionName.evaluate(); // OK
3641 var nameSpace = nameVal.split(".");
3642 var funcName = nameSpace.pop();
3643
3644 var args = [];
3645 if (tokens.matchOpToken("(")) {
3646 if (tokens.matchOpToken(")")) {
3647 // emtpy args list
3648 } else {
3649 do {
3650 args.push(tokens.requireTokenType("IDENTIFIER"));
3651 } while (tokens.matchOpToken(","));
3652 tokens.requireOpToken(")");
3653 }
3654 }
3655
3656 var start = parser.parseElement("commandList", tokens);
3657 if (tokens.matchToken("catch")) {
3658 var errorSymbol = tokens.requireTokenType("IDENTIFIER").value;
3659 var errorHandler = parser.parseElement("commandList", tokens);
3660 }
3661 var functionFeature = {
3662 displayName:
3663 funcName +
3664 "(" +
3665 args
3666 .map(function (arg) {
3667 return arg.value;
3668 })
3669 .join(", ") +
3670 ")",
3671 name: funcName,
3672 args: args,
3673 start: start,
3674 errorHandler: errorHandler,
3675 errorSymbol: errorSymbol,
3676 install: function (target, source) {
3677 var func = function () {
3678 // null, worker
3679 var ctx = runtime.makeContext(source, functionFeature, target, null);
3680
3681 // install error handler if any
3682 ctx.meta.errorHandler = errorHandler;
3683 ctx.meta.errorSymmbol = errorSymbol;
3684
3685 for (var i = 0; i < args.length; i++) {
3686 var name = args[i];
3687 var argumentVal = arguments[i];
3688 if (name) {
3689 ctx[name.value] = argumentVal;
3690 }
3691 }
3692 ctx.meta.caller = arguments[args.length];
3693 if (ctx.meta.caller) {
3694 ctx.meta.callingCommand = ctx.meta.caller.meta.command;
3695 }
3696 var resolve,
3697 reject = null;
3698 var promise = new Promise(function (theResolve, theReject) {
3699 resolve = theResolve;
3700 reject = theReject;
3701 });
3702 start.execute(ctx);
3703 if (ctx.meta.returned) {
3704 return ctx.meta.returnValue;
3705 } else {
3706 ctx.meta.resolve = resolve;
3707 ctx.meta.reject = reject;
3708 return promise;
3709 }
3710 };
3711 func.hyperfunc = true;
3712 func.hypername = nameVal;
3713 runtime.assignToNamespace(target, nameSpace, funcName, func);
3714 },
3715 };
3716
3717 var implicitReturn = {
3718 type: "implicitReturn",
3719 op: function (context) {
3720 // automatically return at the end of the function if nothing else does
3721 context.meta.returned = true;
3722 if (context.meta.resolve) {
3723 context.meta.resolve();
3724 }
3725 return runtime.HALT;
3726 },
3727 execute: function (context) {
3728 // do nothing
3729 },
3730 };
3731 // terminate body
3732 if (start) {
3733 var end = start;
3734 while (end.next) {
3735 end = end.next;
3736 }
3737 end.next = implicitReturn;
3738 } else {
3739 functionFeature.start = implicitReturn;
3740 }
3741
3742 // terminate error handler
3743 if (errorHandler) {
3744 var end = errorHandler;
3745 while (end.next) {
3746 end = end.next;
3747 }
3748 end.next = implicitReturn;
3749 }
3750
3751 parser.setParent(start, functionFeature);
3752 return functionFeature;
3753 });
3754
3755 _parser.addFeature("init", function (parser, runtime, tokens) {
3756 if (!tokens.matchToken("init")) return;
3757
3758 var start = parser.parseElement("commandList", tokens);
3759 var initFeature = {
3760 start: start,
3761 install: function (target, source) {
3762 setTimeout(function () {
3763 start.execute(runtime.makeContext(target, this, target, null));
3764 }, 0);
3765 },
3766 };
3767
3768 var implicitReturn = {
3769 type: "implicitReturn",
3770 op: function (context) {
3771 return runtime.HALT;
3772 },
3773 execute: function (context) {
3774 // do nothing
3775 },
3776 };
3777 // terminate body
3778 if (start) {
3779 var end = start;
3780 while (end.next) {
3781 end = end.next;
3782 }
3783 end.next = implicitReturn;
3784 } else {
3785 initFeature.start = implicitReturn;
3786 }
3787 parser.setParent(start, initFeature);
3788 return initFeature;
3789 });
3790
3791 _parser.addFeature("worker", function (parser, runtime, tokens) {
3792 if (tokens.matchToken("worker")) {
3793 parser.raiseParseError(
3794 tokens,
3795 "In order to use the 'worker' feature, include " +
3796 "the _hyperscript worker plugin. See " +
3797 "https://hyperscript.org/features/worker/ for " +
3798 "more info."
3799 );
3800 }
3801 });
3802
3803 _parser.addFeature("behavior", function (parser, runtime, tokens) {
3804 if (!tokens.matchToken("behavior")) return;
3805 var path = parser.parseElement("dotOrColonPath", tokens).evaluate();
3806 var nameSpace = path.split(".");
3807 var name = nameSpace.pop();
3808
3809 var formalParams = [];
3810 if (tokens.matchOpToken("(") && !tokens.matchOpToken(")")) {
3811 do {
3812 formalParams.push(tokens.requireTokenType("IDENTIFIER").value);
3813 } while (tokens.matchOpToken(","));
3814 tokens.requireOpToken(")");
3815 }
3816 var hs = parser.parseElement("hyperscript", tokens);
3817 for (var i = 0; i < hs.features.length; i++) {
3818 var feature = hs.features[i];
3819 feature.behavior = path;
3820 }
3821
3822 return {
3823 install: function (target, source) {
3824 runtime.assignToNamespace(
3825 globalScope.document && globalScope.document.body,
3826 nameSpace,
3827 name,
3828 function (target, source, innerArgs) {
3829 var internalData = runtime.getInternalData(target);
3830 var elementScope = getOrInitObject(internalData, path + "Scope");
3831 for (var i = 0; i < formalParams.length; i++) {
3832 elementScope[formalParams[i]] = innerArgs[formalParams[i]];
3833 }
3834 hs.apply(target, source);
3835 }
3836 );
3837 },
3838 };
3839 });
3840
3841 _parser.addFeature("install", function (parser, runtime, tokens) {
3842 if (!tokens.matchToken("install")) return;
3843 var behaviorPath = parser.requireElement("dotOrColonPath", tokens).evaluate();
3844 var behaviorNamespace = behaviorPath.split(".");
3845 var args = parser.parseElement("namedArgumentList", tokens);
3846
3847 var installFeature;
3848 return (installFeature = {
3849 install: function (target, source) {
3850 runtime.unifiedEval(
3851 {
3852 args: [args],
3853 op: function (ctx, args) {
3854 var behavior = globalScope;
3855 for (var i = 0; i < behaviorNamespace.length; i++) {
3856 behavior = behavior[behaviorNamespace[i]];
3857 if (typeof behavior !== "object" && typeof behavior !== "function")
3858 throw new Error("No such behavior defined as " + behaviorPath);
3859 }
3860
3861 if (!(behavior instanceof Function))
3862 throw new Error(behaviorPath + " is not a behavior");
3863
3864 behavior(target, source, args);
3865 },
3866 },
3867 runtime.makeContext(target, installFeature, target)
3868 );
3869 },
3870 });
3871 });
3872
3873 _parser.addGrammarElement("jsBody", function (parser, runtime, tokens) {
3874 var jsSourceStart = tokens.currentToken().start;
3875 var jsLastToken = tokens.currentToken();
3876
3877 var funcNames = [];
3878 var funcName = "";
3879 var expectFunctionDeclaration = false;
3880 while (tokens.hasMore()) {
3881 jsLastToken = tokens.consumeToken();
3882 var peek = tokens.currentToken(true);
3883 if (peek.type === "IDENTIFIER" && peek.value === "end") {
3884 break;
3885 }
3886 if (expectFunctionDeclaration) {
3887 if (jsLastToken.type === "IDENTIFIER" || jsLastToken.type === "NUMBER") {
3888 funcName += jsLastToken.value;
3889 } else {
3890 if (funcName !== "") funcNames.push(funcName);
3891 funcName = "";
3892 expectFunctionDeclaration = false;
3893 }
3894 } else if (jsLastToken.type === "IDENTIFIER" && jsLastToken.value === "function") {
3895 expectFunctionDeclaration = true;
3896 }
3897 }
3898 var jsSourceEnd = jsLastToken.end + 1;
3899
3900 return {
3901 type: "jsBody",
3902 exposedFunctionNames: funcNames,
3903 jsSource: tokens.source.substring(jsSourceStart, jsSourceEnd),
3904 };
3905 });
3906
3907 _parser.addFeature("js", function (parser, runtime, tokens) {
3908 if (!tokens.matchToken("js")) return;
3909 var jsBody = parser.parseElement("jsBody", tokens);
3910
3911 var jsSource =
3912 jsBody.jsSource +
3913 "\nreturn { " +
3914 jsBody.exposedFunctionNames
3915 .map(function (name) {
3916 return name + ":" + name;
3917 })
3918 .join(",") +
3919 " } ";
3920 var func = new Function(jsSource);
3921
3922 return {
3923 jsSource: jsSource,
3924 function: func,
3925 exposedFunctionNames: jsBody.exposedFunctionNames,
3926 install: function () {
3927 mergeObjects(globalScope, func());
3928 },
3929 };
3930 });
3931
3932 _parser.addCommand("js", function (parser, runtime, tokens) {
3933 if (!tokens.matchToken("js")) return;
3934 // Parse inputs
3935 var inputs = [];
3936 if (tokens.matchOpToken("(")) {
3937 if (tokens.matchOpToken(")")) {
3938 // empty input list
3939 } else {
3940 do {
3941 var inp = tokens.requireTokenType("IDENTIFIER");
3942 inputs.push(inp.value);
3943 } while (tokens.matchOpToken(","));
3944 tokens.requireOpToken(")");
3945 }
3946 }
3947
3948 var jsBody = parser.parseElement("jsBody", tokens);
3949 tokens.matchToken("end");
3950
3951 var func = varargConstructor(Function, inputs.concat([jsBody.jsSource]));
3952
3953 return {
3954 jsSource: jsBody.jsSource,
3955 function: func,
3956 inputs: inputs,
3957 op: function (context) {
3958 var args = [];
3959 inputs.forEach(function (input) {
3960 args.push(runtime.resolveSymbol(input, context));
3961 });
3962 var result = func.apply(globalScope, args);
3963 if (result && typeof result.then === "function") {
3964 return Promise(function (resolve) {
3965 result.then(function (actualResult) {
3966 context.result = actualResult;
3967 resolve(runtime.findNext(this, context));
3968 });
3969 });
3970 } else {
3971 context.result = result;
3972 return runtime.findNext(this, context);
3973 }
3974 },
3975 };
3976 });
3977
3978 _parser.addCommand("async", function (parser, runtime, tokens) {
3979 if (!tokens.matchToken("async")) return;
3980 if (tokens.matchToken("do")) {
3981 var body = parser.requireElement("commandList", tokens);
3982 tokens.requireToken("end");
3983 } else {
3984 var body = parser.requireElement("command", tokens);
3985 }
3986 return {
3987 body: body,
3988 op: function (context) {
3989 setTimeout(function () {
3990 body.execute(context);
3991 });
3992 return runtime.findNext(this, context);
3993 },
3994 };
3995 });
3996
3997 _parser.addCommand("tell", function (parser, runtime, tokens) {
3998 var startToken = tokens.currentToken();
3999 if (!tokens.matchToken("tell")) return;
4000 var value = parser.requireElement("expression", tokens);
4001 var body = parser.requireElement("commandList", tokens);
4002 if (tokens.hasMore()) {
4003 tokens.requireToken("end");
4004 }
4005 var slot = "tell_" + startToken.start;
4006 var tellCmd = {
4007 value: value,
4008 body: body,
4009 args: [value],
4010 resolveNext: function (context) {
4011 var iterator = context.meta.iterators[slot];
4012 if (iterator.index < iterator.value.length) {
4013 context.beingTold = iterator.value[iterator.index++];
4014 return body;
4015 } else {
4016 // restore original me
4017 context.beingTold = iterator.originalBeingTold;
4018 if (this.next) {
4019 return this.next;
4020 } else {
4021 return runtime.findNext(this.parent, context);
4022 }
4023 }
4024 },
4025 op: function (context, value) {
4026 if (value == null) {
4027 value = [];
4028 } else if (!(Array.isArray(value) || value instanceof NodeList)) {
4029 value = [value];
4030 }
4031 context.meta.iterators[slot] = {
4032 originalBeingTold: context.beingTold,
4033 index: 0,
4034 value: value,
4035 };
4036 return this.resolveNext(context);
4037 },
4038 };
4039 parser.setParent(body, tellCmd);
4040 return tellCmd;
4041 });
4042
4043 _parser.addCommand("wait", function (parser, runtime, tokens) {
4044 if (!tokens.matchToken("wait")) return;
4045 // wait on event
4046 if (tokens.matchToken("for")) {
4047 tokens.matchToken("a"); // optional "a"
4048 var events = [];
4049 do {
4050 events.push({
4051 name: _parser.requireElement("dotOrColonPath", tokens, "Expected event name").evaluate(),
4052 args: parseEventArgs(tokens),
4053 });
4054 } while (tokens.matchToken("or"));
4055
4056 if (tokens.matchToken("from")) {
4057 var on = parser.requireElement("expression", tokens);
4058 }
4059
4060 // wait on event
4061 var waitCmd = {
4062 event: events,
4063 on: on,
4064 args: [on],
4065 op: function (context, on) {
4066 var target = on ? on : context.me;
4067 if (!(target instanceof EventTarget))
4068 throw new Error("Not a valid event target: " + this.on.sourceFor());
4069 return new Promise(function (resolve) {
4070 var resolved = false;
4071 runtime.forEach(events, function (eventInfo) {
4072 var listener = function (event) {
4073 context.result = event;
4074 runtime.forEach(eventInfo.args, function (arg) {
4075 context[arg.value] =
4076 event[arg.value] || (event.detail ? event.detail[arg.value] : null);
4077 });
4078 if (!resolved) {
4079 resolved = true;
4080 resolve(runtime.findNext(waitCmd, context));
4081 }
4082 };
4083 target.addEventListener(eventInfo.name, listener, { once: true });
4084 });
4085 });
4086 },
4087 };
4088 } else {
4089 if (tokens.matchToken("a")) {
4090 tokens.requireToken("tick");
4091 time = 0;
4092 } else {
4093 var time = _parser.requireElement("timeExpression", tokens);
4094 }
4095
4096 var waitCmd = {
4097 type: "waitCmd",
4098 time: time,
4099 args: [time],
4100 op: function (context, timeValue) {
4101 return new Promise(function (resolve) {
4102 setTimeout(function () {
4103 resolve(runtime.findNext(waitCmd, context));
4104 }, timeValue);
4105 });
4106 },
4107 execute: function (context) {
4108 return runtime.unifiedExec(this, context);
4109 },
4110 };
4111 }
4112 return waitCmd;
4113 });
4114
4115 // TODO - colon path needs to eventually become part of ruby-style symbols
4116 _parser.addGrammarElement("dotOrColonPath", function (parser, runtime, tokens) {
4117 var root = tokens.matchTokenType("IDENTIFIER");
4118 if (root) {
4119 var path = [root.value];
4120
4121 var separator = tokens.matchOpToken(".") || tokens.matchOpToken(":");
4122 if (separator) {
4123 do {
4124 path.push(tokens.requireTokenType("IDENTIFIER").value);
4125 } while (tokens.matchOpToken(separator.value));
4126 }
4127
4128 return {
4129 type: "dotOrColonPath",
4130 path: path,
4131 evaluate: function () {
4132 return path.join(separator ? separator.value : "");
4133 },
4134 };
4135 }
4136 });
4137
4138 _parser.addGrammarElement("eventName", function (parser, runtime, tokens) {
4139 var token;
4140 if ((token = tokens.matchTokenType("STRING"))) {
4141 return {
4142 evaluate: function() {
4143 return token.value;
4144 },
4145 };
4146 }
4147
4148 return parser.parseElement("dotOrColonPath", tokens);
4149 });
4150
4151 _parser.addCommand("send", function (parser, runtime, tokens) {
4152 if (!tokens.matchToken("send")) return;
4153 var eventName = parser.requireElement("eventName", tokens);
4154
4155 var details = parser.parseElement("namedArgumentList", tokens);
4156 if (tokens.matchToken("to")) {
4157 var to = parser.requireElement("expression", tokens);
4158 } else {
4159 var to = parser.requireElement("implicitMeTarget", tokens);
4160 }
4161
4162 var sendCmd = {
4163 eventName: eventName,
4164 details: details,
4165 to: to,
4166 args: [to, eventName, details],
4167 op: function (context, to, eventName, details) {
4168 runtime.forEach(to, function (target) {
4169 runtime.triggerEvent(target, eventName, details ? details : {});
4170 });
4171 return runtime.findNext(sendCmd, context);
4172 },
4173 };
4174 return sendCmd;
4175 });
4176
4177 var parseReturnFunction = function (parser, runtime, tokens, returnAValue) {
4178 if (returnAValue) {
4179 var value = parser.requireElement("expression", tokens);
4180 }
4181
4182 var returnCmd = {
4183 value: value,
4184 args: [value],
4185 op: function (context, value) {
4186 var resolve = context.meta.resolve;
4187 context.meta.returned = true;
4188 if (resolve) {
4189 if (value) {
4190 resolve(value);
4191 } else {
4192 resolve();
4193 }
4194 } else {
4195 context.meta.returned = true;
4196 context.meta.returnValue = value;
4197 }
4198 return runtime.HALT;
4199 },
4200 };
4201 return returnCmd;
4202 };
4203
4204 _parser.addCommand("return", function (parser, runtime, tokens) {
4205 if (tokens.matchToken("return")) {
4206 return parseReturnFunction(parser, runtime, tokens, true);
4207 }
4208 });
4209
4210 _parser.addCommand("exit", function (parser, runtime, tokens) {
4211 if (tokens.matchToken("exit")) {
4212 return parseReturnFunction(parser, runtime, tokens, false);
4213 }
4214 });
4215
4216 _parser.addCommand("halt", function (parser, runtime, tokens) {
4217 if (tokens.matchToken("halt")) {
4218 if (tokens.matchToken("the")) {
4219 tokens.requireToken("event");
4220 // optional possessive
4221 if (tokens.matchOpToken("'")) {
4222 tokens.requireToken("s");
4223 }
4224 var keepExecuting = true;
4225 }
4226 if (tokens.matchToken("bubbling")) {
4227 var bubbling = true;
4228 } else if (tokens.matchToken("default")) {
4229 var haltDefault = true;
4230 }
4231 var exit = parseReturnFunction(parser, runtime, tokens, false);
4232
4233 var haltCmd = {
4234 keepExecuting: true,
4235 bubbling: bubbling,
4236 haltDefault: haltDefault,
4237 exit: exit,
4238 op: function (ctx) {
4239 if (ctx.event) {
4240 if (bubbling) {
4241 ctx.event.stopPropagation();
4242 } else if (haltDefault) {
4243 ctx.event.preventDefault();
4244 } else {
4245 ctx.event.stopPropagation();
4246 ctx.event.preventDefault();
4247 }
4248 if (keepExecuting) {
4249 return runtime.findNext(this, ctx);
4250 } else {
4251 return exit;
4252 }
4253 }
4254 },
4255 };
4256 return haltCmd;
4257 }
4258 });
4259
4260 _parser.addCommand("log", function (parser, runtime, tokens) {
4261 if (!tokens.matchToken("log")) return;
4262 var exprs = [parser.parseElement("expression", tokens)];
4263 while (tokens.matchOpToken(",")) {
4264 exprs.push(parser.requireElement("expression", tokens));
4265 }
4266 if (tokens.matchToken("with")) {
4267 var withExpr = parser.requireElement("expression", tokens);
4268 }
4269 var logCmd = {
4270 exprs: exprs,
4271 withExpr: withExpr,
4272 args: [withExpr, exprs],
4273 op: function (ctx, withExpr, values) {
4274 if (withExpr) {
4275 withExpr.apply(null, values);
4276 } else {
4277 console.log.apply(null, values);
4278 }
4279 return runtime.findNext(this, ctx);
4280 },
4281 };
4282 return logCmd;
4283 });
4284
4285 _parser.addCommand("throw", function (parser, runtime, tokens) {
4286 if (!tokens.matchToken("throw")) return;
4287 var expr = parser.requireElement("expression", tokens);
4288 var throwCmd = {
4289 expr: expr,
4290 args: [expr],
4291 op: function (ctx, expr) {
4292 runtime.registerHyperTrace(ctx, expr);
4293 var reject = ctx.meta && ctx.meta.reject;
4294 if (reject) {
4295 reject(expr);
4296 return runtime.HALT;
4297 } else {
4298 throw expr;
4299 }
4300 },
4301 };
4302 return throwCmd;
4303 });
4304
4305 var parseCallOrGet = function (parser, runtime, tokens) {
4306 var expr = parser.requireElement("expression", tokens);
4307 var callCmd = {
4308 expr: expr,
4309 args: [expr],
4310 op: function (context, result) {
4311 context.result = result;
4312 return runtime.findNext(callCmd, context);
4313 },
4314 };
4315 return callCmd;
4316 };
4317 _parser.addCommand("call", function (parser, runtime, tokens) {
4318 if (!tokens.matchToken("call")) return;
4319 var call = parseCallOrGet(parser, runtime, tokens);
4320 if (call.expr && call.expr.type !== "functionCall") {
4321 parser.raiseParseError(tokens, "Must be a function invocation");
4322 }
4323 return call;
4324 });
4325 _parser.addCommand("get", function (parser, runtime, tokens) {
4326 if (tokens.matchToken("get")) {
4327 return parseCallOrGet(parser, runtime, tokens);
4328 }
4329 });
4330
4331 _parser.addCommand("make", function (parser, runtime, tokens) {
4332 if (!tokens.matchToken("make")) return;
4333 tokens.matchToken("a") || tokens.matchToken("an");
4334
4335 var expr = parser.requireElement("expression", tokens);
4336
4337 var args = [];
4338 if (expr.type !== "queryRef" && tokens.matchToken("from")) {
4339 do {
4340 args.push(parser.requireElement("expression", tokens));
4341 } while (tokens.matchOpToken(","));
4342 }
4343
4344 if (tokens.matchToken("called")) {
4345 var name = tokens.requireTokenType("IDENTIFIER").value;
4346 }
4347
4348 if (expr.type === "queryRef")
4349 return {
4350 op: function (ctx) {
4351 var match,
4352 tagname = "div",
4353 id,
4354 classes = [];
4355 var re = /(?:(^|#|\.)([^#\. ]+))/g;
4356 while ((match = re.exec(expr.css))) {
4357 if (match[1] === "") tagname = match[2].trim();
4358 else if (match[1] === "#") id = match[2].trim();
4359 else classes.push(match[2].trim());
4360 }
4361
4362 var result = document.createElement(tagname);
4363 if (id !== undefined) result.id = id;
4364 for (var i = 0; i < classes.length; i++) {
4365 var cls = classes[i];
4366 result.classList.add(cls)
4367 }
4368
4369 ctx.result = result;
4370 if (name) ctx[name] = result;
4371
4372 return runtime.findNext(this, ctx);
4373 },
4374 };
4375 else
4376 return {
4377 args: [expr, args],
4378 op: function (ctx, expr, args) {
4379 ctx.result = varargConstructor(expr, args);
4380 if (name) ctx[name] = ctx.result;
4381
4382 return runtime.findNext(this, ctx);
4383 },
4384 };
4385 });
4386
4387 _parser.addGrammarElement("pseudoCommand", function (parser, runtime, tokens) {
4388 var expr = parser.requireElement("primaryExpression", tokens);
4389 if (expr.type !== "functionCall" && expr.root.type !== "symbol") {
4390 parser.raiseParseError("Implicit function calls must start with a simple function", tokens);
4391 }
4392 // optional "on", "with", or "to"
4393 if (!tokens.matchAnyToken("to", "on", "with") && parser.commandBoundary(tokens.currentToken())) {
4394 var target = parser.requireElement("implicitMeTarget", tokens);
4395 } else {
4396 var target = parser.requireElement("expression", tokens);
4397 }
4398 var functionName = expr.root.name;
4399 var functionArgs = expr.argExressions;
4400
4401 /** @type {GrammarElement} */
4402 var pseudoCommand = {
4403 type: "pseudoCommand",
4404 expr: expr,
4405 args: [target, functionArgs],
4406 op: function (context, target, args) {
4407 var func = target[functionName];
4408 if (func.hyperfunc) {
4409 args.push(context);
4410 }
4411 var result = func.apply(target, args);
4412 context.result = result;
4413 return runtime.findNext(pseudoCommand, context);
4414 },
4415 execute: function (context) {
4416 return runtime.unifiedExec(this, context);
4417 },
4418 };
4419
4420 return pseudoCommand;
4421 });
4422
4423 /**
4424 * @param {ParserObject} parser
4425 * @param {RuntimeObject} runtime
4426 * @param {TokensObject} tokens
4427 * @param {*} target
4428 * @param {*} value
4429 * @returns
4430 */
4431 var makeSetter = function (parser, runtime, tokens, target, value) {
4432 var symbolWrite = target.type === "symbol";
4433 var attributeWrite = target.type === "attributeRef";
4434 if (!attributeWrite && !symbolWrite && target.root == null) {
4435 parser.raiseParseError(tokens, "Can only put directly into symbols, not references");
4436 }
4437
4438 var root = null;
4439 var prop = null;
4440 if (symbolWrite) {
4441 // root is null
4442 } else if (attributeWrite) {
4443 root = parser.requireElement("implicitMeTarget", tokens);
4444 var attribute = target;
4445 } else {
4446 prop = target.prop ? target.prop.value : null;
4447 var attribute = target.attribute;
4448 root = target.root;
4449 }
4450
4451 /** @type {GrammarElement} */
4452 var setCmd = {
4453 target: target,
4454 symbolWrite: symbolWrite,
4455 value: value,
4456 args: [root, value],
4457 op: function (context, root, valueToSet) {
4458 if (symbolWrite) {
4459 runtime.setSymbol(target.name, context, target.symbolType, valueToSet);
4460 } else {
4461 runtime.forEach(root, function (elt) {
4462 if (attribute) {
4463 if (valueToSet == null) {
4464 elt.removeAttribute(attribute.name);
4465 } else {
4466 elt.setAttribute(attribute.name, valueToSet);
4467 }
4468 } else {
4469 elt[prop] = valueToSet;
4470 }
4471 });
4472 }
4473 return runtime.findNext(this, context);
4474 },
4475 };
4476 return setCmd;
4477 };
4478
4479 _parser.addCommand("default", function (parser, runtime, tokens) {
4480 if (!tokens.matchToken("default")) return;
4481 var target = parser.requireElement("assignableExpression", tokens);
4482 tokens.requireToken("to");
4483
4484 var value = parser.requireElement("expression", tokens);
4485
4486 /** @type {GrammarElement} */
4487 var setter = makeSetter(parser, runtime, tokens, target, value);
4488 var defaultCmd = {
4489 target: target,
4490 value: value,
4491 setter: setter,
4492 args: [target],
4493 op: function (context, target) {
4494 if (target) {
4495 return runtime.findNext(this, context);
4496 } else {
4497 return setter;
4498 }
4499 },
4500 };
4501 setter.parent = defaultCmd;
4502 return defaultCmd;
4503 });
4504
4505 _parser.addCommand("set", function (parser, runtime, tokens) {
4506 if (!tokens.matchToken("set")) return;
4507 if (tokens.currentToken().type === "L_BRACE") {
4508 var obj = parser.requireElement("objectLiteral", tokens);
4509 tokens.requireToken("on");
4510 var target = parser.requireElement("expression", tokens);
4511
4512 return {
4513 objectLiteral: obj,
4514 target: target,
4515 args: [obj, target],
4516 op: function (ctx, obj, target) {
4517 mergeObjects(target, obj);
4518 return runtime.findNext(this, ctx);
4519 },
4520 };
4521 }
4522
4523 try {
4524 tokens.pushFollow("to");
4525 var target = parser.requireElement("assignableExpression", tokens);
4526 } finally {
4527 tokens.popFollow();
4528 }
4529 tokens.requireToken("to");
4530 var value = parser.requireElement("expression", tokens);
4531 return makeSetter(parser, runtime, tokens, target, value);
4532 });
4533
4534 _parser.addCommand("if", function (parser, runtime, tokens) {
4535 if (!tokens.matchToken("if")) return;
4536 var expr = parser.requireElement("expression", tokens);
4537 tokens.matchToken("then"); // optional 'then'
4538 var trueBranch = parser.parseElement("commandList", tokens);
4539 if (tokens.matchToken("else")) {
4540 var falseBranch = parser.parseElement("commandList", tokens);
4541 }
4542 if (tokens.hasMore()) {
4543 tokens.requireToken("end");
4544 }
4545
4546 /** @type {GrammarElement} */
4547 var ifCmd = {
4548 expr: expr,
4549 trueBranch: trueBranch,
4550 falseBranch: falseBranch,
4551 args: [expr],
4552 op: function (context, exprValue) {
4553 if (exprValue) {
4554 return trueBranch;
4555 } else if (falseBranch) {
4556 return falseBranch;
4557 } else {
4558 return runtime.findNext(this, context);
4559 }
4560 },
4561 };
4562 parser.setParent(trueBranch, ifCmd);
4563 parser.setParent(falseBranch, ifCmd);
4564 return ifCmd;
4565 });
4566
4567 var parseRepeatExpression = function (parser, tokens, runtime, startedWithForToken) {
4568 var innerStartToken = tokens.currentToken();
4569 if (tokens.matchToken("for") || startedWithForToken) {
4570 var identifierToken = tokens.requireTokenType("IDENTIFIER");
4571 var identifier = identifierToken.value;
4572 tokens.requireToken("in");
4573 var expression = parser.requireElement("expression", tokens);
4574 } else if (tokens.matchToken("in")) {
4575 var identifier = "it";
4576 var expression = parser.requireElement("expression", tokens);
4577 } else if (tokens.matchToken("while")) {
4578 var whileExpr = parser.requireElement("expression", tokens);
4579 } else if (tokens.matchToken("until")) {
4580 var isUntil = true;
4581 if (tokens.matchToken("event")) {
4582 var evt = _parser.requireElement("dotOrColonPath", tokens, "Expected event name");
4583 if (tokens.matchToken("from")) {
4584 var on = parser.requireElement("expression", tokens);
4585 }
4586 } else {
4587 var whileExpr = parser.requireElement("expression", tokens);
4588 }
4589 } else if (tokens.matchTokenType("NUMBER")) {
4590 var times = parseFloat(innerStartToken.value);
4591 tokens.requireToken("times");
4592 } else {
4593 tokens.matchToken("forever"); // consume optional forever
4594 var forever = true;
4595 }
4596
4597 if (tokens.matchToken("index")) {
4598 var identifierToken = tokens.requireTokenType("IDENTIFIER");
4599 var indexIdentifier = identifierToken.value;
4600 }
4601
4602 var loop = parser.parseElement("commandList", tokens);
4603 if (loop && evt) {
4604 // if this is an event based loop, wait a tick at the end of the loop so that
4605 // events have a chance to trigger in the loop condition o_O)))
4606 var last = loop;
4607 while (last.next) {
4608 last = last.next;
4609 }
4610 var waitATick = {
4611 type: "waitATick",
4612 op: function () {
4613 return new Promise(function (resolve) {
4614 setTimeout(function () {
4615 resolve(runtime.findNext(waitATick));
4616 }, 0);
4617 });
4618 },
4619 };
4620 last.next = waitATick;
4621 }
4622 if (tokens.hasMore()) {
4623 tokens.requireToken("end");
4624 }
4625
4626 if (identifier == null) {
4627 identifier = "_implicit_repeat_" + innerStartToken.start;
4628 var slot = identifier;
4629 } else {
4630 var slot = identifier + "_" + innerStartToken.start;
4631 }
4632
4633 var repeatCmd = {
4634 identifier: identifier,
4635 indexIdentifier: indexIdentifier,
4636 slot: slot,
4637 expression: expression,
4638 forever: forever,
4639 times: times,
4640 until: isUntil,
4641 event: evt,
4642 on: on,
4643 whileExpr: whileExpr,
4644 resolveNext: function () {
4645 return this;
4646 },
4647 loop: loop,
4648 args: [whileExpr],
4649 op: function (context, whileValue) {
4650 var iterator = context.meta.iterators[slot];
4651 var keepLooping = false;
4652 if (this.forever) {
4653 keepLooping = true;
4654 } else if (this.until) {
4655 if (evt) {
4656 keepLooping = context.meta.iterators[slot].eventFired === false;
4657 } else {
4658 keepLooping = whileValue !== true;
4659 }
4660 } else if (whileValue) {
4661 keepLooping = true;
4662 } else if (times) {
4663 keepLooping = iterator.index < this.times;
4664 } else {
4665 keepLooping = iterator.value !== null && iterator.index < iterator.value.length;
4666 }
4667
4668 if (keepLooping) {
4669 if (iterator.value) {
4670 context[identifier] = iterator.value[iterator.index];
4671 context.result = iterator.value[iterator.index];
4672 } else {
4673 context.result = iterator.index;
4674 }
4675 if (indexIdentifier) {
4676 context[indexIdentifier] = iterator.index;
4677 }
4678 iterator.index++;
4679 return loop;
4680 } else {
4681 context.meta.iterators[slot] = null;
4682 return runtime.findNext(this.parent, context);
4683 }
4684 },
4685 };
4686 parser.setParent(loop, repeatCmd);
4687 var repeatInit = {
4688 name: "repeatInit",
4689 args: [expression, evt, on],
4690 op: function (context, value, event, on) {
4691 context.meta.iterators[slot] = {
4692 index: 0,
4693 value: value,
4694 eventFired: false,
4695 };
4696 if (evt) {
4697 var target = on || context.me;
4698 target.addEventListener(
4699 event,
4700 function (e) {
4701 context.meta.iterators[slot].eventFired = true;
4702 },
4703 { once: true }
4704 );
4705 }
4706 return repeatCmd; // continue to loop
4707 },
4708 execute: function (context) {
4709 return runtime.unifiedExec(this, context);
4710 },
4711 };
4712 parser.setParent(repeatCmd, repeatInit);
4713 return repeatInit;
4714 };
4715
4716 _parser.addCommand("repeat", function (parser, runtime, tokens) {
4717 if (tokens.matchToken("repeat")) {
4718 return parseRepeatExpression(parser, tokens, runtime, false);
4719 }
4720 });
4721
4722 _parser.addCommand("for", function (parser, runtime, tokens) {
4723 if (tokens.matchToken("for")) {
4724 return parseRepeatExpression(parser, tokens, runtime, true);
4725 }
4726 });
4727
4728 _parser.addGrammarElement("stringLike", function (parser, runtime, tokens) {
4729 return _parser.parseAnyOf(["string", "nakedString"], tokens);
4730 });
4731
4732 _parser.addCommand("append", function (parser, runtime, tokens) {
4733 if (!tokens.matchToken("append")) return;
4734 var target = null;
4735 var prop = null;
4736
4737 var value = parser.requireElement("expression", tokens);
4738
4739 if (tokens.matchToken("to")) {
4740 target = parser.requireElement("expression", tokens);
4741 }
4742
4743 if (target == null) {
4744 prop = "result";
4745 } else if (target.type === "symbol") {
4746 prop = target.name;
4747 } else if (target.type === "propertyAccess") {
4748 prop = target.prop.value;
4749 } else {
4750 throw "Unable to append to " + target.type;
4751 }
4752
4753 return {
4754 value: value,
4755 target: target,
4756 args: [value],
4757 op: function (context, value) {
4758 if (Array.isArray(context[prop])) {
4759 context[prop].push(value);
4760 } else if (context[prop] instanceof Element) {
4761 if (typeof value == "string") {
4762 context[prop].innerHTML += value;
4763 } else {
4764 throw "Don't know how to append non-strings to an HTML Element yet.";
4765 }
4766 } else {
4767 context[prop] += value;
4768 }
4769
4770 return runtime.findNext(this, context);
4771 },
4772 execute: function (context) {
4773 return runtime.unifiedExec(this, context, value, target);
4774 },
4775 };
4776 });
4777
4778 _parser.addCommand("increment", function (parser, runtime, tokens) {
4779 if (!tokens.matchToken("increment")) return;
4780 var amount;
4781
4782 // This is optional. Defaults to "result"
4783 var target = parser.parseElement("assignableExpression", tokens);
4784
4785 // This is optional. Defaults to 1.
4786 if (tokens.matchToken("by")) {
4787 amount = parser.requireElement("expression", tokens);
4788 }
4789
4790 return {
4791 target: target,
4792 args: [target, amount],
4793 op: function (context, targetValue, amount) {
4794 targetValue = targetValue ? parseFloat(targetValue) : 0;
4795 amount = amount ? parseFloat(amount) : 1;
4796 var newValue = targetValue + amount;
4797 var setter = makeSetter(parser, runtime, tokens, target, newValue);
4798 context.result = newValue;
4799 setter.parent = this;
4800 return setter;
4801 },
4802 execute: function (context) {
4803 return runtime.unifiedExec(this, context, target, amount);
4804 },
4805 };
4806 });
4807
4808 _parser.addCommand("decrement", function (parser, runtime, tokens) {
4809 if (!tokens.matchToken("decrement")) return;
4810 var amount;
4811
4812 // This is optional. Defaults to "result"
4813 var target = parser.parseElement("assignableExpression", tokens);
4814
4815 // This is optional. Defaults to 1.
4816 if (tokens.matchToken("by")) {
4817 amount = parser.requireElement("expression", tokens);
4818 }
4819
4820 return {
4821 target: target,
4822 args: [target, amount],
4823 op: function (context, targetValue, amount) {
4824 targetValue = targetValue ? parseFloat(targetValue) : 0;
4825 amount = amount ? parseFloat(amount) : 1;
4826 var newValue = targetValue - amount;
4827 var setter = makeSetter(parser, runtime, tokens, target, newValue);
4828 context.result = newValue;
4829 setter.parent = this;
4830 return setter;
4831 },
4832 execute: function (context) {
4833 return runtime.unifiedExec(this, context, target, amount);
4834 },
4835 };
4836 });
4837
4838 _parser.addCommand("fetch", function (parser, runtime, tokens) {
4839 if (!tokens.matchToken("fetch")) return;
4840 var url = parser.requireElement("stringLike", tokens);
4841 var args = parser.parseElement("objectLiteral", tokens);
4842
4843 var type = "text";
4844 var conversion;
4845 if (tokens.matchToken("as")) {
4846 if (tokens.matchToken("json")) {
4847 type = "json";
4848 } else if (tokens.matchToken("response")) {
4849 type = "response";
4850 } else if (tokens.matchToken("html")) {
4851 type = "html";
4852 } else if (tokens.matchToken("text")) {
4853 // default, ignore
4854 } else {
4855 conversion = parser.requireElement("dotOrColonPath", tokens).evaluate();
4856 }
4857 }
4858
4859 /** @type {GrammarElement} */
4860 var fetchCmd = {
4861 url: url,
4862 argExpressions: args,
4863 args: [url, args],
4864 op: function (context, url, args) {
4865 return fetch(url, args)
4866 .then(function (resp) {
4867 if (type === "response") {
4868 context.result = resp;
4869 return runtime.findNext(fetchCmd, context);
4870 }
4871 if (type === "json") {
4872 return resp.json().then(function (result) {
4873 context.result = result;
4874 return runtime.findNext(fetchCmd, context);
4875 });
4876 }
4877 return resp.text().then(function (result) {
4878 if (conversion) result = runtime.convertValue(result, conversion);
4879
4880 if (type === "html") result = runtime.convertValue(result, "Fragment");
4881
4882 context.result = result;
4883 return runtime.findNext(fetchCmd, context);
4884 });
4885 })
4886 .catch(function (reason) {
4887 runtime.triggerEvent(context.me, "fetch:error", {
4888 reason: reason,
4889 });
4890 throw reason;
4891 });
4892 },
4893 };
4894 return fetchCmd;
4895 });
4896 }
4897
4898 //====================================================================
4899 // Initialization
4900 //====================================================================
4901 function ready(fn) {
4902 if (document.readyState !== "loading") {
4903 setTimeout(fn);
4904 } else {
4905 document.addEventListener("DOMContentLoaded", fn);
4906 }
4907 }
4908
4909 function getMetaConfig() {
4910 var element = document.querySelector('meta[name="htmx-config"]');
4911 if (element) {
4912 return parseJSON(element.content);
4913 } else {
4914 return null;
4915 }
4916 }
4917
4918 function mergeMetaConfig() {
4919 var metaConfig = getMetaConfig();
4920 if (metaConfig) {
4921 _hyperscript.config = mergeObjects(_hyperscript.config, metaConfig);
4922 }
4923 }
4924
4925 if ("document" in globalScope) {
4926 Promise.all(
4927 Array.from(document.querySelectorAll("script[type='text/hyperscript'][src]")).map(function (script) {
4928 return fetch(script.src)
4929 .then(function (res) {
4930 return res.text();
4931 })
4932 .then(function (code) {
4933 return _runtime.evaluate(code);
4934 });
4935 })
4936 ).then(function () {
4937 ready(function () {
4938 mergeMetaConfig();
4939 _runtime.processNode(document.documentElement);
4940 document.addEventListener("htmx:load", function (evt) {
4941 _runtime.processNode(evt.detail.elt);
4942 });
4943 });
4944 });
4945 }
4946
4947 //====================================================================
4948 // API
4949 //====================================================================
4950 return mergeObjects(
4951 function (str, ctx) {
4952 return _runtime.evaluate(str, ctx); //OK
4953 },
4954 {
4955 internals: {
4956 lexer: _lexer,
4957 parser: _parser,
4958 runtime: _runtime,
4959 },
4960 addFeature: function (keyword, definition) {
4961 _parser.addFeature(keyword, definition);
4962 },
4963 addCommand: function (keyword, definition) {
4964 _parser.addCommand(keyword, definition);
4965 },
4966 addLeafExpression: function (name, definition) {
4967 _parser.addLeafExpression(name, definition);
4968 },
4969 addIndirectExpression: function (name, definition) {
4970 _parser.addIndirectExpression(name, definition);
4971 },
4972 evaluate: function (str, ctx) {
4973 //OK
4974 return _runtime.evaluate(str, ctx); //OK
4975 },
4976 parse: function (str) {
4977 //OK
4978 return _runtime.parse(str); //OK
4979 },
4980 processNode: function (elt) {
4981 _runtime.processNode(elt);
4982 },
4983 config: {
4984 attributes: "_, script, data-script",
4985 defaultTransition: "all 500ms ease-in",
4986 disableSelector: "[disable-scripting], [data-disable-scripting]",
4987 conversions: CONVERSIONS,
4988 },
4989 }
4990 );
4991 });
4992
4993 ///=========================================================================
4994 /// This module provides the core web functionality for hyperscript
4995 ///=========================================================================
4996 (function () {
4997 function mergeObjects(obj1, obj2) {
4998 for (var key in obj2) {
4999 if (obj2.hasOwnProperty(key)) {
5000 obj1[key] = obj2[key];
5001 }
5002 }
5003 return obj1;
5004 }
5005
5006 _hyperscript.addCommand("settle", function (parser, runtime, tokens) {
5007 if (tokens.matchToken("settle")) {
5008 if (!parser.commandBoundary(tokens.currentToken())) {
5009 var on = parser.requireElement("expression", tokens);
5010 } else {
5011 var on = parser.requireElement("implicitMeTarget", tokens);
5012 }
5013
5014 var settleCommand = {
5015 type: "settleCmd",
5016 args: [on],
5017 op: function (context, on) {
5018 var resolve = null;
5019 var resolved = false;
5020 var transitionStarted = false;
5021
5022 var promise = new Promise(function (r) {
5023 resolve = r;
5024 });
5025
5026 // listen for a transition begin
5027 on.addEventListener(
5028 "transitionstart",
5029 function () {
5030 transitionStarted = true;
5031 },
5032 { once: true }
5033 );
5034
5035 // if no transition begins in 500ms, cancel
5036 setTimeout(function () {
5037 if (!transitionStarted && !resolved) {
5038 resolve(runtime.findNext(settleCommand, context));
5039 }
5040 }, 500);
5041
5042 // continue on a transition emd
5043 on.addEventListener(
5044 "transitionend",
5045 function () {
5046 if (!resolved) {
5047 resolve(runtime.findNext(settleCommand, context));
5048 }
5049 },
5050 { once: true }
5051 );
5052 return promise;
5053 },
5054 execute: function (context) {
5055 return runtime.unifiedExec(this, context);
5056 },
5057 };
5058 return settleCommand;
5059 }
5060 });
5061
5062 _hyperscript.addCommand("add", function (parser, runtime, tokens) {
5063 if (tokens.matchToken("add")) {
5064 var classRef = parser.parseElement("classRef", tokens);
5065 var attributeRef = null;
5066 var cssDeclaration = null;
5067 if (classRef == null) {
5068 attributeRef = parser.parseElement("attributeRef", tokens);
5069 if (attributeRef == null) {
5070 cssDeclaration = parser.parseElement("objectLiteral", tokens);
5071 if (cssDeclaration == null) {
5072 parser.raiseParseError(tokens, "Expected either a class reference or attribute expression");
5073 }
5074 }
5075 } else {
5076 var classRefs = [classRef];
5077 while ((classRef = parser.parseElement("classRef", tokens))) {
5078 classRefs.push(classRef);
5079 }
5080 }
5081
5082 if (tokens.matchToken("to")) {
5083 var to = parser.requireElement("expression", tokens);
5084 } else {
5085 var to = parser.parseElement("implicitMeTarget", tokens);
5086 }
5087
5088 if (classRefs) {
5089 var addCmd = {
5090 classRefs: classRefs,
5091 to: to,
5092 args: [to],
5093 op: function (context, to) {
5094 runtime.forEach(classRefs, function (classRef) {
5095 runtime.forEach(to, function (target) {
5096 if (target instanceof Element) target.classList.add(classRef.className());
5097 });
5098 });
5099 return runtime.findNext(this, context);
5100 },
5101 };
5102 } else if (attributeRef) {
5103 var addCmd = {
5104 type: "addCmd",
5105 attributeRef: attributeRef,
5106 to: to,
5107 args: [to],
5108 op: function (context, to, attrRef) {
5109 runtime.forEach(to, function (target) {
5110 target.setAttribute(attributeRef.name, attributeRef.value);
5111 });
5112 return runtime.findNext(addCmd, context);
5113 },
5114 execute: function (ctx) {
5115 return runtime.unifiedExec(this, ctx);
5116 },
5117 };
5118 } else {
5119 var addCmd = {
5120 type: "addCmd",
5121 cssDeclaration: cssDeclaration,
5122 to: to,
5123 args: [to, cssDeclaration],
5124 op: function (context, to, css) {
5125 runtime.forEach(to, function (target) {
5126 for (var key in css) {
5127 if (css.hasOwnProperty(key)) {
5128 target.style.setProperty(key, css[key]);
5129 }
5130 }
5131 });
5132 return runtime.findNext(addCmd, context);
5133 },
5134 execute: function (ctx) {
5135 return runtime.unifiedExec(this, ctx);
5136 },
5137 };
5138 }
5139 return addCmd;
5140 }
5141 });
5142
5143 _hyperscript.addCommand("remove", function (parser, runtime, tokens) {
5144 if (tokens.matchToken("remove")) {
5145 var classRef = parser.parseElement("classRef", tokens);
5146 var attributeRef = null;
5147 var elementExpr = null;
5148 if (classRef == null) {
5149 attributeRef = parser.parseElement("attributeRef", tokens);
5150 if (attributeRef == null) {
5151 elementExpr = parser.parseElement("expression", tokens);
5152 if (elementExpr == null) {
5153 parser.raiseParseError(
5154 tokens,
5155 "Expected either a class reference, attribute expression or value expression"
5156 );
5157 }
5158 }
5159 } else {
5160 var classRefs = [classRef];
5161 while ((classRef = parser.parseElement("classRef", tokens))) {
5162 classRefs.push(classRef);
5163 }
5164 }
5165
5166 if (tokens.matchToken("from")) {
5167 var from = parser.requireElement("expression", tokens);
5168 } else {
5169 var from = parser.requireElement("implicitMeTarget", tokens);
5170 }
5171
5172 if (elementExpr) {
5173 var removeCmd = {
5174 elementExpr: elementExpr,
5175 from: from,
5176 args: [elementExpr],
5177 op: function (context, element) {
5178 runtime.forEach(element, function (target) {
5179 if (target.parentElement) {
5180 target.parentElement.removeChild(target);
5181 }
5182 });
5183 return runtime.findNext(this, context);
5184 },
5185 };
5186 } else {
5187 var removeCmd = {
5188 classRefs: classRefs,
5189 attributeRef: attributeRef,
5190 elementExpr: elementExpr,
5191 from: from,
5192 args: [from],
5193 op: function (context, from) {
5194 if (this.classRefs) {
5195 runtime.forEach(classRefs, function (classRef) {
5196 runtime.forEach(from, function (target) {
5197 target.classList.remove(classRef.className());
5198 });
5199 });
5200 } else {
5201 runtime.forEach(from, function (target) {
5202 target.removeAttribute(attributeRef.name);
5203 });
5204 }
5205 return runtime.findNext(this, context);
5206 },
5207 };
5208 }
5209 return removeCmd;
5210 }
5211 });
5212
5213 _hyperscript.addCommand("toggle", function (parser, runtime, tokens) {
5214 if (tokens.matchToken("toggle")) {
5215 if (tokens.matchToken("between")) {
5216 var between = true;
5217 var classRef = parser.parseElement("classRef", tokens);
5218 tokens.requireToken("and");
5219 var classRef2 = parser.requireElement("classRef", tokens);
5220 } else {
5221 var classRef = parser.parseElement("classRef", tokens);
5222 var attributeRef = null;
5223 if (classRef == null) {
5224 attributeRef = parser.parseElement("attributeRef", tokens);
5225 if (attributeRef == null) {
5226 parser.raiseParseError(tokens, "Expected either a class reference or attribute expression");
5227 }
5228 } else {
5229 var classRefs = [classRef];
5230 while ((classRef = parser.parseElement("classRef", tokens))) {
5231 classRefs.push(classRef);
5232 }
5233 }
5234 }
5235
5236 if (tokens.matchToken("on")) {
5237 var on = parser.requireElement("expression", tokens);
5238 } else {
5239 var on = parser.requireElement("implicitMeTarget", tokens);
5240 }
5241
5242 if (tokens.matchToken("for")) {
5243 var time = parser.requireElement("timeExpression", tokens);
5244 } else if (tokens.matchToken("until")) {
5245 var evt = parser.requireElement("dotOrColonPath", tokens, "Expected event name");
5246 if (tokens.matchToken("from")) {
5247 var from = parser.requireElement("expression", tokens);
5248 }
5249 }
5250
5251 var toggleCmd = {
5252 classRef: classRef,
5253 classRef2: classRef2,
5254 classRefs: classRefs,
5255 attributeRef: attributeRef,
5256 on: on,
5257 time: time,
5258 evt: evt,
5259 from: from,
5260 toggle: function (on) {
5261 if (between) {
5262 runtime.forEach(on, function (target) {
5263 if (target.classList.contains(classRef.className())) {
5264 target.classList.remove(classRef.className());
5265 target.classList.add(classRef2.className());
5266 } else {
5267 target.classList.add(classRef.className());
5268 target.classList.remove(classRef2.className());
5269 }
5270 });
5271 } else if (this.classRefs) {
5272 runtime.forEach(this.classRefs, function (classRef) {
5273 runtime.forEach(on, function (target) {
5274 target.classList.toggle(classRef.className());
5275 });
5276 });
5277 } else {
5278 runtime.forEach(on, function (target) {
5279 if (target.hasAttribute(attributeRef.name)) {
5280 target.removeAttribute(attributeRef.name);
5281 } else {
5282 target.setAttribute(attributeRef.name, attributeRef.value);
5283 }
5284 });
5285 }
5286 },
5287 args: [on, time, evt, from],
5288 op: function (context, on, time, evt, from) {
5289 if (time) {
5290 return new Promise(function (resolve) {
5291 toggleCmd.toggle(on);
5292 setTimeout(function () {
5293 toggleCmd.toggle(on);
5294 resolve(runtime.findNext(toggleCmd, context));
5295 }, time);
5296 });
5297 } else if (evt) {
5298 return new Promise(function (resolve) {
5299 var target = from || context.me;
5300 target.addEventListener(
5301 evt,
5302 function () {
5303 toggleCmd.toggle(on);
5304 resolve(runtime.findNext(toggleCmd, context));
5305 },
5306 { once: true }
5307 );
5308 toggleCmd.toggle(on);
5309 });
5310 } else {
5311 this.toggle(on);
5312 return runtime.findNext(toggleCmd, context);
5313 }
5314 },
5315 };
5316 return toggleCmd;
5317 }
5318 });
5319
5320 var HIDE_SHOW_STRATEGIES = {
5321 display: function (op, element, arg) {
5322 if (arg) {
5323 element.style.display = arg;
5324 } else if (op === "hide") {
5325 element.style.display = "none";
5326 } else {
5327 element.style.display = "block";
5328 }
5329 },
5330 visibility: function (op, element, arg) {
5331 if (arg) {
5332 element.style.visibility = arg;
5333 } else if (op === "hide") {
5334 element.style.visibility = "hidden";
5335 } else {
5336 element.style.visibility = "visible";
5337 }
5338 },
5339 opacity: function (op, element, arg) {
5340 if (arg) {
5341 element.style.opacity = arg;
5342 } else if (op === "hide") {
5343 element.style.opacity = "0";
5344 } else {
5345 element.style.opacity = "1";
5346 }
5347 },
5348 };
5349
5350 var parseShowHideTarget = function (parser, runtime, tokens) {
5351 var target;
5352 var currentTokenValue = tokens.currentToken();
5353 if (currentTokenValue.value === "with" || parser.commandBoundary(currentTokenValue)) {
5354 target = parser.parseElement("implicitMeTarget", tokens);
5355 } else {
5356 target = parser.parseElement("expression", tokens);
5357 }
5358 return target;
5359 };
5360
5361 var resolveStrategy = function (parser, tokens, name) {
5362 var configDefault = _hyperscript.config.defaultHideShowStrategy;
5363 var strategies = HIDE_SHOW_STRATEGIES;
5364 if (_hyperscript.config.hideShowStrategies) {
5365 strategies = mergeObjects(strategies, _hyperscript.config.hideShowStrategies); // merge in user provided strategies
5366 }
5367 name = name || configDefault || "display";
5368 var value = strategies[name];
5369 if (value == null) {
5370 parser.raiseParseError(tokens, "Unknown show/hide strategy : " + name);
5371 }
5372 return value;
5373 };
5374
5375 _hyperscript.addCommand("hide", function (parser, runtime, tokens) {
5376 if (tokens.matchToken("hide")) {
5377 var target = parseShowHideTarget(parser, runtime, tokens);
5378
5379 var name = null;
5380 if (tokens.matchToken("with")) {
5381 name = tokens.requireTokenType("IDENTIFIER").value;
5382 }
5383 var hideShowStrategy = resolveStrategy(parser, tokens, name);
5384
5385 return {
5386 target: target,
5387 args: [target],
5388 op: function (ctx, target) {
5389 runtime.forEach(target, function (elt) {
5390 hideShowStrategy("hide", elt);
5391 });
5392 return runtime.findNext(this, ctx);
5393 },
5394 };
5395 }
5396 });
5397
5398 _hyperscript.addCommand("show", function (parser, runtime, tokens) {
5399 if (tokens.matchToken("show")) {
5400 var target = parseShowHideTarget(parser, runtime, tokens);
5401
5402 var name = null;
5403 if (tokens.matchToken("with")) {
5404 name = tokens.requireTokenType("IDENTIFIER").value;
5405 }
5406 var arg = null;
5407 if (tokens.matchOpToken(":")) {
5408 var tokenArr = tokens.consumeUntilWhitespace();
5409 tokens.matchTokenType("WHITESPACE");
5410 arg = tokenArr
5411 .map(function (t) {
5412 return t.value;
5413 })
5414 .join("");
5415 }
5416 var hideShowStrategy = resolveStrategy(parser, tokens, name);
5417
5418 return {
5419 target: target,
5420 args: [target],
5421 op: function (ctx, target) {
5422 runtime.forEach(target, function (elt) {
5423 hideShowStrategy("show", elt, arg);
5424 });
5425 return runtime.findNext(this, ctx);
5426 },
5427 };
5428 }
5429 });
5430
5431 _hyperscript.addCommand("trigger", function (parser, runtime, tokens) {
5432 if (tokens.matchToken("trigger")) {
5433 var eventName = parser.requireElement("eventName", tokens);
5434 var details = parser.parseElement("namedArgumentList", tokens);
5435
5436 var triggerCmd = {
5437 eventName: eventName,
5438 details: details,
5439 args: [eventName, details],
5440 op: function (context, eventNameStr, details) {
5441 runtime.triggerEvent(context.me, eventNameStr, details ? details : {});
5442 return runtime.findNext(triggerCmd, context);
5443 },
5444 };
5445 return triggerCmd;
5446 }
5447 });
5448
5449 _hyperscript.addCommand("take", function (parser, runtime, tokens) {
5450 if (tokens.matchToken("take")) {
5451 var classRef = parser.parseElement("classRef", tokens);
5452
5453 if (tokens.matchToken("from")) {
5454 var from = parser.requireElement("expression", tokens);
5455 } else {
5456 var from = classRef;
5457 }
5458
5459 if (tokens.matchToken("for")) {
5460 var forElt = parser.requireElement("expression", tokens);
5461 } else {
5462 var forElt = parser.requireElement("implicitMeTarget", tokens);
5463 }
5464
5465 var takeCmd = {
5466 classRef: classRef,
5467 from: from,
5468 forElt: forElt,
5469 args: [from, forElt],
5470 op: function (context, from, forElt) {
5471 var clazz = this.classRef.css.substr(1);
5472 runtime.forEach(from, function (target) {
5473 target.classList.remove(clazz);
5474 });
5475 runtime.forEach(forElt, function (target) {
5476 target.classList.add(clazz);
5477 });
5478 return runtime.findNext(this, context);
5479 },
5480 };
5481 return takeCmd;
5482 }
5483 });
5484
5485 function putInto(context, prop, valueToPut) {
5486 if (prop) {
5487 var value = context[prop];
5488 } else {
5489 var value = context;
5490 }
5491 if (value instanceof Element || value instanceof HTMLDocument) {
5492 while (value.firstChild) value.removeChild(value.firstChild);
5493 value.append(_hyperscript.internals.runtime.convertValue(valueToPut, "Fragment"));
5494 } else {
5495 if (prop) {
5496 context[prop] = valueToPut;
5497 } else {
5498 throw "Don't know how to put a value into " + typeof context;
5499 }
5500 }
5501 }
5502
5503 _hyperscript.addCommand("put", function (parser, runtime, tokens) {
5504 if (tokens.matchToken("put")) {
5505 var value = parser.requireElement("expression", tokens);
5506
5507 var operationToken = tokens.matchAnyToken("into", "before", "after");
5508
5509 if (operationToken == null && tokens.matchToken("at")) {
5510 operationToken = tokens.matchAnyToken("start", "end");
5511 tokens.requireToken("of");
5512 }
5513
5514 if (operationToken == null) {
5515 parser.raiseParseError(tokens, "Expected one of 'into', 'before', 'at start of', 'at end of', 'after'");
5516 }
5517 var target = parser.requireElement("expression", tokens);
5518
5519 var operation = operationToken.value;
5520
5521 var symbolWrite = false;
5522 var root = null;
5523 var prop = null;
5524 if (target.type === "propertyAccess" && operation === "into") {
5525 prop = target.prop.value;
5526 root = target.root;
5527 } else if (target.type === "symbol" && operation === "into") {
5528 symbolWrite = true;
5529 prop = target.name;
5530 } else if (target.type === "attributeRef" && operation === "into") {
5531 var attributeWrite = true;
5532 prop = target.name;
5533 root = parser.requireElement("implicitMeTarget", tokens);
5534 } else if (target.type === "attributeRefAccess" && operation === "into") {
5535 var attributeWrite = true;
5536 prop = target.attribute.name;
5537 root = target.root;
5538 } else {
5539 root = target;
5540 }
5541
5542 var putCmd = {
5543 target: target,
5544 operation: operation,
5545 symbolWrite: symbolWrite,
5546 value: value,
5547 args: [root, value],
5548 op: function (context, root, valueToPut) {
5549 if (symbolWrite) {
5550 putInto(context, prop, valueToPut);
5551 } else {
5552 if (operation === "into") {
5553 if (attributeWrite) {
5554 runtime.forEach(root, function (elt) {
5555 elt.setAttribute(prop, valueToPut);
5556 });
5557 } else {
5558 runtime.forEach(root, function (elt) {
5559 putInto(elt, prop, valueToPut);
5560 });
5561 }
5562 } else {
5563 var op =
5564 operation === "before"
5565 ? Element.prototype.before
5566 : operation === "after"
5567 ? Element.prototype.after
5568 : operation === "start"
5569 ? Element.prototype.prepend
5570 : operation === "end"
5571 ? Element.prototype.append
5572 : "unreachable";
5573
5574 runtime.forEach(root, function (elt) {
5575 op.call(
5576 elt,
5577 valueToPut instanceof Node
5578 ? valueToPut
5579 : runtime.convertValue(valueToPut, "Fragment")
5580 );
5581 });
5582 }
5583 }
5584 return runtime.findNext(this, context);
5585 },
5586 };
5587 return putCmd;
5588 }
5589 });
5590
5591 function parsePseudopossessiveTarget(parser, runtime, tokens) {
5592 if (
5593 tokens.matchToken("the") ||
5594 tokens.matchToken("element") ||
5595 tokens.matchToken("elements") ||
5596 tokens.currentToken().type === "CLASS_REF" ||
5597 tokens.currentToken().type === "ID_REF" ||
5598 (tokens.currentToken().op && tokens.currentToken().value === "<")
5599 ) {
5600 parser.possessivesDisabled = true;
5601 try {
5602 var targets = parser.parseElement("expression", tokens);
5603 } finally {
5604 delete parser.possessivesDisabled;
5605 }
5606 // optional possessive
5607 if (tokens.matchOpToken("'")) {
5608 tokens.requireToken("s");
5609 }
5610 } else if (tokens.currentToken().type === "IDENTIFIER" && tokens.currentToken().value === "its") {
5611 var identifier = tokens.matchToken("its");
5612 var targets = {
5613 type: "pseudopossessiveIts",
5614 token: identifier,
5615 name: identifier.value,
5616 evaluate: function (context) {
5617 return runtime.resolveSymbol("it", context);
5618 },
5619 };
5620 } else {
5621 tokens.matchToken("my") || tokens.matchToken("me"); // consume optional 'my'
5622 var targets = parser.parseElement("implicitMeTarget", tokens);
5623 }
5624 return targets;
5625 }
5626
5627 _hyperscript.addCommand("transition", function (parser, runtime, tokens) {
5628 if (tokens.matchToken("transition")) {
5629 var targets = parsePseudopossessiveTarget(parser, runtime, tokens);
5630
5631 var properties = [];
5632 var from = [];
5633 var to = [];
5634 var currentToken = tokens.currentToken();
5635 while (
5636 !parser.commandBoundary(currentToken) &&
5637 currentToken.value !== "over" &&
5638 currentToken.value !== "using"
5639 ) {
5640 properties.push(parser.requireElement("stringLike", tokens));
5641
5642 if (tokens.matchToken("from")) {
5643 from.push(parser.requireElement("stringLike", tokens));
5644 } else {
5645 from.push(null);
5646 }
5647 tokens.requireToken("to");
5648 to.push(parser.requireElement("stringLike", tokens));
5649 currentToken = tokens.currentToken();
5650 }
5651 if (tokens.matchToken("over")) {
5652 var over = parser.requireElement("timeExpression", tokens);
5653 } else if (tokens.matchToken("using")) {
5654 var using = parser.requireElement("expression", tokens);
5655 }
5656
5657 var transition = {
5658 to: to,
5659 args: [targets, properties, from, to, using, over],
5660 op: function (context, targets, properties, from, to, using, over) {
5661 var promises = [];
5662 runtime.forEach(targets, function (target) {
5663 var promise = new Promise(function (resolve, reject) {
5664 var initialTransition = target.style.transition;
5665 if (over) {
5666 target.style.transition = "all " + over + "ms ease-in";
5667 } else if (using) {
5668 target.style.transition = using;
5669 } else {
5670 target.style.transition = _hyperscript.config.defaultTransition;
5671 }
5672 var internalData = runtime.getInternalData(target);
5673 var computedStyles = getComputedStyle(target);
5674
5675 var initialStyles = {};
5676 for (var i = 0; i < computedStyles.length; i++) {
5677 var name = computedStyles[i];
5678 var initialValue = computedStyles[name];
5679 initialStyles[name] = initialValue;
5680 }
5681
5682 // store intitial values
5683 if (!internalData.initalStyles) {
5684 internalData.initalStyles = initialStyles;
5685 }
5686
5687 for (var i = 0; i < properties.length; i++) {
5688 var property = properties[i];
5689 var fromVal = from[i];
5690 if (fromVal == "computed" || fromVal == null) {
5691 target.style[property] = initialStyles[property];
5692 } else {
5693 target.style[property] = fromVal;
5694 }
5695 }
5696 // console.log("transition started", transition);
5697 setTimeout(function () {
5698 var autoProps = [];
5699 for (var i = 0; i < properties.length; i++) {
5700 var property = properties[i];
5701 var toVal = to[i];
5702 if (toVal == "initial") {
5703 var propertyValue = internalData.initalStyles[property];
5704 target.style[property] = propertyValue;
5705 } else {
5706 target.style[property] = toVal;
5707 }
5708 // console.log("set", property, "to", target.style[property], "on", target, "value passed in : ", toVal);
5709 }
5710 target.addEventListener(
5711 "transitionend",
5712 function () {
5713 // console.log("transition ended", transition);
5714 target.style.transition = initialTransition;
5715 resolve();
5716 },
5717 { once: true }
5718 );
5719 }, 5);
5720 });
5721 promises.push(promise);
5722 });
5723 return Promise.all(promises).then(function () {
5724 return runtime.findNext(transition, context);
5725 });
5726 },
5727 };
5728 return transition;
5729 }
5730 });
5731
5732 _hyperscript.addCommand("measure", function (parser, runtime, tokens) {
5733 if (!tokens.matchToken("measure")) return;
5734
5735 var target = parsePseudopossessiveTarget(parser, runtime, tokens);
5736
5737 var propsToMeasure = [];
5738 if (!parser.commandBoundary(tokens.currentToken()))
5739 do {
5740 propsToMeasure.push(tokens.matchTokenType("IDENTIFIER").value);
5741 } while (tokens.matchOpToken(","));
5742
5743 return {
5744 properties: propsToMeasure,
5745 args: [target],
5746 op: function (ctx, target) {
5747 if (0 in target) target = target[0]; // not measuring multiple elts
5748 var rect = target.getBoundingClientRect();
5749 var scroll = {
5750 top: target.scrollTop,
5751 left: target.scrollLeft,
5752 topMax: target.scrollTopMax,
5753 leftMax: target.scrollLeftMax,
5754 height: target.scrollHeight,
5755 width: target.scrollWidth,
5756 };
5757
5758 ctx.result = {
5759 x: rect.x,
5760 y: rect.y,
5761 left: rect.left,
5762 top: rect.top,
5763 right: rect.right,
5764 bottom: rect.bottom,
5765 width: rect.width,
5766 height: rect.height,
5767 bounds: rect,
5768
5769 scrollLeft: scroll.left,
5770 scrollTop: scroll.top,
5771 scrollLeftMax: scroll.leftMax,
5772 scrollTopMax: scroll.topMax,
5773 scrollWidth: scroll.width,
5774 scrollHeight: scroll.height,
5775 scroll: scroll,
5776 };
5777
5778 runtime.forEach(propsToMeasure, function (prop) {
5779 if (prop in ctx.result) ctx[prop] = ctx.result[prop];
5780 else throw "No such measurement as " + prop;
5781 });
5782
5783 return runtime.findNext(this, ctx);
5784 },
5785 };
5786 });
5787
5788 _hyperscript.addLeafExpression("closestExpr", function (parser, runtime, tokens) {
5789 if (tokens.matchToken("closest")) {
5790 if (tokens.matchToken("parent")) {
5791 var parentSearch = true;
5792 }
5793
5794 var css = null;
5795 if (tokens.currentToken().type === "ATTRIBUTE_REF") {
5796 var attributeRef = parser.parseElement("attributeRefAccess", tokens, null);
5797 css = "[" + attributeRef.attribute.name + "]";
5798 }
5799
5800 if (css == null) {
5801 var expr = parser.parseElement("expression", tokens);
5802 if (expr.css == null) {
5803 parser.raiseParseError(tokens, "Expected a CSS expression");
5804 } else {
5805 css = expr.css;
5806 }
5807 }
5808
5809 if (tokens.matchToken("to")) {
5810 var to = parser.parseElement("expression", tokens);
5811 } else {
5812 var to = parser.parseElement("implicitMeTarget", tokens);
5813 }
5814
5815 var closestExpr = {
5816 type: "closestExpr",
5817 parentSearch: parentSearch,
5818 expr: expr,
5819 css: css,
5820 to: to,
5821 args: [to],
5822 op: function (ctx, to) {
5823 if (to == null || !(to instanceof Element)) {
5824 return null;
5825 } else {
5826 if (parentSearch) {
5827 var node = to.parentElement ? to.parentElement.closest(css) : null;
5828 } else {
5829 var node = to.closest(css);
5830 }
5831 return node;
5832 }
5833 },
5834 evaluate: function (context) {
5835 return runtime.unifiedEval(this, context);
5836 },
5837 };
5838
5839 if (attributeRef) {
5840 attributeRef.root = closestExpr;
5841 attributeRef.args = [closestExpr];
5842 return attributeRef;
5843 } else {
5844 return closestExpr;
5845 }
5846 }
5847 });
5848
5849 _hyperscript.addCommand("go", function (parser, runtime, tokens) {
5850 if (tokens.matchToken("go")) {
5851 if (tokens.matchToken("back")) {
5852 var back = true;
5853 } else {
5854 tokens.matchToken("to");
5855 if (tokens.matchToken("url")) {
5856 var target = parser.requireElement("stringLike", tokens);
5857 var url = true;
5858 if (tokens.matchToken("in")) {
5859 tokens.requireToken("new");
5860 tokens.requireToken("window");
5861 var newWindow = true;
5862 }
5863 } else {
5864 tokens.matchToken("the"); // optional the
5865 var verticalPosition = tokens.matchAnyToken("top", "bottom", "middle");
5866 var horizontalPosition = tokens.matchAnyToken("left", "center", "right");
5867 if (verticalPosition || horizontalPosition) {
5868 tokens.requireToken("of");
5869 }
5870 var target = parser.requireElement("expression", tokens);
5871 var smoothness = tokens.matchAnyToken("smoothly", "instantly");
5872
5873 var scrollOptions = {};
5874 if (verticalPosition) {
5875 if (verticalPosition.value === "top") {
5876 scrollOptions.block = "start";
5877 } else if (verticalPosition.value === "bottom") {
5878 scrollOptions.block = "end";
5879 } else if (verticalPosition.value === "middle") {
5880 scrollOptions.block = "center";
5881 }
5882 }
5883
5884 if (horizontalPosition) {
5885 if (horizontalPosition.value === "left") {
5886 scrollOptions.inline = "start";
5887 } else if (horizontalPosition.value === "center") {
5888 scrollOptions.inline = "center";
5889 } else if (horizontalPosition.value === "right") {
5890 scrollOptions.inline = "end";
5891 }
5892 }
5893
5894 if (smoothness) {
5895 if (smoothness.value === "smoothly") {
5896 scrollOptions.behavior = "smooth";
5897 } else if (smoothness.value === "instantly") {
5898 scrollOptions.behavior = "instant";
5899 }
5900 }
5901 }
5902 }
5903
5904 var goCmd = {
5905 target: target,
5906 args: [target],
5907 op: function (ctx, to) {
5908 if (back) {
5909 window.history.back();
5910 } else if (url) {
5911 if (to) {
5912 if (to.indexOf("#") === 0 && !newWindow) {
5913 window.location.href = to;
5914 } else {
5915 window.open(to, newWindow ? "_blank" : null);
5916 }
5917 }
5918 } else {
5919 runtime.forEach(to, function (target) {
5920 target.scrollIntoView(scrollOptions);
5921 });
5922 }
5923 return runtime.findNext(goCmd);
5924 },
5925 };
5926 return goCmd;
5927 }
5928 });
5929
5930 _hyperscript.config.conversions["Values"] = function (/** @type {Node | NodeList} */ node) {
5931 /** @type Object<string,string | string[]> */
5932 var result = {};
5933
5934 var forEach = _hyperscript.internals.runtime.forEach;
5935
5936 forEach(node, function (/** @type HTMLInputElement */ node) {
5937 // Try to get a value directly from this node
5938 var input = getInputInfo(node);
5939
5940 if (input !== undefined) {
5941 result[input.name] = input.value;
5942 return;
5943 }
5944
5945 // Otherwise, try to query all child elements of this node that *should* contain values.
5946 if (node.querySelectorAll != undefined) {
5947 var children = node.querySelectorAll("input,select,textarea");
5948 forEach(children, appendValue);
5949 }
5950 });
5951
5952 return result;
5953
5954 /**
5955 * @param {HTMLInputElement} node
5956 */
5957 function appendValue(node) {
5958 var info = getInputInfo(node);
5959
5960 if (info == undefined) {
5961 return;
5962 }
5963
5964 // If there is no value already stored in this space.
5965 if (result[info.name] == undefined) {
5966 result[info.name] = info.value;
5967 return;
5968 }
5969
5970 if (Array.isArray(result[info.name]) && Array.isArray(info.value)) {
5971 result[info.name] = [].concat(result[info.name], info.value);
5972 return;
5973 }
5974 }
5975
5976 /**
5977 * @param {HTMLInputElement} node
5978 * @returns {{name:string, value:string | string[]} | undefined}
5979 */
5980 function getInputInfo(node) {
5981 try {
5982 /** @type {{name: string, value: string | string[]}}*/
5983 var result = {
5984 name: node.name,
5985 value: node.value,
5986 };
5987
5988 if (result.name == undefined || result.value == undefined) {
5989 return undefined;
5990 }
5991
5992 if (node.type == "radio" && node.checked == false) {
5993 return undefined;
5994 }
5995
5996 if (node.type == "checkbox") {
5997 if (node.checked == false) {
5998 result.value = undefined;
5999 } else if (typeof result.value === "string") {
6000 result.value = [result.value];
6001 }
6002 }
6003
6004 if (node.type == "select-multiple") {
6005 /** @type {NodeListOf<HTMLSelectElement>} */
6006 var selected = node.querySelectorAll("option[selected]");
6007
6008 result.value = [];
6009 for (var index = 0; index < selected.length; index++) {
6010 result.value.push(selected[index].value);
6011 }
6012 }
6013 return result;
6014 } catch (e) {
6015 return undefined;
6016 }
6017 }
6018 };
6019
6020 _hyperscript.config.conversions["HTML"] = function (value) {
6021 var toHTML = /** @returns {string}*/ function (/** @type any*/ value) {
6022 if (value instanceof Array) {
6023 return value
6024 .map(function (item) {
6025 return toHTML(item);
6026 })
6027 .join("");
6028 }
6029
6030 if (value instanceof HTMLElement) {
6031 return value.outerHTML;
6032 }
6033
6034 if (value instanceof NodeList) {
6035 var result = "";
6036 for (var i = 0; i < value.length; i++) {
6037 var node = value[i];
6038 if (node instanceof HTMLElement) {
6039 result += node.outerHTML;
6040 }
6041 }
6042 return result;
6043 }
6044
6045 if (value.toString) {
6046 return value.toString();
6047 }
6048
6049 return "";
6050 };
6051
6052 return toHTML(value);
6053 };
6054
6055 _hyperscript.config.conversions["Fragment"] = function (val) {
6056 var frag = document.createDocumentFragment();
6057 _hyperscript.internals.runtime.forEach(val, function (val) {
6058 if (val instanceof Node) frag.append(val);
6059 else {
6060 var temp = document.createElement("template");
6061 temp.innerHTML = val;
6062 frag.append(temp.content);
6063 }
6064 });
6065 return frag;
6066 };
6067 })();