feat: Clear form element values when hidden
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import type { FormElementDto, FormElementSectionDto } from '~~/.api-client'
|
||||
|
||||
export function useFormElementValueClearing() {
|
||||
function clearHiddenFormElementValues(
|
||||
sections: FormElementSectionDto[],
|
||||
previousVisibilityMap: Map<string, boolean>,
|
||||
currentVisibilityMap: Map<string, boolean>
|
||||
): FormElementSectionDto[] {
|
||||
const elementsToClean = findNewlyHiddenFormElements(previousVisibilityMap, currentVisibilityMap)
|
||||
if (elementsToClean.size === 0) {
|
||||
return sections
|
||||
}
|
||||
|
||||
return sections.map((section) => ({
|
||||
...section,
|
||||
formElementSubSections: section.formElementSubSections.map((subsection) => ({
|
||||
...subsection,
|
||||
formElements: subsection.formElements.map((element) => {
|
||||
const key = element.id || element.reference
|
||||
if (key && elementsToClean.has(key)) {
|
||||
return clearFormElementValue(element)
|
||||
}
|
||||
return element
|
||||
})
|
||||
}))
|
||||
}))
|
||||
}
|
||||
|
||||
function findNewlyHiddenFormElements(
|
||||
previousMap: Map<string, boolean>,
|
||||
currentMap: Map<string, boolean>
|
||||
): Set<string> {
|
||||
const newlyHidden = new Set<string>()
|
||||
currentMap.forEach((isVisible, key) => {
|
||||
const wasVisible = previousMap.get(key) !== false
|
||||
if (wasVisible && !isVisible) {
|
||||
newlyHidden.add(key)
|
||||
}
|
||||
})
|
||||
return newlyHidden
|
||||
}
|
||||
|
||||
function clearFormElementValue(element: FormElementDto): FormElementDto {
|
||||
if (['RADIOBUTTON', 'SELECT', 'CHECKBOX'].includes(element.type)) {
|
||||
return {
|
||||
...element,
|
||||
options: element.options.map((opt) => ({ ...opt, value: 'false' }))
|
||||
}
|
||||
}
|
||||
return {
|
||||
...element,
|
||||
options: element.options.map((opt, i) => (i === 0 ? { ...opt, value: '' } : opt))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
clearHiddenFormElementValues
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user