@builder.io/mitosis 0.0.90 → 0.0.92

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.
@@ -55,6 +55,7 @@ var blockToMitosis = function (json, toMitosisOptions, component) {
55
55
  format: 'lite',
56
56
  stateType: 'useState',
57
57
  stylesType: 'emotion',
58
+ type: 'dom',
58
59
  prettier: options.prettier,
59
60
  }, component);
60
61
  }
@@ -10,9 +10,14 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
13
16
  Object.defineProperty(exports, "__esModule", { value: true });
14
17
  exports.blockToReact = void 0;
15
18
  var lodash_1 = require("lodash");
19
+ var is_children_1 = __importDefault(require("../../helpers/is-children"));
20
+ var slots_1 = require("../../helpers/slots");
16
21
  var filter_empty_text_nodes_1 = require("../../helpers/filter-empty-text-nodes");
17
22
  var is_valid_attribute_name_1 = require("../../helpers/is-valid-attribute-name");
18
23
  var for_1 = require("../../helpers/nodes/for");
@@ -133,7 +138,9 @@ var blockToReact = function (json, options, component, parentSlots) {
133
138
  }
134
139
  if ((_a = json.bindings._text) === null || _a === void 0 ? void 0 : _a.code) {
135
140
  var processed = (0, helpers_1.processBinding)(json.bindings._text.code, options);
136
- if (options.type === 'native') {
141
+ if (options.type === 'native' &&
142
+ !(0, is_children_1.default)({ node: json }) &&
143
+ !(0, slots_1.isSlotProperty)(json.bindings._text.code.split('.')[1] || '')) {
137
144
  return "<Text>{".concat(processed, "}</Text>");
138
145
  }
139
146
  return "{".concat(processed, "}");
@@ -191,6 +198,10 @@ var blockToReact = function (json, options, component, parentSlots) {
191
198
  str += " ".concat(BINDING_MAPPERS[key], "={").concat(useBindingValue, "} ");
192
199
  }
193
200
  }
201
+ else if (key === 'style' && options.type === 'native' && json.name === 'ScrollView') {
202
+ // React Native's ScrollView has a different prop for styles: `contentContainerStyle`
203
+ str += " contentContainerStyle={".concat(useBindingValue, "} ");
204
+ }
194
205
  else {
195
206
  if ((0, is_valid_attribute_name_1.isValidAttributeName)(key)) {
196
207
  str += " ".concat(key, "={").concat(useBindingValue, "} ");
@@ -1,5 +1,5 @@
1
1
  import { TranspilerGenerator } from '../../types/transpiler';
2
2
  import { ToReactOptions } from './types';
3
3
  export declare const contextPropDrillingKey = "_context";
4
- export declare const componentToPreact: TranspilerGenerator<ToReactOptions>;
5
- export declare const componentToReact: TranspilerGenerator<ToReactOptions>;
4
+ export declare const componentToPreact: TranspilerGenerator<Partial<ToReactOptions>>;
5
+ export declare const componentToReact: TranspilerGenerator<Partial<ToReactOptions>>;
@@ -34,7 +34,6 @@ var map_refs_1 = require("../../helpers/map-refs");
34
34
  var process_http_requests_1 = require("../../helpers/process-http-requests");
35
35
  var process_tag_references_1 = require("../../helpers/process-tag-references");
36
36
  var render_imports_1 = require("../../helpers/render-imports");
37
- var replace_new_lines_in_strings_1 = require("../../helpers/replace-new-lines-in-strings");
38
37
  var strip_meta_properties_1 = require("../../helpers/strip-meta-properties");
39
38
  var plugins_1 = require("../../modules/plugins");
40
39
  var context_1 = require("../helpers/context");
@@ -47,6 +46,8 @@ var helpers_2 = require("./helpers");
47
46
  var hash_sum_1 = __importDefault(require("hash-sum"));
48
47
  var bindings_1 = require("../../helpers/bindings");
49
48
  var blocks_1 = require("./blocks");
49
+ var merge_options_1 = require("../../helpers/merge-options");
50
+ var replace_new_lines_in_strings_1 = require("../../helpers/replace-new-lines-in-strings");
50
51
  exports.contextPropDrillingKey = '_context';
51
52
  /**
52
53
  * If the root Mitosis component only has 1 child, and it is a `Show`/`For` node, then we need to wrap it in a fragment.
@@ -131,6 +132,7 @@ var getInitCode = function (json, options) {
131
132
  var DEFAULT_OPTIONS = {
132
133
  stateType: 'useState',
133
134
  stylesType: 'styled-jsx',
135
+ type: 'dom',
134
136
  };
135
137
  var componentToPreact = function (reactOptions) {
136
138
  if (reactOptions === void 0) { reactOptions = {}; }
@@ -142,7 +144,7 @@ var componentToReact = function (reactOptions) {
142
144
  return function (_a) {
143
145
  var component = _a.component;
144
146
  var json = (0, fast_clone_1.fastClone)(component);
145
- var options = __assign(__assign({}, DEFAULT_OPTIONS), reactOptions);
147
+ var options = (0, merge_options_1.mergeOptions)(DEFAULT_OPTIONS, reactOptions);
146
148
  if (options.plugins) {
147
149
  json = (0, plugins_1.runPreJsonPlugins)(json, options.plugins);
148
150
  }
@@ -177,6 +179,35 @@ var componentToReact = function (reactOptions) {
177
179
  };
178
180
  };
179
181
  exports.componentToReact = componentToReact;
182
+ // TODO: import target components when they are required
183
+ var getDefaultImport = function (json, options) {
184
+ var preact = options.preact, type = options.type;
185
+ if (preact) {
186
+ return "\n /** @jsx h */\n import { h, Fragment } from 'preact';\n ";
187
+ }
188
+ if (type === 'native') {
189
+ return "\n import * as React from 'react';\n import { FlatList, ScrollView, View, StyleSheet, Image, Text } from 'react-native';\n ";
190
+ }
191
+ if (type === 'taro') {
192
+ return "\n import * as React from 'react';\n ";
193
+ }
194
+ return "import * as React from 'react';";
195
+ };
196
+ var getPropsDefinition = function (_a) {
197
+ var json = _a.json;
198
+ if (!json.defaultProps)
199
+ return '';
200
+ var defaultPropsString = Object.keys(json.defaultProps)
201
+ .map(function (prop) {
202
+ var _a;
203
+ var value = json.defaultProps.hasOwnProperty(prop)
204
+ ? (_a = json.defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code
205
+ : 'undefined';
206
+ return "".concat(prop, ": ").concat(value);
207
+ })
208
+ .join(',');
209
+ return "".concat(json.name, ".defaultProps = {").concat(defaultPropsString, "};");
210
+ };
180
211
  var _componentToReact = function (json, options, isSubComponent) {
181
212
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
182
213
  if (isSubComponent === void 0) { isSubComponent = false; }
@@ -189,6 +220,9 @@ var _componentToReact = function (json, options, isSubComponent) {
189
220
  (0, getters_to_functions_1.gettersToFunctions)(json);
190
221
  (0, state_2.updateStateSetters)(json, options);
191
222
  }
223
+ if (!json.name) {
224
+ json.name = 'MyComponent';
225
+ }
192
226
  // const domRefs = getRefs(json);
193
227
  var allRefs = Object.keys(json.refs);
194
228
  (0, map_refs_1.mapRefs)(json, function (refName) { return "".concat(refName, ".current"); });
@@ -199,32 +233,33 @@ var _componentToReact = function (json, options, isSubComponent) {
199
233
  var meta = (_b = json.meta.useMetadata) === null || _b === void 0 ? void 0 : _b.forwardRef;
200
234
  options.forwardRef = meta || forwardRef;
201
235
  }
202
- var forwardRefType = json.propsTypeRef && forwardRef && json.propsTypeRef !== 'any'
203
- ? "".concat(json.propsTypeRef, "[\"").concat(forwardRef, "\"]")
204
- : undefined;
205
- var stylesType = options.stylesType || 'emotion';
206
- var stateType = options.stateType || 'mobx';
207
- if (stateType === 'builder') {
236
+ var forwardRefType = options.typescript && json.propsTypeRef && forwardRef && json.propsTypeRef !== 'any'
237
+ ? "<".concat(json.propsTypeRef, "[\"").concat(forwardRef, "\"]>")
238
+ : '';
239
+ if (options.stateType === 'builder') {
208
240
  // Always use state if we are generate Builder react code
209
241
  hasState = true;
210
242
  }
211
- var useStateCode = stateType === 'useState' && (0, state_2.getUseStateCode)(json, options);
243
+ var useStateCode = options.stateType === 'useState' ? (0, state_2.getUseStateCode)(json, options) : '';
212
244
  if (options.plugins) {
213
245
  json = (0, plugins_1.runPostJsonPlugins)(json, options.plugins);
214
246
  }
215
- var css = stylesType === 'styled-jsx'
247
+ var css = options.stylesType === 'styled-jsx'
216
248
  ? (0, collect_css_1.collectCss)(json)
217
- : stylesType === 'style-tag'
249
+ : options.stylesType === 'style-tag'
218
250
  ? (0, collect_css_1.collectCss)(json, {
219
251
  prefix: (0, hash_sum_1.default)(json),
220
252
  })
221
253
  : null;
222
- var styledComponentsCode = stylesType === 'styled-components' && componentHasStyles && (0, collect_styled_components_1.collectStyledComponents)(json);
254
+ var styledComponentsCode = (options.stylesType === 'styled-components' &&
255
+ componentHasStyles &&
256
+ (0, collect_styled_components_1.collectStyledComponents)(json)) ||
257
+ '';
223
258
  if (options.format !== 'lite') {
224
259
  (0, strip_meta_properties_1.stripMetaProperties)(json);
225
260
  }
226
261
  var reactLibImports = new Set();
227
- if (useStateCode && useStateCode.includes('useState')) {
262
+ if (useStateCode.includes('useState')) {
228
263
  reactLibImports.add('useState');
229
264
  }
230
265
  if ((0, context_1.hasContext)(json) && options.contextType !== 'prop-drill') {
@@ -243,81 +278,75 @@ var _componentToReact = function (json, options, isSubComponent) {
243
278
  reactLibImports.add('useEffect');
244
279
  }
245
280
  var wrap = (0, helpers_2.wrapInFragment)(json) ||
246
- (componentHasStyles && (stylesType === 'styled-jsx' || stylesType === 'style-tag')) ||
281
+ (componentHasStyles &&
282
+ (options.stylesType === 'styled-jsx' || options.stylesType === 'style-tag')) ||
247
283
  isRootSpecialNode(json);
248
284
  var _o = getRefsString(json, allRefs, options), hasStateArgument = _o[0], refsString = _o[1];
249
- var nativeStyles = stylesType === 'react-native' && componentHasStyles && (0, react_native_1.collectReactNativeStyles)(json);
285
+ // NOTE: `collectReactNativeStyles` must run before style generation in the component generation body, as it has
286
+ // side effects that delete styles bindings from the JSON.
287
+ var reactNativeStyles = options.stylesType === 'react-native' && componentHasStyles
288
+ ? (0, react_native_1.collectReactNativeStyles)(json)
289
+ : undefined;
250
290
  var propType = json.propsTypeRef || 'any';
251
- var propsArgs = "props".concat(options.typescript ? ":".concat(propType) : '');
252
- var getPropsDefinition = function (_a) {
253
- var json = _a.json;
254
- if (!json.defaultProps)
255
- return '';
256
- var defalutPropsString = Object.keys(json.defaultProps)
257
- .map(function (prop) {
258
- var _a;
259
- var value = json.defaultProps.hasOwnProperty(prop)
260
- ? (_a = json.defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code
261
- : 'undefined';
262
- return "".concat(prop, ": ").concat(value);
263
- })
264
- .join(',');
265
- return "".concat(json.name || 'MyComponent', ".defaultProps = {").concat(defalutPropsString, "};");
266
- };
267
- var str = (0, dedent_1.default)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "", "", "function ", "(", "", ") {\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n\n ", "\n\n return (\n ", "\n ", "\n ", "\n ", "\n );\n }", "\n\n ", "\n\n ", "\n\n ", "\n ", "\n\n "], ["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "", "", "function ", "(", "", ") {\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n\n ", "\n\n return (\n ", "\n ", "\n ", "\n ", "\n );\n }", "\n\n ", "\n\n ", "\n\n ", "\n ", "\n\n "])), options.preact
268
- ? "\n /** @jsx h */\n import { h, Fragment } from 'preact';\n "
269
- : options.type !== 'native'
270
- ? "import * as React from 'react';"
271
- : "\n import * as React from 'react';\n import { FlatList, ScrollView, View, StyleSheet, Image, Text } from 'react-native';\n ", styledComponentsCode ? "import styled from 'styled-components';\n" : '', reactLibImports.size
272
- ? "import { ".concat(Array.from(reactLibImports).join(', '), " } from '").concat(options.preact ? 'preact/hooks' : 'react', "'")
273
- : '', componentHasStyles && stylesType === 'emotion' && options.format !== 'lite'
274
- ? "/** @jsx jsx */\n import { jsx } from '@emotion/react'".trim()
275
- : '', hasState && stateType === 'valtio' ? "import { useLocalProxy } from 'valtio/utils';" : '', hasState && stateType === 'solid' ? "import { useMutable } from 'react-solid-state';" : '', stateType === 'mobx' && hasState
276
- ? "import { useLocalObservable, observer } from 'mobx-react-lite';"
277
- : '', json.types && options.typescript ? json.types.join('\n') : '', (0, render_imports_1.renderPreComponent)({
278
- component: json,
279
- target: options.type === 'native' ? 'reactNative' : 'react',
280
- }), stateType === 'mobx' && isForwardRef ? "const ".concat(json.name || 'MyComponent', " = ") : "", isSubComponent || stateType === 'mobx' ? '' : 'export default ', isForwardRef
281
- ? "forwardRef".concat(forwardRefType && options.typescript ? "<".concat(forwardRefType, ">") : '', "(")
282
- : '', json.name || 'MyComponent', propsArgs, isForwardRef ? ", ".concat(options.forwardRef) : '', options.contextType === 'prop-drill'
291
+ var componentArgs = ["props".concat(options.typescript ? ":".concat(propType) : ''), options.forwardRef]
292
+ .filter(Boolean)
293
+ .join(',');
294
+ var componentBody = (0, dedent_1.default)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n\n ", "\n\n return (\n ", "\n ", "\n ", "\n ", "\n );\n "], ["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n\n ", "\n\n return (\n ", "\n ", "\n ", "\n ", "\n );\n "])), options.contextType === 'prop-drill'
283
295
  ? "const ".concat(exports.contextPropDrillingKey, " = { ...props['").concat(exports.contextPropDrillingKey, "'] };")
284
296
  : '', hasStateArgument ? '' : refsString, hasState
285
- ? stateType === 'mobx'
297
+ ? options.stateType === 'mobx'
286
298
  ? "const state = useLocalObservable(() => (".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json), "));")
287
- : stateType === 'useState'
299
+ : options.stateType === 'useState'
288
300
  ? useStateCode
289
- : stateType === 'solid'
301
+ : options.stateType === 'solid'
290
302
  ? "const state = useMutable(".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json), ");")
291
- : stateType === 'builder'
303
+ : options.stateType === 'builder'
292
304
  ? "const state = useBuilderState(".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json), ");")
293
- : stateType === 'variables'
305
+ : options.stateType === 'variables'
294
306
  ? "const state = ".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json), ";")
