@builder.io/mitosis 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/dist/src/constants/media-sizes.js +4 -5
  2. package/dist/src/generators/alpine/generate.js +114 -132
  3. package/dist/src/generators/alpine/render-mount-hook.js +8 -5
  4. package/dist/src/generators/alpine/render-update-hooks.js +13 -13
  5. package/dist/src/generators/angular/helpers.js +19 -9
  6. package/dist/src/generators/angular/index.js +599 -584
  7. package/dist/src/generators/builder.js +200 -165
  8. package/dist/src/generators/context/angular.js +32 -26
  9. package/dist/src/generators/context/helpers/context-with-symbol-key.js +25 -21
  10. package/dist/src/generators/context/qwik.js +21 -21
  11. package/dist/src/generators/context/react.js +22 -22
  12. package/dist/src/generators/context/rsc.js +20 -22
  13. package/dist/src/generators/context/solid.js +22 -22
  14. package/dist/src/generators/context/svelte.js +33 -28
  15. package/dist/src/generators/context/vue.js +1 -1
  16. package/dist/src/generators/helpers/context.js +6 -13
  17. package/dist/src/generators/helpers/functions.js +8 -8
  18. package/dist/src/generators/helpers/on-mount.js +9 -5
  19. package/dist/src/generators/helpers/rsc.js +7 -9
  20. package/dist/src/generators/html.js +995 -534
  21. package/dist/src/generators/liquid.js +81 -79
  22. package/dist/src/generators/lit/collect-class-string.js +10 -12
  23. package/dist/src/generators/lit/generate.js +204 -159
  24. package/dist/src/generators/marko/generate.js +193 -183
  25. package/dist/src/generators/minify.js +5 -9
  26. package/dist/src/generators/mitosis.js +135 -134
  27. package/dist/src/generators/qwik/component-generator.js +159 -154
  28. package/dist/src/generators/qwik/component.js +51 -81
  29. package/dist/src/generators/qwik/directives.js +68 -84
  30. package/dist/src/generators/qwik/helpers/add-prevent-default.js +6 -7
  31. package/dist/src/generators/qwik/helpers/convert-method-to-function.js +38 -38
  32. package/dist/src/generators/qwik/helpers/handlers.js +16 -25
  33. package/dist/src/generators/qwik/helpers/stable-inject.js +7 -8
  34. package/dist/src/generators/qwik/helpers/stable-serialize.js +7 -8
  35. package/dist/src/generators/qwik/helpers/state.js +36 -43
  36. package/dist/src/generators/qwik/helpers/styles.js +19 -40
  37. package/dist/src/generators/qwik/jsx.js +63 -75
  38. package/dist/src/generators/qwik/src-generator.js +134 -167
  39. package/dist/src/generators/react/blocks.js +122 -127
  40. package/dist/src/generators/react/generator.js +314 -259
  41. package/dist/src/generators/react/helpers.js +23 -28
  42. package/dist/src/generators/react/state.js +34 -51
  43. package/dist/src/generators/react-native/index.js +72 -84
  44. package/dist/src/generators/react-native/sanitize-react-native-block-styles.js +14 -26
  45. package/dist/src/generators/rsc.js +30 -36
  46. package/dist/src/generators/solid/blocks.js +46 -43
  47. package/dist/src/generators/solid/helpers/styles.js +11 -11
  48. package/dist/src/generators/solid/index.js +199 -190
  49. package/dist/src/generators/solid/state/helpers.js +76 -90
  50. package/dist/src/generators/solid/state/signals.js +30 -37
  51. package/dist/src/generators/solid/state/state.js +35 -48
  52. package/dist/src/generators/solid/state/store.js +40 -46
  53. package/dist/src/generators/stencil/collect-class-string.js +10 -12
  54. package/dist/src/generators/stencil/generate.js +158 -145
  55. package/dist/src/generators/svelte/blocks.js +146 -144
  56. package/dist/src/generators/svelte/helpers.js +10 -17
  57. package/dist/src/generators/svelte/svelte.js +321 -287
  58. package/dist/src/generators/swift-ui.js +162 -101
  59. package/dist/src/generators/taro.js +32 -36
  60. package/dist/src/generators/template.js +71 -74
  61. package/dist/src/generators/vue/blocks.js +116 -107
  62. package/dist/src/generators/vue/compositionApi.js +67 -50
  63. package/dist/src/generators/vue/helpers.js +71 -96
  64. package/dist/src/generators/vue/optionsApi.js +134 -105
  65. package/dist/src/generators/vue/vue.js +210 -207
  66. package/dist/src/helpers/babel-transform.js +40 -63
  67. package/dist/src/helpers/bindings.js +4 -12
  68. package/dist/src/helpers/camel-case.js +4 -5
  69. package/dist/src/helpers/capitalize.js +1 -1
  70. package/dist/src/helpers/component-file-extensions.js +23 -35
  71. package/dist/src/helpers/create-mitosis-component.js +22 -26
  72. package/dist/src/helpers/create-mitosis-context.js +5 -12
  73. package/dist/src/helpers/create-mitosis-node.js +10 -12
  74. package/dist/src/helpers/dash-case.js +2 -2
  75. package/dist/src/helpers/dedent.js +18 -22
  76. package/dist/src/helpers/event-handlers.js +1 -1
  77. package/dist/src/helpers/fast-clone.js +1 -1
  78. package/dist/src/helpers/filter-empty-text-nodes.js +2 -2
  79. package/dist/src/helpers/generic-format.js +7 -8
  80. package/dist/src/helpers/get-bindings.js +4 -4
  81. package/dist/src/helpers/get-components-used.js +3 -3
  82. package/dist/src/helpers/get-components.js +4 -4
  83. package/dist/src/helpers/get-custom-imports.js +10 -12
  84. package/dist/src/helpers/get-prop-functions.js +7 -8
  85. package/dist/src/helpers/get-props-ref.js +8 -8
  86. package/dist/src/helpers/get-props.js +12 -13
  87. package/dist/src/helpers/get-refs.js +4 -4
  88. package/dist/src/helpers/get-state-object-string.js +42 -61
  89. package/dist/src/helpers/get-state-used.js +7 -8
  90. package/dist/src/helpers/get-styles.js +6 -6
  91. package/dist/src/helpers/getters-to-functions.js +8 -12
  92. package/dist/src/helpers/handle-missing-state.js +3 -3
  93. package/dist/src/helpers/has-bindings-text.js +6 -6
  94. package/dist/src/helpers/has-component.js +4 -4
  95. package/dist/src/helpers/has-props.js +3 -3
  96. package/dist/src/helpers/has-stateful-dom.js +4 -4
  97. package/dist/src/helpers/has.js +3 -3
  98. package/dist/src/helpers/indent.js +2 -3
  99. package/dist/src/helpers/is-children.js +4 -5
  100. package/dist/src/helpers/is-component.js +1 -1
  101. package/dist/src/helpers/is-html-attribute.js +2 -11
  102. package/dist/src/helpers/is-mitosis-node.js +1 -1
  103. package/dist/src/helpers/is-root-text-node.js +1 -1
  104. package/dist/src/helpers/is-upper-case.js +1 -1
  105. package/dist/src/helpers/is-valid-attribute-name.js +1 -1
  106. package/dist/src/helpers/json.js +2 -2
  107. package/dist/src/helpers/map-refs.js +29 -40
  108. package/dist/src/helpers/merge-options.js +20 -31
  109. package/dist/src/helpers/mitosis-imports.js +5 -6
  110. package/dist/src/helpers/nodes/for.js +2 -3
  111. package/dist/src/helpers/nullable.js +1 -3
  112. package/dist/src/helpers/on-event.js +32 -36
  113. package/dist/src/helpers/output.js +4 -5
  114. package/dist/src/helpers/parse-node.js +13 -5
  115. package/dist/src/helpers/parsers.js +10 -14
  116. package/dist/src/helpers/patterns.js +6 -8
  117. package/dist/src/helpers/plugins/process-code/index.js +114 -120
  118. package/dist/src/helpers/plugins/process-signals.js +114 -125
  119. package/dist/src/helpers/plugins/process-target-blocks.js +18 -20
  120. package/dist/src/helpers/process-http-requests.js +8 -4
  121. package/dist/src/helpers/remove-surrounding-block.js +2 -2
  122. package/dist/src/helpers/render-imports.js +99 -111
  123. package/dist/src/helpers/replace-identifiers.js +40 -49
  124. package/dist/src/helpers/replace-new-lines-in-strings.js +3 -3
  125. package/dist/src/helpers/signals/signals.js +27 -35
  126. package/dist/src/helpers/slots.js +11 -20
  127. package/dist/src/helpers/state.js +1 -3
  128. package/dist/src/helpers/strip-meta-properties.js +6 -6
  129. package/dist/src/helpers/strip-state-and-props-refs.js +21 -32
  130. package/dist/src/helpers/styles/collect-css.js +39 -44
  131. package/dist/src/helpers/styles/collect-styled-components.js +30 -28
  132. package/dist/src/helpers/styles/helpers.js +23 -29
  133. package/dist/src/helpers/trace-reference-to-module-path.js +3 -4
  134. package/dist/src/helpers/transform-state-setters.js +16 -19
  135. package/dist/src/helpers/traverse-nodes.js +2 -2
  136. package/dist/src/helpers/try-prettier-format.js +3 -3
  137. package/dist/src/helpers/typescript-project.js +25 -25
  138. package/dist/src/helpers/typescript.js +1 -3
  139. package/dist/src/modules/plugins.js +20 -28
  140. package/dist/src/parsers/angular.js +49 -57
  141. package/dist/src/parsers/builder/builder.js +448 -343
  142. package/dist/src/parsers/builder/helpers.js +10 -10
  143. package/dist/src/parsers/context.js +15 -17
  144. package/dist/src/parsers/jsx/ast.js +11 -11
  145. package/dist/src/parsers/jsx/component-types.js +22 -32
  146. package/dist/src/parsers/jsx/context.js +12 -12
  147. package/dist/src/parsers/jsx/element-parser.js +43 -54
  148. package/dist/src/parsers/jsx/exports.js +12 -14
  149. package/dist/src/parsers/jsx/function-parser.js +108 -119
  150. package/dist/src/parsers/jsx/helpers.js +11 -13
  151. package/dist/src/parsers/jsx/hooks/helpers.js +14 -16
  152. package/dist/src/parsers/jsx/hooks/index.js +34 -44
  153. package/dist/src/parsers/jsx/hooks/use-target.js +27 -27
  154. package/dist/src/parsers/jsx/imports.js +7 -17
  155. package/dist/src/parsers/jsx/jsx.js +92 -91
  156. package/dist/src/parsers/jsx/props-types.js +8 -10
  157. package/dist/src/parsers/jsx/props.js +15 -23
  158. package/dist/src/parsers/jsx/signals.js +28 -29
  159. package/dist/src/parsers/jsx/state.d.ts +2 -4
  160. package/dist/src/parsers/jsx/state.js +59 -93
  161. package/dist/src/parsers/svelte/css/index.js +1 -1
  162. package/dist/src/parsers/svelte/helpers/bindings.js +18 -19
  163. package/dist/src/parsers/svelte/helpers/children.js +5 -6
  164. package/dist/src/parsers/svelte/helpers/expressions.js +7 -9
  165. package/dist/src/parsers/svelte/helpers/hooks.js +2 -2
  166. package/dist/src/parsers/svelte/helpers/post-process.js +49 -70
  167. package/dist/src/parsers/svelte/helpers/string.js +5 -5
  168. package/dist/src/parsers/svelte/html/actions.js +17 -10
  169. package/dist/src/parsers/svelte/html/each.js +11 -16
  170. package/dist/src/parsers/svelte/html/element.js +68 -78
  171. package/dist/src/parsers/svelte/html/fragment.js +3 -3
  172. package/dist/src/parsers/svelte/html/if-else.js +11 -18
  173. package/dist/src/parsers/svelte/html/index.js +14 -14
  174. package/dist/src/parsers/svelte/html/mustache-tag.js +5 -5
  175. package/dist/src/parsers/svelte/html/slot.js +5 -5
  176. package/dist/src/parsers/svelte/html/text.js +7 -14
  177. package/dist/src/parsers/svelte/index.js +23 -72
  178. package/dist/src/parsers/svelte/instance/context.js +17 -17
  179. package/dist/src/parsers/svelte/instance/expressions.js +2 -2
  180. package/dist/src/parsers/svelte/instance/functions.js +35 -30
  181. package/dist/src/parsers/svelte/instance/hooks.js +4 -5
  182. package/dist/src/parsers/svelte/instance/imports.js +11 -21
  183. package/dist/src/parsers/svelte/instance/index.js +22 -22
  184. package/dist/src/parsers/svelte/instance/properties.js +11 -23
  185. package/dist/src/parsers/svelte/instance/reactive.js +11 -11
  186. package/dist/src/parsers/svelte/instance/references.js +13 -13
  187. package/dist/src/parsers/svelte/instance/statements.js +3 -3
  188. package/dist/src/parsers/svelte/module/index.js +14 -26
  189. package/dist/src/parsers/svelte/typescript/index.js +27 -36
  190. package/dist/src/plugins/compile-away-builder-components.js +223 -156
  191. package/dist/src/plugins/compile-away-components.js +13 -21
  192. package/dist/src/plugins/map-styles.js +7 -7
  193. package/dist/src/symbols/symbol-processor.js +44 -62
  194. package/dist/src/targets.js +19 -19
  195. package/dist/src/types/mitosis-node.js +1 -1
  196. package/package.json +1 -1
@@ -1,108 +1,97 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
14
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
15
- if (ar || !(i in from)) {
16
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
17
- ar[i] = from[i];
18
- }
19
- }
20
- return to.concat(ar || Array.prototype.slice.call(from));
21
- };
22
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
23
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
4
  };
25
5
  Object.defineProperty(exports, "__esModule", { value: true });
26
6
  exports.componentToCustomElement = exports.componentToHtml = void 0;
