@builder.io/mitosis 0.5.16 → 0.5.18

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.
@@ -150,9 +150,6 @@ const processCodeBlockInTemplate = (code) => {
150
150
  const processEventBinding = (key, code, nodeName, customArg) => {
151
151
  let event = key.replace('on', '');
152
152
  event = event.charAt(0).toLowerCase() + event.slice(1);
153
- if (event === 'change' && nodeName === 'input' /* todo: other tags */) {
154
- event = 'input';
155
- }
156
153
  // TODO: proper babel transform to replace. Util for this
157
154
  const eventName = customArg;
158
155
  const regexp = new RegExp('(^|\\n|\\r| |;|\\(|\\[|!)' + eventName + '(\\?\\.|\\.|\\(| |;|\\)|$)', 'g');
@@ -23,7 +23,6 @@ const has_component_1 = require("../../helpers/has-component");
23
23
  const has_props_1 = require("../../helpers/has-props");
24
24
  const has_stateful_dom_1 = require("../../helpers/has-stateful-dom");
25
25
  const is_children_1 = __importDefault(require("../../helpers/is-children"));
26
- const is_component_1 = require("../../helpers/is-component");
27
26
  const is_html_attribute_1 = require("../../helpers/is-html-attribute");
28
27
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
29
28
  const map_refs_1 = require("../../helpers/map-refs");
@@ -298,9 +297,6 @@ const blockToHtml = (json, options, blockOptions = {}) => {
298
297
  const useValue = value;
299
298
  if (key.startsWith('on')) {
300
299
  let event = key.replace('on', '').toLowerCase();
301
- if (!(0, is_component_1.isComponent)(json) && event === 'change') {
302
- event = 'input';
303
- }
304
300
  const fnName = (0, lodash_1.camelCase)(`on-${elId}-${event}`);
305
301
  const codeContent = (0, remove_surrounding_block_1.removeSurroundingBlock)(updateReferencesInCode(useValue, options, blockOptions));
306
302
  const asyncKeyword = ((_h = json.bindings[key]) === null || _h === void 0 ? void 0 : _h.async) ? 'async ' : '';
@@ -81,9 +81,8 @@ const blockToLit = (json, options = {}) => {
81
81
  str += ` ref="${code}" `;
82
82
  }
83
83
  else if (key.startsWith('on')) {
84
- let useKey = key === 'onChange' && json.name === 'input' ? 'onInput' : key;
85
84
  const asyncKeyword = ((_g = json.bindings[key]) === null || _g === void 0 ? void 0 : _g.async) ? 'async ' : '';
86
- useKey = '@' + useKey.substring(2).toLowerCase();
85
+ const useKey = '@' + key.substring(2).toLowerCase();
87
86
  str += ` ${useKey}=\${${asyncKeyword}(${cusArgs.join(',')}) => ${processBinding(code)}} `;
88
87
  }
89
88
  else {
@@ -57,10 +57,10 @@ const NODE_MAPPERS = {
57
57
  return `<>{${slotProp} ${hasChildren ? `|| (${renderChildren()})` : ''}}</>`;
58
58
  },
59
59
  Fragment(json, options, component) {
60
- const wrap = (0, helpers_1.wrapInFragment)(json) || (0, is_root_text_node_1.isRootTextNode)(json);
61
- return `${wrap ? (0, helpers_1.getFragment)('open', options) : ''}${json.children
60
+ const wrap = (0, helpers_1.isFragmentWithKey)(json) || (0, helpers_1.wrapInFragment)(json) || (0, is_root_text_node_1.isRootTextNode)(json);
61
+ return `${wrap ? (0, helpers_1.getFragment)('open', options, json) : ''}${json.children
62
62
  .map((item) => (0, exports.blockToReact)(item, options, component, wrap))
63
- .join('\n')}${wrap ? (0, helpers_1.getFragment)('close', options) : ''}`;
63
+ .join('\n')}${wrap ? (0, helpers_1.getFragment)('close', options, json) : ''}`;
64
64
  },
65
65
  For(_json, options, component, insideJsx) {
66
66
  var _a;
@@ -4,6 +4,7 @@ import { ToReactOptions } from './types';
4
4
  export declare const processBinding: (str: string, options: ToReactOptions) => string;
5
5
  export declare const openFrag: (options: ToReactOptions) => string;
6
6
  export declare const closeFrag: (options: ToReactOptions) => string;
7
- export declare function getFragment(type: 'open' | 'close', options: ToReactOptions): string;
7
+ export declare const isFragmentWithKey: (node?: MitosisNode) => boolean;
8
+ export declare function getFragment(type: 'open' | 'close', options: ToReactOptions, node?: MitosisNode): string;
8
9
  export declare const wrapInFragment: (json: MitosisComponent | MitosisNode) => boolean;
9
10
  export declare function processTagReferences(json: MitosisComponent, options: ToReactOptions): void;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.processTagReferences = exports.wrapInFragment = exports.getFragment = exports.closeFrag = exports.openFrag = exports.processBinding = void 0;
6
+ exports.processTagReferences = exports.wrapInFragment = exports.getFragment = exports.isFragmentWithKey = exports.closeFrag = exports.openFrag = exports.processBinding = void 0;
7
7
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
8
8
  const strip_state_and_props_refs_1 = require("../../helpers/strip-state-and-props-refs");
9
9
  const lodash_1 = require("lodash");
@@ -23,9 +23,21 @@ const openFrag = (options) => getFragment('open', options);
23
23
  exports.openFrag = openFrag;
24
24
  const closeFrag = (options) => getFragment('close', options);
25
25
  exports.closeFrag = closeFrag;
26
- function getFragment(type, options) {
27
- const tagName = options.preact ? 'Fragment' : '';
28
- return type === 'open' ? `<${tagName}>` : `</${tagName}>`;
26
+ const isFragmentWithKey = (node) => (node === null || node === void 0 ? void 0 : node.name) === 'Fragment' && !!(node === null || node === void 0 ? void 0 : node.bindings['key']);
27
+ exports.isFragmentWithKey = isFragmentWithKey;
28
+ function getFragment(type, options, node) {
29
+ var _a;
30
+ let tag = '';
31
+ if (node && node.bindings && (0, exports.isFragmentWithKey)(node)) {
32
+ tag = options.preact ? 'Fragment' : 'React.Fragment';
33
+ if (type === 'open') {
34
+ tag += ` key={${(_a = node.bindings['key']) === null || _a === void 0 ? void 0 : _a.code}}`;
35
+ }
36
+ }
37
+ else if (options.preact) {
38
+ tag = 'Fragment';
39
+ }
40
+ return type === 'open' ? `<${tag}>` : `</${tag}>`;
29
41
  }
30
42
  exports.getFragment = getFragment;
31
43
  const wrapInFragment = (json) => json.children.length !== 1;
@@ -50,7 +50,8 @@ const blockToSolid = (json, component, options, insideJsx) => {
50
50
  </For>`;
51
51
  }
52
52
  let str = '';
53
- if (json.name === 'Fragment') {
53
+ const isFragmentWithoutKey = json.name === 'Fragment' && !json.bindings.key;
54
+ if (isFragmentWithoutKey) {
54
55
  str += '<';
55
56
  }
56
57
  else {
@@ -121,7 +122,7 @@ const blockToSolid = (json, component, options, insideJsx) => {
121
122
  .map((item) => (0, exports.blockToSolid)(item, component, options, true))
122
123
  .join('\n');
123
124
  }
124
- if (json.name === 'Fragment') {
125
+ if (isFragmentWithoutKey) {
125
126
  str += '</>';
126
127
  }
127
128
  else {
@@ -86,9 +86,8 @@ const blockToStencil = (json, options = {}, insideJsx, childComponents) => {
86
86
  str += ` ref={(el) => ${code.startsWith('this.') ? code : `this.${code}`} = el} `;
87
87
  }
88
88
  else if ((0, helpers_1.isEvent)(key)) {
89
- const useKey = key === 'onChange' && blockName === 'input' ? 'onInput' : key;
90
89
  const asyncKeyword = ((_g = json.bindings[key]) === null || _g === void 0 ? void 0 : _g.async) ? 'async ' : '';
91
- str += ` ${useKey}={${asyncKeyword}(${cusArgs.join(',')}) => ${code}} `;
90
+ str += ` ${key}={${asyncKeyword}(${cusArgs.join(',')}) => ${code}} `;
92
91
  }
93
92
  else {
94
93
  str += ` ${key}={${code}} `;
@@ -42,7 +42,9 @@ function generateCompositionApiScript(component, options, template, props, onUpd
42
42
  functions: false,
43
43
  getters: false,
44
44
  format: 'variables',
45
- valueMapper: (code, _, typeParameter) => isTs && typeParameter ? `ref<${typeParameter}>(${code})` : `ref(${code})`,
45
+ valueMapper: (code, _, typeParameter) => {
46
+ return isTs && typeParameter ? `ref<${typeParameter}>(${code})` : `ref(${code})`;
47
+ },
46
48
  keyPrefix: 'const',
47
49
  });
48
50
  let methods = (0, get_state_object_string_1.getStateObjectStringFromComponent)(component, {
@@ -84,8 +86,10 @@ function generateCompositionApiScript(component, options, template, props, onUpd
84
86
  }).join('\n')}
85
87
 
86
88
  ${(_c = Object.keys(component.refs)) === null || _c === void 0 ? void 0 : _c.map((key) => {
89
+ var _a;
87
90
  if (isTs) {
88
- return `const ${key} = ref<${component.refs[key].typeParameter}>()`;
91
+ const type = (_a = component.refs[key].typeParameter) !== null && _a !== void 0 ? _a : 'any';
92
+ return `const ${key} = ref<${type}>(null)`;
89
93
  }
90
94
  else {
91
95
  return `const ${key} = ref(null)`;
@@ -88,12 +88,14 @@ const getAllRefs = (component) => {
88
88
  return allKeys;
89
89
  };
90
90
  function processRefs({ input, component, options, thisPrefix, }) {
91
- const refs = options.api === 'options' ? getContextNames(component) : getAllRefs(component);
91
+ const { api } = options;
92
+ const refs = api === 'options' ? getContextNames(component) : getAllRefs(component);
92
93
  return (0, babel_transform_1.babelTransformExpression)(input, {
93
94
  Identifier(path) {
94
95
  const name = path.node.name;
95
- if (refs.includes(name) && shouldAppendValueToRef(path)) {
96
- const newValue = options.api === 'options' ? `${thisPrefix}.${name}` : `${name}.value`;
96
+ // Composition api should use .value all the time
97
+ if (refs.includes(name) && (api === 'composition' || shouldAppendValueToRef(path))) {
98
+ const newValue = api === 'options' ? `${thisPrefix}.${name}` : `${name}.value`;
97
99
  path.replaceWith(core_1.types.identifier(newValue));
98
100
  }
99
101
  },
@@ -191,7 +191,7 @@ const componentToVue = (userOptions) => ({ component: _component, path }) => {
191
191
  (0, lodash_1.size)(getterKeys) && vueImports.push('computed');
192
192
  (0, lodash_1.size)(component.context.set) && vueImports.push('provide');
193
193
  (0, lodash_1.size)(component.context.get) && vueImports.push('inject');
194
- (0, lodash_1.size)(Object.keys(component.state).filter((key) => { var _a; return ((_a = component.state[key]) === null || _a === void 0 ? void 0 : _a.type) === 'property'; })) && vueImports.push('ref');
194
+ (0, lodash_1.size)(Object.keys(component.state).filter((key) => { var _a; return ((_a = component.state[key]) === null || _a === void 0 ? void 0 : _a.type) === 'property'; })) + (0, lodash_1.size)(component.refs) && vueImports.push('ref');
195
195
  (0, lodash_1.size)(slotsProps) && vueImports.push('useSlots');
196
196
  }
197
197
  const tsLangAttribute = options.typescript ? `lang='ts'` : '';
@@ -5,6 +5,11 @@ type ReplaceArgs = {
5
5
  from: string | string[];
6
6
  to: ReplaceTo;
7
7
  };
8
+ export type NodeMap = {
9
+ from: types.Node;
10
+ condition?: (path: babel.NodePath<types.Node>) => boolean;
11
+ to: types.Node;
12
+ };
8
13
  /**
9
14
  * @deprecated Use `replaceNodes` instead.
10
15
  */
@@ -15,12 +20,8 @@ export declare const replacePropsIdentifier: (to: ReplaceArgs['to']) => (code: s
15
20
  * Replaces all instances of a Babel AST Node with a new Node within a code string.
16
21
  * Uses `generate()` to convert the Node to a string and compare them.
17
22
  */
18
- export declare const replaceNodes: ({ code, nodeMaps, }: {
23
+ export declare const replaceNodes: ({ code, nodeMaps }: {
19
24
  code: string;
20
- nodeMaps: {
21
- from: types.Node;
22
- condition?: ((path: babel.NodePath<types.Node>) => boolean) | undefined;
23
- to: types.Node;
24
- }[];
25
+ nodeMaps: NodeMap[];
25
26
  }) => string;
26
27
  export {};
@@ -146,7 +146,7 @@ const isNewlyGenerated = (node) => { var _a; return (_a = node === null || node
146
146
  * Replaces all instances of a Babel AST Node with a new Node within a code string.
147
147
  * Uses `generate()` to convert the Node to a string and compare them.
148
148
  */
149
- const replaceNodes = ({ code, nodeMaps, }) => {
149
+ const replaceNodes = ({ code, nodeMaps }) => {
150
150
  const searchAndReplace = (path) => {
151
151
  if (isNewlyGenerated(path.node) || isNewlyGenerated(path.parent))
152
152
  return;
@@ -173,6 +173,9 @@ const replaceNodes = ({ code, nodeMaps, }) => {
173
173
  }
174
174
  };
175
175
  return (0, babel_transform_1.babelTransformExpression)(code, {
176
+ ThisExpression(path) {
177
+ searchAndReplace(path);
178
+ },
176
179
  MemberExpression(path) {
177
180
  searchAndReplace(path);
178
181
  },
@@ -8,6 +8,8 @@ const babel_transform_1 = require("../../helpers/babel-transform");
8
8
  const capitalize_1 = require("../../helpers/capitalize");
9
9
  const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
10
10
  const process_code_1 = require("../../helpers/plugins/process-code");
11
+ const replace_identifiers_1 = require("../../helpers/replace-identifiers");
12
+ const core_1 = require("@babel/core");
11
13
  const types_1 = require("@babel/types");
12
14
  const function_1 = require("fp-ts/lib/function");
13
15
  const legacy_1 = __importDefault(require("neotraverse/legacy"));
@@ -119,11 +121,26 @@ function mapStateIdentifiers(json) {
119
121
  });
120
122
  }
121
123
  exports.mapStateIdentifiers = mapStateIdentifiers;
124
+ /**
125
+ * Replaces `this.` with `state.` and trims code
126
+ * @param code origin code
127
+ */
128
+ const getCleanedStateCode = (code) => {
129
+ return (0, replace_identifiers_1.replaceNodes)({
130
+ code,
131
+ nodeMaps: [
132
+ {
133
+ from: core_1.types.thisExpression(),
134
+ to: core_1.types.identifier('state'),
135
+ },
136
+ ],
137
+ }).trim();
138
+ };
122
139
  const processStateObjectSlice = (item) => {
123
140
  if ((0, types_1.isObjectProperty)(item)) {
124
141
  if ((0, types_1.isFunctionExpression)(item.value)) {
125
142
  return {
126
- code: (0, helpers_1.parseCode)(item.value).trim(),
143
+ code: getCleanedStateCode((0, helpers_1.parseCode)(item.value)),
127
144
  type: 'function',
128
145
  };
129
146
  }
@@ -147,7 +164,9 @@ const processStateObjectSlice = (item) => {
147
164
  };
148
165
  }
149
166
  const n = (0, types_1.objectMethod)('method', item.key, item.value.params, item.value.body);
150
- const code = (0, helpers_1.parseCode)(n).trim();
167
+ // Replace this. with state. to handle following
168
+ // const state = useStore({ _do: () => {this._active = !!id;}})
169
+ const code = getCleanedStateCode((0, helpers_1.parseCode)(n));
151
170
  return {
152
171
  code: code,
153
172
  type: 'method',
@@ -158,13 +177,13 @@ const processStateObjectSlice = (item) => {
158
177
  // { foo: ('string' as SomeType) }
159
178
  if ((0, types_1.isTSAsExpression)(item.value)) {
160
179
  return {
161
- code: (0, helpers_1.parseCode)(item.value.expression).trim(),
180
+ code: getCleanedStateCode((0, helpers_1.parseCode)(item.value.expression)),
162
181
  type: 'property',
163
182
  propertyType: 'normal',
164
183
  };
165
184
  }
166
185
  return {
167
- code: (0, helpers_1.parseCode)(item.value).trim(),
186
+ code: getCleanedStateCode((0, helpers_1.parseCode)(item.value)),
168
187
  type: 'property',
169
188
  propertyType: 'normal',
170
189
  };
@@ -179,7 +198,8 @@ const processStateObjectSlice = (item) => {
179
198
  type: 'function',
180
199
  };
181
200
  }
182
- const n = (0, helpers_1.parseCode)({ ...item, returnType: null }).trim();
201
+ const method = (0, types_1.objectMethod)(item.kind, item.key, item.params, item.body, false, false, item.async);
202
+ const n = getCleanedStateCode((0, helpers_1.parseCode)({ ...method, returnType: null }));
183
203
  const isGetter = item.kind === 'get';
184
204
  return {
185
205
  code: n,
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.5.16",
25
+ "version": "0.5.18",
26
26
  "homepage": "https://github.com/BuilderIO/mitosis",
27
27
  "main": "./dist/src/index.js",
28
28
  "exports": {