# All files index.ts

97.14% Statements 102/105
70.37% Branches 57/81
100% Functions 15/15
98.95% Lines 95/96

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
    5x
    5x
    5x

    5x
    5x
    5x
    5x
    5x
    5x

    5x

    5x
    5x
    5x
    5x
    5x

    5x

    1x
    1x

    1x
    1x

    1x
    1x
    1x

    5x

    10x

    10x

    5x

    90x

    90x
    90x
    90x
    89x
    89x
    12x

    89x
    3x

    86x
    86x

    86x

    86x
    12x

    12x
    12x
    12x

    86x
    86x

    81x

    81x

    81x
    81x

    81x
    63x

    62x

    5x
    3x
    3x
    3x

    2x

    5x
    5x

    5x

    6x

    5x
    1x
    1x

    1x
    1x
    1x

    1x
    1x

    5x
    1x
    1x

    1x

    5x

    1x
    1x

    5x

    5x
    5x

    6x

    5x

    5x

    5x

    5x
    1x

    5x
    1x

    5x
    5x
    5x
    5x
    5x
    19x

    5x
     // import React, { createElement, } from 'react';
    import React from "react";
    import ReactDOM from "react-dom";
    import ReactDOMServer from "react-dom/server";
    import * as defs from "./types/jsonx/index";

    import * as jsonxComponents from "./components";
    import * as jsonxProps from "./props";
    import * as jsonxChildren from "./children";
    import * as jsonxUtils from "./utils";
    import numeral from "numeral";
    import * as luxon from "luxon";

    import { ReactElementLike } from "prop-types";
    import { JSONReactElement, Context } from "./types/jsonx/index";
    const createElement = React.createElement;
    const {
      componentMap,
      getComponentFromMap,
      getBoundedComponents,
      DynamicComponent,
      FormComponent,
      ReactHookForm,
      getReactLibrariesAndComponents,
    } = jsonxComponents;
    const { getComputedProps } = jsonxProps;
    const { getJSONXChildren } = jsonxChildren;
    const { displayComponent, validSimpleJSONXSyntax, simpleJSONXSyntax } = jsonxUtils;
    export let renderIndex = 0;

    /**
     * Use JSONX without any configuration to render JSONX JSON to HTML and insert JSONX into querySelector using ReactDOM.render
     * @example
     * // Uses react to create <!DOCTYPE html><body><div id="myApp"><div class="jsonx-generated"><p style="color:red;">hello world</p></div></div></body>
     * jsonx.jsonxRender({ jsonx: { component: 'div', props:{className:'jsonx-generated',children:[{ component:'p',props:{style:{color:'red'}}, children:'hello world' }]}}, querySelector:'#myApp', });
     * @param {object} config - options used to inject html via ReactDOM.render
     * @param {object} config.jsonx - any valid JSONX JSON object
     * @param {object} config.resources - any additional resource used for asynchronous properties
     * @param {string} config.querySelector - selector for document.querySelector
     * @property {object} this - options for getReactElementFromJSONX
     */
    export function jsonxRender(
      this: defs.Context,
      config: defs.RenderConfig = { jsonx: { component: "" }, querySelector: "" }
    ): void {
      const { jsonx, resources, querySelector, DOM, portal } = config;
      const Render = portal ? ReactDOM.createPortal : ReactDOM.render;
      const RenderDOM: HTMLElement | null =
        DOM || document.querySelector(querySelector);
      const JSONXReactElement: any = getReactElementFromJSONX.call(
        this || {},
        jsonx,
        resources
      );
      Iif (!JSONXReactElement) throw ReferenceError("Invalid React Element");
      else Iif (!RenderDOM) throw ReferenceError("Invalid Render DOM Element");
      Render(JSONXReactElement, RenderDOM);
    }

    /**
     * Use ReactDOMServer.renderToString to render html from JSONX
     * @example
     * // Uses react to create <div class="jsonx-generated"><p style="color:red;">hello world</p></div>
     * jsonx.outputHTML({ jsonx: { component: 'div', props:{className:'jsonx-generated',children:[{ component:'p',props:{style:{color:'red'}}, children:'hello world' }]}}, });
     * @param {object} config - options used to inject html via ReactDOM.render
     * @param {object} config.jsonx - any valid JSONX JSON object
     * @param {object} config.resources - any additional resource used for asynchronous properties
     * @property {object} this - options for getReactElementFromJSONX
     * @returns {string} React genereated html via JSONX JSON
     */
    export function outputHTML(
      this: defs.OutputHTMLContext,
      config: defs.OutputHTMLConfig = { jsonx: { component: "" } }
    ): string {
      const { jsonx, resources, type, props, children } = config;

      return this && this.useJSON
        ? ReactDOMServer.renderToString(
            getReactElementFromJSON.call(this || {}, { type:(type||jsonx.type||jsonx.component||'Fragment' as string), props:props||jsonx.props, children:children||jsonx.children })
          )
        : ReactDOMServer.renderToString(
            getReactElementFromJSONX.call(
              this || {},
              jsonx,
              resources
            ) as ReactElementLike
          );
    }

    /**
     * Use React.createElement and JSONX JSON to create React elements
     * @example
     * // Uses react to create the equivalent JSX <myComponent style={{color:blue}}>hello world</myComponent>
     * jsonx.getReactElementFromJSONX({component:'myCompnent',props:{style:{color:'blue'}},children:'hello world'})
     * @param {object} jsonx - any valid JSONX JSON object
     * @param {object} resources - any additional resource used for asynchronous properties
     * @property {object} this - options for getReactElementFromJSONX
     * @property {Object} [this.componentLibraries] - react components to render with JSONX
     * @property {boolean} [this.debug=false] - use debug messages
     * @property {boolean} [this.returnJSON=false] - return json object of {type,props,children} instead of react element
     * @property {boolean} [this.disableRenderIndexKey=false] - disables auto assign a key prop
     * @property {function} [this.logError=console.error] - error logging function
     * @property {string[]} [this.boundedComponents=[]] - list of components that require a bound this context (usefult for redux router)
     * @returns {function} React element via React.createElement
     */
    export function getReactElementFromJSONX(
      this: defs.Context,
      jsonx?: defs.jsonx | defs.simpleJsonx,
      resources = {}
    ): ReactElementLike | JSONReactElement | null |string|undefined{
      // eslint-disable-next-line

      const {
        customComponents,
        debug = false,
        returnJSON = false,
        logError = console.error,
        boundedComponents = [],
        disableRenderIndexKey = true
      } = this || {};
      let {
        componentLibraries = {},
      } = this ||{};
      componentLibraries.ReactHookForm = ReactHookForm
      if (!jsonx) return null;
      if (jsonx.type) jsonx.component = jsonx.type;
      if (!jsonx.component && validSimpleJSONXSyntax(jsonx)) {
        jsonx = simpleJSONXSyntax(jsonx);
      }
      if (!jsonx || !jsonx.component)
        return createElement(
          "span",
          {},
          debug ? "Error: Missing Component Object" : ""
        );
      try {
        let components = Object.assign(
          { DynamicComponent: DynamicComponent.bind(this) },
          { FormComponent: FormComponent.bind(this) },
          componentMap,
          this?.reactComponents
        );

        let reactComponents = boundedComponents.length
          ? getBoundedComponents.call(this, {
              boundedComponents,
              reactComponents: components
            })
          : components;
        if(customComponents && Array.isArray(customComponents) && customComponents.length){
          const cxt = {...this,componentLibraries,reactComponents:components}
          const {
            customComponentLibraries,
            customReactComponents
          } = getReactLibrariesAndComponents.call(cxt,customComponents);
          componentLibraries = {...componentLibraries, ...customComponentLibraries};
          reactComponents = {...reactComponents, ...customReactComponents};
        }
        if(disableRenderIndexKey===false) renderIndex++;
        const element = getComponentFromMap.call(this, {
          jsonx,
          reactComponents,
          componentLibraries,
          debug,
          logError
        });
        const props = getComputedProps.call(this, {
          jsonx,
          resources,
          renderIndex,
          componentLibraries,
          debug,
          logError,
          disableRenderIndexKey
        });
        const displayElement = jsonx.comparisonprops
          ? displayComponent.call(this, {
              jsonx,
              props,
              renderIndex,
              componentLibraries,
              debug
            })
          : true;
        if (displayElement) {
          const children = getJSONXChildren.call(this, {
            jsonx,
            props,
            resources,
            renderIndex
          });
          //@ts -ignore
          if (returnJSON) return { type: element as string, props, children };
          else if (jsonx.test) return JSON.stringify({ element, props, children }, null, 2);
          //TODO: Fix
          else return createElement(element, props, children);
        } else E{
          return null;
        }
      } catch (e) {
        if (debug) {
          logError({ jsonx, resources }, "getReactElementFromJSONX this", this);
          logError(e, (e as Error).stack ? (e as Error).stack : "no stack");
          return (e as Error).toString()
        }
        throw e;
      }
    }

    export const getRenderedJSON = getReactElementFromJSONX;
    export const getReactElement = getReactElementFromJSONX;

    /** converts a json object {type,props,children} into a react element
     * @example
     * jsonx.getReactElementFromJSON({type:'div',props:{title:'some title attribute'},children:'inner html text'})
     * @param {Object|String} options.type - 'div' or react component
     * @param {Object} options.props - props for react element
     * @param {String|[Object]} options.children - children elements
     * @returns {function} React element via React.createElement
     */
    export function getReactElementFromJSON({
      type,
      props,
      children
    }: JSONReactElement): ReactElementLike {
      return createElement(
        type,
        props,
        children && Array.isArray(children)
          ? children.map(getReactElementFromJSON)
          : children
      );
    }

    /** converts a jsonx json object into a react function component
     * @example
     * jsonx.compile({jsonx:{component:'div',props:{title:'some title attribute'},children:'inner html text'}}) //=>React Function Component
     * @param {Object} jsonx - valid JSONX JSON
     * @param {Object} resources - props for react element
     * @returns {function} React element via React.createElement
     */
    export function compile(this: Context, jsonx: defs.jsonx, resources = {}) {
      const context = Object.assign({}, this, { returnJSON: true });
      const json = getReactElementFromJSONX.call(
        context,
        jsonx,
        resources
      ) as defs.JSONReactElement;
      const func = function compiledJSONX(props: any) {
        json.props = Object.assign({}, json.props, props);
        return getReactElementFromJSON(json);
      };
      Object.defineProperty(func, "name", { value: this.name });
      return func;
    }

    /**
     * converts JSONX JSON IR to JSX
     * @example
     * jsonx.jsonToJSX({ type: 'div', props: { key: 5, title: 'test' }, children: 'hello' }) // => '<div key={5} title="test">hello</div>'
     * @param {Object} json - {type,props,children}
     * @returns {String} jsx string
     */
    export function outputJSX(this: Context, jsonx: defs.jsonx, resources = {}) {
      const context = Object.assign({}, this, { returnJSON: true });
      const json = getReactElementFromJSONX.call(
        context,
        jsonx,
        resources
      ) as defs.JSONReactElement;
      return jsonToJSX(json);
    }

    /**
     * Compiles JSONX into JSON IR format for react create element
     * @example
     * jsonx.outputJSON({ component: 'div', props: { title: 'test', }, children: 'hello', }); //=> { type: 'div',
     props: { key: 5, title: 'test' },
     children: 'hello' }
     * @property {object} this - options for getReactElementFromJSONX
     * @param {object} jsonx - any valid JSONX JSON object
     * @param {object} resources - any additional resource used for asynchronous properties
     * @returns {Object} json - {type,props,children}
     */
    export function outputJSON(
      jsonx: defs.jsonx,
      resources = {}
    ): JSONReactElement {
      //@ts-ignore
      const context = Object.assign({}, this, { returnJSON: true });
      return getReactElementFromJSONX.call(
        context,
        jsonx,
        resources
      ) as JSONReactElement;
    }
    export const jsonxHTMLString = outputHTML;

    /**
     * converts JSONX JSON IR to JSX
     * @example
     * jsonx.jsonToJSX({ type: 'div', props: { key: 5, title: 'test' }, children: 'hello' }) // => '<div key={5} title="test">hello</div>'
     * @param {Object} json - {type,props,children}
     * @returns {String} jsx string
     */
    export function jsonToJSX(json: JSONReactElement): string {
      const propsString = json.props
        ? Object.keys(json.props)
            .filter(prop => prop.includes("__eval_") === false)
            .reduce((propString, prop) => {
              propString += ` ${prop.toString()}=${
                typeof json.props[prop] === "string"
                  ? `"${json.props[prop].toString()}"`
                  : `{${(
                      json.props[`__eval_${prop}`] || json.props[prop]
                    ).toString()}}`
              }`;
              return propString;
            }, "")
        : "";
      return Array.isArray(json.children)
        ? `<${json.type} ${propsString}>
      ${json.children.map(jsonToJSX).join('\r\n')}
    </${json.type}>`
        : `<${json.type}${propsString}>${json.children}</${json.type}>`;
    }
    /**
     * Exposes react module used in JSONX
     * @returns {Object} React
     */
    export function __getReact() {
      return React;
    }

    /**
     * Exposes react dom module used in JSONX
     * @returns {Object} ReactDOM
     */
    export function __getReactDOM() {
      return ReactDOM;
    }

    export const _jsonxChildren = jsonxChildren;
    export const _jsonxComponents = jsonxComponents;
    export const _jsonxProps = jsonxProps;
    export const _jsonxUtils = jsonxUtils;
    export const _jsonxHelpers = { numeral, luxon };
    export { __express, __express as renderFile } from "./express";

    export default getReactElementFromJSONX;