diff --git a/legalconsenthub/app/composables/useSectionSpawning.ts b/legalconsenthub/app/composables/useSectionSpawning.ts index 2e1f832..1d05d59 100644 --- a/legalconsenthub/app/composables/useSectionSpawning.ts +++ b/legalconsenthub/app/composables/useSectionSpawning.ts @@ -69,7 +69,31 @@ export function useSectionSpawning() { } const newSection = spawnSectionFromTemplate(templateSection, element.reference!, triggerValue) - return sections.concat(newSection as FormElementSectionDto) + + // Find template index + const templateIndex = sections.findIndex( + (s) => s.isTemplate && s.templateReference === trigger.templateReference + ) + + if (templateIndex === -1) { + // Fallback: append if template not found (shouldn't happen) + return sections.concat(newSection as FormElementSectionDto) + } + + // Find insertion position: after template and after any existing spawned sections from same template + let insertionIndex = templateIndex + 1 + while (insertionIndex < sections.length) { + const section = sections[insertionIndex]! + if (section.isTemplate || section.templateReference !== trigger.templateReference) { + break + } + insertionIndex++ + } + + // Insert at calculated position + const result = [...sections] + result.splice(insertionIndex, 0, newSection as FormElementSectionDto) + return result } function updateSpawnedSectionTitles(