27
- var core_1 = require("@babel/core");
28
- var function_1 = require("fp-ts/lib/function");
29
- var lodash_1 = require("lodash");
30
- var legacy_1 = __importDefault(require("neotraverse/legacy"));
31
- var standalone_1 = require("prettier/standalone");
32
- var html_tags_1 = require("../constants/html_tags");
33
- var babel_transform_1 = require("../helpers/babel-transform");
34
- var dash_case_1 = require("../helpers/dash-case");
35
- var fast_clone_1 = require("../helpers/fast-clone");
36
- var get_prop_functions_1 = require("../helpers/get-prop-functions");
37
- var get_props_1 = require("../helpers/get-props");
38
- var get_props_ref_1 = require("../helpers/get-props-ref");
39
- var get_refs_1 = require("../helpers/get-refs");
40
- var get_state_object_string_1 = require("../helpers/get-state-object-string");
41
- var has_bindings_text_1 = require("../helpers/has-bindings-text");
42
- var has_component_1 = require("../helpers/has-component");
43
- var has_props_1 = require("../helpers/has-props");
44
- var has_stateful_dom_1 = require("../helpers/has-stateful-dom");
45
- var is_children_1 = __importDefault(require("../helpers/is-children"));
46
- var is_component_1 = require("../helpers/is-component");
47
- var is_html_attribute_1 = require("../helpers/is-html-attribute");
48
- var is_mitosis_node_1 = require("../helpers/is-mitosis-node");
49
- var map_refs_1 = require("../helpers/map-refs");
50
- var merge_options_1 = require("../helpers/merge-options");
51
- var for_1 = require("../helpers/nodes/for");
52
- var remove_surrounding_block_1 = require("../helpers/remove-surrounding-block");
53
- var render_imports_1 = require("../helpers/render-imports");
54
- var strip_meta_properties_1 = require("../helpers/strip-meta-properties");
55
- var strip_state_and_props_refs_1 = require("../helpers/strip-state-and-props-refs");
56
- var collect_css_1 = require("../helpers/styles/collect-css");
57
- var plugins_1 = require("../modules/plugins");
58
- var mitosis_node_1 = require("../types/mitosis-node");
59
- var on_mount_1 = require("./helpers/on-mount");
60
- var isAttribute = function (key) {
7
+ const core_1 = require("@babel/core");
8
+ const function_1 = require("fp-ts/lib/function");
9
+ const lodash_1 = require("lodash");
10
+ const legacy_1 = __importDefault(require("neotraverse/legacy"));
11
+ const standalone_1 = require("prettier/standalone");
12
+ const html_tags_1 = require("../constants/html_tags");
13
+ const babel_transform_1 = require("../helpers/babel-transform");
14
+ const dash_case_1 = require("../helpers/dash-case");
15
+ const fast_clone_1 = require("../helpers/fast-clone");
16
+ const get_prop_functions_1 = require("../helpers/get-prop-functions");
17
+ const get_props_1 = require("../helpers/get-props");
18
+ const get_props_ref_1 = require("../helpers/get-props-ref");
19
+ const get_refs_1 = require("../helpers/get-refs");
20
+ const get_state_object_string_1 = require("../helpers/get-state-object-string");
21
+ const has_bindings_text_1 = require("../helpers/has-bindings-text");
22
+ const has_component_1 = require("../helpers/has-component");
23
+ const has_props_1 = require("../helpers/has-props");
24
+ const has_stateful_dom_1 = require("../helpers/has-stateful-dom");
25
+ const is_children_1 = __importDefault(require("../helpers/is-children"));
26
+ const is_component_1 = require("../helpers/is-component");
27
+ const is_html_attribute_1 = require("../helpers/is-html-attribute");
28
+ const is_mitosis_node_1 = require("../helpers/is-mitosis-node");
29
+ const map_refs_1 = require("../helpers/map-refs");
30
+ const merge_options_1 = require("../helpers/merge-options");
31
+ const for_1 = require("../helpers/nodes/for");
32
+ const remove_surrounding_block_1 = require("../helpers/remove-surrounding-block");
33
+ const render_imports_1 = require("../helpers/render-imports");
34
+ const strip_meta_properties_1 = require("../helpers/strip-meta-properties");
35
+ const strip_state_and_props_refs_1 = require("../helpers/strip-state-and-props-refs");
36
+ const collect_css_1 = require("../helpers/styles/collect-css");
37
+ const plugins_1 = require("../modules/plugins");
38
+ const mitosis_node_1 = require("../types/mitosis-node");
39
+ const on_mount_1 = require("./helpers/on-mount");
40
+ const isAttribute = (key) => {
61
41
  return /-/.test(key);
62
42
  };
63
- var ATTRIBUTE_KEY_EXCEPTIONS_MAP = {
43
+ const ATTRIBUTE_KEY_EXCEPTIONS_MAP = {
64
44
  class: 'className',
65
45
  innerHtml: 'innerHTML',
66
46
  };
67
- var updateKeyIfException = function (key) {
47
+ const updateKeyIfException = (key) => {
68
48
  var _a;
69
49
  return (_a = ATTRIBUTE_KEY_EXCEPTIONS_MAP[key]) !== null && _a !== void 0 ? _a : key;
70
50
  };
71
- var generateSetElementAttributeCode = function (key, tagName, useValue, options, meta) {
51
+ const generateSetElementAttributeCode = (key, tagName, useValue, options, meta = {}) => {
72
52
  var _a, _b;
73
- if (meta === void 0) { meta = {}; }
74
53
  if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.props) {
75
54
  return (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.props(key, useValue, options);
76
55
  }
77
- var isKey = key === 'key';
78
- var ignoreKey = /^(innerHTML|key|class|value)$/.test(key);
79
- var isTextarea = key === 'value' && tagName === 'textarea';
80
- var isDataSet = /^data-/.test(key);
81
- var isComponent = Boolean(meta === null || meta === void 0 ? void 0 : meta.component);
82
- var isHtmlAttr = (0, is_html_attribute_1.isHtmlAttribute)(key, tagName);
83
- var setAttr = !ignoreKey && (isHtmlAttr || !isTextarea || isAttribute(key));
56
+ const isKey = key === 'key';
57
+ const ignoreKey = /^(innerHTML|key|class|value)$/.test(key);
58
+ const isTextarea = key === 'value' && tagName === 'textarea';
59
+ const isDataSet = /^data-/.test(key);
60
+ const isComponent = Boolean(meta === null || meta === void 0 ? void 0 : meta.component);
61
+ const isHtmlAttr = (0, is_html_attribute_1.isHtmlAttribute)(key, tagName);
62
+ const setAttr = !ignoreKey && (isHtmlAttr || !isTextarea || isAttribute(key));
84
63
  return [
85
64
  // is html attribute or dash-case
86
- setAttr ? ";el.setAttribute(\"".concat(key, "\", ").concat(useValue, ");") : '',
65
+ setAttr ? `;el.setAttribute("${key}", ${useValue});` : '',
87
66
  // not attr or dataset or html attr
88
67
  !setAttr || !(isHtmlAttr || isDataSet || !isComponent || isKey)
89
- ? "el.".concat(updateKeyIfException((0, lodash_1.camelCase)(key)), " = ").concat(useValue, ";")
68
+ ? `el.${updateKeyIfException((0, lodash_1.camelCase)(key))} = ${useValue};`
90
69
  : '',
91
70
  // is component but not html attribute
92
71
  isComponent && !isHtmlAttr
93
72
  ? // custom-element is created but we're in the middle of the update loop
94
- "\n if (el.props) {\n ;el.props.".concat((0, lodash_1.camelCase)(key), " = ").concat(useValue, ";\n if (el.update) {\n ;el.update();\n }\n } else {\n ;el.props = {};\n ;el.props.").concat((0, lodash_1.camelCase)(key), " = ").concat(useValue, ";\n }\n ")
73
+ `
74
+ if (el.props) {
75
+ ;el.props.${(0, lodash_1.camelCase)(key)} = ${useValue};
76
+ if (el.update) {
77
+ ;el.update();
78
+ }
79
+ } else {
80
+ ;el.props = {};
81
+ ;el.props.${(0, lodash_1.camelCase)(key)} = ${useValue};
82
+ }
83
+ `
95
84
  : '',
96
85
  ].join('\n');
97
86
  };
98
- var addUpdateAfterSet = function (json, options) {
87
+ const addUpdateAfterSet = (json, options) => {
99
88
  (0, legacy_1.default)(json).forEach(function (item) {
100
89
  var _a;
101
90
  if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
102
- for (var key in item.bindings) {
103
- var value = (_a = item.bindings[key]) === null || _a === void 0 ? void 0 : _a.code;
91
+ for (const key in item.bindings) {
92
+ const value = (_a = item.bindings[key]) === null || _a === void 0 ? void 0 : _a.code;
104
93
  if (value) {
105
- var newValue = addUpdateAfterSetInCode(value, options);
94
+ const newValue = addUpdateAfterSetInCode(value, options);
106
95
  if (newValue !== value) {
107
96
  item.bindings[key].code = newValue;
108
97
  }
@@ -111,11 +100,10 @@ var addUpdateAfterSet = function (json, options) {
111
100
  }
112
101
  });
113
102
  };
114
- var getChildComponents = function (json, options) {
115
- var childComponents = [];
116
- json.imports.forEach(function (_a) {
117
- var imports = _a.imports;
118
- Object.keys(imports).forEach(function (key) {
103
+ const getChildComponents = (json, options) => {
104
+ const childComponents = [];
105
+ json.imports.forEach(({ imports }) => {
106
+ Object.keys(imports).forEach((key) => {
119
107
  if (imports[key] === 'default') {
120
108
  childComponents.push(key);
121
109
  }
@@ -123,64 +111,60 @@ var getChildComponents = function (json, options) {
123
111
  });
124
112
  return childComponents;
125
113
  };
126
- var getScopeVars = function (parentScopeVars, value) {
127
- return parentScopeVars.filter(function (scopeVar) {
114
+ const getScopeVars = (parentScopeVars, value) => {
115
+ return parentScopeVars.filter((scopeVar) => {
128
116
  if (typeof value === 'boolean') {
129
117
  return value;
130
118
  }
131
- var checkVar = new RegExp('(\\.\\.\\.|,| |;|\\(|^|!)' + scopeVar + '(\\.|,| |;|\\)|$)', 'g');
119
+ const checkVar = new RegExp('(\\.\\.\\.|,| |;|\\(|^|!)' + scopeVar + '(\\.|,| |;|\\)|$)', 'g');
132
120
  return checkVar.test(value);
133
121
  });
134
122
  };
135
- var addScopeVars = function (parentScopeVars, value, fn) {
136
- return "".concat(getScopeVars(parentScopeVars, value)
137
- .map(function (scopeVar) {
123
+ const addScopeVars = (parentScopeVars, value, fn) => {
124
+ return `${getScopeVars(parentScopeVars, value)
125
+ .map((scopeVar) => {
138
126
  return fn(scopeVar);
139
127
  })
140
- .join('\n'));
128
+ .join('\n')}`;
141
129
  };
142
- var mappers = {
143
- Fragment: function (json, options, blockOptions) {
144
- return json.children.map(function (item) { return blockToHtml(item, options, blockOptions); }).join('\n');
130
+ const mappers = {
131
+ Fragment: (json, options, blockOptions) => {
132
+ return json.children.map((item) => blockToHtml(item, options, blockOptions)).join('\n');
145
133
  },
146
134
  };
147
- var getId = function (json, options) {
148
- var name = json.properties.$name
135
+ const getId = (json, options) => {
136
+ const name = json.properties.$name
149
137
  ? (0, dash_case_1.dashCase)(json.properties.$name)
150
138
  : /^h\d$/.test(json.name || '') // don't dashcase h1 into h-1
151
139
  ? json.name
152
140
  : (0, dash_case_1.dashCase)(json.name || 'div');
153
- var newNameNum = (options.namesMap[name] || 0) + 1;
141
+ const newNameNum = (options.namesMap[name] || 0) + 1;
154
142
  options.namesMap[name] = newNameNum;
155
- return "".concat(name).concat(options.prefix ? "-".concat(options.prefix) : '').concat(name !== json.name && newNameNum === 1 ? '' : "-".concat(newNameNum));
143
+ return `${name}${options.prefix ? `-${options.prefix}` : ''}${name !== json.name && newNameNum === 1 ? '' : `-${newNameNum}`}`;
156
144
  };
157
- var createGlobalId = function (name, options) {
158
- var newNameNum = (options.namesMap[name] || 0) + 1;
145
+ const createGlobalId = (name, options) => {
146
+ const newNameNum = (options.namesMap[name] || 0) + 1;
159
147
  options.namesMap[name] = newNameNum;
160
- return "".concat(name).concat(options.prefix ? "-".concat(options.prefix) : '', "-").concat(newNameNum);
148
+ return `${name}${options.prefix ? `-${options.prefix}` : ''}-${newNameNum}`;
161
149
  };
162
- var deprecatedStripStateAndPropsRefs = function (code, _a) {
163
- var context = _a.context, contextVars = _a.contextVars, domRefs = _a.domRefs, includeProps = _a.includeProps, includeState = _a.includeState, outputVars = _a.outputVars, replaceWith = _a.replaceWith, stateVars = _a.stateVars;
150
+ const deprecatedStripStateAndPropsRefs = (code, { context, contextVars, domRefs, includeProps, includeState, outputVars, replaceWith, stateVars, }) => {
164
151
  return (0, function_1.pipe)((0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(code, {
165
- includeProps: includeProps,
166
- includeState: includeState,
167
- replaceWith: replaceWith,
168
- }), function (newCode) {
169
- return (0, strip_state_and_props_refs_1.DO_NOT_USE_VARS_TRANSFORMS)(newCode, {
170
- context: context,
171
- contextVars: contextVars,
172
- domRefs: domRefs,
173
- outputVars: outputVars,
174
- stateVars: stateVars,
175
- });
176
- });
152
+ includeProps,
153
+ includeState,
154
+ replaceWith,
155
+ }), (newCode) => (0, strip_state_and_props_refs_1.DO_NOT_USE_VARS_TRANSFORMS)(newCode, {
156
+ context,
157
+ contextVars,
158
+ domRefs,
159
+ outputVars,
160
+ stateVars,
161
+ }));
177
162
  };
178
163
  // TODO: overloaded function
179
- var updateReferencesInCode = function (code, options, blockOptions) {
164
+ const updateReferencesInCode = (code, options, blockOptions = {}) => {
180
165
  var _a, _b;
181
- if (blockOptions === void 0) { blockOptions = {}; }
182
- var contextVars = blockOptions.contextVars || [];
183
- var context = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.context) || 'this.';
166
+ const contextVars = blockOptions.contextVars || [];
167
+ const context = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.context) || 'this.';
184
168
  if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.updateReferencesInCode) {
185
169
  return (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.updateReferencesInCode(code, options, {
186
170
  stripStateAndPropsRefs: deprecatedStripStateAndPropsRefs,
@@ -191,33 +175,30 @@ var updateReferencesInCode = function (code, options, blockOptions) {
191
175
  includeProps: false,
192
176
  includeState: true,
193
177
  replaceWith: context + 'state.',
194
- }), function (newCode) {
195
- return (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(newCode, {
196
- // TODO: replace with `this.` and add setters that call this.update()
197
- includeProps: true,
198
- includeState: false,
199
- replaceWith: context + 'props.',
200
- });
201
- }, function (newCode) { return (0, strip_state_and_props_refs_1.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS)({ code: newCode, context: context, contextVars: contextVars }); });
178
+ }), (newCode) => (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(newCode, {
179
+ // TODO: replace with `this.` and add setters that call this.update()
180
+ includeProps: true,
181
+ includeState: false,
182
+ replaceWith: context + 'props.',
183
+ }), (newCode) => (0, strip_state_and_props_refs_1.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS)({ code: newCode, context, contextVars }));
202
184
  }
203
185
  return code;
204
186
  };
205
- var addOnChangeJs = function (id, options, code) {
187
+ const addOnChangeJs = (id, options, code) => {
206
188
  if (!options.onChangeJsById[id]) {
207
189
  options.onChangeJsById[id] = '';
208
190
  }
209
191
  options.onChangeJsById[id] += code;
210
192
  };
211
193
  // TODO: spread support
212
- var blockToHtml = function (json, options, blockOptions) {
194
+ const blockToHtml = (json, options, blockOptions = {}) => {
213
195
  var _a, _b, _c, _d, _e, _f, _g;
214
- if (blockOptions === void 0) { blockOptions = {}; }
215
- var ComponentName = blockOptions.ComponentName;
216
- var scopeVars = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.scopeVars) || [];
217
- var childComponents = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.childComponents) || [];
218
- var hasData = Object.keys(json.bindings).length;
219
- var hasDomState = /input|textarea|select/.test(json.name);
220
- var elId = '';
196
+ const ComponentName = blockOptions.ComponentName;
197
+ const scopeVars = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.scopeVars) || [];
198
+ const childComponents = (blockOptions === null || blockOptions === void 0 ? void 0 : blockOptions.childComponents) || [];
199
+ const hasData = Object.keys(json.bindings).length;
200
+ const hasDomState = /input|textarea|select/.test(json.name);
201
+ let elId = '';
221
202
  if (hasData) {
222
203
  elId = getId(json, options);
223
204
  json.properties['data-el'] = elId;
@@ -229,53 +210,62 @@ var blockToHtml = function (json, options, blockOptions) {
229
210
  return mappers[json.name](json, options, blockOptions);
230
211
  }
231
212
  if ((0, is_children_1.default)({ node: json })) {
232
- return "<slot></slot>";
213
+ return `<slot></slot>`;
233
214
  }
234
215
  if (json.properties._text) {
235
216
  return json.properties._text;
236
217
  }
237
218
  if ((_a = json.bindings._text) === null || _a === void 0 ? void 0 : _a.code) {
238
219
  // TO-DO: textContent might be better performance-wise
239
- addOnChangeJs(elId, options, "\n ".concat(addScopeVars(scopeVars, json.bindings._text.code, function (scopeVar) {
240
- return "const ".concat(scopeVar, " = ").concat(options.format === 'class' ? 'this.' : '', "getScope(el, \"").concat(scopeVar, "\");");
241
- }), "\n ").concat(options.format === 'class' ? 'this.' : '', "renderTextNode(el, ").concat(json.bindings._text.code, ");"));
242
- return "<template data-el=\"".concat(elId, "\"><!-- ").concat((_b = json.bindings._text) === null || _b === void 0 ? void 0 : _b.code, " --></template>");
220
+ addOnChangeJs(elId, options, `
221
+ ${addScopeVars(scopeVars, json.bindings._text.code, (scopeVar) => `const ${scopeVar} = ${options.format === 'class' ? 'this.' : ''}getScope(el, "${scopeVar}");`)}
222
+ ${options.format === 'class' ? 'this.' : ''}renderTextNode(el, ${json.bindings._text.code});`);
223
+ return `<template data-el="${elId}"><!-- ${(_b = json.bindings._text) === null || _b === void 0 ? void 0 : _b.code} --></template>`;
243
224
  }
244
- var str = '';
225
+ let str = '';
245
226
  if ((0, mitosis_node_1.checkIsForNode)(json)) {
246
- var forArguments = (0, for_1.getForArguments)(json);
247
- var localScopeVars_1 = __spreadArray(__spreadArray([], scopeVars, true), forArguments, true);
248
- var argsStr = forArguments.map(function (arg) { return "\"".concat(arg, "\""); }).join(',');
227
+ const forArguments = (0, for_1.getForArguments)(json);
228
+ const localScopeVars = [...scopeVars, ...forArguments];
229
+ const argsStr = forArguments.map((arg) => `"${arg}"`).join(',');
249
230
  addOnChangeJs(elId, options,
250
231
  // TODO: be smarter about rendering, deleting old items and adding new ones by
251
232
  // querying dom potentially
252
- "\n let array = ".concat((_c = json.bindings.each) === null || _c === void 0 ? void 0 : _c.code, ";\n ").concat(options.format === 'class' ? 'this.' : '', "renderLoop(el, array, ").concat(argsStr, ");\n "));
233
+ `
234
+ let array = ${(_c = json.bindings.each) === null || _c === void 0 ? void 0 : _c.code};
235
+ ${options.format === 'class' ? 'this.' : ''}renderLoop(el, array, ${argsStr});
236
+ `);
253
237
  // TODO: decide on how to handle this...
254
- str += "\n <template data-el=\"".concat(elId, "\">");
238
+ str += `
239
+ <template data-el="${elId}">`;
255
240
  if (json.children) {
256
241
  str += json.children
257
- .map(function (item) {
258
- return blockToHtml(item, options, __assign(__assign({}, blockOptions), { scopeVars: localScopeVars_1 }));
259
- })
242
+ .map((item) => blockToHtml(item, options, {
243
+ ...blockOptions,
244
+ scopeVars: localScopeVars,
245
+ }))
260
246
  .join('\n');
261
247
  }
262
248
  str += '</template>';
263
249
  }
264
250
  else if (json.name === 'Show') {
265
- var whenCondition = ((_d = json.bindings.when) === null || _d === void 0 ? void 0 : _d.code).replace(/;$/, '');
266
- addOnChangeJs(elId, options, "\n ".concat(addScopeVars(scopeVars, whenCondition, function (scopeVar) {
267
- return "const ".concat(scopeVar, " = ").concat(options.format === 'class' ? 'this.' : '', "getScope(el, \"").concat(scopeVar, "\");");
268
- }), "\n const whenCondition = ").concat(whenCondition, ";\n if (whenCondition) {\n ").concat(options.format === 'class' ? 'this.' : '', "showContent(el)\n }\n "));
269
- str += "<template data-el=\"".concat(elId, "\">");
251
+ const whenCondition = ((_d = json.bindings.when) === null || _d === void 0 ? void 0 : _d.code).replace(/;$/, '');
252
+ addOnChangeJs(elId, options, `
253
+ ${addScopeVars(scopeVars, whenCondition, (scopeVar) => `const ${scopeVar} = ${options.format === 'class' ? 'this.' : ''}getScope(el, "${scopeVar}");`)}
254
+ const whenCondition = ${whenCondition};
255
+ if (whenCondition) {
256
+ ${options.format === 'class' ? 'this.' : ''}showContent(el)
257
+ }
258
+ `);
259
+ str += `<template data-el="${elId}">`;
270
260
  if (json.children) {
271
- str += json.children.map(function (item) { return blockToHtml(item, options, blockOptions); }).join('\n');
261
+ str += json.children.map((item) => blockToHtml(item, options, blockOptions)).join('\n');
272
262
  }
273
263
  str += '</template>';
274
264
  }
275
265
  else {
276
- var component = childComponents.find(function (impName) { return impName === json.name; });
277
- var elSelector = component ? (0, lodash_1.kebabCase)(json.name) : json.name;
278
- str += "<".concat(elSelector, " ");
266
+ const component = childComponents.find((impName) => impName === json.name);
267
+ const elSelector = component ? (0, lodash_1.kebabCase)(json.name) : json.name;
268
+ str += `<${elSelector} `;
279
269
  // For now, spread is not supported
280
270
  // if (json.bindings._spread === '_spread') {
281
271
  // str += `
@@ -284,61 +274,71 @@ var blockToHtml = function (json, options, blockOptions) {
284
274
  // {% endfor %}
285
275
  // `;
286
276
  // }
287
- for (var key in json.properties) {
277
+ for (const key in json.properties) {
288
278
  if (key === 'innerHTML') {
289
279
  continue;
290
280
  }
291
281
  if (key.startsWith('$')) {
292
282
  continue;
293
283
  }
294
- var value = (json.properties[key] || '').replace(/"/g, '&quot;').replace(/\n/g, '\\n');
295
- str += " ".concat(key, "=\"").concat(value, "\" ");
284
+ const value = (json.properties[key] || '').replace(/"/g, '&quot;').replace(/\n/g, '\\n');
285
+ str += ` ${key}="${value}" `;
296
286
  }
297
287
  // batch all local vars within the bindings
298
- var batchScopeVars_1 = {};
299
- var injectOnce = false;
300
- var startInjectVar = '%%START_VARS%%';
301
- for (var key in json.bindings) {
288
+ let batchScopeVars = {};
289
+ let injectOnce = false;
290
+ let startInjectVar = '%%START_VARS%%';
291
+ for (const key in json.bindings) {
302
292
  if (((_e = json.bindings[key]) === null || _e === void 0 ? void 0 : _e.type) === 'spread' || key === 'css') {
303
293
  continue;
304
294
  }
305
- var value = (_f = json.bindings[key]) === null || _f === void 0 ? void 0 : _f.code;
306
- var cusArg = ((_g = json.bindings[key]) === null || _g === void 0 ? void 0 : _g.arguments) || ['event'];
295
+ const value = (_f = json.bindings[key]) === null || _f === void 0 ? void 0 : _f.code;
296
+ const cusArg = ((_g = json.bindings[key]) === null || _g === void 0 ? void 0 : _g.arguments) || ['event'];
307
297
  // TODO: proper babel transform to replace. Util for this
308
- var useValue = value;
298
+ const useValue = value;
309
299
  if (key.startsWith('on')) {
310
- var event_1 = key.replace('on', '').toLowerCase();
311
- if (!(0, is_component_1.isComponent)(json) && event_1 === 'change') {
312
- event_1 = 'input';
300
+ let event = key.replace('on', '').toLowerCase();
301
+ if (!(0, is_component_1.isComponent)(json) && event === 'change') {
302
+ event = 'input';
313
303
  }
314
- var fnName = (0, lodash_1.camelCase)("on-".concat(elId, "-").concat(event_1));
315
- var codeContent = (0, remove_surrounding_block_1.removeSurroundingBlock)(updateReferencesInCode(useValue, options, blockOptions));
316
- options.js += "\n // Event handler for '".concat(event_1, "' event on ").concat(elId, "\n ").concat(options.format === 'class'
317
- ? "this.".concat(fnName, " = (").concat(cusArg.join(','), ") => {")
318
- : "function ".concat(fnName, " (").concat(cusArg.join(','), ") {"), "\n ").concat(addScopeVars(scopeVars, codeContent, function (scopeVar) {
319
- return "const ".concat(scopeVar, " = ").concat(options.format === 'class' ? 'this.' : '', "getScope(event.currentTarget, \"").concat(scopeVar, "\");");
320
- }), "\n ").concat(codeContent, "\n }\n ");
321
- var fnIdentifier = "".concat(options.format === 'class' ? 'this.' : '').concat(fnName);
322
- addOnChangeJs(elId, options, "\n ;el.removeEventListener('".concat(event_1, "', ").concat(fnIdentifier, ");\n ;el.addEventListener('").concat(event_1, "', ").concat(fnIdentifier, ");\n "));
304
+ const fnName = (0, lodash_1.camelCase)(`on-${elId}-${event}`);
305
+ const codeContent = (0, remove_surrounding_block_1.removeSurroundingBlock)(updateReferencesInCode(useValue, options, blockOptions));
306
+ options.js += `
307
+ // Event handler for '${event}' event on ${elId}
308
+ ${options.format === 'class'
309
+ ? `this.${fnName} = (${cusArg.join(',')}) => {`
310
+ : `function ${fnName} (${cusArg.join(',')}) {`}
311
+ ${addScopeVars(scopeVars, codeContent, (scopeVar) => `const ${scopeVar} = ${options.format === 'class' ? 'this.' : ''}getScope(event.currentTarget, "${scopeVar}");`)}
312
+ ${codeContent}
313
+ }
314
+ `;
315
+ const fnIdentifier = `${options.format === 'class' ? 'this.' : ''}${fnName}`;
316
+ addOnChangeJs(elId, options, `
317
+ ;el.removeEventListener('${event}', ${fnIdentifier});
318
+ ;el.addEventListener('${event}', ${fnIdentifier});
319
+ `);
323
320
  }
324
321
  else if (key === 'ref') {
325
- str += " data-ref=\"".concat(ComponentName, "-").concat(useValue, "\" ");
322
+ str += ` data-ref="${ComponentName}-${useValue}" `;
326
323
  }
327
324
  else {
328
325
  if (key === 'style') {
329
- addOnChangeJs(elId, options, "\n ".concat(addScopeVars(scopeVars, useValue, function (scopeVar) {
330
- return "const ".concat(scopeVar, " = ").concat(options.format === 'class' ? 'this.' : '', "getScope(el, \"").concat(scopeVar, "\");");
331
- }), "\n ;Object.assign(el.style, ").concat(useValue, ");"));
326
+ addOnChangeJs(elId, options, `
327
+ ${addScopeVars(scopeVars, useValue, (scopeVar) => `const ${scopeVar} = ${options.format === 'class' ? 'this.' : ''}getScope(el, "${scopeVar}");`)}
328
+ ;Object.assign(el.style, ${useValue});`);
332
329
  }
333
330
  else {
334
331
  // gather all local vars to inject later
335
- getScopeVars(scopeVars, useValue).forEach(function (key) {
332
+ getScopeVars(scopeVars, useValue).forEach((key) => {
336
333
  // unique keys
337
- batchScopeVars_1[key] = true;
334
+ batchScopeVars[key] = true;
338
335
  });
339
- addOnChangeJs(elId, options, "\n ".concat(injectOnce ? '' : startInjectVar, "\n ").concat(generateSetElementAttributeCode(key, elSelector, useValue, options, {
340
- component: component,
341
- }), "\n "));
336
+ addOnChangeJs(elId, options, `
337
+ ${injectOnce ? '' : startInjectVar}
338
+ ${generateSetElementAttributeCode(key, elSelector, useValue, options, {
339
+ component,
340
+ })}
341
+ `);
342
342
  if (!injectOnce) {
343
343
  injectOnce = true;
344
344
  }
@@ -346,51 +346,49 @@ var blockToHtml = function (json, options, blockOptions) {
346
346
  }
347
347
  }
348
348
  // batch inject local vars in the beginning of the function block
349
- var codeBlock = options.onChangeJsById[elId];
350
- var testInjectVar = new RegExp(startInjectVar);
349
+ const codeBlock = options.onChangeJsById[elId];
350
+ const testInjectVar = new RegExp(startInjectVar);
351
351
  if (codeBlock && testInjectVar.test(codeBlock)) {
352
- var localScopeVars = Object.keys(batchScopeVars_1);
353
- options.onChangeJsById[elId] = codeBlock.replace(startInjectVar, "\n ".concat(addScopeVars(localScopeVars, true, function (scopeVar) {
354
- return "const ".concat(scopeVar, " = ").concat(options.format === 'class' ? 'this.' : '', "getScope(el, \"").concat(scopeVar, "\");");
355
- }), "\n "));
352
+ const localScopeVars = Object.keys(batchScopeVars);
353
+ options.onChangeJsById[elId] = codeBlock.replace(startInjectVar, `
354
+ ${addScopeVars(localScopeVars, true, (scopeVar) => `const ${scopeVar} = ${options.format === 'class' ? 'this.' : ''}getScope(el, "${scopeVar}");`)}
355
+ `);
356
356
  }
357
357
  if (html_tags_1.SELF_CLOSING_HTML_TAGS.has(json.name)) {
358
358
  return str + ' />';
359
359
  }
360
360
  str += '>';
361
361
  if (json.children) {
362
- str += json.children.map(function (item) { return blockToHtml(item, options, blockOptions); }).join('\n');
362
+ str += json.children.map((item) => blockToHtml(item, options, blockOptions)).join('\n');
363
363
  }
364
364
  if (json.properties.innerHTML) {
365
365
  // Maybe put some kind of safety here for broken HTML such as no close tag
366
366
  str += htmlDecode(json.properties.innerHTML);
367
367
  }
368
- str += "</".concat(elSelector, ">");
368
+ str += `</${elSelector}>`;
369
369
  }
370
370
  return str;
371
371
  };
372
- function addUpdateAfterSetInCode(code, options, useString) {
373
- if (code === void 0) { code = ''; }
374
- if (useString === void 0) { useString = options.format === 'class' ? 'this.update' : 'update'; }
375
- var updates = 0;
372
+ function addUpdateAfterSetInCode(code = '', options, useString = options.format === 'class' ? 'this.update' : 'update') {
373
+ let updates = 0;
376
374
  return (0, babel_transform_1.babelTransformExpression)(code, {
377
- AssignmentExpression: function (path) {
375
+ AssignmentExpression(path) {
378
376
  var _a, _b;
379
- var node = path.node;
377
+ const { node } = path;
380
378
  if (core_1.types.isMemberExpression(node.left)) {
381
379
  if (core_1.types.isIdentifier(node.left.object)) {
382
380
  // TODO: utillity to properly trace this reference to the beginning
383
381
  if (node.left.object.name === 'state') {
384
382
  // TODO: ultimately do updates by property, e.g. updateName()
385
383
  // that updates any attributes dependent on name, etcç
386
- var parent_1 = path;
384
+ let parent = path;
387
385
  // `_temp = ` assignments are created sometimes when we insertAfter
388
386
  // for simple expressions. this causes us to re-process the same expression
389
387
  // in an infinite loop
390
- while ((parent_1 = parent_1.parentPath)) {
391
- if (core_1.types.isAssignmentExpression(parent_1.node) &&
392
- core_1.types.isIdentifier(parent_1.node.left) &&
393
- parent_1.node.left.name.startsWith('_temp')) {
388
+ while ((parent = parent.parentPath)) {
389
+ if (core_1.types.isAssignmentExpression(parent.node) &&
390
+ core_1.types.isIdentifier(parent.node.left) &&
391
+ parent.node.left.name.startsWith('_temp')) {
394
392
  return;
395
393
  }
396
394
  }
@@ -401,8 +399,8 @@ function addUpdateAfterSetInCode(code, options, useString) {
401
399
  // }
402
400
  if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.addUpdateAfterSetInCode) {
403
401
  useString = (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.addUpdateAfterSetInCode(useString, options, {
404
- node: node,
405
- code: code,
402
+ node,
403
+ code,
406
404
  types: core_1.types,
407
405
  });
408
406
  }
@@ -413,361 +411,824 @@ function addUpdateAfterSetInCode(code, options, useString) {
413
411
  },
414
412
  });
415
413
  }
416
- var htmlDecode = function (html) { return html.replace(/&quot;/gi, '"'); };
414
+ const htmlDecode = (html) => html.replace(/&quot;/gi, '"');
417
415
  // TODO: props support via custom elements
418
- var componentToHtml = function (_options) {
419
- if (_options === void 0) { _options = {}; }
420
- return function (_a) {
421
- var _b, _c, _d, _e, _f, _g, _h;
422
- var component = _a.component;
423
- var options = (0, merge_options_1.initializeOptions)({
424
- target: 'html',
425
- component: component,
426
- defaults: __assign(__assign({}, _options), { onChangeJsById: {}, js: '', namesMap: {}, format: 'script' }),
427
- });
428
- var json = (0, fast_clone_1.fastClone)(component);
429
- if (options.plugins) {
430
- json = (0, plugins_1.runPreJsonPlugins)({ json: json, plugins: options.plugins });
431
- }
432
- addUpdateAfterSet(json, options);
433
- var componentHasProps = (0, has_props_1.hasProps)(json);
434
- var hasLoop = (0, has_component_1.hasComponent)('For', json);
435
- var hasShow = (0, has_component_1.hasComponent)('Show', json);
436
- var hasTextBinding = (0, has_bindings_text_1.hasBindingsText)(json);
437
- if (options.plugins) {
438
- json = (0, plugins_1.runPostJsonPlugins)({ json: json, plugins: options.plugins });
439
- }
440
- var css = (0, collect_css_1.collectCss)(json, {
441
- prefix: options.prefix,
442
- });
443
- var str = json.children.map(function (item) { return blockToHtml(item, options); }).join('\n');
444
- if (css.trim().length) {
445
- str += "<style>".concat(css, "</style>");
446
- }
447
- var hasChangeListeners = Boolean(Object.keys(options.onChangeJsById).length);
448
- var hasGeneratedJs = Boolean(options.js.trim().length);
449
- if (hasChangeListeners || hasGeneratedJs || json.hooks.onMount.length || hasLoop) {
450
- // TODO: collectJs helper for here and liquid
451
- str += "\n <script>\n (() => {\n const state = ".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
452
- valueMapper: function (value) {
453
- return addUpdateAfterSetInCode(updateReferencesInCode(value, options), options);
454
- },
455
- }), ";\n ").concat(componentHasProps ? "let props = {};" : '', "\n let context = null;\n let nodesToDestroy = [];\n let pendingUpdate = false;\n ").concat(!((_c = (_b = json.hooks) === null || _b === void 0 ? void 0 : _b.onInit) === null || _c === void 0 ? void 0 : _c.code) ? '' : 'let onInitOnce = false;', "\n\n function destroyAnyNodes() {\n // destroy current view template refs before rendering again\n nodesToDestroy.forEach(el => el.remove());\n nodesToDestroy = [];\n }\n ").concat(!hasChangeListeners
456
- ? ''
457
- : "\n \n // Function to update data bindings and loops\n // call update() when you mutate state and need the updates to reflect\n // in the dom\n function update() {\n if (pendingUpdate === true) {\n return;\n }\n pendingUpdate = true;\n ".concat(Object.keys(options.onChangeJsById)
458
- .map(function (key) {
459
- var value = options.onChangeJsById[key];
460
- if (!value) {
461
- return '';
462
- }
463
- return "\n document.querySelectorAll(\"[data-el='".concat(key, "']\").forEach((el) => {\n ").concat(value, "\n });\n ");
464
- })
465
- .join('\n\n'), "\n\n destroyAnyNodes();\n\n ").concat(!((_d = json.hooks.onUpdate) === null || _d === void 0 ? void 0 : _d.length)
466
- ? ''
467
- : "\n ".concat(json.hooks.onUpdate.reduce(function (code, hook) {
468
- code += addUpdateAfterSetInCode(updateReferencesInCode(hook.code, options), options);
469
- return code + '\n';
470
- }, ''), " \n "), "\n\n pendingUpdate = false;\n }\n\n ").concat(options.js, "\n\n // Update with initial state on first load\n update();\n "), "\n\n ").concat(!((_f = (_e = json.hooks) === null || _e === void 0 ? void 0 : _e.onInit) === null || _f === void 0 ? void 0 : _f.code)
471
- ? ''
472
- : "\n if (!onInitOnce) {\n ".concat(updateReferencesInCode(addUpdateAfterSetInCode((_h = (_g = json.hooks) === null || _g === void 0 ? void 0 : _g.onInit) === null || _h === void 0 ? void 0 : _h.code, options), options), "\n onInitOnce = true;\n }\n "), "\n\n ").concat(!json.hooks.onMount.length
473
- ? ''
474
- : // TODO: make prettier by grabbing only the function body
475
- "\n // onMount\n ".concat(updateReferencesInCode(addUpdateAfterSetInCode((0, on_mount_1.stringifySingleScopeOnMount)(json), options), options), " \n "), "\n\n ").concat(!hasShow
476
- ? ''
477
- : "\n function showContent(el) {\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content\n // grabs the content of a node that is between <template> tags\n // iterates through child nodes to register all content including text elements\n // attaches the content after the template\n \n \n const elementFragment = el.content.cloneNode(true);\n const children = Array.from(elementFragment.childNodes)\n children.forEach(child => {\n if (el?.scope) {\n child.scope = el.scope;\n }\n if (el?.context) {\n child.context = el.context;\n }\n nodesToDestroy.push(child);\n });\n el.after(elementFragment);\n }\n \n ", "\n ").concat(!hasTextBinding
478
- ? ''
479
- : "\n // Helper text DOM nodes\n function renderTextNode(el, text) {\n const textNode = document.createTextNode(text);\n if (el?.scope) {\n textNode.scope = el.scope\n }\n if (el?.context) {\n child.context = el.context;\n }\n el.after(textNode);\n nodesToDestroy.push(el.nextSibling);\n }\n ", "\n ").concat(!hasLoop
416
+ const componentToHtml = (_options = {}) => ({ component }) => {
417
+ var _a, _b, _c, _d, _e, _f, _g;
418
+ const options = (0, merge_options_1.initializeOptions)({
419
+ target: 'html',
420
+ component,
421
+ defaults: {
422
+ ..._options,
423
+ onChangeJsById: {},
424
+ js: '',
425
+ namesMap: {},
426
+ format: 'script',
427
+ },
428
+ });
429
+ let json = (0, fast_clone_1.fastClone)(component);
430
+ if (options.plugins) {
431
+ json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
432
+ }
433
+ addUpdateAfterSet(json, options);
434
+ const componentHasProps = (0, has_props_1.hasProps)(json);
435
+ const hasLoop = (0, has_component_1.hasComponent)('For', json);
436
+ const hasShow = (0, has_component_1.hasComponent)('Show', json);
437
+ const hasTextBinding = (0, has_bindings_text_1.hasBindingsText)(json);
438
+ if (options.plugins) {
439
+ json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
440
+ }
441
+ const css = (0, collect_css_1.collectCss)(json, {
442
+ prefix: options.prefix,
443
+ });
444
+ let str = json.children.map((item) => blockToHtml(item, options)).join('\n');
445
+ if (css.trim().length) {
446
+ str += `<style>${css}</style>`;
447
+ }
448
+ const hasChangeListeners = Boolean(Object.keys(options.onChangeJsById).length);
449
+ const hasGeneratedJs = Boolean(options.js.trim().length);
450
+ if (hasChangeListeners || hasGeneratedJs || json.hooks.onMount.length || hasLoop) {
451
+ // TODO: collectJs helper for here and liquid
452
+ str += `
453
+ <script>
454
+ (() => {
455
+ const state = ${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
456
+ valueMapper: (value) => addUpdateAfterSetInCode(updateReferencesInCode(value, options), options),
457
+ })};
458
+ ${componentHasProps ? `let props = {};` : ''}
459
+ let context = null;
460
+ let nodesToDestroy = [];
461
+ let pendingUpdate = false;
462
+ ${!((_b = (_a = json.hooks) === null || _a === void 0 ? void 0 : _a.onInit) === null || _b === void 0 ? void 0 : _b.code) ? '' : 'let onInitOnce = false;'}
463
+
464
+ function destroyAnyNodes() {
465
+ // destroy current view template refs before rendering again
466
+ nodesToDestroy.forEach(el => el.remove());
467
+ nodesToDestroy = [];
468
+ }
469
+ ${!hasChangeListeners
470
+ ? ''
471
+ : `
472
+
473
+ // Function to update data bindings and loops
474
+ // call update() when you mutate state and need the updates to reflect
475
+ // in the dom
476
+ function update() {
477
+ if (pendingUpdate === true) {
478
+ return;
479
+ }
480
+ pendingUpdate = true;
481
+ ${Object.keys(options.onChangeJsById)
482
+ .map((key) => {
483
+ const value = options.onChangeJsById[key];
484
+ if (!value) {
485
+ return '';
486
+ }
487
+ return `
488
+ document.querySelectorAll("[data-el='${key}']").forEach((el) => {
489
+ ${value}
490
+ });
491
+ `;
492
+ })
493
+ .join('\n\n')}
494
+
495
+ destroyAnyNodes();
496
+
497
+ ${!((_c = json.hooks.onUpdate) === null || _c === void 0 ? void 0 : _c.length)
480
498
  ? ''
481
- : "\n // Helper to render loops\n function renderLoop(template, array, itemName, itemIndex, collectionName) {\n const collection = [];\n for (let [index, value] of array.entries()) {\n const elementFragment = template.content.cloneNode(true);\n const children = Array.from(elementFragment.childNodes)\n const localScope = {};\n let scope = localScope;\n if (template?.scope) {\n const getParent = {\n get(target, prop, receiver) {\n if (prop in target) {\n return target[prop];\n }\n if (prop in template.scope) {\n return template.scope[prop];\n }\n return target[prop];\n }\n };\n scope = new Proxy(localScope, getParent);\n }\n children.forEach((child) => {\n if (itemName !== undefined) {\n scope[itemName] = value;\n }\n if (itemIndex !== undefined) {\n scope[itemIndex] = index;\n }\n if (collectionName !== undefined) {\n scope[collectionName] = array;\n }\n child.scope = scope;\n if (template.context) {\n child.context = template.context;\n }\n this.nodesToDestroy.push(child);\n collection.unshift(child);\n });\n collection.forEach(child => template.after(child));\n }\n }\n\n function getScope(el, name) {\n do {\n let value = el?.scope?.[name]\n if (value !== undefined) {\n return value\n }\n } while ((el = el.parentNode));\n }\n ", "\n })()\n </script>\n ");
482
- }
483
- if (options.plugins) {
484
- str = (0, plugins_1.runPreCodePlugins)({ json: json, code: str, plugins: options.plugins });
485
- }
486
- if (options.prettier !== false) {
487
- try {
488
- str = (0, standalone_1.format)(str, {
489
- parser: 'html',
490
- htmlWhitespaceSensitivity: 'ignore',
491
- plugins: [
492
- // To support running in browsers
493
- require('prettier/parser-html'),
494
- require('prettier/parser-postcss'),
495
- require('prettier/parser-babel'),
496
- ],
497
- });
499
+ : `
500
+ ${json.hooks.onUpdate.reduce((code, hook) => {
501
+ code += addUpdateAfterSetInCode(updateReferencesInCode(hook.code, options), options);
502
+ return code + '\n';
503
+ }, '')}
504
+ `}
505
+
506
+ pendingUpdate = false;
507
+ }
508
+
509
+ ${options.js}
510
+
511
+ // Update with initial state on first load
512
+ update();
513
+ `}
514
+
515
+ ${!((_e = (_d = json.hooks) === null || _d === void 0 ? void 0 : _d.onInit) === null || _e === void 0 ? void 0 : _e.code)
516
+ ? ''
517
+ : `
518
+ if (!onInitOnce) {
519
+ ${updateReferencesInCode(addUpdateAfterSetInCode((_g = (_f = json.hooks) === null || _f === void 0 ? void 0 : _f.onInit) === null || _g === void 0 ? void 0 : _g.code, options), options)}
520
+ onInitOnce = true;
521
+ }
522
+ `}
523
+
524
+ ${!json.hooks.onMount.length
525
+ ? ''
526
+ : // TODO: make prettier by grabbing only the function body
527
+ `
528
+ // onMount
529
+ ${updateReferencesInCode(addUpdateAfterSetInCode((0, on_mount_1.stringifySingleScopeOnMount)(json), options), options)}
530
+ `}
531
+
532
+ ${!hasShow
533
+ ? ''
534
+ : `
535
+ function showContent(el) {
536
+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content
537
+ // grabs the content of a node that is between <template> tags
538
+ // iterates through child nodes to register all content including text elements
539
+ // attaches the content after the template
540
+
541
+
542
+ const elementFragment = el.content.cloneNode(true);
543
+ const children = Array.from(elementFragment.childNodes)
544
+ children.forEach(child => {
545
+ if (el?.scope) {
546
+ child.scope = el.scope;
547
+ }
548
+ if (el?.context) {
549
+ child.context = el.context;
550
+ }
551
+ nodesToDestroy.push(child);
552
+ });
553
+ el.after(elementFragment);
554
+ }
555
+
556
+ `}
557
+ ${!hasTextBinding
558
+ ? ''
559
+ : `
560
+ // Helper text DOM nodes
561
+ function renderTextNode(el, text) {
562
+ const textNode = document.createTextNode(text);
563
+ if (el?.scope) {
564
+ textNode.scope = el.scope
498
565
  }
499
- catch (err) {
500
- console.warn('Could not prettify', { string: str }, err);
566
+ if (el?.context) {
567
+ child.context = el.context;
501
568
  }
569
+ el.after(textNode);
570
+ nodesToDestroy.push(el.nextSibling);
571
+ }
572
+ `}
573
+ ${!hasLoop
574
+ ? ''
575
+ : `
576
+ // Helper to render loops
577
+ function renderLoop(template, array, itemName, itemIndex, collectionName) {
578
+ const collection = [];
579
+ for (let [index, value] of array.entries()) {
580
+ const elementFragment = template.content.cloneNode(true);
581
+ const children = Array.from(elementFragment.childNodes)
582
+ const localScope = {};
583
+ let scope = localScope;
584
+ if (template?.scope) {
585
+ const getParent = {
586
+ get(target, prop, receiver) {
587
+ if (prop in target) {
588
+ return target[prop];
589
+ }
590
+ if (prop in template.scope) {
591
+ return template.scope[prop];
592
+ }
593
+ return target[prop];
594
+ }
595
+ };
596
+ scope = new Proxy(localScope, getParent);
597
+ }
598
+ children.forEach((child) => {
599
+ if (itemName !== undefined) {
600
+ scope[itemName] = value;
601
+ }
602
+ if (itemIndex !== undefined) {
603
+ scope[itemIndex] = index;
604
+ }
605
+ if (collectionName !== undefined) {
606
+ scope[collectionName] = array;
607
+ }
608
+ child.scope = scope;
609
+ if (template.context) {
610
+ child.context = template.context;
611
+ }
612
+ this.nodesToDestroy.push(child);
613
+ collection.unshift(child);
614
+ });
615
+ collection.forEach(child => template.after(child));
616
+ }
617
+ }
618
+
619
+ function getScope(el, name) {
620
+ do {
621
+ let value = el?.scope?.[name]
622
+ if (value !== undefined) {
623
+ return value
624
+ }
625
+ } while ((el = el.parentNode));
626
+ }
627
+ `}
628
+ })()
629
+ </script>
630
+ `;
631
+ }
632
+ if (options.plugins) {
633
+ str = (0, plugins_1.runPreCodePlugins)({ json, code: str, plugins: options.plugins });
634
+ }
635
+ if (options.prettier !== false) {
636
+ try {
637
+ str = (0, standalone_1.format)(str, {
638
+ parser: 'html',
639
+ htmlWhitespaceSensitivity: 'ignore',
640
+ plugins: [
641
+ // To support running in browsers
642
+ require('prettier/parser-html'),
643
+ require('prettier/parser-postcss'),
644
+ require('prettier/parser-babel'),
645
+ ],
646
+ });
502
647
  }
503
- if (options.plugins) {
504
- str = (0, plugins_1.runPostCodePlugins)({ json: json, code: str, plugins: options.plugins });
648
+ catch (err) {
649
+ console.warn('Could not prettify', { string: str }, err);
505
650
  }
506
- return str;
507
- };
651
+ }
652
+ if (options.plugins) {
653
+ str = (0, plugins_1.runPostCodePlugins)({ json, code: str, plugins: options.plugins });
654
+ }
655
+ return str;
508
656
  };
509
657
  exports.componentToHtml = componentToHtml;
510
658
  // TODO: props support via custom elements
511
- var componentToCustomElement = function (_options) {
512
- if (_options === void 0) { _options = {}; }
513
- return function (_a) {
514
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13;
515
- var component = _a.component;
516
- var ComponentName = component.name;
517
- var kebabName = (0, lodash_1.kebabCase)(ComponentName);
518
- var options = (0, merge_options_1.initializeOptions)({
519
- target: 'customElement',
520
- component: component,
521
- defaults: __assign(__assign({ prefix: kebabName }, _options), { onChangeJsById: {}, js: '', namesMap: {}, format: 'class' }),
659
+ const componentToCustomElement = (_options = {}) => ({ component }) => {
660
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
661
+ const ComponentName = component.name;
662
+ const kebabName = (0, lodash_1.kebabCase)(ComponentName);
663
+ const options = (0, merge_options_1.initializeOptions)({
664
+ target: 'customElement',
665
+ component,
666
+ defaults: {
667
+ prefix: kebabName,
668
+ ..._options,
669
+ onChangeJsById: {},
670
+ js: '',
671
+ namesMap: {},
672
+ format: 'class',
673
+ },
674
+ });
675
+ let json = (0, fast_clone_1.fastClone)(component);
676
+ if (options.plugins) {
677
+ json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
678
+ }
679
+ const [forwardProp, hasPropRef] = (0, get_props_ref_1.getPropsRef)(json, true);
680
+ const contextVars = Object.keys(((_a = json === null || json === void 0 ? void 0 : json.context) === null || _a === void 0 ? void 0 : _a.get) || {});
681
+ const childComponents = getChildComponents(json, options);
682
+ const componentHasProps = (0, has_props_1.hasProps)(json);
683
+ const componentHasStatefulDom = (0, has_stateful_dom_1.hasStatefulDom)(json);
684
+ const props = (0, get_props_1.getProps)(json);
685
+ // prevent jsx props from showing up as @Input
686
+ if (hasPropRef) {
687
+ props.delete(forwardProp);
688
+ }
689
+ const outputs = (0, get_prop_functions_1.getPropFunctions)(json);
690
+ const domRefs = (0, get_refs_1.getRefs)(json);
691
+ const jsRefs = Object.keys(json.refs).filter((ref) => !domRefs.has(ref));
692
+ (0, map_refs_1.mapRefs)(json, (refName) => `self._${refName}`);
693
+ const context = contextVars.map((variableName) => {
694
+ var _a, _b, _c;
695
+ const token = (_a = json === null || json === void 0 ? void 0 : json.context) === null || _a === void 0 ? void 0 : _a.get[variableName].name;
696
+ if ((_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.htmlContext) {
697
+ return (_c = options === null || options === void 0 ? void 0 : options.experimental) === null || _c === void 0 ? void 0 : _c.htmlContext(variableName, token);
698
+ }
699
+ return `this.${variableName} = this.getContext(this._root, ${token})`;
700
+ });
701
+ const setContext = [];
702
+ for (const key in json.context.set) {
703
+ const { name, value, ref } = json.context.set[key];
704
+ setContext.push({ name, value, ref });
705
+ }
706
+ addUpdateAfterSet(json, options);
707
+ const hasContext = context.length;
708
+ const hasLoop = (0, has_component_1.hasComponent)('For', json);
709
+ const hasScope = hasLoop;
710
+ const hasShow = (0, has_component_1.hasComponent)('Show', json);
711
+ if (options.plugins) {
712
+ json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
713
+ }
714
+ let css = '';
715
+ if ((_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.css) {
716
+ css = (_c = options === null || options === void 0 ? void 0 : options.experimental) === null || _c === void 0 ? void 0 : _c.css(json, options, {
717
+ collectCss: collect_css_1.collectCss,
718
+ prefix: options.prefix,
522
719
  });
523
- var json = (0, fast_clone_1.fastClone)(component);
524
- if (options.plugins) {
525
- json = (0, plugins_1.runPreJsonPlugins)({ json: json, plugins: options.plugins });
526
- }
527
- var _14 = (0, get_props_ref_1.getPropsRef)(json, true), forwardProp = _14[0], hasPropRef = _14[1];
528
- var contextVars = Object.keys(((_b = json === null || json === void 0 ? void 0 : json.context) === null || _b === void 0 ? void 0 : _b.get) || {});
529
- var childComponents = getChildComponents(json, options);
530
- var componentHasProps = (0, has_props_1.hasProps)(json);
531
- var componentHasStatefulDom = (0, has_stateful_dom_1.hasStatefulDom)(json);
532
- var props = (0, get_props_1.getProps)(json);
533
- // prevent jsx props from showing up as @Input
534
- if (hasPropRef) {
535
- props.delete(forwardProp);
536
- }
537
- var outputs = (0, get_prop_functions_1.getPropFunctions)(json);
538
- var domRefs = (0, get_refs_1.getRefs)(json);
539
- var jsRefs = Object.keys(json.refs).filter(function (ref) { return !domRefs.has(ref); });
540
- (0, map_refs_1.mapRefs)(json, function (refName) { return "self._".concat(refName); });
541
- var context = contextVars.map(function (variableName) {
542
- var _a, _b, _c;
543
- var token = (_a = json === null || json === void 0 ? void 0 : json.context) === null || _a === void 0 ? void 0 : _a.get[variableName].name;
544
- if ((_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.htmlContext) {
545
- return (_c = options === null || options === void 0 ? void 0 : options.experimental) === null || _c === void 0 ? void 0 : _c.htmlContext(variableName, token);
546
- }
547
- return "this.".concat(variableName, " = this.getContext(this._root, ").concat(token, ")");
720
+ }
721
+ else {
722
+ css = (0, collect_css_1.collectCss)(json, {
723
+ prefix: options.prefix,
548
724
  });
549
- var setContext = [];
550
- for (var key in json.context.set) {
551
- var _15 = json.context.set[key], name_1 = _15.name, value = _15.value, ref = _15.ref;
552
- setContext.push({ name: name_1, value: value, ref: ref });
553
- }
554
- addUpdateAfterSet(json, options);
555
- var hasContext = context.length;
556
- var hasLoop = (0, has_component_1.hasComponent)('For', json);
557
- var hasScope = hasLoop;
558
- var hasShow = (0, has_component_1.hasComponent)('Show', json);
559
- if (options.plugins) {
560
- json = (0, plugins_1.runPostJsonPlugins)({ json: json, plugins: options.plugins });
561
- }
562
- var css = '';
563
- if ((_c = options === null || options === void 0 ? void 0 : options.experimental) === null || _c === void 0 ? void 0 : _c.css) {
564
- css = (_d = options === null || options === void 0 ? void 0 : options.experimental) === null || _d === void 0 ? void 0 : _d.css(json, options, {
565
- collectCss: collect_css_1.collectCss,
566
- prefix: options.prefix,
725
+ }
726
+ (0, strip_meta_properties_1.stripMetaProperties)(json);
727
+ let html = json.children
728
+ .map((item) => blockToHtml(item, options, {
729
+ childComponents,
730
+ props,
731
+ outputs,
732
+ ComponentName,
733
+ contextVars,
734
+ }))
735
+ .join('\n');
736
+ if ((_d = options === null || options === void 0 ? void 0 : options.experimental) === null || _d === void 0 ? void 0 : _d.childrenHtml) {
737
+ html = (_e = options === null || options === void 0 ? void 0 : options.experimental) === null || _e === void 0 ? void 0 : _e.childrenHtml(html, kebabName, json, options);
738
+ }
739
+ if ((_f = options === null || options === void 0 ? void 0 : options.experimental) === null || _f === void 0 ? void 0 : _f.cssHtml) {
740
+ html += (_g = options === null || options === void 0 ? void 0 : options.experimental) === null || _g === void 0 ? void 0 : _g.cssHtml(css);
741
+ }
742
+ else if (css.length) {
743
+ html += `<style>${css}</style>`;
744
+ }
745
+ if (options.prettier !== false) {
746
+ try {
747
+ html = (0, standalone_1.format)(html, {
748
+ parser: 'html',
749
+ htmlWhitespaceSensitivity: 'ignore',
750
+ plugins: [
751
+ // To support running in browsers
752
+ require('prettier/parser-html'),
753
+ require('prettier/parser-postcss'),
754
+ require('prettier/parser-babel'),
755
+ require('prettier/parser-typescript'),
756
+ ],
567
757
  });
758
+ html = html.trim().replace(/\n/g, '\n ');
568
759
  }
569
- else {
570
- css = (0, collect_css_1.collectCss)(json, {
571
- prefix: options.prefix,
760
+ catch (err) {
761
+ console.warn('Could not prettify', { string: html }, err);
762
+ }
763
+ }
764
+ let str = `
765
+ ${json.types ? json.types.join('\n') : ''}
766
+ ${(0, render_imports_1.renderPreComponent)({
767
+ explicitImportFileExtension: options.explicitImportFileExtension,
768
+ component: json,
769
+ target: 'customElement',
770
+ })}
771
+ /**
772
+ * Usage:
773
+ *
774
+ * <${kebabName}></${kebabName}>
775
+ *
776
+ */
777
+ class ${ComponentName} extends ${((_h = options === null || options === void 0 ? void 0 : options.experimental) === null || _h === void 0 ? void 0 : _h.classExtends)
778
+ ? (_j = options === null || options === void 0 ? void 0 : options.experimental) === null || _j === void 0 ? void 0 : _j.classExtends(json, options)
779
+ : 'HTMLElement'} {
780
+ ${Array.from(domRefs)
781
+ .map((ref) => {
782
+ return `
783
+ get _${ref}() {
784
+ return this._root.querySelector("[data-ref='${ComponentName}-${ref}']")
785
+ }
786
+ `;
787
+ })
788
+ .join('\n')}
789
+
790
+ get _root() {
791
+ return this.shadowRoot || this;
792
+ }
793
+
794
+ constructor() {
795
+ super();
796
+ const self = this;
797
+ ${
798
+ // TODO: more than one context not injector
799
+ setContext.length === 1 && ((_k = setContext === null || setContext === void 0 ? void 0 : setContext[0]) === null || _k === void 0 ? void 0 : _k.ref)
800
+ ? `this.context = ${setContext[0].ref}`
801
+ : ''}
802
+
803
+ ${!((_m = (_l = json.hooks) === null || _l === void 0 ? void 0 : _l.onInit) === null || _m === void 0 ? void 0 : _m.code) ? '' : 'this.onInitOnce = false;'}
804
+
805
+ this.state = ${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
806
+ valueMapper: (value) => (0, function_1.pipe)((0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(addUpdateAfterSetInCode(value, options, 'self.update'), {
807
+ includeProps: false,
808
+ includeState: true,
809
+ // TODO: if it's an arrow function it's this.state.
810
+ replaceWith: 'self.state.',
811
+ }), (newCode) => (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(newCode, {
812
+ // TODO: replace with `this.` and add setters that call this.update()
813
+ includeProps: true,
814
+ includeState: false,
815
+ replaceWith: 'self.props.',
816
+ }), (code) => (0, strip_state_and_props_refs_1.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS)({
817
+ code,
818
+ contextVars,
819
+ // correctly ref the class not state object
820
+ context: 'self.',
821
+ })),
822
+ })};
823
+ if (!this.props) {
824
+ this.props = {};
825
+ }
826
+ ${!componentHasProps
827
+ ? ''
828
+ : `
829
+ this.componentProps = [${Array.from(props)
830
+ .map((prop) => `"${prop}"`)
831
+ .join(',')}];
832
+ `}
833
+
834
+ ${!((_o = json.hooks.onUpdate) === null || _o === void 0 ? void 0 : _o.length)
835
+ ? ''
836
+ : `
837
+ this.updateDeps = [${(_p = json.hooks.onUpdate) === null || _p === void 0 ? void 0 : _p.map((hook) => updateReferencesInCode((hook === null || hook === void 0 ? void 0 : hook.deps) || '[]', options)).join(',')}];
838
+ `}
839
+
840
+ // used to keep track of all nodes created by show/for
841
+ this.nodesToDestroy = [];
842
+ // batch updates
843
+ this.pendingUpdate = false;
844
+ ${((_q = options === null || options === void 0 ? void 0 : options.experimental) === null || _q === void 0 ? void 0 : _q.componentConstructor)
845
+ ? (_r = options === null || options === void 0 ? void 0 : options.experimental) === null || _r === void 0 ? void 0 : _r.componentConstructor(json, options)
846
+ : ''}
847
+
848
+ ${options.js}
849
+
850
+ ${jsRefs
851
+ .map((ref) => {
852
+ var _a;
853
+ // const typeParameter = json['refs'][ref]?.typeParameter || '';
854
+ const argument = ((_a = json['refs'][ref]) === null || _a === void 0 ? void 0 : _a.argument) || 'null';
855
+ return `this._${ref} = ${argument}`;
856
+ })
857
+ .join('\n')}
858
+
859
+ if (${(_s = json.meta.useMetadata) === null || _s === void 0 ? void 0 : _s.isAttachedToShadowDom}) {
860
+ this.attachShadow({ mode: 'open' })
861
+ }
862
+ }
863
+
864
+
865
+ ${!((_t = json.hooks.onUnMount) === null || _t === void 0 ? void 0 : _t.code)
866
+ ? ''
867
+ : `
868
+ disconnectedCallback() {
869
+ ${((_u = options === null || options === void 0 ? void 0 : options.experimental) === null || _u === void 0 ? void 0 : _u.disconnectedCallback)
870
+ ? (_v = options === null || options === void 0 ? void 0 : options.experimental) === null || _v === void 0 ? void 0 : _v.disconnectedCallback(json, options)
871
+ : `
872
+ // onUnMount
873
+ ${updateReferencesInCode(addUpdateAfterSetInCode(json.hooks.onUnMount.code, options), options, {
874
+ contextVars,
875
+ })}
876
+ this.destroyAnyNodes(); // clean up nodes when component is destroyed
877
+ ${!((_x = (_w = json.hooks) === null || _w === void 0 ? void 0 : _w.onInit) === null || _x === void 0 ? void 0 : _x.code) ? '' : 'this.onInitOnce = false;'}
878
+ `}
879
+ }
880
+ `}
881
+
882
+ destroyAnyNodes() {
883
+ // destroy current view template refs before rendering again
884
+ this.nodesToDestroy.forEach(el => el.remove());
885
+ this.nodesToDestroy = [];
886
+ }
887
+
888
+ connectedCallback() {
889
+ ${context.join('\n')}
890
+ ${!componentHasProps
891
+ ? ''
892
+ : `
893
+ this.getAttributeNames().forEach((attr) => {
894
+ const jsVar = attr.replace(/-/g, '');
895
+ const regexp = new RegExp(jsVar, 'i');
896
+ this.componentProps.forEach(prop => {
897
+ if (regexp.test(prop)) {
898
+ const attrValue = this.getAttribute(attr);
899
+ if (this.props[prop] !== attrValue) {
900
+ this.props[prop] = attrValue;
901
+ }
902
+ }
572
903
  });
904
+ });
905
+ `}
906
+ ${((_y = options === null || options === void 0 ? void 0 : options.experimental) === null || _y === void 0 ? void 0 : _y.connectedCallbackUpdate)
907
+ ? (_z = options === null || options === void 0 ? void 0 : options.experimental) === null || _z === void 0 ? void 0 : _z.connectedCallbackUpdate(json, html, options)
908
+ : `
909
+ this._root.innerHTML = \`
910
+ ${html}\`;
911
+ this.pendingUpdate = true;
912
+ ${!((_1 = (_0 = json.hooks) === null || _0 === void 0 ? void 0 : _0.onInit) === null || _1 === void 0 ? void 0 : _1.code) ? '' : 'this.onInit();'}
913
+ this.render();
914
+ this.onMount();
915
+ this.pendingUpdate = false;
916
+ this.update();
917
+ `}
573
918
  }
574
- (0, strip_meta_properties_1.stripMetaProperties)(json);
575
- var html = json.children
576
- .map(function (item) {
577
- return blockToHtml(item, options, {
578
- childComponents: childComponents,
579
- props: props,
580
- outputs: outputs,
581
- ComponentName: ComponentName,
582
- contextVars: contextVars,
919
+ ${!((_3 = (_2 = json.hooks) === null || _2 === void 0 ? void 0 : _2.onInit) === null || _3 === void 0 ? void 0 : _3.code)
920
+ ? ''
921
+ : `
922
+ onInit() {
923
+ ${!((_5 = (_4 = json.hooks) === null || _4 === void 0 ? void 0 : _4.onInit) === null || _5 === void 0 ? void 0 : _5.code)
924
+ ? ''
925
+ : `
926
+ if (!this.onInitOnce) {
927
+ ${updateReferencesInCode(addUpdateAfterSetInCode((_7 = (_6 = json.hooks) === null || _6 === void 0 ? void 0 : _6.onInit) === null || _7 === void 0 ? void 0 : _7.code, options), options, {
928
+ contextVars,
929
+ })}
930
+ this.onInitOnce = true;
931
+ }`}
932
+ }
933
+ `}
934
+
935
+ ${!hasShow
936
+ ? ''
937
+ : `
938
+ showContent(el) {
939
+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content
940
+ // grabs the content of a node that is between <template> tags
941
+ // iterates through child nodes to register all content including text elements
942
+ // attaches the content after the template
943
+
944
+
945
+ const elementFragment = el.content.cloneNode(true);
946
+ const children = Array.from(elementFragment.childNodes)
947
+ children.forEach(child => {
948
+ if (el?.scope) {
949
+ child.scope = el.scope;
950
+ }
951
+ if (el?.context) {
952
+ child.context = el.context;
953
+ }
954
+ this.nodesToDestroy.push(child);
583
955
  });
584
- })
585
- .join('\n');
586
- if ((_e = options === null || options === void 0 ? void 0 : options.experimental) === null || _e === void 0 ? void 0 : _e.childrenHtml) {
587
- html = (_f = options === null || options === void 0 ? void 0 : options.experimental) === null || _f === void 0 ? void 0 : _f.childrenHtml(html, kebabName, json, options);
588
- }
589
- if ((_g = options === null || options === void 0 ? void 0 : options.experimental) === null || _g === void 0 ? void 0 : _g.cssHtml) {
590
- html += (_h = options === null || options === void 0 ? void 0 : options.experimental) === null || _h === void 0 ? void 0 : _h.cssHtml(css);
591
- }
592
- else if (css.length) {
593
- html += "<style>".concat(css, "</style>");
594
- }
595
- if (options.prettier !== false) {
596
- try {
597
- html = (0, standalone_1.format)(html, {
598
- parser: 'html',
599
- htmlWhitespaceSensitivity: 'ignore',
600
- plugins: [
601
- // To support running in browsers
602
- require('prettier/parser-html'),
603
- require('prettier/parser-postcss'),
604
- require('prettier/parser-babel'),
605
- require('prettier/parser-typescript'),
606
- ],
607
- });
608
- html = html.trim().replace(/\n/g, '\n ');
956
+ el.after(elementFragment);
957
+ }`}
958
+ ${!((_8 = options === null || options === void 0 ? void 0 : options.experimental) === null || _8 === void 0 ? void 0 : _8.attributeChangedCallback)
959
+ ? ''
960
+ : `
961
+ attributeChangedCallback(name, oldValue, newValue) {
962
+ ${(_9 = options === null || options === void 0 ? void 0 : options.experimental) === null || _9 === void 0 ? void 0 : _9.attributeChangedCallback(['name', 'oldValue', 'newValue'], json, options)}
963
+ }
964
+ `}
965
+
966
+ onMount() {
967
+ ${!json.hooks.onMount.length
968
+ ? ''
969
+ : // TODO: make prettier by grabbing only the function body
970
+ `
971
+ // onMount
972
+ ${updateReferencesInCode(addUpdateAfterSetInCode((0, on_mount_1.stringifySingleScopeOnMount)(json), options), options, {
973
+ contextVars,
974
+ })}
975
+ `}
976
+ }
977
+
978
+ onUpdate() {
979
+ ${!((_10 = json.hooks.onUpdate) === null || _10 === void 0 ? void 0 : _10.length)
980
+ ? ''
981
+ : `
982
+ const self = this;
983
+ ${json.hooks.onUpdate.reduce((code, hook, index) => {
984
+ // create check update
985
+ if (hook === null || hook === void 0 ? void 0 : hook.deps) {
986
+ code += `
987
+ ;(function (__prev, __next) {
988
+ const __hasChange = __prev.find((val, index) => val !== __next[index]);
989
+ if (__hasChange !== undefined) {
990
+ ${updateReferencesInCode(hook.code, options, {
991
+ contextVars,
992
+ context: 'self.',
993
+ })}
994
+ self.updateDeps[${index}] = __next;
995
+ }
996
+ }(self.updateDeps[${index}], ${updateReferencesInCode((hook === null || hook === void 0 ? void 0 : hook.deps) || '[]', options, {
997
+ contextVars,
998
+ context: 'self.',
999
+ })}));
1000
+ `;
609
1001
  }
610
- catch (err) {
611
- console.warn('Could not prettify', { string: html }, err);
1002
+ else {
1003
+ code += `
1004
+ ${updateReferencesInCode(hook.code, options, {
1005
+ contextVars,
1006
+ context: 'self.',
1007
+ })}
1008
+ `;
612
1009
  }
1010
+ return code + '\n';
1011
+ }, '')}
1012
+ `}
613
1013
  }
614
- var str = "\n ".concat(json.types ? json.types.join('\n') : '', "\n ").concat((0, render_imports_1.renderPreComponent)({
615
- explicitImportFileExtension: options.explicitImportFileExtension,
616
- component: json,
617
- target: 'customElement',
618
- }), "\n /**\n * Usage:\n * \n * <").concat(kebabName, "></").concat(kebabName, ">\n * \n */\n class ").concat(ComponentName, " extends ").concat(((_j = options === null || options === void 0 ? void 0 : options.experimental) === null || _j === void 0 ? void 0 : _j.classExtends)
619
- ? (_k = options === null || options === void 0 ? void 0 : options.experimental) === null || _k === void 0 ? void 0 : _k.classExtends(json, options)
620
- : 'HTMLElement', " {\n ").concat(Array.from(domRefs)
621
- .map(function (ref) {
622
- return "\n get _".concat(ref, "() {\n return this._root.querySelector(\"[data-ref='").concat(ComponentName, "-").concat(ref, "']\")\n }\n ");
623
- })
624
- .join('\n'), "\n\n get _root() {\n return this.shadowRoot || this;\n }\n\n constructor() {\n super();\n const self = this;\n ").concat(
625
- // TODO: more than one context not injector
626
- setContext.length === 1 && ((_l = setContext === null || setContext === void 0 ? void 0 : setContext[0]) === null || _l === void 0 ? void 0 : _l.ref)
627
- ? "this.context = ".concat(setContext[0].ref)
628
- : '', "\n\n ").concat(!((_o = (_m = json.hooks) === null || _m === void 0 ? void 0 : _m.onInit) === null || _o === void 0 ? void 0 : _o.code) ? '' : 'this.onInitOnce = false;', "\n\n this.state = ").concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
629
- valueMapper: function (value) {
630
- return (0, function_1.pipe)((0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(addUpdateAfterSetInCode(value, options, 'self.update'), {
631
- includeProps: false,
632
- includeState: true,
633
- // TODO: if it's an arrow function it's this.state.
634
- replaceWith: 'self.state.',
635
- }), function (newCode) {
636
- return (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(newCode, {
637
- // TODO: replace with `this.` and add setters that call this.update()
638
- includeProps: true,
639
- includeState: false,
640
- replaceWith: 'self.props.',
641
- });
642
- }, function (code) {
643
- return (0, strip_state_and_props_refs_1.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS)({
644
- code: code,
645
- contextVars: contextVars,
646
- // correctly ref the class not state object
647
- context: 'self.',
648
- });
649
- });
650
- },
651
- }), ";\n if (!this.props) {\n this.props = {};\n }\n ").concat(!componentHasProps
652
- ? ''
653
- : "\n this.componentProps = [".concat(Array.from(props)
654
- .map(function (prop) { return "\"".concat(prop, "\""); })
655
- .join(','), "];\n "), "\n\n ").concat(!((_p = json.hooks.onUpdate) === null || _p === void 0 ? void 0 : _p.length)
656
- ? ''
657
- : "\n this.updateDeps = [".concat((_q = json.hooks.onUpdate) === null || _q === void 0 ? void 0 : _q.map(function (hook) { return updateReferencesInCode((hook === null || hook === void 0 ? void 0 : hook.deps) || '[]', options); }).join(','), "];\n "), "\n\n // used to keep track of all nodes created by show/for\n this.nodesToDestroy = [];\n // batch updates\n this.pendingUpdate = false;\n ").concat(((_r = options === null || options === void 0 ? void 0 : options.experimental) === null || _r === void 0 ? void 0 : _r.componentConstructor)
658
- ? (_s = options === null || options === void 0 ? void 0 : options.experimental) === null || _s === void 0 ? void 0 : _s.componentConstructor(json, options)
659
- : '', "\n\n ").concat(options.js, "\n\n ").concat(jsRefs
660
- .map(function (ref) {
661
- var _a;
662
- // const typeParameter = json['refs'][ref]?.typeParameter || '';
663
- var argument = ((_a = json['refs'][ref]) === null || _a === void 0 ? void 0 : _a.argument) || 'null';
664
- return "this._".concat(ref, " = ").concat(argument);
665
- })
666
- .join('\n'), "\n\n if (").concat((_t = json.meta.useMetadata) === null || _t === void 0 ? void 0 : _t.isAttachedToShadowDom, ") {\n this.attachShadow({ mode: 'open' })\n }\n }\n\n\n ").concat(!((_u = json.hooks.onUnMount) === null || _u === void 0 ? void 0 : _u.code)
667
- ? ''
668
- : "\n disconnectedCallback() {\n ".concat(((_v = options === null || options === void 0 ? void 0 : options.experimental) === null || _v === void 0 ? void 0 : _v.disconnectedCallback)
669
- ? (_w = options === null || options === void 0 ? void 0 : options.experimental) === null || _w === void 0 ? void 0 : _w.disconnectedCallback(json, options)
670
- : "\n // onUnMount\n ".concat(updateReferencesInCode(addUpdateAfterSetInCode(json.hooks.onUnMount.code, options), options, {
671
- contextVars: contextVars,
672
- }), "\n this.destroyAnyNodes(); // clean up nodes when component is destroyed\n ").concat(!((_y = (_x = json.hooks) === null || _x === void 0 ? void 0 : _x.onInit) === null || _y === void 0 ? void 0 : _y.code) ? '' : 'this.onInitOnce = false;', "\n "), "\n }\n "), "\n\n destroyAnyNodes() {\n // destroy current view template refs before rendering again\n this.nodesToDestroy.forEach(el => el.remove());\n this.nodesToDestroy = [];\n }\n\n connectedCallback() {\n ").concat(context.join('\n'), "\n ").concat(!componentHasProps
673
- ? ''
674
- : "\n this.getAttributeNames().forEach((attr) => {\n const jsVar = attr.replace(/-/g, '');\n const regexp = new RegExp(jsVar, 'i');\n this.componentProps.forEach(prop => {\n if (regexp.test(prop)) {\n const attrValue = this.getAttribute(attr);\n if (this.props[prop] !== attrValue) {\n this.props[prop] = attrValue;\n }\n }\n });\n });\n ", "\n ").concat(((_z = options === null || options === void 0 ? void 0 : options.experimental) === null || _z === void 0 ? void 0 : _z.connectedCallbackUpdate)
675
- ? (_0 = options === null || options === void 0 ? void 0 : options.experimental) === null || _0 === void 0 ? void 0 : _0.connectedCallbackUpdate(json, html, options)
676
- : "\n this._root.innerHTML = `\n ".concat(html, "`;\n this.pendingUpdate = true;\n ").concat(!((_2 = (_1 = json.hooks) === null || _1 === void 0 ? void 0 : _1.onInit) === null || _2 === void 0 ? void 0 : _2.code) ? '' : 'this.onInit();', "\n this.render();\n this.onMount();\n this.pendingUpdate = false;\n this.update();\n "), "\n }\n ").concat(!((_4 = (_3 = json.hooks) === null || _3 === void 0 ? void 0 : _3.onInit) === null || _4 === void 0 ? void 0 : _4.code)
677
- ? ''
678
- : "\n onInit() {\n ".concat(!((_6 = (_5 = json.hooks) === null || _5 === void 0 ? void 0 : _5.onInit) === null || _6 === void 0 ? void 0 : _6.code)
679
- ? ''
680
- : "\n if (!this.onInitOnce) {\n ".concat(updateReferencesInCode(addUpdateAfterSetInCode((_8 = (_7 = json.hooks) === null || _7 === void 0 ? void 0 : _7.onInit) === null || _8 === void 0 ? void 0 : _8.code, options), options, {
681
- contextVars: contextVars,
682
- }), "\n this.onInitOnce = true;\n }"), "\n }\n "), "\n\n ").concat(!hasShow
683
- ? ''
684
- : "\n showContent(el) {\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content\n // grabs the content of a node that is between <template> tags\n // iterates through child nodes to register all content including text elements\n // attaches the content after the template\n \n \n const elementFragment = el.content.cloneNode(true);\n const children = Array.from(elementFragment.childNodes)\n children.forEach(child => {\n if (el?.scope) {\n child.scope = el.scope;\n }\n if (el?.context) {\n child.context = el.context;\n }\n this.nodesToDestroy.push(child);\n });\n el.after(elementFragment);\n }", "\n ").concat(!((_9 = options === null || options === void 0 ? void 0 : options.experimental) === null || _9 === void 0 ? void 0 : _9.attributeChangedCallback)
685
- ? ''
686
- : "\n attributeChangedCallback(name, oldValue, newValue) {\n ".concat((_10 = options === null || options === void 0 ? void 0 : options.experimental) === null || _10 === void 0 ? void 0 : _10.attributeChangedCallback(['name', 'oldValue', 'newValue'], json, options), "\n }\n "), "\n\n onMount() {\n ").concat(!json.hooks.onMount.length
687
- ? ''
688
- : // TODO: make prettier by grabbing only the function body
689
- "\n // onMount\n ".concat(updateReferencesInCode(addUpdateAfterSetInCode((0, on_mount_1.stringifySingleScopeOnMount)(json), options), options, {
690
- contextVars: contextVars,
691
- }), "\n "), "\n }\n\n onUpdate() {\n ").concat(!((_11 = json.hooks.onUpdate) === null || _11 === void 0 ? void 0 : _11.length)
692
- ? ''
693
- : "\n const self = this;\n ".concat(json.hooks.onUpdate.reduce(function (code, hook, index) {
694
- // create check update
695
- if (hook === null || hook === void 0 ? void 0 : hook.deps) {
696
- code += "\n ;(function (__prev, __next) {\n const __hasChange = __prev.find((val, index) => val !== __next[index]);\n if (__hasChange !== undefined) {\n ".concat(updateReferencesInCode(hook.code, options, {
697
- contextVars: contextVars,
698
- context: 'self.',
699
- }), "\n self.updateDeps[").concat(index, "] = __next;\n }\n }(self.updateDeps[").concat(index, "], ").concat(updateReferencesInCode((hook === null || hook === void 0 ? void 0 : hook.deps) || '[]', options, {
700
- contextVars: contextVars,
701
- context: 'self.',
702
- }), "));\n ");
703
- }
704
- else {
705
- code += "\n ".concat(updateReferencesInCode(hook.code, options, {
706
- contextVars: contextVars,
707
- context: 'self.',
708
- }), "\n ");
709
- }
710
- return code + '\n';
711
- }, ''), " \n "), "\n }\n\n update() {\n if (this.pendingUpdate === true) {\n return;\n }\n this.pendingUpdate = true;\n this.render();\n this.onUpdate();\n this.pendingUpdate = false;\n }\n\n render() {\n ").concat(!componentHasStatefulDom
712
- ? ''
713
- : "\n // grab previous input state\n const preStateful = this.getStateful(this._root);\n const preValues = this.prepareHydrate(preStateful);\n ", "\n\n // re-rendering needs to ensure that all nodes generated by for/show are refreshed\n this.destroyAnyNodes();\n this.updateBindings();\n\n ").concat(!componentHasStatefulDom
714
- ? ''
715
- : "\n // hydrate input state\n if (preValues.length) {\n const nextStateful = this.getStateful(this._root);\n this.hydrateDom(preValues, nextStateful);\n }\n ", "\n }\n ").concat(!componentHasStatefulDom
716
- ? ''
717
- : "\n getStateful(el) {\n const stateful = el.querySelectorAll('[data-dom-state]');\n return stateful ? Array.from(stateful) : [];\n }\n prepareHydrate(stateful) {\n return stateful.map(el => {\n return {\n id: el.dataset.domState,\n value: el.value,\n active: document.activeElement === el,\n selectionStart: el.selectionStart\n };\n });\n }\n hydrateDom(preValues, stateful) {\n return stateful.map((el, index) => {\n const prev = preValues.find((prev) => el.dataset.domState === prev.id);\n if (prev) {\n el.value = prev.value;\n if (prev.active) {\n el.focus();\n el.selectionStart = prev.selectionStart;\n }\n }\n });\n }\n ", "\n\n updateBindings() {\n ").concat(Object.keys(options.onChangeJsById)
718
- .map(function (key) {
719
- var _a, _b, _c, _d, _e, _f, _g;
720
- var value = options.onChangeJsById[key];
721
- if (!value) {
722
- return '';
1014
+
1015
+ update() {
1016
+ if (this.pendingUpdate === true) {
1017
+ return;
1018
+ }
1019
+ this.pendingUpdate = true;
1020
+ this.render();
1021
+ this.onUpdate();
1022
+ this.pendingUpdate = false;
1023
+ }
1024
+
1025
+ render() {
1026
+ ${!componentHasStatefulDom
1027
+ ? ''
1028
+ : `
1029
+ // grab previous input state
1030
+ const preStateful = this.getStateful(this._root);
1031
+ const preValues = this.prepareHydrate(preStateful);
1032
+ `}
1033
+
1034
+ // re-rendering needs to ensure that all nodes generated by for/show are refreshed
1035
+ this.destroyAnyNodes();
1036
+ this.updateBindings();
1037
+
1038
+ ${!componentHasStatefulDom
1039
+ ? ''
1040
+ : `
1041
+ // hydrate input state
1042
+ if (preValues.length) {
1043
+ const nextStateful = this.getStateful(this._root);
1044
+ this.hydrateDom(preValues, nextStateful);
1045
+ }
1046
+ `}
1047
+ }
1048
+ ${!componentHasStatefulDom
1049
+ ? ''
1050
+ : `
1051
+ getStateful(el) {
1052
+ const stateful = el.querySelectorAll('[data-dom-state]');
1053
+ return stateful ? Array.from(stateful) : [];
723
1054
  }
724
- var code = '';
725
- if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.updateBindings) {
726
- key = (_c = (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.updateBindings) === null || _c === void 0 ? void 0 : _c.key(key, value, options);
727
- code = (_e = (_d = options === null || options === void 0 ? void 0 : options.experimental) === null || _d === void 0 ? void 0 : _d.updateBindings) === null || _e === void 0 ? void 0 : _e.code(key, value, options);
1055
+ prepareHydrate(stateful) {
1056
+ return stateful.map(el => {
1057
+ return {
1058
+ id: el.dataset.domState,
1059
+ value: el.value,
1060
+ active: document.activeElement === el,
1061
+ selectionStart: el.selectionStart
1062
+ };
1063
+ });
728
1064
  }
729
- else {
730
- code = updateReferencesInCode(value, options, {
731
- contextVars: contextVars,
732
- });
1065
+ hydrateDom(preValues, stateful) {
1066
+ return stateful.map((el, index) => {
1067
+ const prev = preValues.find((prev) => el.dataset.domState === prev.id);
1068
+ if (prev) {
1069
+ el.value = prev.value;
1070
+ if (prev.active) {
1071
+ el.focus();
1072
+ el.selectionStart = prev.selectionStart;
1073
+ }
1074
+ }
1075
+ });
733
1076
  }
734
- return "\n ".concat(((_f = options === null || options === void 0 ? void 0 : options.experimental) === null || _f === void 0 ? void 0 : _f.generateQuerySelectorAll)
735
- ? "\n ".concat((_g = options === null || options === void 0 ? void 0 : options.experimental) === null || _g === void 0 ? void 0 : _g.generateQuerySelectorAll(key, code), "\n ")
736
- : " \n this._root.querySelectorAll(\"[data-el='".concat(key, "']\").forEach((el) => {\n ").concat(code, "\n })\n "), "\n ");
737
- })
738
- .join('\n\n'), "\n }\n\n // Helper to render content\n renderTextNode(el, text) {\n const textNode = document.createTextNode(text);\n if (el?.scope) {\n textNode.scope = el.scope;\n }\n if (el?.context) {\n textNode.context = el.context;\n }\n el.after(textNode);\n this.nodesToDestroy.push(el.nextSibling);\n }\n ").concat(!hasContext
739
- ? ''
740
- : "\n // get Context Helper\n getContext(el, token) {\n do {\n let value;\n if (el?.context?.get) {\n value = el.context.get(token);\n } else if (el?.context?.[token]) {\n value = el.context[token];\n }\n if (value !== undefined) {\n return value;\n }\n } while ((el = el.parentNode));\n }\n ", "\n ").concat(!hasScope
741
- ? ''
742
- : "\n // scope helper\n getScope(el, name) {\n do {\n let value = el?.scope?.[name]\n if (value !== undefined) {\n return value\n }\n } while ((el = el.parentNode));\n }\n ", "\n\n ").concat(!hasLoop
743
- ? ''
744
- : "\n\n // Helper to render loops\n renderLoop(template, array, itemName, itemIndex, collectionName) {\n const collection = [];\n for (let [index, value] of array.entries()) {\n const elementFragment = template.content.cloneNode(true);\n const children = Array.from(elementFragment.childNodes)\n const localScope = {};\n let scope = localScope;\n if (template?.scope) {\n const getParent = {\n get(target, prop, receiver) {\n if (prop in target) {\n return target[prop];\n }\n if (prop in template.scope) {\n return template.scope[prop];\n }\n return target[prop];\n }\n };\n scope = new Proxy(localScope, getParent);\n }\n children.forEach((child) => {\n if (itemName !== undefined) {\n scope[itemName] = value;\n }\n if (itemIndex !== undefined) {\n scope[itemIndex] = index;\n }\n if (collectionName !== undefined) {\n scope[collectionName] = array;\n }\n child.scope = scope;\n if (template.context) {\n child.context = context;\n }\n this.nodesToDestroy.push(child);\n collection.unshift(child)\n });\n }\n collection.forEach(child => template.after(child));\n }\n ", "\n }\n\n ").concat(((_12 = options === null || options === void 0 ? void 0 : options.experimental) === null || _12 === void 0 ? void 0 : _12.customElementsDefine)
745
- ? (_13 = options === null || options === void 0 ? void 0 : options.experimental) === null || _13 === void 0 ? void 0 : _13.customElementsDefine(kebabName, component, options)
746
- : "customElements.define('".concat(kebabName, "', ").concat(ComponentName, ");"), "\n ");
747
- if (options.plugins) {
748
- str = (0, plugins_1.runPreCodePlugins)({ json: json, code: str, plugins: options.plugins });
749
- }
750
- if (options.prettier !== false) {
751
- try {
752
- str = (0, standalone_1.format)(str, {
753
- parser: 'typescript',
754
- plugins: [
755
- // To support running in browsers
756
- require('prettier/parser-html'),
757
- require('prettier/parser-postcss'),
758
- require('prettier/parser-babel'),
759
- require('prettier/parser-typescript'),
760
- ],
761
- });
1077
+ `}
1078
+
1079
+ updateBindings() {
1080
+ ${Object.keys(options.onChangeJsById)
1081
+ .map((key) => {
1082
+ var _a, _b, _c, _d, _e, _f, _g;
1083
+ const value = options.onChangeJsById[key];
1084
+ if (!value) {
1085
+ return '';
1086
+ }
1087
+ let code = '';
1088
+ if ((_a = options === null || options === void 0 ? void 0 : options.experimental) === null || _a === void 0 ? void 0 : _a.updateBindings) {
1089
+ key = (_c = (_b = options === null || options === void 0 ? void 0 : options.experimental) === null || _b === void 0 ? void 0 : _b.updateBindings) === null || _c === void 0 ? void 0 : _c.key(key, value, options);
1090
+ code = (_e = (_d = options === null || options === void 0 ? void 0 : options.experimental) === null || _d === void 0 ? void 0 : _d.updateBindings) === null || _e === void 0 ? void 0 : _e.code(key, value, options);
1091
+ }
1092
+ else {
1093
+ code = updateReferencesInCode(value, options, {
1094
+ contextVars,
1095
+ });
1096
+ }
1097
+ return `
1098
+ ${((_f = options === null || options === void 0 ? void 0 : options.experimental) === null || _f === void 0 ? void 0 : _f.generateQuerySelectorAll)
1099
+ ? `
1100
+ ${(_g = options === null || options === void 0 ? void 0 : options.experimental) === null || _g === void 0 ? void 0 : _g.generateQuerySelectorAll(key, code)}
1101
+ `
1102
+ : `
1103
+ this._root.querySelectorAll("[data-el='${key}']").forEach((el) => {
1104
+ ${code}
1105
+ })
1106
+ `}
1107
+ `;
1108
+ })
1109
+ .join('\n\n')}
1110
+ }
1111
+
1112
+ // Helper to render content
1113
+ renderTextNode(el, text) {
1114
+ const textNode = document.createTextNode(text);
1115
+ if (el?.scope) {
1116
+ textNode.scope = el.scope;
1117
+ }
1118
+ if (el?.context) {
1119
+ textNode.context = el.context;
1120
+ }
1121
+ el.after(textNode);
1122
+ this.nodesToDestroy.push(el.nextSibling);
1123
+ }
1124
+ ${!hasContext
1125
+ ? ''
1126
+ : `
1127
+ // get Context Helper
1128
+ getContext(el, token) {
1129
+ do {
1130
+ let value;
1131
+ if (el?.context?.get) {
1132
+ value = el.context.get(token);
1133
+ } else if (el?.context?.[token]) {
1134
+ value = el.context[token];
1135
+ }
1136
+ if (value !== undefined) {
1137
+ return value;
1138
+ }
1139
+ } while ((el = el.parentNode));
1140
+ }
1141
+ `}
1142
+ ${!hasScope
1143
+ ? ''
1144
+ : `
1145
+ // scope helper
1146
+ getScope(el, name) {
1147
+ do {
1148
+ let value = el?.scope?.[name]
1149
+ if (value !== undefined) {
1150
+ return value
1151
+ }
1152
+ } while ((el = el.parentNode));
762
1153
  }
763
- catch (err) {
764
- console.warn('Could not prettify', { string: str }, err);
1154
+ `}
1155
+
1156
+ ${!hasLoop
1157
+ ? ''
1158
+ : `
1159
+
1160
+ // Helper to render loops
1161
+ renderLoop(template, array, itemName, itemIndex, collectionName) {
1162
+ const collection = [];
1163
+ for (let [index, value] of array.entries()) {
1164
+ const elementFragment = template.content.cloneNode(true);
1165
+ const children = Array.from(elementFragment.childNodes)
1166
+ const localScope = {};
1167
+ let scope = localScope;
1168
+ if (template?.scope) {
1169
+ const getParent = {
1170
+ get(target, prop, receiver) {
1171
+ if (prop in target) {
1172
+ return target[prop];
1173
+ }
1174
+ if (prop in template.scope) {
1175
+ return template.scope[prop];
1176
+ }
1177
+ return target[prop];
1178
+ }
1179
+ };
1180
+ scope = new Proxy(localScope, getParent);
1181
+ }
1182
+ children.forEach((child) => {
1183
+ if (itemName !== undefined) {
1184
+ scope[itemName] = value;
1185
+ }
1186
+ if (itemIndex !== undefined) {
1187
+ scope[itemIndex] = index;
1188
+ }
1189
+ if (collectionName !== undefined) {
1190
+ scope[collectionName] = array;
1191
+ }
1192
+ child.scope = scope;
1193
+ if (template.context) {
1194
+ child.context = context;
1195
+ }
1196
+ this.nodesToDestroy.push(child);
1197
+ collection.unshift(child)
1198
+ });
765
1199
  }
1200
+ collection.forEach(child => template.after(child));
1201
+ }
1202
+ `}
1203
+ }
1204
+
1205
+ ${((_11 = options === null || options === void 0 ? void 0 : options.experimental) === null || _11 === void 0 ? void 0 : _11.customElementsDefine)
1206
+ ? (_12 = options === null || options === void 0 ? void 0 : options.experimental) === null || _12 === void 0 ? void 0 : _12.customElementsDefine(kebabName, component, options)
1207
+ : `customElements.define('${kebabName}', ${ComponentName});`}
1208
+ `;
1209
+ if (options.plugins) {
1210
+ str = (0, plugins_1.runPreCodePlugins)({ json, code: str, plugins: options.plugins });
1211
+ }
1212
+ if (options.prettier !== false) {
1213
+ try {
1214
+ str = (0, standalone_1.format)(str, {
1215
+ parser: 'typescript',
1216
+ plugins: [
1217
+ // To support running in browsers
1218
+ require('prettier/parser-html'),
1219
+ require('prettier/parser-postcss'),
1220
+ require('prettier/parser-babel'),
1221
+ require('prettier/parser-typescript'),
1222
+ ],
1223
+ });
766
1224
  }
767
- if (options.plugins) {
768
- str = (0, plugins_1.runPostCodePlugins)({ json: json, code: str, plugins: options.plugins });
1225
+ catch (err) {
1226
+ console.warn('Could not prettify', { string: str }, err);
769
1227
  }
770
- return str;
771
- };
1228
+ }
1229
+ if (options.plugins) {
1230
+ str = (0, plugins_1.runPostCodePlugins)({ json, code: str, plugins: options.plugins });
1231
+ }
1232
+ return str;
772
1233
  };
773
1234
  exports.componentToCustomElement = componentToCustomElement;