|
| 1 | +<script lang="ts" setup> |
| 2 | +interface Props { |
| 3 | + modelValue?: Args |
| 4 | + schema: ArgSchema |
| 5 | +} |
| 6 | +
|
| 7 | +const { schema, modelValue: initialState } = defineProps<Props>() |
| 8 | +const form = ref() |
| 9 | +const state = reactive(clone(initialState || {})) |
| 10 | +
|
| 11 | +if ( schema ) { |
| 12 | + for ( const k in schema.properties ) { |
| 13 | + if ( typeof state[k] !== 'string' ) { |
| 14 | + state[k] = '' |
| 15 | + } |
| 16 | + } |
| 17 | +} |
| 18 | +
|
| 19 | +// function validate(state: Args): FormError[] { |
| 20 | +// const errors: FormError[] = [] |
| 21 | +function validate(state: Args) { |
| 22 | + const errors: {path: string, message: string}[] = [] |
| 23 | +
|
| 24 | + if ( schema && schema.required?.length ) { |
| 25 | + for ( const k of schema.required ) { |
| 26 | + if ( ! (state[k] || '').trim() ) { |
| 27 | + errors.push({ path: k, message: 'Required' }) |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | +
|
| 32 | + return errors |
| 33 | +} |
| 34 | +
|
| 35 | +const valid = computed(() => { |
| 36 | + return form.value?.errors?.length === 0 || false |
| 37 | +}) |
| 38 | +
|
| 39 | +defineExpose({form, valid}) |
| 40 | +
|
| 41 | +// async function onError (event: FormErrorEvent) { |
| 42 | +async function onError (event: any) { |
| 43 | + const element = document.getElementById(event.errors[0].id) |
| 44 | + element?.focus() |
| 45 | + element?.scrollIntoView({ behavior: 'smooth', block: 'center' }) |
| 46 | +} |
| 47 | +
|
| 48 | +// eslint-disable-next-line func-call-spacing |
| 49 | +const emit = defineEmits<{ |
| 50 | + (e: 'update:modelValue', value: Args): void |
| 51 | +}>() |
| 52 | +
|
| 53 | +watchEffect(() => { |
| 54 | + emit('update:modelValue', state) |
| 55 | +}) |
| 56 | +</script> |
| 57 | + |
| 58 | +<template> |
| 59 | + <div> |
| 60 | + <UForm |
| 61 | + ref="form" |
| 62 | + :validate="validate" |
| 63 | + :state="state" |
| 64 | + class="space-y-4" |
| 65 | + @error="onError" |
| 66 | + > |
| 67 | + <template v-if="schema"> |
| 68 | + <UFormGroup v-for="(p, k) in schema?.properties" :key="k" :label="k" :name="k" :required="schema.required?.includes(k)"> |
| 69 | + <UTextarea autoresize :rows="1" :value="state[k]" @update:modelValue="(v) => state[k] = v" /> |
| 70 | + </UFormGroup> |
| 71 | + </template> |
| 72 | + <template v-else> |
| 73 | + <UTextarea autoresize :rows="1" :value="state[k]" @update:modelValue="(v) => state[k] = v" /> |
| 74 | + </template> |
| 75 | + </UForm> |
| 76 | + </div> |
| 77 | +</template> |
0 commit comments