All files / src ItemRender.vue

87.44% Statements 202/231
96.66% Branches 29/30
66.66% Functions 6/9
87.44% Lines 202/231

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 2321x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 7x 7x 9x 9x 9x 1x 1x 1x 1x 1x 9x 9x 9x 9x 7x 7x 7x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 18x 18x 18x 6x 6x 13x 13x 1x 1x 1x 6x 1x 1x 1x     1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 11x 11x 2x 2x 2x 2x 2x 11x 8x 11x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 4x 4x 4x 1x 1x 1x                         1x 1x 6x 6x 6x         6x 1x 1x  
<template>
  <FormItem :key="item.key" ref="formItem$" :class-list="formItemClass" :label-width="labelWidth" :data="model"
    :label-position="labelPosition">
    <template #label>
      <slot name="label" v-bind="{ item, model: model.$value, shake }">
        {{ item.label }}
      </slot>
    </template>
    <div class="flex">
      <component :is="item.component" v-bind="mergeProps(proxyRefs(item.props ?? {}), item.attrs ?? {}, vModelProps)
        " ref="comp$">
        <template v-for="(k, name) in slots" v-slot:[name]="data">
          <component :is="slotItem(k, data)"></component>
        </template>
      </component>
 
      <slot name="append" v-bind="{ item, model: model.$value }" />
    </div>
  </FormItem>
</template>
<script setup lang="ts">
import { isObject, useValidation } from 'vue-composable'
import { FormItem, provideFormItemState } from './FormItem'
import { useSmartFormState } from './inject'
import { FormItemData } from './types'
import {
  Ref,
  proxyRefs,
  computed,
  ref,
  mergeProps,
  toRef,
  nextTick,
  defineComponent,
  h,
  reactive,
} from 'vue'
import { sleep } from './utils'
import schmea from 'async-validator'
import { pausableWatch, until, type WatchPausableReturn } from '@vueuse/core'
 
defineOptions({
  name: 'ItemRender',
})
 
const props = defineProps<{
  item: FormItemData
  modelValue: any
  disabled?: boolean
  light: boolean
}>()
 
const { labelPosition, labelWidth, itemClass, emit, modelValue, rules } =
  useSmartFormState()
 
const itemEmit = defineEmits<{
  (name: 'update:modelValue', e: any, modelKey?: string): void
}>()
const modelKeyMap = computed(() => {
  return props.item.modelKeyMap ? props.item.modelKeyMap : { [props.item.modelValueKey ?? 'modelValue']: props.item.key }
})
const createValidation = () => {
  const data: Record<string, any> = {}
  Object.entries(modelKeyMap.value).forEach(([modelValueKey, modelKey]) => {
    const r = rules.value[modelKey] ?? {}
    const validator: Record<string, any> = {}
    if (Object.keys(r).length) {
      validator.validate = {
        $validator: createRules(r),
        $message: ref('error'),
      }
    }
    data[modelValueKey] = {
      $value: modelValue.value[modelKey] ?? null,
      ...validator,
    }
  })
  return useValidation(data) //as any as ValidateModel
}
 
const model = ref<ReturnType<typeof createValidation>>({} as any)
 
const update = (cur: any, modelValueKey = 'modelValue') => {
  emit('itemChange', props.item.key, cur, model.value.$value, props.item)
  model.value[modelValueKey].$value = cur
 
  if (!props.light) {
    pausableReturn.pause()
    itemEmit('update:modelValue', cur, modelKeyMap.value[modelValueKey])
    nextTick(() => {
      pausableReturn.resume()
    })
  }
}
 
const watchHandler = (cur: Record<string, any>, prev?: Record<string, any>) => {
  /**
   * todo
   * shallow compare
   */
  model.value = createValidation()
}
 
//todo check
let pausableReturn = pausableWatch(
  [modelValue, modelKeyMap], // 当modelValue 为undefined时,返回空字符串触发watch
  watchHandler,
  {
    immediate: true,
    deep: true,
  }
)
 
const vModelProps = computed(() => {
  const data: Record<string, any> = {}
  Object.entries(modelKeyMap.value).forEach(([_modelValueKey, modelKey]) => {
    //@ts-ignore
    data[_modelValueKey] = model.value[_modelValueKey].$value
    data[`onUpdate:${_modelValueKey}`] = (cur: any) => {
      update(cur, _modelValueKey)
    }
  })
  return data
})
 
const formItemClass = computed(() => {
  return [itemClass.value, props.item.itemClass].filter((e) => e).join(' ')
})
 
const reset = () => {
  model.value.$reset()
}
 
const formItem$ = ref<{ el: Ref<HTMLElement> } | null>(null)
const formItemEl = computed(() => formItem$.value?.el ?? null)
const comp$ = ref()
 
const shake = async (opt: ScrollIntoViewOptions = { behavior: 'smooth' }) => {
  const el = formItemEl.value
  if (!el) return
  el.scrollIntoView(opt)
  // animate
  if (!el) return
  el.classList.add('animate__animated')
  el.classList.add('animate__shakeY')
  await sleep(1000)
  el.classList.remove('animate__animated')
  el.classList.remove('animate__shakeY')
}
 
provideFormItemState(
  reactive({ el: formItemEl, shake, item: toRef(props, 'item') })
)
 
const getResult = async () => {
  const r: Record<string, any> = {}
  model.value.$touch()
  const keys = Object.keys(model.value as Record<string, any>)
    .filter(x => x[0] !== '$' && isObject((model.value as Record<string, any>)[x]))
 
  for (const k of keys) {
    const validate = model.value[k].validate
    if (validate) {
      if (validate.$pending) {
        await until(() => validate.$pending as Ref<boolean>).not.toBeTruthy()
      }
      await model.value[k].validate.$promise.value
    }
  }
  Object.entries(modelKeyMap.value).forEach(([key, modelKey]) => {
    r[modelKey] = model.value[key as any].$value
  })
  return r
}
 
defineExpose({
  model,
  reset,
  shake,
  formItem$,
  comp$,
  getResult
})
 
function createRules(r: Record<string, any>, modelValueKey = 'modelValue') {
  // useValidation 会通过执行一次校验器以捕获,外部依赖
  // 因为 useValidation 在getter里用执行了一次校验器,又在onChange里执行一次
  // 所以一般会打印两条errors
  return async (v: any) => {
    const key = props.item.key
    const validator = new schmea({ [key]: r })
    const res = await validator
      .validate({ [key]: v }, { first: true })
      .then(() => true)
      .catch(({ errors, fields }) => {
        console.log('errors', errors)
        if (modelValueKey) {
          //@ts-ignore
          model.value[modelValueKey].validate.$message = errors[0].message
        }
        return false // errors[0].message
      })
    return res
  }
}
 
const slotItem = (slot: any, data: any) => {
  const __type = typeof slot
  switch (__type) {
    case 'string':
      return defineComponent(() => () => slot)
    case 'object':
      return slot
    case 'function':
      return () => slot(data)
    default:
      throw new Error('invalid slot ?')
  }
}
 
const slots = computed(() => {
  const { slot, slots } = props.item
  //避免没东西的时候,渲染空列表,导致组件异常
  return slot
    ? {
      default: slot,
      ...slots,
    }
    : slots
})
</script>