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

51 lines
1.7 KiB
TypeScript

import type { FormElementDto } from '~~/.api-client'
export function useFormElementDuplication() {
function cloneElement(elementToClone: FormElementDto, existingElements: FormElementDto[]): FormElementDto {
const newReference = elementToClone.reference
? generateNextReference(existingElements, elementToClone.reference)
: undefined
const isTextField = elementToClone.type === 'TEXTAREA' || elementToClone.type === 'TEXTFIELD'
const clonedElement = JSON.parse(JSON.stringify(elementToClone)) 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
}
}