# All files components.ts

61.62% Statements 114/185
50.29% Branches 88/175
42.86% Functions 15/35
64.74% Lines 112/173

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    7484x

    4x
    4x
    4x

    4x
    4x

    4x
    4x

    4x
    4x

    4x

    4x

    4x

    6x
    6x

    5x

    10x
    10x

    1x

    4x

    5x
    5x

    6x
    6x
    6x

    1x

    5x

    3x

    6x
    5x

    4x

    57x

    57x
    57x

    1x

    56x
    48x

    8x

    2x
    6x

    1x

    5x

    5x
    5x

    4x
    11x
    11x
    11x
    11x
    11x
    11x
    1x

    11x

    4x

    4x

    1x

    3x

    3x
    3x

    3x
    3x

    3x
    33x
    12x
    12x
    12x
    12x

    12x

    12x
    3x

    9x

    12x

    3x
    3x

    3x

    3x

    4x

    1x
    1x

    1x

    4x

    1x
    1x

    1x

    4x

    5x

    1x

    4x
    4x
    4x

    4x
    4x

    4x
    1x

    4x

    4x
    2x

    4x

    4x
    1x
    1x
    1x

    4x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    4x
    1x

     import React, {
      useState,
      useEffect,
      useContext,
      useReducer,
      useCallback,
      useMemo,
      useRef,
      useImperativeHandle,
      useLayoutEffect,
      useDebugValue,
      Fragment,
      Suspense,
      lazy,
      createContext,
      ReactElement,
      FunctionComponent
    } from "react";
    import { ReactElementLike } from "prop-types";
    import * as memoryCache from "memory-cache";
    import { useForm, useController, useFieldArray, useWatch, Controller, } from 'react-hook-form';
    import { ErrorMessage } from '@hookform/error-message';

    // import {cache} from 'memory-cache';
    // import cache from 'memory-cache';
    //@ts-ignore
    import { default as ReactDOMElements } from "react-dom-factories";
    import { getAdvancedBinding, fetchJSON } from "./utils";
    //@ts-ignore
    import createReactClass from "create-react-class";
    import { getReactElementFromJSONX } from ".";

    import * as defs from "./types/jsonx/index";
    import { ReactComponentLike } from "prop-types";
    declare global {
      interface window {
        [index: string]: any;
      }
      interface Window {
        [index: string]: any;
      }
      namespace NodeJS {
        interface Global {
          document: Document;
          window: Window;
          navigator: Navigator;
        }
      }
    }

    const cache = new memoryCache.Cache();
    export const ReactHookForm = { ErrorMessage, Controller }
    // if (typeof window === 'undefined') {
    //   var window = window || global.window || {};
    // }
    /**

     */
    //@ts-ignore
    export let advancedBinding = getAdvancedBinding();
    // require;
    /**
     * object of all react components available for JSONX

     */
    //@ts-ignore
    export let componentMap = Object.assign(
      { Fragment, Suspense },
      ReactDOMElements,
      window && typeof window === "object" ? window.__jsonx_custom_elements : {}
    );

    /**
     * getBoundedComponents returns reactComponents with certain elements that have this bounded to select components in the boundedComponents list

     * @param {Object} options - options for getBoundedComponents
     * @param {Object} options.reactComponents - all react components available for JSONX
     * @param {string[]} boundedComponents - list of components to bind JSONX this context (usually helpful for navigation and redux-router)
     * @returns {Object} reactComponents object of all react components available for JSONX
     */
    export function getBoundedComponents(
      this: defs.Context,
      options: {
        advancedBinding?: boolean;
        reactComponents?: defs.jsonx["jsonxComponents"];
        boundedComponents?: string[];
      } = {}
    ) {
      const { reactComponents, boundedComponents = [] } = options;
      if (
        (typeof options.advancedBinding === 'boolean' && options.advancedBinding) || (typeof options.advancedBinding==='undefined' &&
        advancedBinding)) {
        return Object.assign(
          {},
          reactComponents,
          boundedComponents.reduce(
            (result: defs.jsonx["jsonxComponents"], componentName) => {
              result[componentName] = reactComponents[componentName].bind(this);
              return result;
            },
            {}
          )
        );
        // reactComponents.ResponsiveLink = ResponsiveLink.bind(this);
      } else return reactComponents;
    }

    /**
     * returns a react component from a component library

     * @param {Object} options - options for getComponentFromLibrary
     * @param {Object} [options.componentLibraries={}] - react component library like bootstrap
     * @param {Object} [options.jsonx={}] - any valid JSONX JSON
     * @returns {function|undefined} react component from react library like bootstrap, material design or bulma
     */
    export function getComponentFromLibrary(
      options: {
        jsonx: defs.jsonx;
        componentLibraries?: defs.jsonx["jsonxLibrary"];
      } = { jsonx: {} }
    ) {
      const { componentLibraries = {}, jsonx = {} } = options;
      const libComponent = Object.keys(componentLibraries)
        .map(libraryName => {
          //@ts-ignore
          const cleanLibraryName = jsonx.component.replace(`${libraryName}.`, "");
          const libraryNameArray = cleanLibraryName.split(".");
          if (
            libraryNameArray.length === 2 &&
            componentLibraries[libraryName] &&
            componentLibraries[libraryName][libraryNameArray[0]] &&
            typeof componentLibraries[libraryName][libraryNameArray[0]][
              libraryNameArray[1]
            ] !== "undefined"
          ) {
            return componentLibraries[libraryName][libraryNameArray[0]][
              libraryNameArray[1]
            ];
          } else if (
            typeof componentLibraries[libraryName][cleanLibraryName] !== "undefined"
          ) {
            return componentLibraries[libraryName][cleanLibraryName];
          }
        })
        .filter(val => val)[0];
      return libComponent;
    }

    /**
     * returns a react element from jsonx.component

     * @example
     * // returns react elements
     * getComponentFromMap({jsonx:{component:'div'}})=>div
     * getComponentFromMap({jsonx:{component:'MyModal'},reactComponents:{MyModal:MyModal extends React.Component}})=>MyModal
     * getComponentFromMap({jsonx:{component:'reactBootstap.nav'},componentLibraries:{reactBootstrap,}})=>reactBootstap.nav
     * @param {Object} options - options for getComponentFromMap
     * @param {object} [options.jsonx={}] - any valid JSONX JSON object
     * @param {Object} [options.reactComponents={}] - react components to render
     * @param {Object} [options.componentLibraries={}] - react components to render from another component library like bootstrap or bulma
     * @param {function} [options.logError=console.error] - error logging function
     * @param {boolean} [options.debug=false] - use debug messages
     * @returns {string|function|class} valid react element
     */
    export function getComponentFromMap(
      options: {
        jsonx?: defs.jsonx;
        reactComponents?: defs.jsonx["jsonxComponents"];
        componentLibraries?: defs.jsonx["jsonxLibrary"];
        logError?: any;
        debug?: boolean;
      } = {}
    ): any {
      //ReactElementLike | ReactComponentLike | ReactElement | ReactComponentLike
      // eslint-disable-next-line
      const {
        jsonx = {},
        reactComponents = {},
        componentLibraries = {},
        logError = console.error,
        debug
      } = options;

      try {
        if (
          typeof jsonx.component !== "string" &&
          typeof jsonx.component === "function"
        ) {
          return jsonx.component;
          //@ts-ignore
        } else if (jsonx.component && ReactDOMElements[jsonx.component]) {
          return jsonx.component;
          //@ts-ignore
        } else if (reactComponents[jsonx.component]) {
          //@ts-ignore
          return reactComponents[jsonx.component];
        } else if (
          typeof jsonx.component === "string" &&
          jsonx.component.indexOf(".") > 0 &&
          getComponentFromLibrary({ jsonx, componentLibraries })
        ) {
          return getComponentFromLibrary({ jsonx, componentLibraries });
        } else {
          throw new ReferenceError(`Invalid React Component (${jsonx.component})`);
        }
      } catch (e) {
        if (debug) logError(e, e.stack ? e.stack : "no stack");
        throw e;
      }
    }

    /**
     * Returns a new function from an options object

     * @param {Object} options
     * @param {String} [options.body=''] - Function string body
     * @param {String[]} [options.args=[]] - Function arguments
     * @returns {Function}
     */
    export function getFunctionFromEval(options: any = {}) {
      Iif (typeof options === "function") return options;
      const { body = "", args = [], name } = options;
      const argus: string[] = [].concat(args);
      argus.push(body);
      const evalFunction = Function.prototype.constructor.apply({ name }, argus);
      if (name) {
        Object.defineProperty(evalFunction, "name", { value: name });
      }
      return evalFunction;
    }

    /**
     * Returns a new React Component

     * @param {Boolean} [options.returnFactory=true] - returns a React component if true otherwise returns Component Class
     * @param {Object} [options.resources={}] - asyncprops for component
     * @param {String} [options.name ] - Component name
     * @param {Function} [options.lazy ] - function that resolves {reactComponent,options} to lazy load component for code splitting
     * @param {Boolean} [options.use_getState=true] - define getState prop
     * @param {Boolean} [options.bindContext=true] - bind class this reference to render function components
     * @param {Boolean} [options.passprops ] - pass props to rendered component
     * @param {Boolean} [options.passstate] - pass state as props to rendered component
     * @param {Object} [reactComponent={}] - an object of functions used for create-react-class
     * @param {Object} reactComponent.render.body - Valid JSONX JSON
     * @param {String} reactComponent.getDefaultProps.body - return an object for the default props
     * @param {String} reactComponent.getInitialState.body - return an object for the default state
     * @returns {Function}
     * @see {@link https://reactjs.org/docs/react-without-es6.html}
     */
    export function getReactClassComponent(
      this: defs.Context,
      reactComponent = {},
      options: any = {}
    ): ReactComponentLike {
      // const util = require('util');
      // console.log(util.inspect({ reactComponent },{depth:20}));
      if (options.lazy) {
        //@ts-ignore
        return lazy(() =>
          options
            .lazy(reactComponent, Object.assign({}, options, { lazy: false }))
            .then((lazyComponent: any) => {
              return {
                //@ts-ignore
                default: getReactClassComponent(...lazyComponent)
              };
            })
        );
      }
      const context: defs.Context = this || {};
      const {
        returnFactory = true,
        resources = {},
        use_getState = true,
        bindContext = true,
        disableRenderIndexKey = true
      } = options;
      const rjc: any = {
        //mounting
        getDefaultProps: {
          body: "return {};"
        },
        // (unsupported) getDerivedStateFromProps: undefined, // {body:'return null;', args:['props','state',]}
        getInitialState: {
          body: "return {};"
        },
        componentDidMount: undefined,
        UNSAFE_componentWillMount: undefined,

        //updating
        // (unsupported) getDerivedStateFromProps
        shouldComponentUpdate: undefined, // {body:'return true;', args:['nextProps','nextState',]}
        getSnapshotBeforeUpdate: undefined, // {body:'return snapshot;', args:['prevProps', 'prevState)',]}
        componentDidUpdate: undefined, // {body:'', args:['prevProps', 'prevState','snapshot')',]}
        UNSAFE_componentWillUpdate: undefined, // {body:';', args:['nextProps','nextState',]}
        UNSAFE_componentWillReceiveProps: undefined, // {body:';', args:['nextProps',]}

        //unmounting
        componentWillUnmount: undefined,

        //error handling
        // (unsupported) componentDidCatch:undefined, // { body:'return ;', args:['error','info'] }
        // (unsupported) getDerivedStateFromError: undefined, // {body:' return { hasError:true}', args:['error')',]}

        //body
        ...reactComponent
      };
      const rjcKeys = Object.keys(rjc);
      Iif (rjcKeys.includes("render") === false) {
        throw new ReferenceError("React components require a render method");
      }
      const classOptions = rjcKeys.reduce((result: any, val: string) => {
        if (!rjc[val]) return result;
        Iif (typeof rjc[val] === "function") rjc[val] = { body: rjc[val] };
        const args = rjc[val].arguments;
        const body = rjc[val].body;
        Iif (!body) {
          console.warn({ rjc });
          throw new SyntaxError(`Function(${val}) requires a function body`);
        }
        Iif (
          args &&
          !Array.isArray(args) &&
          args.length &&
          args.length &&
          args.filter((arg: string) => typeof arg === "string").length
        ) {
          throw new TypeError(
            `Function(${val}) arguments must be an array or variable names`
          );
        }
        if (val === "render") {
          result[val] = function() {
            //@ts-ignore
            if (options.passprops && this && this.props)
              body.props = Object.assign({}, body.props, this.props);
            //@ts-ignore
            if (options.passstate && this.state)
              body.props = Object.assign({}, body.props, this.state);
            return getReactElementFromJSONX.call(
              Object.assign(
                {},
                context,
                bindContext ? this : { props: {} },
                { disableRenderIndexKey },
                {
                  props:
                    use_getState && this && this.props
                      ? //@ts-ignore
                        Object.assign({}, this.props, {
                          getState: () => this.state
                        })
                      : //@ts-ignore
                        this.props
                }
              ),
              body,
              resources
            );
          };
        } else {
          //@ts-ignore
          result[val] =
            typeof body === "function"
              ? body
              : getFunctionFromEval({
                  body,
                  args
                });
        }

        return result;
      }, {});
      const reactComponentClass = createReactClass(classOptions);
      Iif (options.name) {
        Object.defineProperty(reactComponentClass, "name", {
          value: options.name
        });
      }
      const reactClass = returnFactory
        ? React.createFactory(reactComponentClass)
        : reactComponentClass;
      return reactClass;
    }

    /**
     * A helper component that allows you to create forms with [react-hook-form](https://react-hook-form.com/) without needed to add external form libraries
     * @param this
     * @param props
     */
    export function FormComponent(
      this: defs.Context,
      props: defs.formComponentProps = {}) {
      function FormComponentFunction(this: defs.Context, componentProps:any){
        const {
          hookFormOptions = {},
          // formComponent = { component: "div", children: "empty form" },
          onSubmit,
          formWrapperComponent,
          formKey,
          formWrapperProps,
        } = props;
        const formComponent = {
          component: "div",
          children: "empty form",
          ...props.formComponent,
        }
        formComponent.props = {...formComponent.props,...componentProps};
        // const { register, unregister, errors, watch, handleSubmit, reset, setError, clearError, setValue, getValues, triggerValidation, control, formState, } = useForm(hookFormOptions);
        const reactHookForm = useForm(hookFormOptions);
        const context = {
          ...this || {},
          ...{ reactHookForm, },
        };
        if (!context.componentLibraries || !context.componentLibraries.ReactHookForm) {
          context.componentLibraries = {
          ...context.componentLibraries,
          ...{
              ReactHookForm: {
                Controller, ErrorMessage,
              }
            }
          }
        }
        const formWrapperJXM = formWrapperComponent||{
          component: 'form',
          props: {
            onSubmit: onSubmit ? reactHookForm.handleSubmit(onSubmit) : undefined,
            key: formKey ? `formWrapperJXM-${formKey}` : undefined,
            ...formWrapperProps,
          }
        };
        formWrapperJXM.children = Array.isArray(formComponent) ? formComponent : [formComponent];

        const renderJSONX = useMemo(() => getReactElementFromJSONX.bind(context), [
          context
        ]);
        return renderJSONX(formWrapperJXM);
      }
      Eif (props.name) {
        Object.defineProperty(FormComponentFunction, "name", {
          value: props.name
        });
      }
      return FormComponentFunction.bind(this);
    }

    /**
     * A helper component that allows you to create components that load data and render asynchronously.
     * @param this
     * @param props
     */
    export function DynamicComponent(
      this: defs.Context,
      props: defs.dynamicComponentProps = {}
    ) {
      function DynamicComponentFunction(this: defs.Context, componentProps:any){
        //@ts-ignore
        const {
          useCache = true,
          cacheTimeout = 60 * 60 * 5,
          loadingJSONX = { component: "div", children: "...Loading" },
          //@ts-ignore
          loadingErrorJSONX = {
            component: "div",
            children: [
              { component: "span", children: "Error: " },
              {
                component: "span",
                resourceprops: { _children: ["error", "message"] }
              }
            ]
          },
          cacheTimeoutFunction = () => {},
          transformFunction = (data: any) => data,
          fetchURL,
          fetchOptions,
          fetchFunction
        } = props;
        const jsonx = {
          ...props.jsonx,
        }
        jsonx.props = {...jsonx.props,...componentProps};
        const context = this || {};
        const [state, setState] = useState({
          hasLoaded: false,
          hasError: false,
          resources: {},
          error: undefined
        });
        const transformer = useMemo(() => getFunctionFromEval(transformFunction), [
          transformFunction
        ]);
        const timeoutFunction = useMemo(
          () => getFunctionFromEval(cacheTimeoutFunction),
          [cacheTimeoutFunction]
        );
        const renderJSONX = useMemo(() => getReactElementFromJSONX.bind(context), [
          context
        ]);
        const loadingComponent = useMemo(() => renderJSONX(loadingJSONX), [
          loadingJSONX
        ]);
        const loadingError = useMemo(
          () => renderJSONX(loadingErrorJSONX, { error: state.error }),
          [loadingErrorJSONX, state.error]
        );

        useEffect(() => {
          async function getData() {
            try {
              //@ts-ignore
              let transformedData: unknown;
              if (useCache && cache.get(fetchURL)) {
                transformedData = cache.get(fetchURL);
              } else {
                let fetchedData;
                if (fetchFunction) {
                  fetchedData = await fetchFunction(fetchURL, fetchOptions);
                } else fetchedData = await fetchJSON(fetchURL, fetchOptions);
                transformedData = await transformer(fetchedData);
                if (useCache)
                  cache.put(fetchURL, transformedData, cacheTimeout, timeoutFunction);
              }
              //@ts-ignore
              setState(prevState =>
                Object.assign({}, prevState, {
                  hasLoaded: true,
                  hasError: false,
                  resources: { DynamicComponentData: transformedData }
                })
              );
            } catch (e) {
              if (context.debug) console.warn(e);
              //@ts-ignore
              setState({ hasError: true, error: e });
            }
          }
          if (fetchURL) getData();
        }, [fetchURL, fetchOptions]);
        if (!fetchURL) return null;
        else if (state.hasError) {
          return loadingError;
        } else if (state.hasLoaded === false) {
          return loadingComponent;
        } else return renderJSONX(jsonx, state.resources);
      }
      Eif (props.name) {
        Object.defineProperty(DynamicComponentFunction, "name", {
          value: props.name
        });
      }
      return DynamicComponentFunction.bind(this);
    }

    /**
     * Returns new React Function Component

     * @todo set 'functionprops' to set arguments for function
     * @param {*} reactComponent - Valid JSONX to render
     * @param {String} functionBody - String of function component body
     * @param {String} options.name - Function Component name
     * @returns {Function}
     * @see {@link https://reactjs.org/docs/hooks-intro.html}
     * @example
      const jsonxRender = {
       component:'div',
       passprops:'true',
       children:[
         {
          component:'input',
          thisprops:{
              value:['count'],
            },
         },
          {
            component:'button',
           __dangerouslyBindEvalProps:{
            onClick:function(count,setCount){
              setCount(count+1);
              console.log('this is inline',{count,setCount});
            },
            // onClick:`(function(count,setCount){
            //   setCount(count+1)
            //   console.log('this is inline',{count,setCount});
            // })`,
            children:'Click me'
          }
       ]
      };
      const functionBody = 'const [count, setCount] = useState(0); const functionprops = {count,setCount};'
      const options = { name: IntroHook}
      const MyCustomFunctionComponent = jsonx._jsonxComponents.getReactFunctionComponent({jsonxRender, functionBody, options});
       */
    export function getReactFunctionComponent(
      this: defs.Context,
      reactComponent = {},
      functionBody: string | defs.functionParam = "",
      options: any = {}
    ) {
      if (options.lazy) {
        //@ts-ignore
        return lazy(() =>
          options
            .lazy(
              reactComponent,
              functionBody,
              Object.assign({}, options, { lazy: false })
            )
            .then((lazyComponent: any) => {
              return {
                //@ts-ignore
                default: getReactFunctionComponent(...lazyComponent)
              };
            })
        );
      }
      Eif (typeof options === "undefined" || typeof options.bind === "undefined")
        options.bind = true;
      const { resources = {}, args = [] } = options;
      //@ts-ignore
      const props = Object.assign({}, reactComponent.props);
      const functionArgs = [
        React,
        useState,
        useEffect,
        useContext,
        useReducer,
        useCallback,
        useMemo,
        useRef,
        useImperativeHandle,
        useLayoutEffect,
        useDebugValue,
        getReactElementFromJSONX,
        reactComponent,
        resources,
        props,
        useForm,
        useController,
        useFieldArray,
        useWatch,
      ];
      //@ts-ignore
      if (typeof functionBody === "function")
        functionBody = functionBody.toString();

      const functionComponent = Function(
        "React",
        "useState",
        "useEffect",
        "useContext",
        "useReducer",
        "useCallback",
        "useMemo",
        "useRef",
        "useImperativeHandle",
        "useLayoutEffect",
        "useDebugValue",
        "getReactElementFromJSONX",
        "reactComponent",
        "resources",
        "props",
        "useForm",
        "useController",
        "useFieldArray",
        "useWatch",
        `
        'use strict';
        const self = this || {};

        return function ${options.name || "Anonymous"}(props){
          ${functionBody}
          if(typeof exposeprops==='undefined' || exposeprops){
            reactComponent.props = Object.assign({},props,typeof exposeprops==='undefined'?{}:exposeprops);
            if(typeof exposeprops!=='undefined') reactComponent.__functionargs = Object.keys(exposeprops);
          } else{
            reactComponent.props =  props;
          }
          if(!props.children) {
          //  delete props.children;
          }
          const context = ${options.bind ? "Object.assign(self,this||{})" : "this"};
          return getReactElementFromJSONX.call(context, reactComponent);
        }
      `
      );
      if (options.name) {
        Object.defineProperty(functionComponent, "name", {
          value: options.name
        });
      }
      return options.bind
        ? functionComponent.call(this, ...functionArgs)
        : functionComponent(...functionArgs);
    }

    /**
     * Returns the string of a function, the difference between calling .toString() on a function definition is, the toString method will return the entire function definition (with paramaters and the name, etc)
     * @param {Function} - The function you want the body string for
     * @returns {String}
     * @example
    function myFunc(){
      const a = 1;
      const b = 3;
      return a + b;
    }
    getFunctionBody(myFunc) => `
      const a = 1;
      const b = 3;
      return a + b;
    `
     */
    export function getFunctionBody(func:()=>any){
      const functionString = func.toString()
      Iif(functionString.includes('return')===false) throw new EvalError('JSONX Function Components can not use implicit returns')
      return functionString.substring(
        functionString.indexOf("{") + 1,
        functionString.lastIndexOf("}")
      )
    }

    /**
     * A helpful function that lets you write a regular JavaScript function and passes the appropriate arguments to getReactFunctionComponent
     * @param {Function} func - function definition to turn into React Component Function
     * @property {object} this - options for getReactElementFromJSONX
     * @returns {Function} - React Component Function
     */
    export function makeFunctionComponent(
      this: defs.Context,
      func:()=>any,
      options:any
      ){
      const scopedEval = eval;
      const fullFunctionBody = getFunctionBody(func)
      const [functionBody,] = fullFunctionBody.split('return');
      let reactComponentString = fullFunctionBody.replace(functionBody,'').trim()
      const reactComponent = scopedEval(`(()=>{${reactComponentString}})()`);
      const functionOptions = {name:func.name,...options};
      return getReactFunctionComponent.call(this,reactComponent,functionBody,functionOptions)
    }
    /**
     *
     */
    export function getReactContext(options: any = {}) {
      return createContext(options.value);
    }