295
307
  : "const state = useLocalProxy(".concat((0, get_state_object_string_1.getStateObjectStringFromComponent)(json), ");")
296
308
  : '', hasStateArgument ? refsString : '', getContextString(json, options), getInitCode(json, options), contextStr || '', ((_g = json.hooks.onInit) === null || _g === void 0 ? void 0 : _g.code)
297
- ? "\n useEffect(() => {\n ".concat((0, state_2.processHookCode)({
309
+ ? "\n useEffect(() => {\n ".concat((0, state_2.processHookCode)({
298
310
  str: json.hooks.onInit.code,
299
311
  options: options,
300
- }), "\n }, [])\n ")
312
+ }), "\n }, [])\n ")
301
313
  : '', ((_h = json.hooks.onMount) === null || _h === void 0 ? void 0 : _h.code)
302
- ? "useEffect(() => {\n ".concat((0, state_2.processHookCode)({
314
+ ? "useEffect(() => {\n ".concat((0, state_2.processHookCode)({
303
315
  str: json.hooks.onMount.code,
304
316
  options: options,
305
- }), "\n }, [])")
306
- : '', (_k = (_j = json.hooks.onUpdate) === null || _j === void 0 ? void 0 : _j.map(function (hook) { return "useEffect(() => {\n ".concat((0, state_2.processHookCode)({ str: hook.code, options: options }), "\n },\n ").concat(hook.deps ? (0, state_2.processHookCode)({ str: hook.deps, options: options }) : '', ")"); }).join(';')) !== null && _k !== void 0 ? _k : '', ((_l = json.hooks.onUnMount) === null || _l === void 0 ? void 0 : _l.code)
307
- ? "useEffect(() => {\n return () => {\n ".concat((0, state_2.processHookCode)({
317
+ }), "\n }, [])")
318
+ : '', (_k = (_j = json.hooks.onUpdate) === null || _j === void 0 ? void 0 : _j.map(function (hook) { return "useEffect(() => {\n ".concat((0, state_2.processHookCode)({ str: hook.code, options: options }), "\n },\n ").concat(hook.deps ? (0, state_2.processHookCode)({ str: hook.deps, options: options }) : '', ")"); }).join(';')) !== null && _k !== void 0 ? _k : '', ((_l = json.hooks.onUnMount) === null || _l === void 0 ? void 0 : _l.code)
319
+ ? "useEffect(() => {\n return () => {\n ".concat((0, state_2.processHookCode)({
308
320
  str: json.hooks.onUnMount.code,
309
321
  options: options,
310
- }), "\n }\n }, [])")
311
- : '', wrap ? (0, helpers_2.openFrag)(options) : '', json.children.map(function (item) { return (0, blocks_1.blockToReact)(item, options, json, []); }).join('\n'), componentHasStyles && stylesType === 'styled-jsx'
322
+ }), "\n }\n }, [])")
323
+ : '', wrap ? (0, helpers_2.openFrag)(options) : '', json.children.map(function (item) { return (0, blocks_1.blockToReact)(item, options, json, []); }).join('\n'), componentHasStyles && options.stylesType === 'styled-jsx'
312
324
  ? "<style jsx>{`".concat(css, "`}</style>")
