feat(frontend): Add useFormElementDuplication test
This commit is contained in:
50
legalconsenthub/app/composables/useFormElementDuplication.ts
Normal file
50
legalconsenthub/app/composables/useFormElementDuplication.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user