All files / src/components FormulateSchema.js

91.3% Statements 21/23
65.22% Branches 15/23
88.89% Functions 8/9
95.24% Lines 20/21

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                12x 12x 12x 12x 12x 12x 12x         12x   12x   10x             24x 12x 12x 12x   12x       12x                   12x 12x 12x 12x        
import { createElement, defineComponent } from '@vue/composition-api'
import Formulate from '@braid/vue-formulate'
 
import { Hooks } from '../libs/hooks'
import hooksProp from '../composables/hooksProp'
import FormulateInput from './FormulateInput.vue'
 
function leaf(item, index, { hooks, h, state } = {}) {
  Eif (item && typeof item === 'object' && !Array.isArray(item)) {
    const { children = null, component = FormulateInput, depth = 1, modelHook, ...attrs } = item
    const type = component === FormulateInput ? attrs.type || 'text' : ''
    const name = attrs.name || type || 'el'
    const key = attrs.id || `${name}-${depth}-${index}`
    const els = Array.isArray(children) ? children.map((child) => Object.assign(child, { depth: depth + 1 })) : children
    const _modelHook = new Hooks()
      .setHooks(hooks.model)
      .addHook(modelHook)
      .asSingleHook()
 
    const node = Object.assign({ type, key, depth, component, definition: { attrs: { ...attrs, modelHook: _modelHook } }, children: tree(els, { hooks, h, state }) })
 
    return new Hooks()
      .setHooks(hooks.schemaNode)
      .setDefault(() => node)
      .apply(node, { state })
  }
  return null
}
 
function tree(schema, { hooks, h, state } = {}) {
  if (Array.isArray(schema)) {
    return schema.map((el, idx) => {
      const item = leaf(el, idx, { hooks, h, state })
      return new Hooks()
        .setHooks(hooks.schemaComponent)
        .setDefault(() => h(item.component, item.definition, item.children))
        .apply(item)
    })
  }
  return schema
}
 
export default defineComponent({
  name: 'FormulateSchema',
  props: {
    schema: Formulate.defaults.components.FormulateForm.props.schema,
    hooks: hooksProp,
  },
  setup(props, { emit }) {
    const schemaHooks = new Hooks().setHooks(props.hooks.schema)
    const schemaOptionsHooks = new Hooks().setHooks(props.hooks.schemaOptions).setDefault((x) => x)
    return () => {
      return schemaHooks.apply(createElement('div', {}, tree(props.schema, schemaOptionsHooks.apply({ hooks: props.hooks, h: createElement, state: {} }, { emit, props }))), { emit, props })
    }
  },
})