opnform/resources/js/components/forms/useFormInput.js

89 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-10-24 09:00:54 +00:00
import { ref, computed, watch } from 'vue'
2023-10-19 08:46:04 +00:00
import { themes } from '~/config/form-themes.js'
export const inputProps = {
id: { type: String, default: null },
name: { type: String, required: true },
label: { type: String, required: false },
form: { type: Object, required: false },
2023-12-01 20:24:38 +00:00
theme: { type: Object, default: () => themes.default },
2023-11-17 11:56:12 +00:00
modelValue: { required: false },
2023-10-19 08:46:04 +00:00
required: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
placeholder: { type: String, default: null },
uppercaseLabels: { type: Boolean, default: false },
2023-10-28 10:17:50 +00:00
hideFieldName: { type: Boolean, default: false },
2023-10-19 08:46:04 +00:00
help: { type: String, default: null },
helpPosition: { type: String, default: 'below_input' },
color: { type: String, default: '#3B82F6' },
wrapperClass: { type: String, default: 'relative mb-3' }
}
2023-10-24 09:00:54 +00:00
export function useFormInput (props, context, formPrefixKey = null) {
2023-10-19 08:46:04 +00:00
const content = ref(props.modelValue)
const inputStyle = computed(() => {
return {
'--tw-ring-color': props.color
}
})
const hasValidation = computed(() => {
return props.form !== null && props.form !== undefined && props.form.hasOwnProperty('errors')
})
const hasError = computed(() => {
2023-10-28 10:17:50 +00:00
return hasValidation && props.form?.errors?.has(name)
2023-10-19 08:46:04 +00:00
})
const compVal = computed({
get: () => {
if (props.form) {
2023-10-24 09:00:54 +00:00
return props.form[(formPrefixKey || '') + props.name]
2023-10-19 08:46:04 +00:00
}
return content.value
},
set: (val) => {
if (props.form) {
2023-10-24 09:00:54 +00:00
props.form[(formPrefixKey || '') + props.name] = val
2023-10-19 08:46:04 +00:00
} else {
content.value = val
}
if (hasValidation.value) {
props.form.errors.clear(props.name)
}
2023-10-24 09:00:54 +00:00
context.emit('update:modelValue', compVal.value)
2023-10-19 08:46:04 +00:00
}
})
2023-12-01 20:24:38 +00:00
const inputWrapperProps = computed(() => {
const wrapperProps = {}
Object.keys(inputProps).forEach((key) => {
if (!['modelValue', 'disabled', 'placeholder', 'color'].includes(key)) {
wrapperProps[key] = props[key]
}
})
return wrapperProps
})
2023-10-19 08:46:04 +00:00
// Watch for changes in props.modelValue and update the local content
watch(
() => props.modelValue,
(newValue) => {
2023-12-01 20:24:38 +00:00
if (content.value !== newValue) {
2023-11-29 03:32:21 +00:00
content.value = newValue
}
2023-10-19 08:46:04 +00:00
}
)
return {
compVal,
inputStyle,
hasValidation,
2023-12-01 20:24:38 +00:00
hasError,
inputWrapperProps
2023-10-19 08:46:04 +00:00
}
}