@builder.io/mitosis 0.6.6 → 0.6.8

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.
@@ -461,7 +461,7 @@ function isGlobalStyle(key) {
461
461
  key.startsWith('@'));
462
462
  }
463
463
  const blockToBuilder = (json, options = {}, _internalOptions = {}) => {
464
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
464
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
465
465
  const mapper = !_internalOptions.skipMapper && componentMappers[json.name];
466
466
  if (mapper) {
467
467
  const element = mapper(json, options);
@@ -562,13 +562,6 @@ const blockToBuilder = (json, options = {}, _internalOptions = {}) => {
562
562
  }
563
563
  delete json.bindings.css;
564
564
  }
565
- if (thisIsComponent) {
566
- for (const key in json.bindings) {
567
- if (!((_o = json.slots) === null || _o === void 0 ? void 0 : _o[key])) {
568
- builderBindings[`component.options.${key}`] = json.bindings[key].code;
569
- }
570
- }
571
- }
572
565
  const element = el({
573
566
  tagName: thisIsComponent ? undefined : json.name,
574
567
  ...(hasCss && {
@@ -14,7 +14,7 @@ const slots_1 = require("../../helpers/slots");
14
14
  const mitosis_node_1 = require("../../types/mitosis-node");
15
15
  const html_tags_1 = require("../../constants/html_tags");
16
16
  const helpers_1 = require("./helpers");
17
- const state_1 = require("./state");
17
+ const state_1 = require("./helpers/state");
18
18
  const NODE_MAPPERS = {
19
19
  Slot(json, options, component, _insideJsx, parentSlots) {
20
20
  var _a, _b;
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.componentToReact = exports.componentToPreact = exports.contextPropDrillingKey = void 0;
7
+ const default_props_1 = require("../../generators/react/helpers/default-props");
8
+ const hooks_1 = require("../../generators/react/helpers/hooks");
7
9
  const bindings_1 = require("../../helpers/bindings");
8
10
  const create_mitosis_node_1 = require("../../helpers/create-mitosis-node");
9
11
  const dedent_1 = require("../../helpers/dedent");
@@ -28,17 +30,17 @@ const strip_meta_properties_1 = require("../../helpers/strip-meta-properties");
28
30
  const collect_css_1 = require("../../helpers/styles/collect-css");
29
31
  const collect_styled_components_1 = require("../../helpers/styles/collect-styled-components");
30
32
  const helpers_1 = require("../../helpers/styles/helpers");
33
+ const plugins_1 = require("../../modules/plugins");
31
34
  const core_1 = require("@babel/core");
32
35
  const hash_sum_1 = __importDefault(require("hash-sum"));
33
36
  const json5_1 = __importDefault(require("json5"));
34
37
  const standalone_1 = require("prettier/standalone");
35
- const plugins_1 = require("../../modules/plugins");
36
38
  const context_1 = require("../helpers/context");
37
39
  const rsc_1 = require("../helpers/rsc");
38
40
  const react_native_1 = require("../react-native");
39
41
  const blocks_1 = require("./blocks");
40
42
  const helpers_2 = require("./helpers");
41
- const state_2 = require("./state");
43
+ const state_2 = require("./helpers/state");
42
44
  exports.contextPropDrillingKey = '_context';
43
45
  /**
44
46
  * 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.
@@ -216,42 +218,6 @@ const componentToReact = (reactOptions = {}) => ({ component, path }) => {
216
218
  return str;
217
219
  };
218
220
  exports.componentToReact = componentToReact;
219
- // TODO: import target components when they are required
220
- const getDefaultImport = (json, options) => {
221
- const { preact, type } = options;
222
- if (preact) {
223
- return `
224
- /** @jsx h */
225
- import { h, Fragment } from 'preact';
226
- `;
227
- }
228
- if (type === 'native') {
229
- return `
230
- import * as React from 'react';
231
- import { FlatList, ScrollView, View, StyleSheet, Image, Text, Pressable, TextInput, TouchableOpacity, Button, Linking } from 'react-native';
232
- `;
233
- }
234
- if (type === 'taro') {
235
- return `
236
- import * as React from 'react';
237
- `;
238
- }
239
- return "import * as React from 'react';";
240
- };
241
- const getPropsDefinition = ({ json }) => {
242
- if (!json.defaultProps)
243
- return '';
244
- const defaultPropsString = Object.keys(json.defaultProps)
245
- .map((prop) => {
246
- var _a;
247
- const value = json.defaultProps.hasOwnProperty(prop)
248
- ? (_a = json.defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code
249
- : 'undefined';
250
- return `${prop}: ${value}`;
251
- })
252
- .join(',');
253
- return `${json.name}.defaultProps = {${defaultPropsString}};`;
254
- };
255
221
  const isRSC = (json, options) => {
256
222
  var _a, _b;
257
223
  // When using RSC generator, we check `componentType` field in metadata to determine if it's a server component
@@ -271,7 +237,7 @@ const checkShouldAddUseClientDirective = (json, options) => {
271
237
  return !isRSC(json, options);
272
238
  };
273
239
  const _componentToReact = (json, options, isSubComponent = false) => {
274
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
240
+ var _a, _b, _c, _d, _e, _f;
275
241
  (0, process_http_requests_1.processHttpRequests)(json);
276
242
  (0, handle_missing_state_1.handleMissingState)(json);
277
243
  (0, helpers_2.processTagReferences)(json, options);
@@ -290,11 +256,9 @@ const _componentToReact = (json, options, isSubComponent = false) => {
290
256
  // Always use state if we are generate Builder react code
291
257
  const hasState = options.stateType === 'builder' || (0, state_1.checkHasState)(json);
292
258
  const [forwardRef, hasPropRef] = (0, get_props_ref_1.getPropsRef)(json);
293
- const isForwardRef = !options.preact &&
294
- Boolean(((_a = json.meta.useMetadata) === null || _a === void 0 ? void 0 : _a.forwardRef) || ((_c = (_b = json.meta.useMetadata) === null || _b === void 0 ? void 0 : _b.react) === null || _c === void 0 ? void 0 : _c.forwardRef) || hasPropRef);
259
+ const isForwardRef = !options.preact && Boolean((0, helpers_2.isReactForwardRef)(json) || hasPropRef);
295
260
  if (isForwardRef) {
296
- const meta = (((_d = json.meta.useMetadata) === null || _d === void 0 ? void 0 : _d.forwardRef) ||
297
- ((_f = (_e = json.meta.useMetadata) === null || _e === void 0 ? void 0 : _e.react) === null || _f === void 0 ? void 0 : _f.forwardRef));
261
+ const meta = (0, helpers_2.isReactForwardRef)(json);
298
262
  options.forwardRef = meta || forwardRef;
299
263
  }
300
264
  const forwardRefType = options.typescript && json.propsTypeRef && forwardRef && json.propsTypeRef !== 'any'
@@ -327,16 +291,16 @@ const _componentToReact = (json, options, isSubComponent = false) => {
327
291
  }
328
292
  const shouldAddUseClientDirective = checkShouldAddUseClientDirective(json, options);
329
293
  const shouldInlineOnInitHook = !shouldAddUseClientDirective && options.rsc && isRSC(json, options);
330
- if (allRefs.length || (((_g = json.hooks.onInit) === null || _g === void 0 ? void 0 : _g.code) && !shouldInlineOnInitHook)) {
294
+ if (allRefs.length || (((_a = json.hooks.onInit) === null || _a === void 0 ? void 0 : _a.code) && !shouldInlineOnInitHook)) {
331
295
  reactLibImports.add('useRef');
332
296
  }
333
297
  if (!options.preact && hasPropRef) {
334
298
  reactLibImports.add('forwardRef');
335
299
  }
336
- if (json.hooks.onMount.length || ((_h = json.hooks.onUnMount) === null || _h === void 0 ? void 0 : _h.code) || ((_j = json.hooks.onUpdate) === null || _j === void 0 ? void 0 : _j.length)) {
300
+ if (json.hooks.onMount.length || ((_b = json.hooks.onUnMount) === null || _b === void 0 ? void 0 : _b.code) || ((_c = json.hooks.onUpdate) === null || _c === void 0 ? void 0 : _c.length)) {
337
301
  reactLibImports.add('useEffect');
338
302
  }
339
- const hasCustomStyles = !!((_k = json.style) === null || _k === void 0 ? void 0 : _k.length);
303
+ const hasCustomStyles = !!((_d = json.style) === null || _d === void 0 ? void 0 : _d.length);
340
304
  const shouldInjectCustomStyles = hasCustomStyles &&
341
305
  (options.stylesType === 'styled-components' || options.stylesType === 'emotion');
342
306
  const wrap = (0, helpers_2.wrapInFragment)(json) ||
@@ -360,86 +324,17 @@ const _componentToReact = (json, options, isSubComponent = false) => {
360
324
  ? `const ${exports.contextPropDrillingKey} = { ...props['${exports.contextPropDrillingKey}'] };`
361
325
  : ''}
362
326
  ${hasStateArgument ? '' : refsString}
363
- ${hasState
364
- ? options.stateType === 'mobx'
365
- ? `const state = useLocalObservable(() => (${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)}));`
366
- : options.stateType === 'useState'
367
- ? useStateCode
368
- : options.stateType === 'solid'
369
- ? `const state = useMutable(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
370
- : options.stateType === 'builder'
371
- ? `const state = useBuilderState(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
372
- : options.stateType === 'variables'
373
- ? (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
374
- format: 'variables',
375
- keyPrefix: 'const',
376
- valueMapper: (code, type, _, key) => {
377
- if (type === 'getter')
378
- return `${key} = function ${code.replace('get ', '')}`;
379
- if (type === 'function')
380
- return code.startsWith('async') ? code : `${key} = function ${code}`;
381
- return code;
382
- },
383
- })
384
- : `const state = useLocalProxy(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
385
- : ''}
327
+ ${(0, state_2.getReactVariantStateString)({ hasState, useStateCode, json, options })}
386
328
  ${hasStateArgument ? refsString : ''}
387
329
  ${getContextString(json, options)}
388
- ${((_l = json.hooks.init) === null || _l === void 0 ? void 0 : _l.code) ? (0, state_2.processHookCode)({ str: (_m = json.hooks.init) === null || _m === void 0 ? void 0 : _m.code, options }) : ''}
330
+ ${((_e = json.hooks.init) === null || _e === void 0 ? void 0 : _e.code) ? (0, state_2.processHookCode)({ str: (_f = json.hooks.init) === null || _f === void 0 ? void 0 : _f.code, options }) : ''}
389
331
  ${contextStr || ''}
390
332
 
391
- ${((_o = json.hooks.onInit) === null || _o === void 0 ? void 0 : _o.code)
392
- ? shouldInlineOnInitHook
393
- ? (0, state_2.processHookCode)({ str: json.hooks.onInit.code, options })
394
- : `
395
- const hasInitialized = useRef(false);
396
- if (!hasInitialized.current) {
397
- ${(0, state_2.processHookCode)({
398
- str: json.hooks.onInit.code,
399
- options,
400
- })}
401
- hasInitialized.current = true;
402
- }
403
- `
404
- : ''}
405
-
406
- ${json.hooks.onEvent
407
- .map((hook) => {
408
- const eventName = `"${hook.eventName}"`;
409
- const handlerName = (0, on_event_1.getOnEventHandlerName)(hook);
410
- return `
411
- useEffect(() => {
412
- ${hook.refName}.current?.addEventListener(${eventName}, ${handlerName});
413
- return () => ${hook.refName}.current?.removeEventListener(${eventName}, ${handlerName});
414
- }, []);
415
- `;
416
- })
417
- .join('\n')}
418
-
419
- ${json.hooks.onMount
420
- .map((hook) => `useEffect(() => {
421
- ${(0, state_2.processHookCode)({
422
- str: hook.code,
423
- options,
424
- })}
425
- }, [])`)
426
- .join('\n')}
427
-
428
- ${(_q = (_p = json.hooks.onUpdate) === null || _p === void 0 ? void 0 : _p.map((hook) => `useEffect(() => {
429
- ${(0, state_2.processHookCode)({ str: hook.code, options })}
430
- },
431
- ${hook.deps ? (0, state_2.processHookCode)({ str: hook.deps, options }) : ''})`).join(';')) !== null && _q !== void 0 ? _q : ''}
432
-
433
- ${((_r = json.hooks.onUnMount) === null || _r === void 0 ? void 0 : _r.code)
434
- ? `useEffect(() => {
435
- return () => {
436
- ${(0, state_2.processHookCode)({
437
- str: json.hooks.onUnMount.code,
438
- options,
439
- })}
440
- }
441
- }, [])`
442
- : ''}
333
+ ${(0, hooks_1.getOnInitHookComponentBody)({ shouldInlineOnInitHook, json, options })}
334
+ ${(0, hooks_1.getOnEventHookComponentBody)(json)}
335
+ ${(0, hooks_1.getOnMountComponentBody)({ json, options })}
336
+ ${(0, hooks_1.getOnUpdateComponentBody)({ json, options })}
337
+ ${(0, hooks_1.getOnUnMountComponentBody)({ json, options })}
443
338
 
444
339
  return (
445
340
  ${wrap ? (0, helpers_2.openFrag)(options) : ''}
@@ -456,7 +351,7 @@ const _componentToReact = (json, options, isSubComponent = false) => {
456
351
  `;
457
352
  const str = (0, dedent_1.dedent) `
458
353
  ${shouldAddUseClientDirective ? `'use client';` : ''}
459
- ${getDefaultImport(json, options)}
354
+ ${(0, state_2.getDefaultImport)(options)}
460
355
  ${styledComponentsCode ? `import styled from 'styled-components';\n` : ''}
461
356
  ${reactLibImports.size
462
357
  ? `import { ${Array.from(reactLibImports).join(', ')} } from '${options.preact ? 'preact/hooks' : 'react'}'`
@@ -466,15 +361,7 @@ const _componentToReact = (json, options, isSubComponent = false) => {
466
361
  ? `/** @jsx jsx */
467
362
  import { jsx } from '@emotion/react'`.trim()
468
363
  : ''}
469
- ${!hasState
470
- ? ''
471
- : options.stateType === 'valtio'
472
- ? `import { useLocalProxy } from 'valtio/utils';`
473
- : options.stateType === 'solid'
474
- ? `import { useMutable } from 'react-solid-state';`
475
- : options.stateType === 'mobx'
476
- ? `import { useLocalObservable, observer } from 'mobx-react-lite';`
477
- : ''}
364
+ ${(0, state_2.getReactVariantStateImportString)(hasState, options)}
478
365
  ${json.types && options.typescript ? json.types.join('\n') : ''}
479
366
  ${(0, render_imports_1.renderPreComponent)({
480
367
  explicitImportFileExtension: options.explicitImportFileExtension,
@@ -482,11 +369,10 @@ const _componentToReact = (json, options, isSubComponent = false) => {
482
369
  target: options.type === 'native' ? 'reactNative' : 'react',
483
370
  })}
484
371
  ${isForwardRef ? `const ${json.name} = forwardRef${forwardRefType}(` : ''}function ${json.name}(${componentArgs}) {
372
+ ${(0, default_props_1.getDefaultProps)(json)}
485
373
  ${componentBody}
486
374
  }${isForwardRef ? ')' : ''}
487
375
 
488
- ${getPropsDefinition({ json })}
489
-
490
376
  ${reactNativeStyles
491
377
  ? `const styles = StyleSheet.create(${json5_1.default.stringify(reactNativeStyles)});`
492
378
  : ''}
@@ -0,0 +1,2 @@
1
+ import { MitosisComponent } from '../../../types/mitosis-component';
2
+ export declare const getDefaultProps: (json: MitosisComponent) => string;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDefaultProps = void 0;
4
+ const getDefaultProps = (json) => {
5
+ if (!json.defaultProps)
6
+ return '';
7
+ const defaultPropsString = Object.keys(json.defaultProps)
8
+ .map((prop) => {
9
+ var _a;
10
+ const value = json.defaultProps.hasOwnProperty(prop)
11
+ ? (_a = json.defaultProps[prop]) === null || _a === void 0 ? void 0 : _a.code
12
+ : 'undefined';
13
+ return `${prop}: ${value}`;
14
+ })
15
+ .join(',');
16
+ if (defaultPropsString) {
17
+ return `props = {${defaultPropsString}, ...props}`;
18
+ }
19
+ return '';
20
+ };
21
+ exports.getDefaultProps = getDefaultProps;
@@ -0,0 +1,20 @@
1
+ import { ToReactOptions } from '../../../generators/react';
2
+ import { MitosisComponent } from '../../../types/mitosis-component';
3
+ export declare const getOnInitHookComponentBody: ({ shouldInlineOnInitHook, options, json, }: {
4
+ json: MitosisComponent;
5
+ options: ToReactOptions;
6
+ shouldInlineOnInitHook?: boolean | undefined;
7
+ }) => string;
8
+ export declare const getOnEventHookComponentBody: (json: MitosisComponent) => string;
9
+ export declare const getOnMountComponentBody: ({ options, json, }: {
10
+ json: MitosisComponent;
11
+ options: ToReactOptions;
12
+ }) => string;
13
+ export declare const getOnUpdateComponentBody: ({ options, json, }: {
14
+ json: MitosisComponent;
15
+ options: ToReactOptions;
16
+ }) => string;
17
+ export declare const getOnUnMountComponentBody: ({ options, json, }: {
18
+ json: MitosisComponent;
19
+ options: ToReactOptions;
20
+ }) => string;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getOnUnMountComponentBody = exports.getOnUpdateComponentBody = exports.getOnMountComponentBody = exports.getOnEventHookComponentBody = exports.getOnInitHookComponentBody = void 0;
4
+ const state_1 = require("../../../generators/react/helpers/state");
5
+ const on_event_1 = require("../../../helpers/on-event");
6
+ const getOnInitHookComponentBody = ({ shouldInlineOnInitHook, options, json, }) => {
7
+ var _a;
8
+ return ((_a = json.hooks.onInit) === null || _a === void 0 ? void 0 : _a.code)
9
+ ? shouldInlineOnInitHook
10
+ ? (0, state_1.processHookCode)({ str: json.hooks.onInit.code, options })
11
+ : `
12
+ const hasInitialized = useRef(false);
13
+ if (!hasInitialized.current) {
14
+ ${(0, state_1.processHookCode)({
15
+ str: json.hooks.onInit.code,
16
+ options,
17
+ })}
18
+ hasInitialized.current = true;
19
+ }
20
+ `
21
+ : '';
22
+ };
23
+ exports.getOnInitHookComponentBody = getOnInitHookComponentBody;
24
+ const getOnEventHookComponentBody = (json) => json.hooks.onEvent
25
+ .map((hook) => {
26
+ const eventName = `"${hook.eventName}"`;
27
+ const handlerName = (0, on_event_1.getOnEventHandlerName)(hook);
28
+ return `
29
+ useEffect(() => {
30
+ ${hook.refName}.current?.addEventListener(${eventName}, ${handlerName});
31
+ return () => ${hook.refName}.current?.removeEventListener(${eventName}, ${handlerName});
32
+ }, []);
33
+ `;
34
+ })
35
+ .join('\n');
36
+ exports.getOnEventHookComponentBody = getOnEventHookComponentBody;
37
+ const getOnMountComponentBody = ({ options, json, }) => json.hooks.onMount
38
+ .map((hook) => `useEffect(() => {
39
+ ${(0, state_1.processHookCode)({
40
+ str: hook.code,
41
+ options,
42
+ })}
43
+ }, [])`)
44
+ .join('\n');
45
+ exports.getOnMountComponentBody = getOnMountComponentBody;
46
+ const getOnUpdateComponentBody = ({ options, json, }) => {
47
+ var _a, _b;
48
+ return (_b = (_a = json.hooks.onUpdate) === null || _a === void 0 ? void 0 : _a.map((hook) => `useEffect(() => {
49
+ ${(0, state_1.processHookCode)({ str: hook.code, options })}
50
+ },
51
+ ${hook.deps ? (0, state_1.processHookCode)({ str: hook.deps, options }) : ''})`).join(';')) !== null && _b !== void 0 ? _b : '';
52
+ };
53
+ exports.getOnUpdateComponentBody = getOnUpdateComponentBody;
54
+ const getOnUnMountComponentBody = ({ options, json, }) => {
55
+ var _a;
56
+ return ((_a = json.hooks.onUnMount) === null || _a === void 0 ? void 0 : _a.code)
57
+ ? `useEffect(() => {
58
+ return () => {
59
+ ${(0, state_1.processHookCode)({
60
+ str: json.hooks.onUnMount.code,
61
+ options,
62
+ })}
63
+ }
64
+ }, [])`
65
+ : '';
66
+ };
67
+ exports.getOnUnMountComponentBody = getOnUnMountComponentBody;
@@ -1,6 +1,6 @@
1
- import { MitosisComponent } from '../../types/mitosis-component';
2
- import { MitosisNode } from '../../types/mitosis-node';
3
- import { ToReactOptions } from './types';
1
+ import { MitosisComponent } from '../../../types/mitosis-component';
2
+ import { MitosisNode } from '../../../types/mitosis-node';
3
+ 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;
@@ -8,3 +8,4 @@ export declare const isFragmentWithKey: (node?: MitosisNode) => boolean;
8
8
  export declare function getFragment(type: 'open' | 'close', options: ToReactOptions, node?: MitosisNode): string;
9
9
  export declare const wrapInFragment: (json: MitosisComponent | MitosisNode) => boolean;
10
10
  export declare function processTagReferences(json: MitosisComponent, options: ToReactOptions): void;
11
+ export declare const isReactForwardRef: (json: MitosisComponent) => string | undefined;
@@ -3,9 +3,9 @@ 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.isFragmentWithKey = exports.closeFrag = exports.openFrag = exports.processBinding = void 0;
7
- const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
8
- const strip_state_and_props_refs_1 = require("../../helpers/strip-state-and-props-refs");
6
+ exports.isReactForwardRef = exports.processTagReferences = exports.wrapInFragment = exports.getFragment = exports.isFragmentWithKey = exports.closeFrag = exports.openFrag = exports.processBinding = void 0;
7
+ const is_mitosis_node_1 = require("../../../helpers/is-mitosis-node");
8
+ const strip_state_and_props_refs_1 = require("../../../helpers/strip-state-and-props-refs");
9
9
  const lodash_1 = require("lodash");
10
10
  const legacy_1 = __importDefault(require("neotraverse/legacy"));
11
11
  const processBinding = (str, options) => {
@@ -93,3 +93,5 @@ function processTagReferences(json, options) {
93
93
  });
94
94
  }
95
95
  exports.processTagReferences = processTagReferences;
96
+ const isReactForwardRef = (json) => { var _a, _b, _c; return ((_a = json.meta.useMetadata) === null || _a === void 0 ? void 0 : _a.forwardRef) || ((_c = (_b = json.meta.useMetadata) === null || _b === void 0 ? void 0 : _b.react) === null || _c === void 0 ? void 0 : _c.forwardRef); };
97
+ exports.isReactForwardRef = isReactForwardRef;
@@ -0,0 +1,17 @@
1
+ import { MitosisComponent } from '../../../types/mitosis-component';
2
+ import { ToReactOptions } from '../types';
3
+ export declare const processHookCode: ({ str, options }: {
4
+ str: string;
5
+ options: ToReactOptions;
6
+ }) => string;
7
+ export declare const getUseStateCode: (json: MitosisComponent, options: ToReactOptions) => string;
8
+ export declare const updateStateSetters: (json: MitosisComponent, options: ToReactOptions) => void;
9
+ export declare const updateStateSettersInCode: (value: string, options: ToReactOptions) => string;
10
+ export declare const getReactVariantStateImportString: (hasState: boolean, options: ToReactOptions) => "" | "import { useLocalProxy } from 'valtio/utils';" | "import { useMutable } from 'react-solid-state';" | "import { useLocalObservable, observer } from 'mobx-react-lite';";
11
+ export declare const getReactVariantStateString: ({ hasState, options, json, useStateCode, }: {
12
+ useStateCode: string;
13
+ hasState: boolean;
14
+ json: MitosisComponent;
15
+ options: ToReactOptions;
16
+ }) => string;
17
+ export declare const getDefaultImport: (options: ToReactOptions) => string;
@@ -0,0 +1,156 @@
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.getDefaultImport = exports.getReactVariantStateString = exports.getReactVariantStateImportString = exports.updateStateSettersInCode = exports.updateStateSetters = exports.getUseStateCode = exports.processHookCode = void 0;
7
+ const capitalize_1 = require("../../../helpers/capitalize");
8
+ const get_function_string_1 = require("../../../helpers/get-function-string");
9
+ const get_state_object_string_1 = require("../../../helpers/get-state-object-string");
10
+ const get_typed_function_1 = require("../../../helpers/get-typed-function");
11
+ const is_mitosis_node_1 = require("../../../helpers/is-mitosis-node");
12
+ const patterns_1 = require("../../../helpers/patterns");
13
+ const transform_state_setters_1 = require("../../../helpers/transform-state-setters");
14
+ const core_1 = require("@babel/core");
15
+ const function_1 = require("fp-ts/lib/function");
16
+ const legacy_1 = __importDefault(require("neotraverse/legacy"));
17
+ const helpers_1 = require("../helpers");
18
+ /**
19
+ * Removes all `this.` references.
20
+ */
21
+ const stripThisRefs = (str, options) => {
22
+ if (options.stateType !== 'useState') {
23
+ return str;
24
+ }
25
+ return str.replace(/this\.([a-zA-Z_\$0-9]+)/g, '$1');
26
+ };
27
+ const processHookCode = ({ str, options }) => (0, helpers_1.processBinding)((0, exports.updateStateSettersInCode)(str, options), options);
28
+ exports.processHookCode = processHookCode;
29
+ const valueMapper = (options) => (val) => {
30
+ const x = (0, exports.processHookCode)({ str: val, options });
31
+ return stripThisRefs(x, options);
32
+ };
33
+ const getSetStateFnName = (stateName) => `set${(0, capitalize_1.capitalize)(stateName)}`;
34
+ const processStateValue = (options) => {
35
+ const mapValue = valueMapper(options);
36
+ return ([key, stateVal]) => {
37
+ if (!stateVal) {
38
+ return '';
39
+ }
40
+ let value = stateVal.code || '';
41
+ const type = stateVal.type;
42
+ const typeParameter = stateVal.typeParameter;
43
+ const stateType = options.typescript && stateVal.typeParameter ? `<${stateVal.typeParameter}>` : '';
44
+ let result = '';
45
+ if (type === 'getter') {
46
+ result = (0, function_1.pipe)(value, patterns_1.replaceGetterWithFunction, mapValue);
47
+ }
48
+ else if (type === 'function') {
49
+ result = mapValue(value);
50
+ }
51
+ else if (type === 'method') {
52
+ result = (0, function_1.pipe)(value, patterns_1.prefixWithFunction, mapValue);
53
+ }
54
+ else {
55
+ return `const [${key}, ${getSetStateFnName(key)}] = useState${stateType}(() => (${mapValue(value)}))`;
56
+ }
57
+ return (0, get_typed_function_1.getTypedFunction)(result, options.typescript, typeParameter);
58
+ };
59
+ };
60
+ const getUseStateCode = (json, options) => {
61
+ const lineItemDelimiter = '\n\n\n';
62
+ const stringifiedState = Object.entries(json.state).map(processStateValue(options));
63
+ return stringifiedState.join(lineItemDelimiter);
64
+ };
65
+ exports.getUseStateCode = getUseStateCode;
66
+ const updateStateSetters = (json, options) => {
67
+ if (options.stateType !== 'useState') {
68
+ return;
69
+ }
70
+ (0, legacy_1.default)(json).forEach(function (item) {
71
+ if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
72
+ for (const key in item.bindings) {
73
+ let values = item.bindings[key];
74
+ const newValue = (0, exports.updateStateSettersInCode)(values === null || values === void 0 ? void 0 : values.code, options);
75
+ if (newValue !== (values === null || values === void 0 ? void 0 : values.code)) {
76
+ item.bindings[key] = {
77
+ ...values,
78
+ code: newValue,
79
+ };
80
+ }
81
+ }
82
+ }
83
+ });
84
+ };
85
+ exports.updateStateSetters = updateStateSetters;
86
+ const updateStateSettersInCode = (value, options) => {
87
+ if (options.stateType !== 'useState') {
88
+ return value;
89
+ }
90
+ return (0, transform_state_setters_1.transformStateSetters)({
91
+ value,
92
+ transformer: ({ path, propertyName }) => core_1.types.callExpression(core_1.types.identifier(getSetStateFnName(propertyName)), [path.node.right]),
93
+ });
94
+ };
95
+ exports.updateStateSettersInCode = updateStateSettersInCode;
96
+ const getReactVariantStateImportString = (hasState, options) => {
97
+ return !hasState
98
+ ? ''
99
+ : options.stateType === 'valtio'
100
+ ? `import { useLocalProxy } from 'valtio/utils';`
101
+ : options.stateType === 'solid'
102
+ ? `import { useMutable } from 'react-solid-state';`
103
+ : options.stateType === 'mobx'
104
+ ? `import { useLocalObservable, observer } from 'mobx-react-lite';`
105
+ : '';
106
+ };
107
+ exports.getReactVariantStateImportString = getReactVariantStateImportString;
108
+ const getReactVariantStateString = ({ hasState, options, json, useStateCode, }) => hasState
109
+ ? options.stateType === 'mobx'
110
+ ? `const state = useLocalObservable(() => (${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)}));`
111
+ : options.stateType === 'useState'
112
+ ? useStateCode
113
+ : options.stateType === 'solid'
114
+ ? `const state = useMutable(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
115
+ : options.stateType === 'builder'
116
+ ? `const state = useBuilderState(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
117
+ : options.stateType === 'variables'
118
+ ? (0, get_state_object_string_1.getStateObjectStringFromComponent)(json, {
119
+ format: 'variables',
120
+ keyPrefix: 'const',
121
+ valueMapper: (code, type, _, key) => {
122
+ if (key) {
123
+ const constPrefix = !code.startsWith('function') ? `${key} = ` : '';
124
+ if (type === 'getter')
125
+ return `${constPrefix}${(0, get_function_string_1.getFunctionString)(code.replace('get ', ''))}`;
126
+ if (type === 'function')
127
+ return code.startsWith('async') ? code : `${constPrefix}${(0, get_function_string_1.getFunctionString)(code)}`;
128
+ }
129
+ return code;
130
+ },
131
+ })
132
+ : `const state = useLocalProxy(${(0, get_state_object_string_1.getStateObjectStringFromComponent)(json)});`
133
+ : '';
134
+ exports.getReactVariantStateString = getReactVariantStateString;
135
+ const getDefaultImport = (options) => {
136
+ const { preact, type } = options;
137
+ if (preact) {
138
+ return `
139
+ /** @jsx h */
140
+ import { h, Fragment } from 'preact';
141
+ `;
142
+ }
143
+ if (type === 'native') {
144
+ return `
145
+ import * as React from 'react';
146
+ import { FlatList, ScrollView, View, StyleSheet, Image, Text, Pressable, TextInput, TouchableOpacity, Button, Linking } from 'react-native';
147
+ `;
148
+ }
149
+ if (type === 'taro') {
150
+ return `
151
+ import * as React from 'react';
152
+ `;
153
+ }
154
+ return "import * as React from 'react';";
155
+ };
156
+ exports.getDefaultImport = getDefaultImport;
@@ -39,7 +39,7 @@ const componentToStencil = (_options = {
39
39
  const defaultProps = json.defaultProps;
40
40
  const childComponents = (0, get_child_components_1.getChildComponents)(json);
41
41
  const processBindingOptions = { events };
42
- options.plugins = (0, get_code_processor_plugins_1.getCodeProcessorPlugins)(options, processBindingOptions);
42
+ options.plugins = (0, get_code_processor_plugins_1.getCodeProcessorPlugins)(json, options, processBindingOptions);
43
43
  if (options.plugins) {
44
44
  json = (0, plugins_1.runPostJsonPlugins)({ json, plugins: options.plugins });
45
45
  }
@@ -102,8 +102,6 @@ const componentToStencil = (_options = {
102
102
  ${(0, helpers_1.getImports)(json, options, childComponents)}
103
103
 
104
104
  import { ${coreImports} } from '@stencil/core';
105
-
106
- ${json.types ? json.types.join('\n') : ''}
107
105
 
108
106
  @Component({
109
107
  tag: '${tagName}',
@@ -115,10 +113,10 @@ const componentToStencil = (_options = {
115
113
  })
116
114
  export class ${json.name} {
117
115
  ${refs}
118
- ${(0, helpers_1.getPropsAsCode)(props, defaultProps, json.propsTypeRef)}
116
+ ${(0, helpers_1.getPropsAsCode)(props, json, defaultProps)}
119
117
  ${dataString}
120
118
  ${methodsString}
121
-
119
+ ${(0, helpers_1.getExportsAndLocal)(json)}
122
120
  ${withAttributePassing ? (0, attribute_passing_1.getAttributePassingString)(true) : ''}
123
121
 
124
122
  ${dependencyOnUpdateHooks
@@ -5,9 +5,9 @@ export declare const isEvent: (key: string) => boolean;
5
5
  export type ProcessBindingOptions = {
6
6
  events: string[];
7
7
  };
8
- export declare const processBinding: (code: string, { events }: ProcessBindingOptions) => string;
8
+ export declare const processBinding: (json: MitosisComponent, code: string, { events }: ProcessBindingOptions) => string;
9
9
  export declare const getTagName: (name: string, { prefix }: ToStencilOptions) => string;
10
- export declare const getPropsAsCode: (props: string[], defaultProps?: MitosisState | undefined, propsTypeRef?: string) => string;
10
+ export declare const getPropsAsCode: (props: string[], json: MitosisComponent, defaultProps?: MitosisState | undefined) => string;
11
11
  /**
12
12
  * Check for root element if it needs a wrapping <Host>
13
13
  * @param children
@@ -34,3 +34,4 @@ export declare const getImports: (json: MitosisComponent, options: ToStencilOpti
34
34
  * @param deps The hook dependencies as string e.g.: "[this.a,this.b]"
35
35
  */
36
36
  export declare const getDepsAsArray: (deps: string) => string[];
37
+ export declare const getExportsAndLocal: (json: MitosisComponent) => string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDepsAsArray = exports.getImports = exports.getStencilCoreImportsAsString = exports.needsWrap = exports.getPropsAsCode = exports.getTagName = exports.processBinding = exports.isEvent = void 0;
3
+ exports.getExportsAndLocal = exports.getDepsAsArray = exports.getImports = exports.getStencilCoreImportsAsString = exports.needsWrap = exports.getPropsAsCode = exports.getTagName = exports.processBinding = exports.isEvent = void 0;
4
4
  const dash_case_1 = require("../../../helpers/dash-case");
5
5
  const event_handlers_1 = require("../../../helpers/event-handlers");
6
6
  const render_imports_1 = require("../../../helpers/render-imports");
@@ -19,8 +19,17 @@ const appendEmits = (str, events) => {
19
19
  }
20
20
  return code;
21
21
  };
22
- const processBinding = (code, { events }) => {
23
- return (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(appendEmits(code, events), { replaceWith: 'this.' });
22
+ const processBinding = (json, code, { events }) => {
23
+ let resolvedCode = (0, strip_state_and_props_refs_1.stripStateAndPropsRefs)(appendEmits(code, events), { replaceWith: 'this.' });
24
+ if (json.exports) {
25
+ // We need to use local exports with `this.` in stencil
26
+ Object.entries(json.exports)
27
+ .filter(([, value]) => value.usedInLocal)
28
+ .forEach(([key]) => {
29
+ resolvedCode = resolvedCode.replaceAll(key, `this.${key}`);
30
+ });
31
+ }
32
+ return resolvedCode;
24
33
  };
25
34
  exports.processBinding = processBinding;
26
35
  const getTagName = (name, { prefix }) => {
@@ -34,7 +43,10 @@ const getTagName = (name, { prefix }) => {
34
43
  return dashName;
35
44
  };
36
45
  exports.getTagName = getTagName;
37
- const getPropsAsCode = (props, defaultProps, propsTypeRef) => {
46
+ const getPropsAsCode = (props, json, defaultProps) => {
47
+ const propsTypeRef = json.propsTypeRef;
48
+ const internalTypes = json.types;
49
+ const isInternalType = propsTypeRef && internalTypes && internalTypes.find((iType) => iType.includes(propsTypeRef));
38
50
  return props
39
51
  .map((item) => {
40
52
  var _a;
@@ -46,7 +58,8 @@ const getPropsAsCode = (props, defaultProps, propsTypeRef) => {
46
58
  const type = propsTypeRef &&
47
59
  propsTypeRef !== 'any' &&
48
60
  propsTypeRef !== 'unknown' &&
49
- propsTypeRef !== 'never'
61
+ propsTypeRef !== 'never' &&
62
+ !isInternalType
50
63
  ? `${propsTypeRef}["${item}"]`
51
64
  : 'any';
52
65
  return `@Prop() ${item}: ${type}${defaultPropString}`;
@@ -101,6 +114,7 @@ const getImports = (json, options, childComponents) => {
101
114
  explicitImportFileExtension: options.explicitImportFileExtension,
102
115
  component: json,
103
116
  target: 'stencil',
117
+ excludeExportAndLocal: true,
104
118
  importMapper: (_, theImport, importedValues) => {
105
119
  const childImport = importedValues.defaultImport;
106
120
  if (childImport && childComponents.includes(childImport)) {
@@ -124,3 +138,14 @@ const getDepsAsArray = (deps) => {
124
138
  .map((dep) => dep.trim());
125
139
  };
126
140
  exports.getDepsAsArray = getDepsAsArray;
141
+ const getExportsAndLocal = (json) => {
142
+ return Object.entries(json.exports || {})
143
+ .map(([key, { usedInLocal, code }]) => {
144
+ if (usedInLocal) {
145
+ return `${key} = ${code.substring(code.indexOf('=') + 1)}`;
146
+ }
147
+ return '';
148
+ })
149
+ .join('\n');
150
+ };
151
+ exports.getExportsAndLocal = getExportsAndLocal;
@@ -1,3 +1,4 @@
1
1
  import { ProcessBindingOptions } from '../../../generators/stencil/helpers/index';
2
2
  import { ToStencilOptions } from '../../../generators/stencil/types';
3
- export declare const getCodeProcessorPlugins: (options: ToStencilOptions, processBindingOptions: ProcessBindingOptions) => import("../../..").MitosisPlugin[];
3
+ import { MitosisComponent } from '../../../types/mitosis-component';
4
+ export declare const getCodeProcessorPlugins: (json: MitosisComponent, options: ToStencilOptions, processBindingOptions: ProcessBindingOptions) => import("../../..").MitosisPlugin[];
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCodeProcessorPlugins = void 0;
4
4
  const index_1 = require("../../../generators/stencil/helpers/index");
5
5
  const process_code_1 = require("../../../helpers/plugins/process-code");
6
- const getCodeProcessorPlugins = (options, processBindingOptions) => {
6
+ const getCodeProcessorPlugins = (json, options, processBindingOptions) => {
7
7
  return [
8
8
  ...(options.plugins || []),
9
9
  (0, process_code_1.CODE_PROCESSOR_PLUGIN)((codeType) => {
@@ -16,7 +16,7 @@ const getCodeProcessorPlugins = (options, processBindingOptions) => {
16
16
  case 'context-set':
17
17
  case 'dynamic-jsx-elements':
18
18
  case 'types':
19
- return (code) => (0, index_1.processBinding)(code, processBindingOptions);
19
+ return (code) => (0, index_1.processBinding)(json, code, processBindingOptions);
20
20
  }
21
21
  }),
22
22
  ];
@@ -286,11 +286,11 @@ const componentToSvelte = (userProvidedOptions) => ({ component }) => {
286
286
  if (options.typescript && json.propsTypeRef && json.propsTypeRef !== 'any') {
287
287
  propDeclaration += `: ${json.propsTypeRef.split(' |')[0]}['${name}']`;
288
288
  }
289
- if ((_b = (_a = json.props) === null || _a === void 0 ? void 0 : _a[name]) === null || _b === void 0 ? void 0 : _b.optional) {
290
- propDeclaration += `= undefined`;
291
- }
292
289
  if (json.defaultProps && json.defaultProps.hasOwnProperty(name)) {
293
- propDeclaration += `=${(_c = json.defaultProps[name]) === null || _c === void 0 ? void 0 : _c.code}`;
290
+ propDeclaration += `=${(_a = json.defaultProps[name]) === null || _a === void 0 ? void 0 : _a.code}`;
291
+ }
292
+ else if ((_c = (_b = json.props) === null || _b === void 0 ? void 0 : _b[name]) === null || _c === void 0 ? void 0 : _c.optional) {
293
+ propDeclaration += `= undefined`;
294
294
  }
295
295
  propDeclaration += ';';
296
296
  return propDeclaration;
@@ -14,7 +14,7 @@ const getCompositionPropDefinition = ({ options, component, props, }) => {
14
14
  const isTs = options.typescript;
15
15
  let str = 'const props = ';
16
16
  if (component.defaultProps) {
17
- const generic = isTs ? `<${component.propsTypeRef}>` : '';
17
+ const generic = isTs && component.propsTypeRef !== 'any' ? `<${component.propsTypeRef}>` : '';
18
18
  const defalutPropsString = props
19
19
  .map((prop) => {
20
20
  var _a;
@@ -0,0 +1 @@
1
+ export declare const getFunctionString: (code: string) => string;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFunctionString = void 0;
4
+ const getFunctionString = (code) => code.startsWith('function') ? code : `function ${code}`;
5
+ exports.getFunctionString = getFunctionString;
@@ -28,9 +28,10 @@ type ImportArgs = {
28
28
  export declare const renderImport: ({ theImport, target, asyncComponentImports, preserveFileExtensions, component, componentsUsed, importMapper, explicitImportFileExtension, }: ImportArgs & {
29
29
  theImport: MitosisImport;
30
30
  }) => string;
31
- export declare const renderPreComponent: ({ component, target, excludeMitosisComponents, asyncComponentImports, preserveFileExtensions, componentsUsed, importMapper, explicitImportFileExtension, }: Omit<ImportArgs, "explicitImportFileExtension" | "asyncComponentImports"> & Partial<Pick<ImportArgs, "explicitImportFileExtension" | "asyncComponentImports">> & {
31
+ export declare const renderPreComponent: ({ component, target, excludeMitosisComponents, asyncComponentImports, preserveFileExtensions, componentsUsed, importMapper, explicitImportFileExtension, excludeExportAndLocal, }: Omit<ImportArgs, "explicitImportFileExtension" | "asyncComponentImports"> & Partial<Pick<ImportArgs, "explicitImportFileExtension" | "asyncComponentImports">> & {
32
32
  component: MitosisComponent;
33
33
  target: Target;
34
34
  excludeMitosisComponents?: boolean | undefined;
35
+ excludeExportAndLocal?: boolean | undefined;
35
36
  }) => string;
36
37
  export {};
@@ -143,7 +143,7 @@ const renderImports = ({ imports, target, asyncComponentImports, excludeMitosisC
143
143
  explicitImportFileExtension,
144
144
  }))
145
145
  .join('\n');
146
- const renderPreComponent = ({ component, target, excludeMitosisComponents, asyncComponentImports = false, preserveFileExtensions = false, componentsUsed = [], importMapper, explicitImportFileExtension = false, }) => {
146
+ const renderPreComponent = ({ component, target, excludeMitosisComponents, asyncComponentImports = false, preserveFileExtensions = false, componentsUsed = [], importMapper, explicitImportFileExtension = false, excludeExportAndLocal = false, }) => {
147
147
  var _a;
148
148
  return `
149
149
  ${renderImports({
@@ -157,7 +157,7 @@ const renderPreComponent = ({ component, target, excludeMitosisComponents, async
157
157
  importMapper,
158
158
  explicitImportFileExtension,
159
159
  })}
160
- ${renderExportAndLocal(component)}
160
+ ${excludeExportAndLocal ? '' : renderExportAndLocal(component)}
161
161
  ${((_a = component.hooks.preComponent) === null || _a === void 0 ? void 0 : _a.code) || ''}
162
162
  `;
163
163
  };
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.6.6",
25
+ "version": "0.6.8",
26
26
  "homepage": "https://github.com/BuilderIO/mitosis",
27
27
  "main": "./dist/src/index.js",
28
28
  "exports": {
@@ -1,9 +0,0 @@
1
- import { MitosisComponent } from '../../types/mitosis-component';
2
- import { ToReactOptions } from './types';
3
- export declare const processHookCode: ({ str, options }: {
4
- str: string;
5
- options: ToReactOptions;
6
- }) => string;
7
- export declare const getUseStateCode: (json: MitosisComponent, options: ToReactOptions) => string;
8
- export declare const updateStateSetters: (json: MitosisComponent, options: ToReactOptions) => void;
9
- export declare const updateStateSettersInCode: (value: string, options: ToReactOptions) => string;
@@ -1,93 +0,0 @@
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.updateStateSettersInCode = exports.updateStateSetters = exports.getUseStateCode = exports.processHookCode = void 0;
7
- const capitalize_1 = require("../../helpers/capitalize");
8
- const get_typed_function_1 = require("../../helpers/get-typed-function");
9
- const is_mitosis_node_1 = require("../../helpers/is-mitosis-node");
10
- const patterns_1 = require("../../helpers/patterns");
11
- const transform_state_setters_1 = require("../../helpers/transform-state-setters");
12
- const core_1 = require("@babel/core");
13
- const function_1 = require("fp-ts/lib/function");
14
- const legacy_1 = __importDefault(require("neotraverse/legacy"));
15
- const helpers_1 = require("./helpers");
16
- /**
17
- * Removes all `this.` references.
18
- */
19
- const stripThisRefs = (str, options) => {
20
- if (options.stateType !== 'useState') {
21
- return str;
22
- }
23
- return str.replace(/this\.([a-zA-Z_\$0-9]+)/g, '$1');
24
- };
25
- const processHookCode = ({ str, options }) => (0, helpers_1.processBinding)((0, exports.updateStateSettersInCode)(str, options), options);
26
- exports.processHookCode = processHookCode;
27
- const valueMapper = (options) => (val) => {
28
- const x = (0, exports.processHookCode)({ str: val, options });
29
- return stripThisRefs(x, options);
30
- };
31
- const getSetStateFnName = (stateName) => `set${(0, capitalize_1.capitalize)(stateName)}`;
32
- const processStateValue = (options) => {
33
- const mapValue = valueMapper(options);
34
- return ([key, stateVal]) => {
35
- if (!stateVal) {
36
- return '';
37
- }
38
- let value = stateVal.code || '';
39
- const type = stateVal.type;
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
- }
52
- else {
53
- return `const [${key}, ${getSetStateFnName(key)}] = useState${stateType}(() => (${mapValue(value)}))`;
54
- }
55
- return (0, get_typed_function_1.getTypedFunction)(result, options.typescript, typeParameter);
56
- };
57
- };
58
- const getUseStateCode = (json, options) => {
59
- const lineItemDelimiter = '\n\n\n';
60
- const stringifiedState = Object.entries(json.state).map(processStateValue(options));
61
- return stringifiedState.join(lineItemDelimiter);
62
- };
63
- exports.getUseStateCode = getUseStateCode;
64
- const updateStateSetters = (json, options) => {
65
- if (options.stateType !== 'useState') {
66
- return;
67
- }
68
- (0, legacy_1.default)(json).forEach(function (item) {
69
- if ((0, is_mitosis_node_1.isMitosisNode)(item)) {
70
- for (const key in item.bindings) {
71
- let values = item.bindings[key];
72
- const newValue = (0, exports.updateStateSettersInCode)(values === null || values === void 0 ? void 0 : values.code, options);
73
- if (newValue !== (values === null || values === void 0 ? void 0 : values.code)) {
74
- item.bindings[key] = {
75
- ...values,
76
- code: newValue,
77
- };
78
- }
79
- }
80
- }
81
- });
82
- };
83
- exports.updateStateSetters = updateStateSetters;
84
- const updateStateSettersInCode = (value, options) => {
85
- if (options.stateType !== 'useState') {
86
- return value;
87
- }
88
- return (0, transform_state_setters_1.transformStateSetters)({
89
- value,
90
- transformer: ({ path, propertyName }) => core_1.types.callExpression(core_1.types.identifier(getSetStateFnName(propertyName)), [path.node.right]),
91
- });
92
- };
93
- exports.updateStateSettersInCode = updateStateSettersInCode;