Files
gremiumhub/legalconsenthub/app/composables/useClonableElements.ts

49 lines
1.6 KiB
TypeScript

import type { FormElementDto } from '~~/.api-client'
export function useClonableElements() {
function cloneElement(element: FormElementDto, existingElements: FormElementDto[]): FormElementDto {
const newReference = element.reference ? generateNextReference(existingElements, element.reference) : undefined
const isTextField = element.type === 'TEXTAREA' || element.type === 'TEXTFIELD'
const clonedElement = JSON.parse(JSON.stringify(element)) as FormElementDto
const resetOptions = clonedElement.options.map((option) => ({
...option,
value: isTextField ? '' : option.value
}))
return {
...clonedElement,
id: undefined,
formElementSubSectionId: undefined,
reference: newReference,
options: resetOptions
}
}
function generateNextReference(existingElements: FormElementDto[], baseReference: string): string {
const { base } = extractReferenceBase(baseReference)
const existingSuffixes = existingElements
.filter((el) => el.reference && el.reference.startsWith(base))
.map((el) => {
const { suffix } = extractReferenceBase(el.reference!)
return suffix
})
const maxSuffix = existingSuffixes.length > 0 ? Math.max(...existingSuffixes) : 0
return `${base}_${maxSuffix + 1}`
}
function extractReferenceBase(reference: string): { base: string; suffix: number } {
const match = reference.match(/^(.+?)_(\d+)$/)
if (match && match[1] && match[2]) {
return { base: match[1], suffix: parseInt(match[2], 10) }
}
return { base: reference, suffix: 1 }
}
return {
cloneElement
}
}