313
- : componentHasStyles && stylesType === 'style-tag'
325
+ : componentHasStyles && options.stylesType === 'style-tag'
314
326
  ? "<style>{`".concat(css, "`}</style>")
315
- : '', wrap ? (0, helpers_2.closeFrag)(options) : '', isForwardRef ? ')' : '', getPropsDefinition({ json: json }), !nativeStyles
327
+ : '', wrap ? (0, helpers_2.closeFrag)(options) : '');
328
+ var str = (0, dedent_1.default)(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "function ", "(", ") {\n ", "\n }", "\n\n ", "\n\n ", "\n\n ", "\n ", "\n\n "], ["\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "\n ", "function ", "(", ") {\n ", "\n }", "\n\n ", "\n\n ", "\n\n ", "\n ", "\n\n "])), getDefaultImport(json, options), styledComponentsCode ? "import styled from 'styled-components';\n" : '', reactLibImports.size
329
+ ? "import { ".concat(Array.from(reactLibImports).join(', '), " } from '").concat(options.preact ? 'preact/hooks' : 'react', "'")
330
+ : '', componentHasStyles && options.stylesType === 'emotion' && options.format !== 'lite'
331
+ ? "/** @jsx jsx */\n import { jsx } from '@emotion/react'".trim()
332
+ : '', !hasState
316
333
  ? ''
317
- : "\n const styles = StyleSheet.create(".concat(json5_1.default.stringify(nativeStyles), ");\n "), styledComponentsCode ? styledComponentsCode : '', stateType === 'mobx'
318
- ? "\n const observed".concat(json.name || 'MyComponent', " = observer(").concat(json.name || 'MyComponent', ");\n export default observed").concat(json.name || 'MyComponent', ";\n ")
319
- : '');
320
- str = (0, replace_new_lines_in_strings_1.stripNewlinesInStrings)(str);
321
- return str;
334
+ : options.stateType === 'valtio'
335
+ ? "import { useLocalProxy } from 'valtio/utils';"
336
+ : options.stateType === 'solid'
337
+ ? "import { useMutable } from 'react-solid-state';"
338
+ : options.stateType === 'mobx'
339
+ ? "import { useLocalObservable, observer } from 'mobx-react-lite';"
340
+ : '', json.types && options.typescript ? json.types.join('\n') : '', (0, render_imports_1.renderPreComponent)({
341
+ component: json,
342
+ target: options.type === 'native' ? 'reactNative' : 'react',
343
+ }), isForwardRef ? "const ".concat(json.name, " = forwardRef").concat(forwardRefType, "(") : '', json.name, componentArgs, componentBody, isForwardRef ? ')' : '', getPropsDefinition({ json: json }), reactNativeStyles
344
+ ? "const styles = StyleSheet.create(".concat(json5_1.default.stringify(reactNativeStyles), ");")
345
+ : '', styledComponentsCode !== null && styledComponentsCode !== void 0 ? styledComponentsCode : '', isSubComponent
346
+ ? ''
347
+ : options.stateType === 'mobx'
348
+ ? "\n const observed".concat(json.name, " = observer(").concat(json.name, ");\n export default observed").concat(json.name, ";\n ")
349
+ : "export default ".concat(json.name, ";"));
350
+ return (0, replace_new_lines_in_strings_1.stripNewlinesInStrings)(str);
322
351
  };
