@builder.io/mitosis 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/src/generators/angular/helpers.d.ts +7 -0
  2. package/dist/src/generators/angular/helpers.js +38 -1
  3. package/dist/src/generators/angular/index.js +21 -51
  4. package/dist/src/generators/angular/types.d.ts +6 -0
  5. package/dist/src/generators/helpers/functions.js +5 -3
  6. package/dist/src/generators/react/state.js +15 -14
  7. package/dist/src/generators/stencil/blocks.d.ts +3 -0
  8. package/dist/src/generators/stencil/blocks.js +108 -0
  9. package/dist/src/generators/stencil/component.js +140 -0
  10. package/dist/src/generators/stencil/helpers/collect-class-string.d.ts +2 -0
  11. package/dist/src/generators/stencil/{collect-class-string.js → helpers/collect-class-string.js} +4 -2
  12. package/dist/src/generators/stencil/helpers/index.d.ts +24 -0
  13. package/dist/src/generators/stencil/helpers/index.js +110 -0
  14. package/dist/src/generators/stencil/index.d.ts +1 -1
  15. package/dist/src/generators/stencil/index.js +1 -1
  16. package/dist/src/generators/stencil/plugins/get-code-processor-plugins.d.ts +3 -0
  17. package/dist/src/generators/stencil/plugins/get-code-processor-plugins.js +24 -0
  18. package/dist/src/generators/stencil/types.d.ts +10 -0
  19. package/dist/src/generators/vue/compositionApi.js +7 -0
  20. package/dist/src/helpers/get-child-components.d.ts +2 -0
  21. package/dist/src/helpers/get-child-components.js +26 -0
  22. package/dist/src/helpers/get-state-object-string.d.ts +1 -0
  23. package/dist/src/helpers/get-state-object-string.js +8 -6
  24. package/dist/src/helpers/get-typed-function.d.ts +4 -0
  25. package/dist/src/helpers/get-typed-function.js +20 -0
  26. package/dist/src/helpers/map-refs.js +2 -1
  27. package/dist/src/helpers/render-imports.js +5 -1
  28. package/dist/src/helpers/strip-state-and-props-refs.js +2 -2
  29. package/dist/src/parsers/jsx/function-parser.js +8 -0
  30. package/package.json +1 -1
  31. package/dist/src/generators/stencil/collect-class-string.d.ts +0 -2
  32. package/dist/src/generators/stencil/generate.js +0 -214
  33. /package/dist/src/generators/stencil/{generate.d.ts → component.d.ts} +0 -0
@@ -26,3 +26,10 @@ export declare const addCodeToOnInit: (root: MitosisComponent, code: string) =>
26
26
  * @param code The code to be added to the onInit and onUpdate hooks.
27
27
  */
28
28
  export declare const makeReactiveState: (root: MitosisComponent, stateName: string, code: string) => void;
