From 21777e98252c6f0d403ea6223a007eb5c8ba1866 Mon Sep 17 00:00:00 2001 From: Danielo Rodriguez Date: Tue, 12 Sep 2023 14:06:09 +0200 Subject: [PATCH] feat: allow to duplicate fields fixes #20 --- src/views/FormBuilder.svelte | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/views/FormBuilder.svelte b/src/views/FormBuilder.svelte index f42f0c5b..d4e048e1 100644 --- a/src/views/FormBuilder.svelte +++ b/src/views/FormBuilder.svelte @@ -42,6 +42,32 @@ }); } + function findFreeName(fieldIndex: number): string { + const field = definition.fields[fieldIndex]; + let name = field.name; + const allNames = definition.fields.map((f) => f.name); + let i = 1; + while (allNames.includes(name)) { + name = `${field.name}_${i}`; + i++; + } + return name; + } + + function duplicateField(fieldIndex: number) { + const field = definition.fields[fieldIndex]; + const newField = { + ...field, + name: findFreeName(fieldIndex), + }; + definition.fields = [ + ...definition.fields.slice(0, fieldIndex + 1), + newField, + ...definition.fields.slice(fieldIndex + 1), + ]; + onChange(); + } + function moveField(from: number, direction: "up" | "down") { const to = direction === "up" ? from - 1 : from + 1; if (to < 0 || to >= definition.fields.length) return; @@ -296,6 +322,11 @@ use:setIcon={"arrow-down"} on:click={() => moveField(index, "down")} /> +