323
- var templateObject_1;
352
+ var templateObject_1, templateObject_2;
@@ -1,9 +1,9 @@
1
1
  import { BaseTranspilerOptions } from '../../types/transpiler';
2
2
  export interface ToReactOptions extends BaseTranspilerOptions {
3
- stylesType?: 'emotion' | 'styled-components' | 'styled-jsx' | 'react-native' | 'style-tag';
4
- stateType?: 'useState' | 'mobx' | 'valtio' | 'solid' | 'builder' | 'variables';
3
+ stylesType: 'emotion' | 'styled-components' | 'styled-jsx' | 'react-native' | 'style-tag';
4
+ stateType: 'useState' | 'mobx' | 'valtio' | 'solid' | 'builder' | 'variables';
5
5
  format?: 'lite' | 'safe';
6
- type?: 'dom' | 'native';
6
+ type: 'dom' | 'native' | 'taro';
7
7
  preact?: boolean;
8
8
  forwardRef?: string;
9
9
  experimental?: any;
@@ -2,8 +2,8 @@ import { ClassStyleMap } from '../helpers/styles/helpers';
2
2
  import { MitosisComponent } from '../types/mitosis-component';
3
3
  import { BaseTranspilerOptions, TranspilerGenerator } from '../types/transpiler';
4
4
  export interface ToReactNativeOptions extends BaseTranspilerOptions {
5
- stylesType?: 'emotion' | 'react-native';
6
- stateType?: 'useState' | 'mobx' | 'valtio' | 'solid' | 'builder';
5
+ stylesType: 'emotion' | 'react-native';
6
+ stateType: 'useState' | 'mobx' | 'valtio' | 'solid' | 'builder';
7
7
  }
8
8
  export declare const collectReactNativeStyles: (json: MitosisComponent) => ClassStyleMap;
9
- export declare const componentToReactNative: TranspilerGenerator<ToReactNativeOptions>;
9
+ export declare const componentToReactNative: TranspilerGenerator<Partial<ToReactNativeOptions>>;
@@ -10,15 +10,6 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
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
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
23
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
15
  };
