homemanager-fe/src/components/form/FormField.vue

104 lines
2.5 KiB
Vue

<template>
<div class="flex flex-col space-y-1">
<label
:for="forId"
:class="[
'block text-sm font-medium transition-colors duration-200',
errors.length ? 'text-red-500' : 'text-gray-700',
]"
>{{ label }}</label
>
<input
:type="type"
:id="forId"
:name="name"
:value="value"
:class="inputClass"
:placeholder="placeholder"
@input="onInput($event)"
@change="onChange($event)"
@focus="onFocus"
@blur="onBlur"
/>
<slot />
<span
class="text-sm text-red-500"
v-for="error of errors"
aria-live="assertive"
>{{ error }}</span
>
</div>
</template>
<script setup lang="ts">
import { computed, Ref } from 'vue';
import { inject } from 'vue';
import { FormData, FormErrors } from './form.types';
const props = withDefaults(
defineProps<{
type?:
| 'text'
| 'number'
| 'password'
| 'color'
| 'email'
| 'checkbox'
| 'radio';
label: string;
name: string;
placeholder?: string;
}>(),
{
type: 'text',
}
);
const emit = defineEmits<{
(e: 'change', value: unknown): void;
(e: 'focus'): void;
(e: 'blur'): void;
}>();
const formData = inject<Ref<FormData>>('formData');
const formErrors = inject<Ref<FormErrors>>('formErrors');
const fieldChange = inject<(field: string) => void>('fieldChange');
const forId = computed(() => `form-${props.name}`);
const value = computed(() => formData?.value[props.name]);
const errors = computed(() => formErrors?.value[props.name] || []);
const inputClass = computed(() => {
return [
errors.value.length
? 'border-red-300 focus:border-red-500 focus:ring-red-500'
: 'border-gray-300 focus:border-blue-500 focus:ring-blue-500',
`mt-1 block w-full rounded-md shadow-sm sm:text-sm transition-colors duration-200`,
];
});
const onInput = (ev: Event) => {
if (!formData) return;
const value = (ev.target as HTMLInputElement).value;
const cleanValue = props.type === 'number' ? parseFloat(value) : value;
formData.value[props.name] = cleanValue;
emit('change', cleanValue);
fieldChange?.(props.name);
};
const onChange = (ev: Event) => {
if (!formData) return;
if (props.type === 'checkbox' || props.type === 'radio') {
const cleanValue = (ev.target as HTMLInputElement).checked;
formData.value[props.name] = cleanValue;
emit('change', cleanValue);
fieldChange?.(props.name);
}
};
const onFocus = () => emit('focus');
const onBlur = () => {
emit('blur');
fieldChange?.(props.name);
};
</script>