@builder.io/mitosis 0.4.6 → 0.4.7

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.
@@ -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;
@@ -14,6 +14,7 @@ const get_props_1 = require("../../helpers/get-props");
14
14
  const get_props_ref_1 = require("../../helpers/get-props-ref");
15
15
  const get_refs_1 = require("../../helpers/get-refs");
16
16
  const get_state_object_string_1 = require("../../helpers/get-state-object-string");
17
+ const get_typed_function_1 = require("../../helpers/get-typed-function");
17
18
  const indent_1 = require("../../helpers/indent");
18
19
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
19
20
  const is_upper_case_1 = require("../../helpers/is-upper-case");
@@ -568,25 +569,6 @@ const classPropertiesPlugin = () => ({
568
569
  },
569
570
  },
570
571
  });
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
572
  const componentToAngular = (userOptions = {}) => ({ component: _component }) => {
591
573
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
592
574
  // Make a copy we can safely mutate, similar to babel's toolchain
@@ -742,16 +724,23 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
742
724
  childComponents,
743
725
  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
726
  });
745
- transformState(json);
727
+ (0, helpers_2.transformState)(json);
746
728
  const dataString = (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
747
729
  format: 'class',
748
- valueMapper: processAngularCode({
749
- replaceWith: 'this',
750
- contextVars,
751
- outputVars,
752
- domRefs: Array.from(domRefs),
753
- stateVars,
754
- }),
730
+ withType: options.typescript,
731
+ valueMapper: (code, type, typeParameter) => {
732
+ let value = code;
733
+ if (type !== 'data') {
734
+ value = (0, get_typed_function_1.getTypedFunction)(code, options.typescript, typeParameter);
735
+ }
736
+ return processAngularCode({
737
+ replaceWith: 'this',
738
+ contextVars,
739
+ outputVars,
740
+ domRefs: Array.from(domRefs),
741
+ stateVars,
742
+ })(value);
743
+ },
755
744
  });
756
745
  const refsForObjSpread = (0, get_refs_1.getRefs)(json, 'spreadRef');
757
746
  const hostDisplayCss = options.visuallyIgnoreHostElement ? ':host { display: contents; }' : '';
@@ -782,20 +771,6 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
782
771
  Object.entries(json.meta.angularConfig || {}).forEach(([key, value]) => {
783
772
  componentMetadata[key] = value;
784
773
  });
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
774
  const hasConstructor = Boolean(injectables.length) || dynamicComponents.size || refsForObjSpread.size;
800
775
  const angularCoreImports = [
801
776
  ...(outputs.length ? ['Output', 'EventEmitter'] : []),
@@ -814,7 +789,7 @@ const componentToAngular = (userOptions = {}) => ({ component: _component }) =>
814
789
  ${options.standalone ? `import { CommonModule } from '@angular/common';` : ''}
815
790
 
816
791
  ${json.types ? json.types.join('\n') : ''}
817
- ${getPropsDefinition({ json })}
792
+ ${(0, helpers_2.getDefaultProps)(json)}
818
793
  ${(0, render_imports_1.renderPreComponent)({
819
794
  explicitImportFileExtension: options.explicitImportFileExtension,
820
795
  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) => {
@@ -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' : ''}) {
@@ -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, ': ', 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
  };
@@ -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.4.7",
26
26
  "homepage": "https://github.com/BuilderIO/mitosis",
27
27
  "main": "./dist/src/index.js",
28
28
  "exports": {