@@ -31,6 +22,8 @@ var traverse_1 = __importDefault(require("traverse"));
31
22
  var is_mitosis_node_1 = require("../helpers/is-mitosis-node");
32
23
  var react_1 = require("./react");
33
24
  var bindings_1 = require("../helpers/bindings");
25
+ var merge_options_1 = require("../helpers/merge-options");
26
+ var is_children_1 = __importDefault(require("../helpers/is-children"));
34
27
  var stylePropertiesThatMustBeNumber = new Set(['lineHeight']);
35
28
  var MEDIA_QUERY_KEY_REGEX = /^@media.*/;
36
29
  var collectReactNativeStyles = function (json) {
@@ -88,10 +81,14 @@ var PROCESS_REACT_NATIVE_PLUGIN = function () { return ({
88
81
  var _a, _b, _c, _d;
89
82
  if ((0, is_mitosis_node_1.isMitosisNode)(node)) {
90
83
  // TODO: handle TextInput, Image, etc
91
- if (node.name.toLowerCase() === node.name) {
84
+ if ((0, is_children_1.default)({ node: node })) {
85
+ node.name = '';
86
+ }
87
+ else if (node.name.toLowerCase() === node.name) {
92
88
  node.name = 'View';
93
89
  }
94
- if (((_a = node.properties._text) === null || _a === void 0 ? void 0 : _a.trim().length) || ((_d = (_c = (_b = node.bindings._text) === null || _b === void 0 ? void 0 : _b.code) === null || _c === void 0 ? void 0 : _c.trim()) === null || _d === void 0 ? void 0 : _d.length)) {
90
+ else if (((_a = node.properties._text) === null || _a === void 0 ? void 0 : _a.trim().length) ||
91
+ ((_d = (_c = (_b = node.bindings._text) === null || _b === void 0 ? void 0 : _b.code) === null || _c === void 0 ? void 0 : _c.trim()) === null || _d === void 0 ? void 0 : _d.length)) {
95
92
  node.name = 'Text';
96
93
  }
97
94
  if (node.properties.class) {
@@ -121,8 +118,8 @@ var componentToReactNative = function (_options) {
121
118
  return function (_a) {
122
119
  var component = _a.component, path = _a.path;
123
120
  var json = (0, fast_clone_1.fastClone)(component);
124
- var options = __assign(__assign(__assign({}, DEFAULT_OPTIONS), _options), { plugins: __spreadArray(__spreadArray([], (DEFAULT_OPTIONS.plugins || []), true), (_options.plugins || []), true), type: 'native' });
125
- return (0, react_1.componentToReact)(options)({ component: json, path: path });
121
+ var options = (0, merge_options_1.mergeOptions)(DEFAULT_OPTIONS, _options);
122
+ return (0, react_1.componentToReact)(__assign(__assign({}, options), { type: 'native' }))({ component: json, path: path });
126
123
  };
127
124
  };
128
125
  exports.componentToReactNative = componentToReactNative;
@@ -1,4 +1,4 @@
1
- import { BaseTranspilerOptions, TranspilerGenerator } from '../types/transpiler';
2
- export interface ToRscOptions extends BaseTranspilerOptions {
3
- }
4
- export declare const componentToRsc: TranspilerGenerator<ToRscOptions>;
1
+ import { TranspilerGenerator } from '../types/transpiler';
2
+ import { ToReactOptions } from './react';
3
+ export declare type ToRscOptions = ToReactOptions;
4
+ export declare const componentToRsc: TranspilerGenerator<Partial<ToRscOptions>>;
@@ -1,24 +1,4 @@
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
  };
@@ -29,6 +9,7 @@ var traverse_1 = __importDefault(require("traverse"));
29
9
  var fast_clone_1 = require("../helpers/fast-clone");
30
10
  var is_mitosis_node_1 = require("../helpers/is-mitosis-node");
31
11
  var react_1 = require("./react");
12
+ var merge_options_1 = require("../helpers/merge-options");
32
13
  /**
33
14
  * Transform react to be RSC compatible, such as
34
15
  * - remove event listeners
@@ -84,7 +65,11 @@ var componentToRsc = function (_options) {
84
65
  return function (_a) {
85
66
  var component = _a.component, path = _a.path;
86
67
  var json = (0, fast_clone_1.fastClone)(component);
87
- var options = __assign(__assign(__assign({}, DEFAULT_OPTIONS), _options), { plugins: __spreadArray(__spreadArray([], (DEFAULT_OPTIONS.plugins || []), true), (_options.plugins || []), true), stylesType: 'style-tag', stateType: 'variables', contextType: 'prop-drill' });
68
+ var options = (0, merge_options_1.mergeOptions)(DEFAULT_OPTIONS, _options, {
69
+ stylesType: 'style-tag',
70
+ stateType: 'variables',
71
+ contextType: 'prop-drill',
72
+ });
88
73
  return (0, react_1.componentToReact)(options)({ component: json, path: path });
89
74
  };
90
75
  };
@@ -0,0 +1,9 @@
1
+ import { ClassStyleMap } from '../helpers/styles/helpers';
2
+ import { MitosisComponent } from '../types/mitosis-component';
3
+ import { ToReactOptions } from './react';
4
+ import { TranspilerGenerator } from '../types/transpiler';
5
+ export declare const DEFAULT_Component_SET: Set<string>;
6
+ export declare type ToTaroOptions = ToReactOptions;
7
+ export declare const collectTaroStyles: (json: MitosisComponent) => ClassStyleMap;
8
+ export declare const TagMap: Record<string, string>;
9
+ export declare const componentToTaro: TranspilerGenerator<Partial<ToTaroOptions>>;
@@ -0,0 +1,172 @@
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.componentToTaro = exports.TagMap = exports.collectTaroStyles = exports.DEFAULT_Component_SET = void 0;
7
+ var json5_1 = __importDefault(require("json5"));
8
+ var lodash_1 = require("lodash");
9
+ var traverse_1 = __importDefault(require("traverse"));
10
+ var fast_clone_1 = require("../helpers/fast-clone");
11
+ var is_mitosis_node_1 = require("../helpers/is-mitosis-node");
12
+ var react_1 = require("./react");
13
+ var bindings_1 = require("../helpers/bindings");
14
+ var merge_options_1 = require("../helpers/merge-options");
15
+ // @tarojs/components
16
+ exports.DEFAULT_Component_SET = new Set([
17
+ 'View',
18
+ 'Icon',
19
+ 'Progress',
20
+ 'RichText',
21
+ 'Text',
22
+ 'Button',
23
+ 'Checkbox',
24
+ 'CheckboxGroup',
25
+ 'Form',
26
+ 'Input',
27
+ 'Label',
28
+ 'Picker',
29
+ 'PickerView',
30
+ 'PickerViewColumn',
31
+ 'Radio',
32
+ 'RadioGroup',
33
+ 'Slider',
34
+ 'Switch',
35
+ 'CoverImage',
36
+ 'Textarea',
37
+ 'CoverView',
38
+ 'MovableArea',
39
+ 'MovableView',
40
+ 'ScrollView',
41
+ 'Swiper',
42
+ 'SwiperItem',
43
+ 'Navigator',
44
+ 'Audio',
45
+ 'Camera',
46
+ 'Image',
47
+ 'LivePlayer',
48
+ 'Video',
49
+ 'Canvas',
50
+ 'Ad',
51
+ 'WebView',
52
+ 'Block',
53
+ 'Map',
54
+ 'Slot',
55
+ 'SlotView',
56
+ 'Editor',
57
+ 'MatchMedia',
58
+ 'FunctionalPageNavigator',
59
+ 'LivePusher',
60
+ 'OfficialAccount',
61
+ 'OpenData',
62
+ 'NavigationBar',
63
+ 'PageMeta',
64
+ 'VoipRoom',
65
+ 'AdCustom',
66
+ ]);
67
+ // TODO: px to 2 px
68
+ var collectTaroStyles = function (json) {
69
+ var styleMap = {};
70
+ var componentIndexes = {};
71
+ (0, traverse_1.default)(json).forEach(function (item) {
72
+ var _a;
73
+ if (!(0, is_mitosis_node_1.isMitosisNode)(item) || typeof ((_a = item.bindings.css) === null || _a === void 0 ? void 0 : _a.code) !== 'string') {
74
+ return;
75
+ }
76
+ var value = json5_1.default.parse(item.bindings.css.code);
77
+ delete item.bindings.css;
78
+ if (!(0, lodash_1.size)(value)) {
79
+ return;
80
+ }
81
+ for (var key in value) {
82
+ var propertyValue = value[key];
83
+ // convert px to 2 * px, PX to PX
84
+ if (typeof propertyValue === 'string' && propertyValue.match(/^\d/)) {
85
+ var newValue = parseFloat(propertyValue);
86
+ if (!isNaN(newValue)) {
87
+ if (propertyValue.endsWith('px')) {
88
+ newValue = 2 * newValue;
89
+ value[key] = "".concat(newValue, "px");
90
+ }
91
+ else {
92
+ value[key] = newValue;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ var componentName = (0, lodash_1.camelCase)(item.name || 'view');
98
+ var index = (componentIndexes[componentName] = (componentIndexes[componentName] || 0) + 1);
99
+ var className = "".concat(componentName).concat(index);
100
+ item.bindings.style = (0, bindings_1.createSingleBinding)({ code: "styles.".concat(className) });
101
+ styleMap[className] = value;
102
+ });
103
+ return styleMap;
104
+ };
105
+ exports.collectTaroStyles = collectTaroStyles;
106
+ exports.TagMap = {
107
+ span: 'Text',
108
+ button: 'Button',
109
+ input: 'Input',
110
+ img: 'Image',
111
+ form: 'Form',
112
+ textarea: 'Textarea',
113
+ };
114
+ /**
115
+ * Plugin that handles necessary transformations from React to React Native:
116
+ * - Converts DOM tags to @tarojs/components
117
+ * - Removes redundant `class`/`className` attributes
118
+ */
119
+ var PROCESS_TARO_PLUGIN = function () { return ({
120
+ json: {
121
+ pre: function (json) {
122
+ var TaroComponentsImports = { path: '@tarojs/components', imports: {} };
123
+ json.imports.push(TaroComponentsImports);
124
+ (0, traverse_1.default)(json).forEach(function (node) {
125
+ var _a, _b, _c, _d;
126
+ if ((0, is_mitosis_node_1.isMitosisNode)(node)) {
127
+ // TODO: More dom tags convert to @tarojs/components
128
+ if (!!exports.TagMap[node.name]) {
129
+ TaroComponentsImports.imports[exports.TagMap[node.name]] = exports.TagMap[node.name];
130
+ node.name = exports.TagMap[node.name];
131
+ }
132
+ else if (node.name.toLowerCase() === node.name) {
133
+ TaroComponentsImports.imports.View = 'View';
134
+ node.name = 'View';
135
+ }
136
+ if (((_a = node.properties._text) === null || _a === void 0 ? void 0 : _a.trim().length) || ((_d = (_c = (_b = node.bindings._text) === null || _b === void 0 ? void 0 : _b.code) === null || _c === void 0 ? void 0 : _c.trim()) === null || _d === void 0 ? void 0 : _d.length)) {
137
+ TaroComponentsImports.imports.Text = 'Text';
138
+ node.name = 'Text';
139
+ }
140
+ if (node.properties.class) {
141
+ delete node.properties.class;
142
+ }
143
+ if (node.properties.className) {
144
+ delete node.properties.className;
145
+ }
146
+ if (node.bindings.class) {
147
+ delete node.bindings.class;
148
+ }
149
+ if (node.bindings.className) {
150
+ delete node.bindings.className;
151
+ }
152
+ }
153
+ });
154
+ },
155
+ },
156
+ }); };
157
+ var DEFAULT_OPTIONS = {
158
+ stateType: 'useState',
159
+ plugins: [PROCESS_TARO_PLUGIN],
160
+ };
161
+ var componentToTaro = function (_options) {
162
+ if (_options === void 0) { _options = {}; }
163
+ return function (_a) {
164
+ var component = _a.component, path = _a.path;
165
+ var json = (0, fast_clone_1.fastClone)(component);
166
+ var options = (0, merge_options_1.mergeOptions)(DEFAULT_OPTIONS, _options, {
167
+ type: 'taro',
168
+ });
169
+ return (0, react_1.componentToReact)(options)({ component: json, path: path });
170
+ };
171
+ };
172
+ exports.componentToTaro = componentToTaro;