import type { FormElementDto, FormElementSectionDto } from '~~/.api-client' export function useFormElementValueClearing() { function clearHiddenFormElementValues( sections: FormElementSectionDto[], previousVisibilityMap: Map, currentVisibilityMap: Map ): 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, currentMap: Map ): Set { const newlyHidden = new Set() 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 } }