29
+ export declare const getDefaultProps: ({ defaultProps }: MitosisComponent) => string;
30
+ /**
31
+ * if any state "property" is trying to access state.* or props.*
32
+ * then we need to move them to onInit where they can be accessed
33
+ * @param json The MitosisComponent.
34
+ */
35
+ export declare const transformState: (json: MitosisComponent) => void;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeReactiveState = exports.addCodeToOnInit = exports.addCodeToOnUpdate = exports.getAppropriateTemplateFunctionKeys = exports.HELPER_FUNCTIONS = void 0;
3
+ exports.transformState = exports.getDefaultProps = exports.makeReactiveState = exports.addCodeToOnInit = exports.addCodeToOnUpdate = exports.getAppropriateTemplateFunctionKeys = exports.HELPER_FUNCTIONS = void 0;
4
+ const strip_state_and_props_refs_1 = require("../../helpers/strip-state-and-props-refs");
4
5
  const HELPER_FUNCTIONS = (isTs) => ({
5
6
  useObjectWrapper: `useObjectWrapper(...args${isTs ? ': any[]' : ''}) {
6
7
  let obj = {}
@@ -83,3 +84,39 @@ const makeReactiveState = (root, stateName, code) => {
83
84
  (0, exports.addCodeToOnUpdate)(root, code);
84
85
  };
85
86
  exports.makeReactiveState = makeReactiveState;
87
+ const getDefaultProps = ({ defaultProps }) => {
88
+ if (!defaultProps)
89
+ return '';
90
+ const defalutPropsString = Object.keys(defaultProps)
91
+ .map((prop) => {
92
+ var _a;
93
+ const value = defaultProps.hasOwnProperty(prop) ? (_a = defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code : 'undefined';
94
+ return `${prop}: ${value}`;
95
+ })
96
+ .join(',');
97
+ return `const defaultProps = {${defalutPropsString}};\n`;
98
+ };
99
+ exports.getDefaultProps = getDefaultProps;
100
+ /**
101
+ * if any state "property" is trying to access state.* or props.*
102
+ * then we need to move them to onInit where they can be accessed
103
+ * @param json The MitosisComponent.
104
+ */
105
+ const transformState = (json) => {
106
+ Object.entries(json.state)
107
+ .reverse()
108
+ .forEach(([key, value]) => {
109
+ var _a;
110
+ if ((value === null || value === void 0 ? void 0 : value.type) === 'property') {
111
+ if (value.code && (value.code.includes('state.') || value.code.includes('props.'))) {
112
+ const code = (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(value.code, { replaceWith: 'this' });
113
+ json.state[key].code = 'null';
114
+ if (!((_a = json.hooks.onInit) === null || _a === void 0 ? void 0 : _a.code)) {
115
+ json.hooks.onInit = { code: '' };
116
+ }
117
+ json.hooks.onInit.code = `\nthis.${key} = ${code};\n${json.hooks.onInit.code}`;
118
+ }
119
+ }
120
+ });
121
+ };
122
+ exports.transformState = transformState;
@@ -7,6 +7,7 @@ exports.componentToAngular = exports.blockToAngular = void 0;
7
7
  const html_tags_1 = require("../../constants/html_tags");
8
8
  const dedent_1 = require("../../helpers/dedent");
9
9
  const fast_clone_1 = require("../../helpers/fast-clone");
10
+ const get_child_components_1 = require("../../helpers/get-child-components");
10
11
  const get_components_used_1 = require("../../helpers/get-components-used");
11
12
  const get_custom_imports_1 = require("../../helpers/get-custom-imports");
12
13
  const get_prop_functions_1 = require("../../helpers/get-prop-functions");
@@ -14,6 +15,7 @@ const get_props_1 = require("../../helpers/get-props");
14
15
  const get_props_ref_1 = require("../../helpers/get-props-ref");
15
16
  const get_refs_1 = require("../../helpers/get-refs");
16
17
  const get_state_object_string_1 = require("../../helpers/get-state-object-string");
18
+ const get_typed_function_1 = require("../../helpers/get-typed-function");
17
19
  const indent_1 = require("../../helpers/indent");
18
20
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
19
21
  const is_upper_case_1 = require("../../helpers/is-upper-case");
@@ -173,7 +175,8 @@ const stringifyBinding = (node, options, blockOptions) => ([key, binding]) => {
173
175
  // TODO: proper babel transform to replace. Util for this
174
176
  if (keyToUse.startsWith('on')) {
175
177
  const { event, value } = processEventBinding(keyToUse, code, node.name, cusArgs[0]);
176
- return ` (${event})="${value}"`;
178
+ // Angular events are all lowerCased
179
+ return ` (${event.toLowerCase()})="${value}"`;
177
180
  }
178
181
  else if (keyToUse === 'class') {
179
182
  return ` [class]="${code}" `;
@@ -568,25 +571,6 @@ const classPropertiesPlugin = () => ({
568
571
  },
569
572
  },
570
573
  });
571
- // if any state "property" is trying to access state.* or props.*
572
- // then we need to move them to onInit where they can be accessed
573
- const transformState = (json) => {
574
- Object.entries(json.state)
575
- .reverse()
576
- .forEach(([key, value]) => {
577
- var _a;
578
- if ((value === null || value === void 0 ? void 0 : value.type) === 'property') {
579
- if (value.code && (value.code.includes('state.') || value.code.includes('props.'))) {
580
- const code = (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(value.code, { replaceWith: 'this' });
581
- json.state[key].code = 'null';
582
- if (!((_a = json.hooks.onInit) === null || _a === void 0 ? void 0 : _a.code)) {
583
- json.hooks.onInit = { code: '' };
584
- }
585
- json.hooks.onInit.code = `\nthis.${key} = ${code};\n${json.hooks.onInit.code}`;
586
- }
587
- }
588
- });
589
- };
590
574
  const componentToAngular = (userOptions = {}) => ({ component: _component }) => {
591
575
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
592
576
  // Make a copy we can safely mutate, similar to babel's toolchain
@@ -656,15 +640,8 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
656
640
  json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
657
641
  }
658
642
  const [forwardProp, hasPropRef] = (0, get_props_ref_1.getPropsRef)(json, true);
659
- const childComponents = [json.name]; // a component can be recursively used in itself
660
643
  const propsTypeRef = json.propsTypeRef !== 'any' ? json.propsTypeRef : undefined;
661
- json.imports.forEach(({ imports }) => {
662
- Object.keys(imports).forEach((key) => {
663
- if (imports[key] === 'default') {
664
- childComponents.push(key);
665
- }
666
- });
667
- });
644
+ const childComponents = (0, get_child_components_1.getChildComponents)(json);
668
645
  const customImports = (0, get_custom_imports_1.getCustomImports)(json);
669
646
  const { exports: localExports = {} } = json;
670
647
  const localExportVars = Object.keys(localExports)
@@ -742,16 +719,23 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
742
719
  childComponents,
743
720
  nativeAttributes: (_d = (_c = useMetadata === null || useMetadata === void 0 ? void 0 : useMetadata.angular) === null || _c === void 0 ? void 0 : _c.nativeAttributes) !== null && _d !== void 0 ? _d : [],
744
721
  });
745
- transformState(json);
722
+ (0, helpers_2.transformState)(json);
746
723
  const dataString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
747
724
  format: 'class',
748
- valueMapper: processAngularCode({
749
- replaceWith: 'this',
750
- contextVars,
751
- outputVars,
752
- domRefs: Array.from(domRefs),
753
- stateVars,
754
- }),
725
+ withType: options.typescript,
726
+ valueMapper: (code, type, typeParameter) => {
727
+ let value = code;
728
+ if (type !== 'data') {
729
+ value = (0, get_typed_function_1.getTypedFunction)(code, options.typescript, typeParameter);
730
+ }
731
+ return processAngularCode({
732
+ replaceWith: 'this',
733
+ contextVars,
734
+ outputVars,
735
+ domRefs: Array.from(domRefs),
736
+ stateVars,
737
+ })(value);
738
+ },
755
739
  });
756
740
  const refsForObjSpread = (0, get_refs_1.getRefs)(json, 'spreadRef');
757
741
  const hostDisplayCss = options.visuallyIgnoreHostElement ? ':host { display: contents; }' : '';
@@ -782,20 +766,6 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
782
766
  Object.entries(json.meta.angularConfig || {}).forEach(([key, value]) => {
783
767
  componentMetadata[key] = value;
784
768
  });
785
- const getPropsDefinition = ({ json }) => {
786
- if (!json.defaultProps)
787
- return '';
788
- const defalutPropsString = Object.keys(json.defaultProps)
789
- .map((prop) => {
790
- var _a;
791
- const value = json.defaultProps.hasOwnProperty(prop)
792
- ? (_a = json.defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code
793
- : 'undefined';
794
- return `${prop}: ${value}`;
795
- })
796
- .join(',');
797
- return `const defaultProps = {${defalutPropsString}};\n`;
798
- };
799
769
  const hasConstructor = Boolean(injectables.length) || dynamicComponents.size || refsForObjSpread.size;
800
770
  const angularCoreImports = [
801
771
  ...(outputs.length ? ['Output', 'EventEmitter'] : []),
@@ -814,7 +784,7 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
814
784
  ${options.standalone ? `import { CommonModule } from '@angular/common';` : ''}
815
785
 
816
786
  ${json.types ? json.types.join('\n') : ''}
817
- ${getPropsDefinition({ json })}
787
+ ${(0, helpers_2.getDefaultProps)(json)}
818
788
  ${(0, render_imports_1.renderPreComponent)({
819
789
  explicitImportFileExtension: options.explicitImportFileExtension,
820
790
  component: json,
@@ -1,3 +1,4 @@
1
+ import { MitosisComponent } from '../../types/mitosis-component';
1
2
  import { BaseTranspilerOptions } from '../../types/transpiler';
2
3
  export declare const BUILT_IN_COMPONENTS: Set<string>;
3
4
  export interface ToAngularOptions extends BaseTranspilerOptions {
@@ -8,6 +9,11 @@ export interface ToAngularOptions extends BaseTranspilerOptions {
8
9
  importMapper?: Function;
9
10
  bootstrapMapper?: Function;
10
11
  visuallyIgnoreHostElement?: boolean;
12
+ experimental?: {
13
+ injectables?: (variableName: string, variableType: string) => string;
14
+ inject?: boolean;
15
+ outputs?: (json: MitosisComponent, variableName: string) => string;
16
+ };
11
17
  }
12
18
  export declare const DEFAULT_ANGULAR_OPTIONS: ToAngularOptions;
13
19
  export type AngularMetadata = {
@@ -5,19 +5,21 @@ const patterns_1 = require("../../helpers/patterns");
5
5
  const FUNCTION_HACK_PLUGIN = () => ({
6
6
  json: {
7
7
  pre: (json) => {
8
- var _a, _b;
9
8
  for (const key in json.state) {
10
- const value = (_a = json.state[key]) === null || _a === void 0 ? void 0 : _a.code;
11
- const type = (_b = json.state[key]) === null || _b === void 0 ? void 0 : _b.type;
9
+ const state = json.state[key];
10
+ const value = state === null || state === void 0 ? void 0 : state.code;
11
+ const type = state === null || state === void 0 ? void 0 : state.type;
12
12
  if (typeof value === 'string' && type === 'method') {
13
13
  const newValue = (0, patterns_1.prefixWithFunction)(value);
14
14
  json.state[key] = {
15
+ ...state,
15
16
  code: newValue,
16
17
  type: 'method',
17
18
  };
18
19
  }
19
20
  else if (typeof value === 'string' && type === 'function') {
20
21
  json.state[key] = {
22
+ ...state,
21
23
  code: value,
22
24
  type: 'method',
23
25
  };
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.updateStateSettersInCode = exports.updateStateSetters = exports.getUseStateCode = exports.processHookCode = void 0;
7
7
  const capitalize_1 = require("../../helpers/capitalize");
8
+ const get_typed_function_1 = require("../../helpers/get-typed-function");
8
9
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
9
10
  const patterns_1 = require("../../helpers/patterns");
10
11
  const transform_state_setters_1 = require("../../helpers/transform-state-setters");
@@ -34,24 +35,24 @@ const processStateValue = (options) => {
34
35
  if (!stateVal) {
35
36
  return '';
36
37
  }
37
- const getDefaultCase = () => `const [${key}, ${getSetStateFnName(key)}] = useState(() => (${mapValue(value)}))`;
38
- const value = stateVal.code || '';
38
+ let value = stateVal.code || '';
39
39
  const type = stateVal.type;
40
- if (typeof value === 'string') {
41
- switch (type) {
42
- case 'getter':
43
- return (0, function_1.pipe)(value, patterns_1.replaceGetterWithFunction, mapValue);
44
- case 'function':
45
- return mapValue(value);
46
- case 'method':
47
- return (0, function_1.pipe)(value, patterns_1.prefixWithFunction, mapValue);
48
- default:
49
- return getDefaultCase();
50
- }
40
+ const typeParameter = stateVal.typeParameter;
41
+ const stateType = options.typescript && stateVal.typeParameter ? `<${stateVal.typeParameter}>` : '';
42
+ let result = '';
43
+ if (type === 'getter') {
44
+ result = (0, function_1.pipe)(value, patterns_1.replaceGetterWithFunction, mapValue);
45
+ }
46
+ else if (type === 'function') {
47
+ result = mapValue(value);
48
+ }
49
+ else if (type === 'method') {
50
+ result = (0, function_1.pipe)(value, patterns_1.prefixWithFunction, mapValue);
51
51
  }
52
52
  else {
53
- return getDefaultCase();
53
+ return `const [${key}, ${getSetStateFnName(key)}] = useState${stateType}(() => (${mapValue(value)}))`;
54
54
  }
55
+ return (0, get_typed_function_1.getTypedFunction)(result, options.typescript, typeParameter);
55
56
  };
56
57
  };
57
58
  const getUseStateCode = (json, options) => {
@@ -0,0 +1,3 @@
1
+ import { ToStencilOptions } from '../../generators/stencil/types';
2
+ import { MitosisNode } from '../../types/mitosis-node';
3
+ export declare const blockToStencil: (json: MitosisNode, options: ToStencilOptions | undefined, insideJsx: boolean, childComponents: string[]) => string;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.blockToStencil = void 0;
4
+ const html_tags_1 = require("../../constants/html_tags");
5
+ const helpers_1 = require("../../generators/stencil/helpers");
6
+ const collect_class_string_1 = require("../../generators/stencil/helpers/collect-class-string");
7
+ const filter_empty_text_nodes_1 = require("../../helpers/filter-empty-text-nodes");
8
+ const for_1 = require("../../helpers/nodes/for");
9
+ const mitosis_node_1 = require("../../types/mitosis-node");
10
+ const blockToStencil = (json, options = {}, insideJsx, childComponents) => {
11
+ var _a, _b, _c, _d, _e, _f;
12
+ let blockName = childComponents.find((impName) => impName === json.name)
13
+ ? (0, helpers_1.getTagName)(json.name, options)
14
+ : json.name;
15
+ if (json.properties._text) {
16
+ return json.properties._text;
17
+ }
18
+ if ((_a = json.bindings._text) === null || _a === void 0 ? void 0 : _a.code) {
19
+ if (((_b = json.bindings._text) === null || _b === void 0 ? void 0 : _b.code) === 'this.children') {
20
+ // Replace this.children with default <slot>
21
+ return '<slot></slot>';
22
+ }
23
+ let code = json.bindings._text.code;
24
+ if (insideJsx) {
25
+ return `{${code}}`;
26
+ }
27
+ return code;
28
+ }
29
+ if ((0, mitosis_node_1.checkIsForNode)(json) && ((_c = json.bindings.each) === null || _c === void 0 ? void 0 : _c.code)) {
30
+ const wrap = json.children.length !== 1;
31
+ const forArgs = (0, for_1.getForArguments)(json).join(', ');
32
+ const expression = `${(_d = json.bindings.each) === null || _d === void 0 ? void 0 : _d.code}?.map((${forArgs}) => (
33
+ ${wrap ? '<Fragment>' : ''}
34
+ ${json.children
35
+ .filter(filter_empty_text_nodes_1.filterEmptyTextNodes)
36
+ .map((item) => (0, exports.blockToStencil)(item, options, wrap, childComponents))
37
+ .join('\n')}
38
+ ${wrap ? '</Fragment>' : ''}
39
+ ))`;
40
+ if (insideJsx) {
41
+ return `{${expression}}`;
42
+ }
43
+ else {
44
+ return expression;
45
+ }
46
+ }
47
+ else if (blockName === 'Show' && ((_e = json.bindings.when) === null || _e === void 0 ? void 0 : _e.code)) {
48
+ const wrap = json.children.length !== 1;
49
+ const expression = `${(_f = json.bindings.when) === null || _f === void 0 ? void 0 : _f.code} ? (
50
+ ${wrap ? '<Fragment>' : ''}
51
+ ${json.children
52
+ .filter(filter_empty_text_nodes_1.filterEmptyTextNodes)
53
+ .map((item) => (0, exports.blockToStencil)(item, options, wrap, childComponents))
54
+ .join('\n')}
55
+ ${wrap ? '</Fragment>' : ''}
56
+ ) : ${!json.meta.else
57
+ ? 'null'
58
+ : `(${(0, exports.blockToStencil)(json.meta.else, options, false, childComponents)})`}`;
59
+ if (insideJsx) {
60
+ return `{${expression}}`;
61
+ }
62
+ else {
63
+ return expression;
64
+ }
65
+ }
66
+ else if (blockName === 'Slot') {
67
+ blockName = 'slot';
68
+ }
69
+ let str = '';
70
+ str += `<${blockName} `;
71
+ const classString = (0, collect_class_string_1.collectClassString)(json);
72
+ if (classString) {
73
+ str += ` class=${classString} `;
74
+ }
75
+ for (const key in json.properties) {
76
+ const value = json.properties[key];
77
+ str += ` ${key}="${value}" `;
78
+ }
79
+ for (const key in json.bindings) {
80
+ const { code, arguments: cusArgs = [], type } = json.bindings[key];
81
+ if (type === 'spread') {
82
+ str += ` {...(${code})} `;
83
+ }
84
+ else if (key === 'ref') {
85
+ // TODO: Add correct type here
86
+ str += ` ref={(el) => ${code.startsWith('this.') ? code : `this.${code}`} = el} `;
87
+ }
88
+ else if ((0, helpers_1.isEvent)(key)) {
89
+ const useKey = key === 'onChange' && blockName === 'input' ? 'onInput' : key;
90
+ str += ` ${useKey}={(${cusArgs.join(',')}) => ${code}} `;
91
+ }
92
+ else {
93
+ str += ` ${key}={${code}} `;
94
+ }
95
+ }
96
+ if (html_tags_1.SELF_CLOSING_HTML_TAGS.has(blockName)) {
97
+ return str + ' />';
98
+ }
99
+ str += '>';
100
+ if (json.children) {
101
+ str += json.children
102
+ .map((item) => (0, exports.blockToStencil)(item, options, true, childComponents))
103
+ .join('\n');
104
+ }
105
+ str += `</${blockName}>`;
106
+ return str;
107
+ };
108
+ exports.blockToStencil = blockToStencil;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.componentToStencil = void 0;
4
+ const on_mount_1 = require("../../generators/helpers/on-mount");
5
+ const blocks_1 = require("../../generators/stencil/blocks");
6
+ const helpers_1 = require("../../generators/stencil/helpers");
7
+ const get_code_processor_plugins_1 = require("../../generators/stencil/plugins/get-code-processor-plugins");
8
+ const dedent_1 = require("../../helpers/dedent");
9
+ const fast_clone_1 = require("../../helpers/fast-clone");
10
+ const get_child_components_1 = require("../../helpers/get-child-components");
11
+ const get_props_1 = require("../../helpers/get-props");
12
+ const get_state_object_string_1 = require("../../helpers/get-state-object-string");
13
+ const indent_1 = require("../../helpers/indent");
14
+ const map_refs_1 = require("../../helpers/map-refs");
15
+ const merge_options_1 = require("../../helpers/merge-options");
16
+ const strip_meta_properties_1 = require("../../helpers/strip-meta-properties");
17
+ const collect_css_1 = require("../../helpers/styles/collect-css");
18
+ const plugins_1 = require("../../modules/plugins");
19
+ const standalone_1 = require("prettier/standalone");
20
+ const componentToStencil = (_options = {
21
+ typescript: true, // Stencil is uses .tsx always
22
+ }) => ({ component }) => {
23
+ var _a, _b, _c, _d, _e;
24
+ let json = (0, fast_clone_1.fastClone)(component);
25
+ const options = (0, merge_options_1.initializeOptions)({
26
+ target: 'stencil',
27
+ component,
28
+ defaults: _options,
29
+ });
30
+ if (options.plugins) {
31
+ json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
32
+ }
33
+ (0, map_refs_1.mapRefs)(json, (refName) => `this.${refName}`);
34
+ let css = (0, collect_css_1.collectCss)(json);
35
+ const props = Array.from((0, get_props_1.getProps)(json));
36
+ const events = props.filter((prop) => (0, helpers_1.isEvent)(prop));
37
+ const defaultProps = json.defaultProps;
38
+ const childComponents = (0, get_child_components_1.getChildComponents)(json);
39
+ const processBindingOptions = { events };
40
+ options.plugins = (0, get_code_processor_plugins_1.getCodeProcessorPlugins)(options, processBindingOptions);
41
+ if (options.plugins) {
42
+ json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
43
+ }
44
+ (0, strip_meta_properties_1.stripMetaProperties)(json);
45
+ const dataString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
46
+ format: 'class',
47
+ data: true,
48
+ functions: false,
49
+ getters: false,
50
+ keyPrefix: '@State() ',
51
+ });
52
+ const methodsString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
53
+ format: 'class',
54
+ data: false,
55
+ functions: true,
56
+ getters: true,
57
+ });
58
+ const refs = json.refs
59
+ ? Object.entries(json.refs)
60
+ .map(([key, value]) => {
61
+ var _a;
62
+ return `private ${key}!: ${(_a = value.typeParameter) !== null && _a !== void 0 ? _a : 'HTMLElement'}`;
63
+ })
64
+ .join('\n')
65
+ : '';
66
+ const wrap = (0, helpers_1.needsWrap)(json.children);
67
+ if (options.prettier !== false) {
68
+ try {
69
+ css = (0, standalone_1.format)(css, {
70
+ parser: 'css',
71
+ plugins: [require('prettier/parser-postcss')],
72
+ });
73
+ }
74
+ catch (err) {
75
+ console.warn('Could not format css', err);
76
+ }
77
+ }
78
+ let tagName = (0, helpers_1.getTagName)(json.name, options);
79
+ if ((_a = json.meta.useMetadata) === null || _a === void 0 ? void 0 : _a.tagName) {
80
+ // Deprecated option, we shouldn't use this, instead change the name of your Mitosis component
81
+ tagName = (_b = json.meta.useMetadata) === null || _b === void 0 ? void 0 : _b.tagName;
82
+ }
83
+ const coreImports = (0, helpers_1.getStencilCoreImportsAsString)(wrap, events, props, dataString);
84
+ let str = (0, dedent_1.dedent) `
85
+ ${(0, helpers_1.getImports)(json, options, childComponents)}
86
+
87
+ import { ${coreImports} } from '@stencil/core';
88
+
89
+ ${json.types ? json.types.join('\n') : ''}
90
+
91
+ @Component({
92
+ tag: '${tagName}',
93
+ ${((_c = json.meta.useMetadata) === null || _c === void 0 ? void 0 : _c.isAttachedToShadowDom) ? 'shadow: true,' : ''}
94
+ ${css.length
95
+ ? `styles: \`
96
+ ${(0, indent_1.indent)(css, 8)}\`,`
97
+ : ''}
98
+ })
99
+ export class ${json.name} {
100
+ ${refs}
101
+ ${(0, helpers_1.getPropsAsCode)(props, defaultProps, json.propsTypeRef)}
102
+ ${dataString}
103
+ ${methodsString}
104
+
105
+ ${!json.hooks.onMount.length
106
+ ? ''
107
+ : `componentDidLoad() { ${(0, on_mount_1.stringifySingleScopeOnMount)(json)} }`}
108
+ ${!((_d = json.hooks.onUnMount) === null || _d === void 0 ? void 0 : _d.code)
109
+ ? ''
110
+ : `disconnectedCallback() { ${json.hooks.onUnMount.code} }`}
111
+ ${!((_e = json.hooks.onUpdate) === null || _e === void 0 ? void 0 : _e.length)
112
+ ? ''
113
+ : `componentDidUpdate() { ${json.hooks.onUpdate.map((hook) => hook.code).join('\n')} }`}
114
+
115
+ render() {
116
+ return (${wrap ? '<Host>' : ''}
117
+
118
+ ${json.children
119
+ .map((item) => (0, blocks_1.blockToStencil)(item, options, true, childComponents))
120
+ .join('\n')}
121
+
122
+ ${wrap ? '</Host>' : ''})
123
+ }
124
+ }
125
+ `;
126
+ if (options.plugins) {
127
+ str = (0, plugins_1.runPreCodePlugins)({ json, code: str, plugins: options.plugins });
128
+ }
129
+ if (options.prettier !== false) {
130
+ str = (0, standalone_1.format)(str, {
131
+ parser: 'typescript',
132
+ plugins: [require('prettier/parser-typescript')],
133
+ });
134
+ }
135
+ if (options.plugins) {
136
+ str = (0, plugins_1.runPostCodePlugins)({ json, code: str, plugins: options.plugins });
137
+ }
138
+ return str;
139
+ };
140
+ exports.componentToStencil = componentToStencil;
@@ -0,0 +1,2 @@
1
+ import { MitosisNode } from '../../../types/mitosis-node';
2
+ export declare const collectClassString: (json: MitosisNode) => string | null;
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collectClassString = void 0;
4
+ const bindingOpenChar = '{';
5
+ const bindingCloseChar = '}';
4
6
  // This should really be a preprocessor mapping the `class` attribute binding based on what other values have
5
7
  // to make this more pluggable
6
- function collectClassString(json, bindingOpenChar = '{', bindingCloseChar = '}') {
8
+ const collectClassString = (json) => {
7
9
  var _a, _b;
8
10
  const staticClasses = [];
9
11
  if (json.properties.class) {
@@ -37,5 +39,5 @@ function collectClassString(json, bindingOpenChar = '{', bindingCloseChar = '}')
37
39
  return `${bindingOpenChar}"${staticClassesString} " + ${dynamicClassesString}${bindingCloseChar}`;
38
40
  }
39
41
  return null;
40
- }
42
+ };
41
43
  exports.collectClassString = collectClassString;
@@ -0,0 +1,24 @@
1
+ import { ToStencilOptions } from '../../../generators/stencil/types';
2
+ import { MitosisComponent, MitosisState } from '../../../types/mitosis-component';
3
+ import { MitosisNode } from '../../../types/mitosis-node';
4
+ export declare const isEvent: (key: string) => boolean;
5
+ export type ProcessBindingOptions = {
6
+ events: string[];
7
+ };
8
+ export declare const processBinding: (code: string, { events }: ProcessBindingOptions) => string;
9
+ export declare const getTagName: (name: string, { prefix }: ToStencilOptions) => string;
10
+ export declare const getPropsAsCode: (props: string[], defaultProps?: MitosisState | undefined, propsTypeRef?: string) => string;
11
+ /**
12
+ * Check for root element if it needs a wrapping <Host>
13
+ * @param children
14
+ */
15
+ export declare const needsWrap: (children: MitosisNode[]) => boolean;
16
+ /**
17
+ * Dynamically creates all imports from `@stencil/core`
18
+ * @param wrap
19
+ * @param events
20
+ * @param props
21
+ * @param dataString
22
+ */
23
+ export declare const getStencilCoreImportsAsString: (wrap: boolean, events: string[], props: string[], dataString: string) => string;
24
+ export declare const getImports: (json: MitosisComponent, options: ToStencilOptions, childComponents: string[]) => string;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getImports = exports.getStencilCoreImportsAsString = exports.needsWrap = exports.getPropsAsCode = exports.getTagName = exports.processBinding = exports.isEvent = void 0;
4
+ const dash_case_1 = require("../../../helpers/dash-case");
5
+ const render_imports_1 = require("../../../helpers/render-imports");
6
+ const strip_state_and_props_refs_1 = require("../../../helpers/strip-state-and-props-refs");
7
+ const isEvent = (key) => key.startsWith('on');
8
+ exports.isEvent = isEvent;
9
+ /**
10
+ * We need to "emit" events those can be on multiple places, so we do it as post step
11
+ */
12
+ const appendEmits = (str, events) => {
13
+ let code = str;
14
+ if (events.length) {
15
+ for (const event of events) {
16
+ code = code.replaceAll(`props.${event}(`, `props.${event}.emit(`);
17
+ }
18
+ }
19
+ return code;
20
+ };
21
+ const processBinding = (code, { events }) => {
22
+ return (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(appendEmits(code, events), { replaceWith: 'this.' });
23
+ };
24
+ exports.processBinding = processBinding;
25
+ const getTagName = (name, { prefix }) => {
26
+ const dashName = (0, dash_case_1.dashCase)(name);
27
+ if (prefix) {
28
+ const dashPrefix = prefix.endsWith('-') ? prefix : `${prefix}-`;
29
+ if (!dashName.startsWith(dashPrefix)) {
30
+ return `${dashPrefix}${dashName}`;
31
+ }
32
+ }
33
+ return dashName;
34
+ };
35
+ exports.getTagName = getTagName;
36
+ const getPropsAsCode = (props, defaultProps, propsTypeRef) => {
37
+ return props
38
+ .map((item) => {
39
+ var _a;
40
+ const defaultProp = defaultProps ? (_a = defaultProps[item]) === null || _a === void 0 ? void 0 : _a.code : undefined;
41
+ const defaultPropString = defaultProp ? ` = ${defaultProp}` : '';
42
+ if ((0, exports.isEvent)(item)) {
43
+ return `@Event() ${item}: any${defaultPropString}`;
44
+ }
45
+ const type = propsTypeRef &&
46
+ propsTypeRef !== 'any' &&
47
+ propsTypeRef !== 'unknown' &&
48
+ propsTypeRef !== 'never'
49
+ ? `${propsTypeRef}["${item}"]`
50
+ : 'any';
51
+ return `@Prop() ${item}: ${type}${defaultPropString}`;
52
+ })
53
+ .join(';\n');
54
+ };
55
+ exports.getPropsAsCode = getPropsAsCode;
56
+ /**
57
+ * Check for root element if it needs a wrapping <Host>
58
+ * @param children
59
+ */
60
+ const needsWrap = (children) => {
61
+ if (children.length !== 1) {
62
+ return true;
63
+ }
64
+ else if (children.length === 1) {
65
+ const firstChild = children.at(0);
66
+ if ((firstChild === null || firstChild === void 0 ? void 0 : firstChild.name) === 'Show' || (firstChild === null || firstChild === void 0 ? void 0 : firstChild.name) === 'For') {
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ };
72
+ exports.needsWrap = needsWrap;
73
+ /**
74
+ * Dynamically creates all imports from `@stencil/core`
75
+ * @param wrap
76
+ * @param events
77
+ * @param props
78
+ * @param dataString
79
+ */
80
+ const getStencilCoreImportsAsString = (wrap, events, props, dataString) => {
81
+ const stencilCoreImports = {
82
+ Component: true,
83
+ h: true,
84
+ Fragment: true,
85
+ Host: wrap,
86
+ Event: events.length > 0,
87
+ Prop: props.length > 0,
88
+ State: dataString.length > 0,
89
+ };
90
+ return Object.entries(stencilCoreImports)
91
+ .map(([key, bool]) => (bool ? key : ''))
92
+ .filter((key) => !!key)
93
+ .join(', ');
94
+ };
95
+ exports.getStencilCoreImportsAsString = getStencilCoreImportsAsString;
96
+ const getImports = (json, options, childComponents) => {
97
+ return (0, render_imports_1.renderPreComponent)({
98
+ explicitImportFileExtension: options.explicitImportFileExtension,
99
+ component: json,
100
+ target: 'stencil',
101
+ importMapper: (_, theImport, importedValues) => {
102
+ const childImport = importedValues.defaultImport;
103
+ if (childImport && childComponents.includes(childImport)) {
104
+ return `import {${childImport}} from '${theImport.path}';`;
105
+ }
106
+ return undefined;
107
+ },
108
+ });
109
+ };
110
+ exports.getImports = getImports;
@@ -1 +1 @@
1
- export * from './generate';
1
+ export * from './component';
@@ -14,4 +14,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./generate"), exports);
17
+ __exportStar(require("./component"), exports);
@@ -0,0 +1,3 @@
1
+ import { ProcessBindingOptions } from '../../../generators/stencil/helpers/index';
2
+ import { ToStencilOptions } from '../../../generators/stencil/types';
3
+ export declare const getCodeProcessorPlugins: (options: ToStencilOptions, processBindingOptions: ProcessBindingOptions) => import("../../..").Plugin[];
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCodeProcessorPlugins = void 0;
4
+ const index_1 = require("../../../generators/stencil/helpers/index");
5
+ const process_code_1 = require("../../../helpers/plugins/process-code");
6
+ const getCodeProcessorPlugins = (options, processBindingOptions) => {
7
+ return [
8
+ ...(options.plugins || []),
9
+ (0, process_code_1.CODE_PROCESSOR_PLUGIN)((codeType) => {
10
+ switch (codeType) {
11
+ case 'bindings':
12
+ case 'properties':
13
+ case 'hooks':
14
+ case 'hooks-deps':
15
+ case 'state':
16
+ case 'context-set':
17
+ case 'dynamic-jsx-elements':
18
+ case 'types':
19
+ return (code) => (0, index_1.processBinding)(code, processBindingOptions);
20
+ }
21
+ }),
22
+ ];
23
+ };
24
+ exports.getCodeProcessorPlugins = getCodeProcessorPlugins;
@@ -1,4 +1,14 @@
1
1
  import { BaseTranspilerOptions } from '../../types/transpiler';
2
2
  export interface ToStencilOptions extends BaseTranspilerOptions {
3
+ /**
4
+ * Add a prefix for every component like `my`.
5
+ * A Stencil component needs a prefix with a dash.
6
+ * You don't need this option if your Mitosis component includes the prefix already:
7
+ *
8
+ * Error: `export default function Button ...` -> tag: 'button'
9
+ * Success: `export default function MyButton ...` -> tag: 'my-button'
10
+ * Success: prefix="my" + `export default function Button ...` -> tag: 'my-button'
11
+ */
12
+ prefix?: string;
3
13
  }
4
14
  export type StencilMetadata = {};
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.generateCompositionApiScript = void 0;
7
7
  const dedent_1 = require("../../helpers/dedent");
8
8
  const get_state_object_string_1 = require("../../helpers/get-state-object-string");
9
+ const get_typed_function_1 = require("../../helpers/get-typed-function");
9
10
  const json5_1 = __importDefault(require("json5"));
10
11
  const lodash_1 = require("lodash");
11
12
  const helpers_1 = require("./helpers");
@@ -49,6 +50,12 @@ function generateCompositionApiScript(component, options, template, props, onUpd
49
50
  getters: false,
50
51
  functions: true,
51
52
  format: 'variables',
53
+ valueMapper: (code, type, typeParameter) => {
54
+ if (type != 'data') {
55
+ return (0, get_typed_function_1.getTypedFunction)(code, isTs, typeParameter);
56
+ }
57
+ return code;
58
+ },
52
59
  });
53
60
  if (template.includes('_classStringToObject')) {
54
61
  methods += ` function _classStringToObject(str${isTs ? ': string' : ''}) {
@@ -0,0 +1,2 @@
1
+ import { MitosisComponent } from '../types/mitosis-component';
2
+ export declare const getChildComponents: (json: MitosisComponent) => string[];
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getChildComponents = void 0;
7
+ const is_mitosis_node_1 = require("../helpers/is-mitosis-node");
8
+ const legacy_1 = __importDefault(require("neotraverse/legacy"));
9
+ const getChildComponents = (json) => {
10
+ const nodes = [];
11
+ const childComponents = [json.name]; // a component can be recursively used in itself
12
+ (0, legacy_1.default)(json).forEach(function (item) {
13
+ if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
14
+ nodes.push(item.name);
15
+ }
16
+ });
17
+ for (const { imports } of json.imports) {
18
+ for (const key of Object.keys(imports)) {
19
+ if (nodes.includes(key)) {
20
+ childComponents.push(key);
21
+ }
22
+ }
23
+ }
24
+ return childComponents;
25
+ };
26
+ exports.getChildComponents = getChildComponents;
@@ -8,6 +8,7 @@ interface GetStateObjectStringOptions {
8
8
  valueMapper?: ValueMapper;
9
9
  format?: 'object' | 'class' | 'variables';
10
10
  keyPrefix?: string;
11
+ withType?: boolean;
11
12
  }
12
13
  export declare const getMemberObjectString: (object: MitosisComponent['state'], userOptions?: GetStateObjectStringOptions) => string;
13
14
  export declare const stringifyContextValue: (object: MitosisContext['value'], userOptions?: GetStateObjectStringOptions) => string;
@@ -8,37 +8,39 @@ const DEFAULT_OPTIONS = {
8
8
  data: true,
9
9
  functions: true,
10
10
  getters: true,
11
+ withType: false,
11
12
  };
12
- const convertStateMemberToString = ({ data, format, functions, getters, keyPrefix, valueMapper }) => ([key, state]) => {
13
+ const convertStateMemberToString = ({ data, format, functions, getters, keyPrefix, valueMapper, withType }) => ([key, state]) => {
13
14
  const keyValueDelimiter = format === 'object' ? ':' : '=';
14
15
  if (!state) {
15
16
  return undefined;
16
17
  }
17
18
  const { code, typeParameter } = state;
19
+ const type = withType && typeParameter ? `:${typeParameter}` : '';
18
20
  switch (state.type) {
19
21
  case 'function': {
20
- if (functions === false || typeof code !== 'string') {
22
+ if (!functions) {
21
23
  return undefined;
22
24
  }
23
25
  return `${keyPrefix} ${key} ${keyValueDelimiter} ${valueMapper(code, 'function', typeParameter, key)}`;
24
26
  }
25
27
  case 'method': {
26
- if (functions === false || typeof code !== 'string') {
28
+ if (!functions) {
27
29
  return undefined;
28
30
  }
29
31
  return `${keyPrefix} ${valueMapper(code, 'function', typeParameter, key)}`;
30
32
  }
31
33
  case 'getter': {
32
- if (getters === false || typeof code !== 'string') {
34
+ if (!getters) {
33
35
  return undefined;
34
36
  }
35
37
  return `${keyPrefix} ${valueMapper(code, 'getter', typeParameter, key)}`;
36
38
  }
37
39
  case 'property': {
38
- if (data === false) {
40
+ if (!data) {
39
41
  return undefined;
40
42
  }
41
- return `${keyPrefix} ${key}${keyValueDelimiter} ${valueMapper(code, 'data', typeParameter, key)}`;
43
+ return `${keyPrefix} ${key}${type}${keyValueDelimiter} ${valueMapper(code, 'data', typeParameter, key)}`;
42
44
  }
43
45
  default:
44
46
  break;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Get functions with typescript typing
3
+ */
4
+ export declare const getTypedFunction: (code: string, typescript?: boolean, typeParameter?: string) => string;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTypedFunction = void 0;
4
+ /**
5
+ * Get functions with typescript typing
6
+ */
7
+ const getTypedFunction = (code, typescript, typeParameter) => {
8
+ if (!typeParameter || !typescript) {
9
+ return code;
10
+ }
11
+ const firstParenthesisIndex = code.indexOf('{');
12
+ // The function should have at least one {
13
+ if (firstParenthesisIndex < 0) {
14
+ return code;
15
+ }
16
+ const preType = code.slice(0, firstParenthesisIndex - 1);
17
+ const postType = code.slice(firstParenthesisIndex, code.length);
18
+ return [preType, ': ', `ReturnType<${typeParameter}>`, postType].join('');
19
+ };
20
+ exports.getTypedFunction = getTypedFunction;
@@ -36,12 +36,13 @@ const mapRefs = (component, mapper) => {
36
36
  const isGet = stateVal.type === 'getter';
37
37
  const isSet = Boolean(value.match(patterns_1.SETTER));
38
38
  component.state[key] = {
39
+ ...stateVal,
39
40
  code: replaceRefsInString(value.replace(/^(get |set )?/, 'function '), refs, mapper).replace(/^function /, isGet ? 'get ' : isSet ? 'set ' : ''),
40
- type: stateVal.type,
41
41
  };
42
42
  break;
43
43
  case 'function':
44
44
  component.state[key] = {
45
+ ...stateVal,
45
46
  code: replaceRefsInString(value, refs, mapper),
46
47
  type: 'function',
47
48
  };
@@ -105,7 +105,11 @@ const renderImport = ({ theImport, target, asyncComponentImports, preserveFileEx
105
105
  }
106
106
  }
107
107
  if (importMapper) {
108
- return importMapper(component, theImport, importedValues, componentsUsed);
108
+ const importMapperResult = importMapper(component, theImport, importedValues, componentsUsed);
109
+ // If import mapper has no result we skip this
110
+ if (importMapperResult) {
111
+ return importMapperResult;
112
+ }
109
113
  }
110
114
  return importValue
111
115
  ? `import ${isTypeImport ? 'type' : ''} ${importValue} from '${path}';`
@@ -71,14 +71,14 @@ const stripStateAndPropsRefs = (code, _options = {}) => {
71
71
  ...DEFAULT_OPTIONS,
72
72
  ..._options,
73
73
  };
74
- if (includeProps !== false) {
74
+ if (includeProps) {
75
75
  newCode = (0, replace_identifiers_1.replacePropsIdentifier)(replaceWith)(newCode);
76
76
  // TODO: webcomponent edge-case
77
77
  if (/el\.this\.props/.test(newCode)) {
78
78
  newCode = newCode.replace(/el\.this\.props/g, 'el.props');
79
79
  }
80
80
  }
81
- if (includeState !== false) {
81
+ if (includeState) {
82
82
  newCode = (0, replace_identifiers_1.replaceStateIdentifier)(replaceWith)(newCode);
83
83
  }
84
84
  return newCode;
@@ -258,6 +258,14 @@ const componentFunctionToJson = (node, context) => {
258
258
  if (types.isObjectExpression(firstArg)) {
259
259
  const useStoreState = (0, state_1.parseStateObjectToMitosisState)(firstArg);
260
260
  Object.assign(state, useStoreState);
261
+ const stateKeys = Object.keys(useStoreState);
262
+ if (types.isTSTypeParameterInstantiation(init.typeParameters)) {
263
+ const type = (0, generator_1.default)(init.typeParameters.params[0]);
264
+ // Type for store has to be an object so we can use it like this
265
+ for (const key of stateKeys) {
266
+ state[key].typeParameter = `${type.code}["${key}"]`;
267
+ }
268
+ }
261
269
  }
262
270
  }
263
271
  else if (init.callee.name === hooks_1.HOOKS.CONTEXT) {
package/package.json CHANGED
@@ -22,7 +22,7 @@
22
22
  "name": "Builder.io",
23
23
  "url": "https://www.builder.io"
24
24
  },
25
- "version": "0.4.6",
25
+ "version": "0.5.0",
26
26
  "homepage": "https://github.com/BuilderIO/mitosis",
27
27
  "main": "./dist/src/index.js",
28
28
  "exports": {
@@ -1,2 +0,0 @@
1
- import { MitosisNode } from '../../types/mitosis-node';
2
- export declare function collectClassString(json: MitosisNode, bindingOpenChar?: string, bindingCloseChar?: string): string | null;
@@ -1,214 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.componentToStencil = void 0;
4
- const dash_case_1 = require("../../helpers/dash-case");
5
- const dedent_1 = require("../../helpers/dedent");
6
- const fast_clone_1 = require("../../helpers/fast-clone");
7
- const filter_empty_text_nodes_1 = require("../../helpers/filter-empty-text-nodes");
8
- const get_props_1 = require("../../helpers/get-props");
9
- const get_state_object_string_1 = require("../../helpers/get-state-object-string");
10
- const indent_1 = require("../../helpers/indent");
11
- const map_refs_1 = require("../../helpers/map-refs");
12
- const merge_options_1 = require("../../helpers/merge-options");
13
- const for_1 = require("../../helpers/nodes/for");
14
- const render_imports_1 = require("../../helpers/render-imports");
15
- const strip_meta_properties_1 = require("../../helpers/strip-meta-properties");
16
- const strip_state_and_props_refs_1 = require("../../helpers/strip-state-and-props-refs");
17
- const collect_css_1 = require("../../helpers/styles/collect-css");
18
- const mitosis_node_1 = require("../../types/mitosis-node");
19
- const standalone_1 = require("prettier/standalone");
20
- const html_tags_1 = require("../../constants/html_tags");
21
- const plugins_1 = require("../../modules/plugins");
22
- const on_mount_1 = require("../helpers/on-mount");
23
- const collect_class_string_1 = require("./collect-class-string");
24
- const blockToStencil = (json, options = {}, insideJsx) => {
25
- var _a, _b, _c, _d;
26
- if (json.properties._text) {
27
- return json.properties._text;
28
- }
29
- if ((_a = json.bindings._text) === null || _a === void 0 ? void 0 : _a.code) {
30
- if (insideJsx) {
31
- return `{${processBinding(json.bindings._text.code)}}`;
32
- }
33
- return processBinding((_b = json.bindings) === null || _b === void 0 ? void 0 : _b._text.code);
34
- }
35
- if ((0, mitosis_node_1.checkIsForNode)(json)) {
36
- const wrap = json.children.length !== 1;
37
- const forArgs = (0, for_1.getForArguments)(json).join(', ');
38
- const expression = `${processBinding((_c = json.bindings.each) === null || _c === void 0 ? void 0 : _c.code)}?.map((${forArgs}) => (
39
- ${wrap ? '<>' : ''}${json.children
40
- .filter(filter_empty_text_nodes_1.filterEmptyTextNodes)
41
- .map((item) => blockToStencil(item, options, wrap))
42
- .join('\n')}${wrap ? '</>' : ''}
43
- ))`;
44
- if (insideJsx) {
45
- return `{${expression}}`;
46
- }
47
- else {
48
- return expression;
49
- }
50
- }
51
- else if (json.name === 'Show') {
52
- const wrap = json.children.length !== 1;
53
- const expression = `${processBinding((_d = json.bindings.when) === null || _d === void 0 ? void 0 : _d.code)} ? (
54
- ${wrap ? '<>' : ''}${json.children
55
- .filter(filter_empty_text_nodes_1.filterEmptyTextNodes)
56
- .map((item) => blockToStencil(item, options, wrap))
57
- .join('\n')}${wrap ? '</>' : ''}
58
- ) : ${!json.meta.else ? 'null' : blockToStencil(json.meta.else, options, false)}`;
59
- if (insideJsx) {
60
- return `{${expression}}`;
61
- }
62
- else {
63
- return expression;
64
- }
65
- }
66
- let str = '';
67
- str += `<${json.name} `;
68
- const classString = (0, collect_class_string_1.collectClassString)(json);
69
- if (classString) {
70
- str += ` class=${classString} `;
71
- }
72
- for (const key in json.properties) {
73
- const value = json.properties[key];
74
- str += ` ${key}="${value}" `;
75
- }
76
- for (const key in json.bindings) {
77
- const { code, arguments: cusArgs = ['event'], type } = json.bindings[key];
78
- if (type === 'spread') {
79
- str += ` {...(${code})} `;
80
- }
81
- else if (key === 'ref') {
82
- str += ` ref={(el) => this.${code} = el} `;
83
- }
84
- else if (key.startsWith('on')) {
85
- const useKey = key === 'onChange' && json.name === 'input' ? 'onInput' : key;
86
- str += ` ${useKey}={${cusArgs.join(',')} => ${processBinding(code)}} `;
87
- }
88
- else {
89
- str += ` ${key}={${processBinding(code)}} `;
90
- }
91
- }
92
- if (html_tags_1.SELF_CLOSING_HTML_TAGS.has(json.name)) {
93
- return str + ' />';
94
- }
95
- str += '>';
96
- if (json.children) {
97
- str += json.children.map((item) => blockToStencil(item, options, true)).join('\n');
98
- }
99
- str += `</${json.name}>`;
100
- return str;
101
- };
102
- function processBinding(code) {
103
- return (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(code, { replaceWith: 'this.' });
104
- }
105
- const componentToStencil = (_options = {}) => ({ component }) => {
106
- var _a, _b, _c;
107
- const options = (0, merge_options_1.initializeOptions)({ target: 'stencil', component, defaults: _options });
108
- let json = (0, fast_clone_1.fastClone)(component);
109
- if (options.plugins) {
110
- json = (0, plugins_1.runPreJsonPlugins)({ json, plugins: options.plugins });
111
- }
112
- const props = (0, get_props_1.getProps)(component);
113
- let css = (0, collect_css_1.collectCss)(json);
114
- (0, map_refs_1.mapRefs)(component, (refName) => `this.${refName}`);
115
- if (options.plugins) {
116
- json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
117
- }
118
- (0, strip_meta_properties_1.stripMetaProperties)(json);
119
- const dataString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
120
- format: 'class',
121
- data: true,
122
- functions: false,
123
- getters: false,
124
- keyPrefix: '@State() ',
125
- valueMapper: (code) => processBinding(code),
126
- });
127
- const methodsString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
128
- format: 'class',
129
- data: false,
130
- functions: true,
131
- getters: true,
132
- valueMapper: (code) => processBinding(code),
133
- });
134
- const wrap = json.children.length !== 1;
135
- if (options.prettier !== false) {
136
- try {
137
- css = (0, standalone_1.format)(css, {
138
- parser: 'css',
139
- plugins: [require('prettier/parser-postcss')],
140
- });
141
- }
142
- catch (err) {
143
- console.warn('Could not format css', err);
144
- }
145
- }
146
- let str = (0, dedent_1.dedent) `
147
- ${(0, render_imports_1.renderPreComponent)({
148
- explicitImportFileExtension: options.explicitImportFileExtension,
149
- component: json,
150
- target: 'stencil',
151
- })}
152
-
153
- import { Component, Prop, h, State, Fragment } from '@stencil/core';
154
-
155
- @Component({
156
- tag: '${
157
- /**
158
- * You can set the tagName in your Mitosis component as
159
- *
160
- * useMetadata({
161
- * tagName: 'my-tag
162
- * })
163
- *
164
- * export default function ...
165
- */
166
- ((_a = json.meta.useMetadata) === null || _a === void 0 ? void 0 : _a.tagName) || (0, dash_case_1.dashCase)(json.name)}',
167
- ${css.length
168
- ? `styles: \`
169
- ${(0, indent_1.indent)(css, 8)}\`,`
170
- : ''}
171
- })
172
- export default class ${json.name} {
173
-
174
- ${Array.from(props)
175
- .map((item) => `@Prop() ${item}: any`)
176
- .join('\n')}
177
-
178
- ${dataString}
179
- ${methodsString}
180
-
181
- ${!json.hooks.onMount.length
182
- ? ''
183
- : `componentDidLoad() { ${processBinding((0, on_mount_1.stringifySingleScopeOnMount)(json))} }`}
184
- ${!((_b = json.hooks.onUnMount) === null || _b === void 0 ? void 0 : _b.code)
185
- ? ''
186
- : `disconnectedCallback() { ${processBinding(json.hooks.onUnMount.code)} }`}
187
- ${!((_c = json.hooks.onUpdate) === null || _c === void 0 ? void 0 : _c.length)
188
- ? ''
189
- : json.hooks.onUpdate.map((hook) => `componentDidUpdate() { ${processBinding(hook.code)} }`)}
190
-
191
- render() {
192
- return (${wrap ? '<>' : ''}
193
-
194
- ${json.children.map((item) => blockToStencil(item, options, true)).join('\n')}
195
-
196
- ${wrap ? '</>' : ''})
197
- }
198
- }
199
- `;
200
- if (options.plugins) {
201
- str = (0, plugins_1.runPreCodePlugins)({ json, code: str, plugins: options.plugins });
202
- }
203
- if (options.prettier !== false) {
204
- str = (0, standalone_1.format)(str, {
205
- parser: 'typescript',
206
- plugins: [require('prettier/parser-typescript')],
207
- });
208
- }
209
- if (options.plugins) {
210
- str = (0, plugins_1.runPostCodePlugins)({ json, code: str, plugins: options.plugins });
211
- }
212
- return str;
213
- };
214
- exports.componentToStencil = componentToStencil;