From 1c4c058e01a90474490a2e23f3e4ad40efb011d2 Mon Sep 17 00:00:00 2001 From: Baptiste Arnaud Date: Fri, 12 Jan 2024 14:59:28 +0100 Subject: [PATCH] :bug: (editor) Fix duplicate group unique key parsing Closes #1148 --- .../editor/providers/typebotActions/groups.ts | 18 +++++++-------- packages/lib/parseUniqueKey.ts | 22 +++++++++++++------ 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/apps/builder/src/features/editor/providers/typebotActions/groups.ts b/apps/builder/src/features/editor/providers/typebotActions/groups.ts index 6f5220856..410136dd1 100644 --- a/apps/builder/src/features/editor/providers/typebotActions/groups.ts +++ b/apps/builder/src/features/editor/providers/typebotActions/groups.ts @@ -9,6 +9,7 @@ import { } from './blocks' import { isEmpty } from '@typebot.io/lib' import { Coordinates } from '@/features/graph/types' +import { parseUniqueKey } from '@typebot.io/lib/parseUniqueKey' export type GroupsActions = { createGroup: ( @@ -64,19 +65,16 @@ const groupsActions = (setTypebot: SetTypebot): GroupsActions => ({ const group = typebot.groups[groupIndex] const id = createId() - const totalGroupsWithSameTitle = typebot.groups.filter( - (g) => g.title === group.title - ).length + const groupTitle = isEmpty(group.title) + ? '' + : parseUniqueKey( + group.title, + typebot.groups.map((g) => g.title) + ) const newGroup: GroupV6 = { ...group, - title: isEmpty(group.title) - ? '' - : `${group.title}${ - totalGroupsWithSameTitle > 0 - ? ` (${totalGroupsWithSameTitle})` - : '' - }`, + title: groupTitle, id, blocks: group.blocks.map((block) => duplicateBlockDraft(block)), graphCoordinates: { diff --git a/packages/lib/parseUniqueKey.ts b/packages/lib/parseUniqueKey.ts index 25a944e0c..a08e0228c 100644 --- a/packages/lib/parseUniqueKey.ts +++ b/packages/lib/parseUniqueKey.ts @@ -1,8 +1,16 @@ -export const parseUniqueKey = ( - key: string, - existingKeys: string[], - count = 0 -): string => { - if (!existingKeys.includes(key)) return key - return parseUniqueKey(`${key} (${count + 1})`, existingKeys, count + 1) +export const parseUniqueKey = (key: string, existingKeys: string[]): string => { + const keyMatcher = /^(.*?)\s*\(\d+\)$/ + const parsedKey = keyMatcher.test(key) ? key.match(keyMatcher)![1] : key + const sameKeyCount = existingKeys.reduce((acc, existingKey) => { + if ( + (keyMatcher.test(existingKey) && + existingKey.match(keyMatcher)![1] === parsedKey) || + parsedKey === existingKey + ) { + return acc + 1 + } + return acc + }, 0) + if (sameKeyCount === 0) return parsedKey + return `${parsedKey} (${sameKeyCount})` }