@case-framework/survey-core 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"editor.mjs","names":[],"sources":["../src/editor/item-copy-paste.ts","../src/editor/undo-redo.ts","../src/editor/survey-editor.ts"],"sourcesContent":["import { Survey } from \"../survey/survey\";\nimport { SurveyItemCore } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport { ReservedSurveyItemTypes } from \"../survey/items/types\";\nimport { SurveyItemTranslations, JsonComponentContent } from \"../survey/utils\";\nimport { RawSurveyItem } from \"../survey/items/survey-item-json\";\nimport { Target } from \"./types\";\nimport { generateId } from \"../utils\";\n\n// Serialized translation data format for clipboard\nexport type SerializedTranslations = {\n [locale: string]: JsonComponentContent;\n};\n\n// Clipboard data structure for copy-paste functionality\nexport interface SurveyItemClipboardData {\n type: \"survey-item\";\n version: string;\n items: Array<{\n itemId: string;\n itemData: RawSurveyItem;\n }>;\n translations: { [itemId: string]: SerializedTranslations };\n rootItemId: string; // The id of the main item being copied\n timestamp: number;\n}\n\nexport class ItemCopyPaste {\n private survey: Survey;\n\n constructor(survey: Survey) {\n this.survey = survey;\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * When copying a group, automatically includes all items in the subtree\n * @param itemId - The id of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const item = this.survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Collect all items to copy (including subtree for groups)\n const itemsToCopy = this.collectItemsForCopy(itemId);\n\n // Create items array with their data\n const items = itemsToCopy.map((id) => {\n const item = this.survey.surveyItems.get(id);\n if (!item) throw new Error(`Item with id '${id}' not found during copy`);\n return { itemId: id, itemData: item.rawItem };\n });\n\n // Collect translations for all items\n const translations: { [itemId: string]: SerializedTranslations } = {};\n itemsToCopy.forEach((id) => {\n try {\n const itemTranslations = this.survey.getItemTranslations(id);\n if (itemTranslations?.locales?.length) {\n const serializedTranslations: SerializedTranslations = {};\n itemTranslations.locales.forEach((locale) => {\n const localeContent = itemTranslations.getAllForLocale(locale);\n if (localeContent) {\n serializedTranslations[locale] = localeContent;\n }\n });\n translations[id] = serializedTranslations;\n } else {\n translations[id] = {};\n }\n } catch {\n translations[id] = {};\n }\n });\n\n // Create clipboard data\n const clipboardData: SurveyItemClipboardData = {\n type: \"survey-item\",\n version: \"1.0.0\",\n items: items,\n translations: translations,\n rootItemId: itemId,\n timestamp: Date.now(),\n };\n\n return clipboardData;\n }\n\n /**\n * Collect all items that should be copied, including subtree for groups\n * @param itemId - The root item id\n * @returns Array of item keys to copy\n */\n private collectItemsForCopy(itemId: string): string[] {\n const itemsToCopy: string[] = [itemId];\n const item = this.survey.surveyItems.get(itemId);\n\n if (!item) {\n return [];\n }\n\n // If this is a group item, collect all child items recursively\n if (item instanceof GroupItemCore) {\n const childIds = item.items;\n if (childIds.length > 0) {\n childIds.forEach((childId) => {\n const childItems = this.collectItemsForCopy(childId);\n itemsToCopy.push(...childItems);\n });\n }\n }\n\n return itemsToCopy;\n }\n\n /**\n * Add an item to its parent group.\n * Ensures key uniqueness among siblings.\n * @param target - Target location information\n * @param item - The item to add (may have key adjusted for uniqueness)\n */\n private addItemToParentGroup(target: Target, item: SurveyItemCore): void {\n const parentGroup = this.survey.surveyItems.get(target.parentId);\n\n if (!parentGroup) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(parentGroup instanceof GroupItemCore)) {\n throw new Error(`Parent item '${target.parentId}' is not a group item`);\n }\n\n const siblingIds = parentGroup.items;\n const siblings = siblingIds\n .map((id) => this.survey.surveyItems.get(id))\n .filter((s): s is SurveyItemCore => s !== undefined);\n const siblingKeys = new Set(siblings.map((s) => s.key));\n\n let uniqueKey = item.key;\n if (siblingKeys.has(uniqueKey)) {\n let counter = 1;\n const originalKey = item.key;\n while (siblingKeys.has(uniqueKey)) {\n uniqueKey = originalKey + `_${counter}`;\n counter++;\n }\n if (uniqueKey !== item.key) {\n const updatedRawItem = { ...item.rawItem, key: uniqueKey };\n const newItem = this.survey.createItemFromRaw(updatedRawItem);\n this.survey.surveyItems.delete(item.id);\n this.survey.surveyItems.set(newItem.id, newItem);\n item = newItem;\n }\n }\n\n const insertIndex =\n target.index !== undefined\n ? Math.min(target.index, parentGroup.items.length)\n : parentGroup.items.length;\n\n parentGroup.addChild(item.id, insertIndex);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * Handles multiple items and subtrees from the clipboard data\n * @param clipboardData - The clipboard data containing the item(s) to paste\n * @param target - Target location where to paste the item\n * @returns The id of the pasted root item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n // Validate clipboard data\n if (!ItemCopyPaste.isValidClipboardData(clipboardData)) {\n throw new Error(\"Invalid clipboard data format\");\n }\n\n // Create id mapping for all items in the subtree\n const idMapping: { [oldId: string]: string } = {};\n clipboardData.items.forEach(({ itemId }) => {\n idMapping[itemId] = generateId();\n });\n\n // Create all items with updated ids\n clipboardData.items.forEach(({ itemId, itemData }) => {\n const newId = idMapping[itemId];\n if (newId) {\n const updatedItemData = this.updateItemIdsInData(itemData, idMapping);\n updatedItemData.id = newId;\n\n const newItem = this.survey.createItemFromRaw(updatedItemData);\n this.survey.surveyItems.set(newItem.id, newItem);\n\n if (itemId === clipboardData.rootItemId) {\n this.addItemToParentGroup(target, newItem);\n }\n }\n });\n\n // Update translations with new IDs\n const updatedTranslations = this.updateTranslations(clipboardData.translations, idMapping);\n Object.keys(updatedTranslations).forEach((itemId) => {\n // Convert serialized translations back to SurveyItemTranslations instance\n const itemTranslations = new SurveyItemTranslations();\n const serializedData = updatedTranslations[itemId];\n Object.keys(serializedData).forEach((locale) => {\n itemTranslations.setAllForLocale(locale, serializedData[locale]);\n });\n this.survey.translations.setItemTranslations(itemId, itemTranslations);\n });\n\n return idMapping[clipboardData.rootItemId];\n }\n\n // PRIVATE HELPER METHODS\n /**\n * Update all item ids in the raw item data recursively\n */\n private updateItemIdsInData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n ): RawSurveyItem {\n const updatedData = JSON.parse(JSON.stringify(itemData));\n\n if (updatedData.itemType === ReservedSurveyItemTypes.Group && updatedData.config) {\n const config = updatedData.config as { items?: string[] };\n if (config.items) {\n config.items = config.items.map((childId: string) => idMapping[childId] ?? childId);\n }\n }\n\n this.updateExpressionsInItemData(updatedData, idMapping);\n return updatedData;\n }\n\n /**\n * Update expressions in item data that reference the old ids\n */\n private updateExpressionsInItemData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n ): void {\n // Update display conditions\n if (itemData.displayConditions?.root) {\n this.updateExpressionReferences(itemData.displayConditions.root, idMapping);\n }\n if (itemData.displayConditions?.components) {\n Object.values(itemData.displayConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update disabled conditions\n if (itemData.disabledConditions?.components) {\n Object.values(itemData.disabledConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update validations\n if (itemData.validations) {\n Object.values(itemData.validations).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n if (itemData.prefills) {\n itemData.prefills.forEach((prefill) => {\n if (prefill.when) {\n this.updateExpressionReferences(prefill.when, idMapping);\n }\n\n if (prefill.source.type === \"expression\") {\n this.updateExpressionReferences(prefill.source.expression, idMapping);\n }\n\n if (prefill.source.type === \"previousResponse\") {\n prefill.source.ref.itemId =\n idMapping[prefill.source.ref.itemId] ?? prefill.source.ref.itemId;\n }\n });\n }\n }\n\n /**\n * Update references in a single expression (recursive)\n */\n private updateExpressionReferences(\n expression: unknown,\n idMapping: { [oldId: string]: string },\n ): void {\n if (!expression || typeof expression !== \"object\") {\n return;\n }\n\n const expr = expression as Record<string, unknown>;\n if (Array.isArray(expr.data)) {\n expr.data.forEach((arg: unknown) => {\n if (arg && typeof arg === \"object\" && arg !== null && \"str\" in arg) {\n const argObj = arg as { str?: string };\n if (\n typeof argObj.str === \"string\" &&\n Object.prototype.hasOwnProperty.call(idMapping, argObj.str)\n ) {\n argObj.str = idMapping[argObj.str];\n }\n this.updateExpressionReferences(arg, idMapping);\n }\n });\n }\n\n Object.keys(expr).forEach((key) => {\n const val = expr[key];\n if (val && typeof val === \"object\") {\n this.updateExpressionReferences(val, idMapping);\n }\n });\n }\n\n /**\n * Update translation keys for the pasted item\n */\n private updateTranslations(\n translations: { [itemId: string]: SerializedTranslations },\n idMapping: { [oldId: string]: string },\n ): { [itemId: string]: SerializedTranslations } {\n const newTranslations: { [itemId: string]: SerializedTranslations } = {};\n\n // Update ids for all items in the translation data\n Object.keys(translations).forEach((itemId) => {\n const itemTranslations = translations[itemId];\n\n // Determine the new key for this item (update the key mapping)\n const newItemId = idMapping[itemId];\n\n // Copy the serialized translations as-is (content is preserved, only keys change)\n newTranslations[newItemId] = itemTranslations;\n });\n\n return newTranslations;\n }\n\n /**\n * Validate clipboard data format\n */\n static isValidClipboardData(data: unknown): data is SurveyItemClipboardData {\n if (typeof data !== \"object\" || data === null || data === undefined) return false;\n const clipboardData = data as SurveyItemClipboardData;\n\n if (\n clipboardData.rootItemId === undefined ||\n typeof clipboardData.rootItemId !== \"string\" ||\n !Array.isArray(clipboardData.items) ||\n clipboardData.items.length === 0 ||\n typeof clipboardData.translations !== \"object\" ||\n clipboardData.translations === null ||\n Array.isArray(clipboardData.translations)\n ) {\n return false;\n }\n\n return (\n clipboardData.type === \"survey-item\" &&\n clipboardData.version === \"1.0.0\" &&\n clipboardData.items.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n typeof item.itemId === \"string\" &&\n item.itemId.length > 0 &&\n typeof item.itemData === \"object\" &&\n item.itemData !== null &&\n !Array.isArray(item.itemData) &&\n typeof item.itemData.itemType === \"string\",\n ) &&\n clipboardData.items.some((item) => item.itemId === clipboardData.rootItemId)\n );\n }\n}\n","import { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { structuredCloneMethod } from \"../utils\";\n\nexport interface UndoRedoConfig {\n maxTotalMemoryMB: number;\n minHistorySize: number;\n maxHistorySize: number;\n}\n\nexport const CommitSource = {\n USER: \"user\",\n SYSTEM: \"system\",\n ASSISTANT: \"assistant\",\n} as const;\nexport type CommitSource = (typeof CommitSource)[keyof typeof CommitSource];\n\nexport interface CommitMeta {\n label: string;\n source?: CommitSource;\n}\n\nexport interface AssetPatch {\n assetId: string;\n prev?: RawSurveyAsset;\n next?: RawSurveyAsset;\n}\n\ninterface BaseHistoryEntry {\n timestamp: number;\n meta: CommitMeta;\n memorySize: number;\n}\n\ninterface SurveySnapshotHistoryEntry extends BaseHistoryEntry {\n kind: \"survey-snapshot\";\n survey: RawSurvey;\n}\n\ninterface AssetChangeHistoryEntry extends BaseHistoryEntry {\n kind: \"asset-change\";\n changes: AssetPatch[];\n}\n\ntype HistoryEntry = SurveySnapshotHistoryEntry | AssetChangeHistoryEntry;\ntype PendingHistoryEntry =\n | Omit<SurveySnapshotHistoryEntry, \"timestamp\" | \"memorySize\">\n | Omit<AssetChangeHistoryEntry, \"timestamp\" | \"memorySize\">;\n\nexport interface SurveyEditorHistoryCommit {\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n}\n\ntype SerializedHistoryEntry =\n | SurveySnapshotHistoryEntry\n | AssetChangeHistoryEntry\n | (BaseHistoryEntry & { survey: RawSurvey });\n\n// Memory calculation utilities\nclass MemoryCalculator {\n private static encoder = new TextEncoder();\n\n static calculateSize(obj: object): number {\n const jsonString = JSON.stringify(obj);\n return this.encoder.encode(jsonString).length;\n }\n\n static formatBytes(bytes: number): string {\n const units = [\"B\", \"KB\", \"MB\", \"GB\"];\n let size = bytes;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n}\n\nfunction cloneAssets(\n assets?: Record<string, RawSurveyAsset>,\n): Record<string, RawSurveyAsset> | undefined {\n if (!assets || Object.keys(assets).length === 0) {\n return undefined;\n }\n return structuredCloneMethod(assets);\n}\n\nfunction normalizeHistoryEntry(entry: SerializedHistoryEntry): HistoryEntry {\n if (\"kind\" in entry) {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: structuredCloneMethod(entry.changes),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n}\n\nexport class SurveyEditorUndoRedo {\n private history: HistoryEntry[] = [];\n private currentIndex: number = -1;\n private _config: UndoRedoConfig;\n private _initialAssets?: Record<string, RawSurveyAsset>;\n\n constructor(\n initialSurvey: RawSurvey,\n config: Partial<UndoRedoConfig> = {},\n meta: CommitMeta = { label: \"Initial state\", source: CommitSource.SYSTEM },\n initialAssets?: Record<string, RawSurveyAsset>,\n ) {\n this._config = {\n maxTotalMemoryMB: 50,\n minHistorySize: 10,\n maxHistorySize: 200,\n ...config,\n };\n this._initialAssets = cloneAssets(initialAssets);\n\n this.saveSnapshot(initialSurvey, meta);\n }\n\n private saveEntry(entry: PendingHistoryEntry): void {\n const payload =\n entry.kind === \"survey-snapshot\"\n ? { kind: entry.kind, survey: entry.survey }\n : { kind: entry.kind, changes: entry.changes };\n\n const memorySize = MemoryCalculator.calculateSize(payload);\n\n // Remove any history after current index\n this.history = this.history.slice(0, this.currentIndex + 1);\n\n this.history.push({\n ...structuredCloneMethod(entry),\n timestamp: Date.now(),\n memorySize,\n } as HistoryEntry);\n\n this.currentIndex++;\n\n // Clean up history based on memory usage\n this.cleanupHistory();\n }\n\n private saveSnapshot(survey: RawSurvey, meta: CommitMeta): void {\n this.saveEntry({\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(survey),\n meta,\n });\n }\n\n private getBaseAssetsSize(): number {\n return this._initialAssets ? MemoryCalculator.calculateSize(this._initialAssets) : 0;\n }\n\n private cleanupHistory(): void {\n const maxMemoryBytes = this._config.maxTotalMemoryMB * 1024 * 1024;\n\n // Remove oldest states while preserving minimum.\n while (\n this.history.length > this._config.minHistorySize &&\n (this.getTotalMemoryUsage() > maxMemoryBytes ||\n this.history.length > this._config.maxHistorySize)\n ) {\n if (this.dropOldestState() <= 0) {\n break;\n }\n }\n }\n\n private dropOldestState(): number {\n if (this.history.length <= 1) {\n return 0;\n }\n\n const nextStateIndex = 1;\n const nextStateSurvey = this.getStateAtIndex(nextStateIndex);\n const nextStateAssets = this.getAssetsAtIndex(nextStateIndex);\n const nextEntry = this.history[nextStateIndex];\n\n const newFirstEntry: SurveySnapshotHistoryEntry = {\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n meta: nextEntry.meta,\n timestamp: nextEntry.timestamp,\n memorySize: MemoryCalculator.calculateSize({\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n }),\n };\n\n const removedBytes = this.history[0].memorySize;\n\n this._initialAssets = cloneAssets(nextStateAssets);\n this.history = [newFirstEntry, ...this.history.slice(nextStateIndex + 1)];\n this.currentIndex--;\n\n return removedBytes;\n }\n\n private getTotalMemoryUsage(): number {\n return (\n this.getBaseAssetsSize() + this.history.reduce((total, entry) => total + entry.memorySize, 0)\n );\n }\n\n private getStateAtIndex(index: number): RawSurvey {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n for (let i = index; i >= 0; i--) {\n const entry = this.history[i];\n if (entry.kind === \"survey-snapshot\") {\n return structuredCloneMethod(entry.survey);\n }\n }\n\n throw new Error(\"Invalid history state\");\n }\n\n private applyAssetPatch(\n assets: Record<string, RawSurveyAsset>,\n patch: AssetPatch,\n ): Record<string, RawSurveyAsset> {\n const nextAssets = structuredCloneMethod(assets);\n if (patch.next) {\n nextAssets[patch.assetId] = structuredCloneMethod(patch.next);\n } else {\n delete nextAssets[patch.assetId];\n }\n return nextAssets;\n }\n\n private getAssetsAtIndex(index: number): Record<string, RawSurveyAsset> | undefined {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n let assets = cloneAssets(this._initialAssets) ?? {};\n\n for (let i = 1; i <= index; i++) {\n const entry = this.history[i];\n if (entry.kind !== \"asset-change\") {\n continue;\n }\n\n for (const patch of entry.changes) {\n assets = this.applyAssetPatch(assets, patch);\n }\n }\n\n return Object.keys(assets).length > 0 ? assets : undefined;\n }\n\n // Commit a change to history\n commit(survey: RawSurvey, meta: CommitMeta): void {\n this.saveSnapshot(survey, meta);\n }\n\n commitAssetChange(changes: AssetPatch[], meta: CommitMeta): void {\n if (changes.length === 0) {\n return;\n }\n\n this.saveEntry({\n kind: \"asset-change\",\n changes: structuredCloneMethod(changes),\n meta,\n });\n }\n\n // Get current committed state\n getCurrentState(): RawSurvey {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getStateAtIndex(this.currentIndex);\n }\n\n getCurrentAssets(): Record<string, RawSurveyAsset> | undefined {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getAssetsAtIndex(this.currentIndex);\n }\n\n undo(): RawSurvey | null {\n if (!this.canUndo()) return null;\n\n this.currentIndex--;\n return this.getCurrentState();\n }\n\n redo(): RawSurvey | null {\n if (!this.canRedo()) return null;\n\n this.currentIndex++;\n return this.getCurrentState();\n }\n\n canUndo(): boolean {\n return this.currentIndex > 0;\n }\n\n canRedo(): boolean {\n return this.currentIndex < this.history.length - 1;\n }\n\n getUndoMeta(): CommitMeta | null {\n if (!this.canUndo()) return null;\n return this.history[this.currentIndex].meta;\n }\n\n getRedoMeta(): CommitMeta | null {\n if (!this.canRedo()) return null;\n return this.history[this.currentIndex + 1].meta;\n }\n\n getMemoryUsage(): { totalMB: number; entries: number } {\n return {\n totalMB: this.getTotalMemoryUsage() / (1024 * 1024),\n entries: this.history.length,\n };\n }\n\n getConfig(): UndoRedoConfig {\n return { ...this._config };\n }\n\n /**\n * Get the full history list with metadata\n */\n getHistory(): Array<{\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n }> {\n return this.history.map((entry, index) => ({\n index,\n kind: entry.kind,\n meta: entry.meta,\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n }));\n }\n\n /**\n * Get committed history entries after the initial state up to the current index.\n *\n * Redo-only future entries are intentionally omitted so the returned list describes the active\n * change chain from the initial state to the current editor state.\n */\n getCommitsSinceInitial(): SurveyEditorHistoryCommit[] {\n return this.history.slice(1, this.currentIndex + 1).map((entry, offset) => {\n const index = offset + 1;\n return {\n index,\n kind: entry.kind,\n meta: entry.meta,\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n };\n });\n }\n\n /**\n * Get the current index in the history\n */\n getCurrentIndex(): number {\n return this.currentIndex;\n }\n\n /**\n * Get the total number of history entries\n */\n getHistoryLength(): number {\n return this.history.length;\n }\n\n /**\n * Jump to a specific index in the history (can go forward or backward)\n * @param targetIndex The index to jump to\n * @returns The survey state at the target index, or null if invalid\n */\n jumpToIndex(targetIndex: number): RawSurvey | null {\n if (\n targetIndex < 0 ||\n targetIndex >= this.history.length ||\n targetIndex === this.currentIndex\n ) {\n return null;\n }\n\n this.currentIndex = targetIndex;\n return this.getCurrentState();\n }\n\n /**\n * Check if we can jump to a specific index\n */\n canJumpToIndex(targetIndex: number): boolean {\n return (\n targetIndex >= 0 && targetIndex < this.history.length && targetIndex !== this.currentIndex\n );\n }\n\n /**\n * Serialize the undo/redo state to JSON\n * @returns A JSON-serializable object containing the complete state\n */\n serialize(): {\n history: Array<HistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n } {\n return {\n history: this.history.map((entry) => {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: entry.survey,\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: entry.changes,\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }),\n currentIndex: this.currentIndex,\n config: { ...this._config },\n initialAssets: cloneAssets(this._initialAssets),\n };\n }\n\n /**\n * Create a new SurveyEditorUndoRedo instance from JSON data\n * @param jsonData The serialized undo/redo state\n * @returns A new SurveyEditorUndoRedo instance with the restored state\n */\n static deserialize(\n jsonData: {\n history: Array<SerializedHistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n },\n initialAssetsOverride?: Record<string, RawSurveyAsset>,\n ): SurveyEditorUndoRedo {\n if (!jsonData.history || !Array.isArray(jsonData.history) || jsonData.history.length === 0) {\n throw new Error(\"Invalid object: history must be an array and must not be empty\");\n }\n\n if (\n typeof jsonData.currentIndex !== \"number\" ||\n jsonData.currentIndex < 0 ||\n jsonData.currentIndex >= jsonData.history.length\n ) {\n throw new Error(\n \"Invalid object: currentIndex must be a valid index within the history array\",\n );\n }\n\n if (!jsonData.config) {\n throw new Error(\"Invalid object: config is required\");\n }\n\n const normalizedHistory = jsonData.history.map(normalizeHistoryEntry);\n\n // Create a new instance with the first survey and config\n const firstEntry = normalizedHistory[0];\n const firstSurvey =\n firstEntry.kind === \"survey-snapshot\"\n ? firstEntry.survey\n : (() => {\n throw new Error(\n \"Invalid object: first history entry must resolve to a survey snapshot\",\n );\n })();\n\n const instance = new SurveyEditorUndoRedo(\n firstSurvey,\n jsonData.config,\n firstEntry.meta,\n initialAssetsOverride ?? jsonData.initialAssets,\n );\n\n // Clear the default initial state and restore the full history\n instance.history = normalizedHistory;\n instance.currentIndex = jsonData.currentIndex;\n instance._initialAssets = cloneAssets(initialAssetsOverride ?? jsonData.initialAssets);\n\n return instance;\n }\n}\n","import { Survey } from \"../survey/survey\";\nimport { CommitMeta, CommitSource, SurveyEditorUndoRedo, type UndoRedoConfig } from \"./undo-redo\";\nimport {\n SurveyItemTranslations,\n SurveyCardContent,\n NavigationContent,\n Content,\n} from \"../survey/utils\";\nimport { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { ItemCopyPaste, SurveyItemClipboardData } from \"./item-copy-paste\";\nimport { Target } from \"./types\";\nimport { SurveyItemCore, RawSurveyItem } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport type { ItemTypeRegistry } from \"../survey/registry/item-registry\";\nimport type { TemplateValueDefinition } from \"../expressions/template-value\";\nimport { structuredCloneMethod } from \"../utils\";\n\n// Interface for serializing SurveyEditor state\nexport interface SerializedSurveyEditor {\n version: string;\n survey: RawSurvey;\n undoRedo: ReturnType<SurveyEditorUndoRedo[\"serialize\"]>;\n hasUncommittedChanges: boolean;\n}\n\nexport interface SurveyEditorConfig extends Partial<UndoRedoConfig> {\n /** Plugin registry for deserializing survey state during undo/redo. Required when survey contains custom item types. */\n pluginRegistry?: ItemTypeRegistry;\n}\n\nfunction stripAssetsFromSurveySnapshot(survey: RawSurvey): RawSurvey {\n const snapshot = structuredCloneMethod(survey);\n delete snapshot.assets;\n return snapshot;\n}\n\nfunction mergeSurveySnapshotWithAssets(\n snapshot: RawSurvey,\n assets?: RawSurvey[\"assets\"],\n): RawSurvey {\n const merged = structuredCloneMethod(snapshot);\n\n if (assets && Object.keys(assets).length > 0) {\n merged.assets = structuredCloneMethod(assets);\n } else {\n delete merged.assets;\n }\n\n return merged;\n}\n\nexport class SurveyEditor {\n private _survey: Survey;\n private _undoRedo: SurveyEditorUndoRedo;\n private _hasUncommittedChanges: boolean = false;\n private _pluginRegistry?: ItemTypeRegistry;\n\n constructor(survey: Survey, config: SurveyEditorConfig = {}, meta?: CommitMeta) {\n this._survey = survey;\n const { pluginRegistry, ...undoRedoConfig } = config;\n this._pluginRegistry = pluginRegistry;\n const serialized = survey.serialize();\n this._undoRedo = new SurveyEditorUndoRedo(\n stripAssetsFromSurveySnapshot(serialized),\n undoRedoConfig,\n meta,\n serialized.assets,\n );\n }\n\n /** Returns an immutable copy of the current survey state. */\n get survey(): Survey {\n const serialized = this._survey.serialize();\n const registry = this._pluginRegistry ?? this._survey.getPluginRegistry();\n return Survey.fromJson(serialized, registry);\n }\n\n get hasUncommittedChanges(): boolean {\n return this._hasUncommittedChanges;\n }\n\n // Expose the undo-redo instance directly\n get undoRedo(): SurveyEditorUndoRedo {\n return this._undoRedo;\n }\n\n // Commit current changes to undo/redo history\n commit(meta: CommitMeta): void {\n if (!this._hasUncommittedChanges) {\n return;\n }\n\n this._undoRedo.commit(stripAssetsFromSurveySnapshot(this._survey.serialize()), meta);\n this._hasUncommittedChanges = false;\n }\n\n private restoreHistoryState(snapshot: RawSurvey, assets?: RawSurvey[\"assets\"]): void {\n this._survey = Survey.fromJson(\n mergeSurveySnapshotWithAssets(snapshot, assets),\n this._pluginRegistry,\n );\n }\n\n commitIfNeeded(): void {\n if (this._hasUncommittedChanges) {\n this.commit({\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n });\n }\n }\n\n // Undo to previous state\n undo(): boolean {\n if (this._hasUncommittedChanges) {\n // If there are uncommitted changes, revert to last committed state\n this.restoreHistoryState(this._undoRedo.getCurrentState(), this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n } else {\n // Normal undo operation\n const previousState = this._undoRedo.undo();\n if (previousState) {\n this.restoreHistoryState(previousState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n }\n\n // Redo to next state\n redo(): boolean {\n if (this._hasUncommittedChanges) {\n // Cannot redo when there are uncommitted changes\n return false;\n }\n\n const nextState = this._undoRedo.redo();\n if (nextState) {\n this.restoreHistoryState(nextState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n // Enhanced undo/redo methods that use the exposed instance\n /**\n * Jump to a specific index in the history (can go forward or backward)\n */\n jumpToIndex(targetIndex: number): boolean {\n if (this._hasUncommittedChanges) {\n // Cannot jump to specific index with uncommitted changes\n return false;\n }\n\n const targetState = this._undoRedo.jumpToIndex(targetIndex);\n if (targetState) {\n this.restoreHistoryState(targetState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n canUndo(): boolean {\n return this._hasUncommittedChanges || this._undoRedo.canUndo();\n }\n\n canRedo(): boolean {\n return !this._hasUncommittedChanges && this._undoRedo.canRedo();\n }\n\n getUndoMeta(): CommitMeta | null {\n if (this._hasUncommittedChanges) {\n return {\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n };\n }\n return this._undoRedo.getUndoMeta();\n }\n\n getRedoMeta(): CommitMeta | null {\n if (this._hasUncommittedChanges) {\n return null;\n }\n return this._undoRedo.getRedoMeta();\n }\n\n // Get memory usage statistics\n getMemoryUsage(): { totalMB: number; entries: number } {\n return this._undoRedo.getMemoryUsage();\n }\n\n // Get undo/redo configuration\n getUndoRedoConfig(): UndoRedoConfig {\n return this._undoRedo.getConfig();\n }\n\n /**\n * Get committed changes after the initial editor state up to the current undo/redo position.\n */\n getCommitsSinceInitial() {\n return this._undoRedo.getCommitsSinceInitial();\n }\n\n /**\n * Serialize the SurveyEditor state to JSON\n * @returns A JSON-serializable object containing the complete editor state\n */\n toJson(): SerializedSurveyEditor {\n return {\n version: \"1.0.0\",\n survey: this._survey.serialize(),\n undoRedo: this._undoRedo.serialize(),\n hasUncommittedChanges: this._hasUncommittedChanges,\n };\n }\n\n /**\n * Create a new SurveyEditor instance from JSON data\n * @param jsonData The serialized editor state\n * @param pluginRegistry Optional plugin registry for deserializing survey state (required when survey contains custom item types)\n * @returns A new SurveyEditor instance with the restored state\n */\n static fromJson(\n jsonData: SerializedSurveyEditor,\n pluginRegistry?: ItemTypeRegistry,\n ): SurveyEditor {\n if (!jsonData.survey) {\n throw new Error(\"Invalid object: survey is required\");\n }\n\n if (!jsonData.undoRedo) {\n throw new Error(\"Invalid object: undoRedo is required\");\n }\n\n if (typeof jsonData.hasUncommittedChanges !== \"boolean\") {\n throw new Error(\"Invalid object: hasUncommittedChanges must be a boolean\");\n }\n\n // Validate version (for future compatibility)\n if (jsonData.version && !jsonData.version.startsWith(\"1.\")) {\n console.warn(\n `Warning: Loading SurveyEditor with version ${jsonData.version}, current version is 1.0.0`,\n );\n }\n\n // Create survey from JSON\n const survey = Survey.fromJson(jsonData.survey, pluginRegistry);\n\n // Create a new editor instance\n const editor = new SurveyEditor(survey, { pluginRegistry });\n\n // Restore undo/redo state\n editor._undoRedo = SurveyEditorUndoRedo.deserialize(\n {\n ...jsonData.undoRedo,\n history: jsonData.undoRedo.history.map((entry) =>\n \"survey\" in entry\n ? {\n ...entry,\n survey: stripAssetsFromSurveySnapshot(entry.survey),\n }\n : entry,\n ),\n },\n jsonData.survey.assets,\n );\n\n // Infer whether the live survey contains uncommitted survey changes by comparing\n // the current survey content to the current history entry, ignoring assets.\n editor._hasUncommittedChanges =\n JSON.stringify(stripAssetsFromSurveySnapshot(jsonData.survey)) !==\n JSON.stringify(editor._undoRedo.getCurrentState());\n\n return editor;\n }\n\n private markAsModified(): void {\n this._hasUncommittedChanges = true;\n }\n\n private createEditorTimestamp(): string {\n return new Date().toISOString();\n }\n\n private touchItemModifiedMetadata(\n itemId: string,\n timestamp = this.createEditorTimestamp(),\n ): void {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return;\n }\n\n item.setModifiedAt(timestamp);\n }\n\n addItem(target: Target, item: SurveyItemCore, content?: SurveyItemTranslations): void {\n if (this._survey.surveyItems.has(item.id)) {\n throw new Error(`Item with id '${item.id}' already exists in the survey`);\n }\n\n // Mark as modified (uncommitted change)\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n\n // Find the parent group item\n let parentGroup: GroupItemCore;\n\n if (!target) {\n // If no target provided, add to root\n\n const rootItem = this._survey.rootItem;\n if (!rootItem) {\n throw new Error(\"No root group found in survey\");\n }\n if (!(rootItem instanceof GroupItemCore)) {\n throw new Error(\"Root item is not a group item\");\n }\n parentGroup = rootItem;\n } else {\n // Find the target parent group\n const targetItem = this._survey.surveyItems.get(target.parentId);\n\n if (!targetItem) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Parent item '${target.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n parentGroup = targetItem;\n }\n\n if (parentGroup.hasChild(item.id)) {\n throw new Error(`Item ${item.id} already in this group`);\n }\n\n // ensure that item's key not already used within the group\n const siblings = Array.from(this._survey.surveyItems.values()).filter((sItem) =>\n parentGroup.items?.includes(sItem.id),\n );\n let counter = 1;\n const originalKey = item.key;\n let uniqueKey = originalKey;\n while (siblings.some((sibling) => sibling.key === uniqueKey)) {\n uniqueKey = `${originalKey}_${counter}`;\n counter++;\n }\n\n // Determine insertion index\n let insertIndex: number;\n if (target?.index !== undefined) {\n // Insert at specified index, or at end if index is larger than array length\n insertIndex = Math.min(target.index, parentGroup.items.length);\n } else {\n // Insert at the end\n insertIndex = parentGroup.items.length;\n }\n\n item.updateRawItem({\n ...item.rawItem,\n key: uniqueKey,\n });\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n\n // Add the item to the survey items collection\n this._survey.surveyItems.set(item.id, item);\n\n // Add the item to the parent group (uses addChild for proper persistence)\n parentGroup.addChild(item.id, insertIndex);\n this.touchItemModifiedMetadata(parentGroup.id, timestamp);\n\n // Update translations in the survey\n if (content) {\n this._survey.translations.setItemTranslations(item.id, content);\n }\n }\n\n // Remove an item from the survey\n removeItem(itemId: string, nested: boolean = false): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n // Find parent group and remove from its items array\n const parentItem = this._survey.getParentItem(itemId);\n if (!parentItem) {\n throw new Error(`Item with id '${itemId}' is the root item`);\n }\n\n if (item instanceof GroupItemCore) {\n for (const childId of item.getChildrenIds()) {\n this.removeItem(childId, true);\n }\n }\n\n // Remove from survey items\n this._survey.surveyItems.delete(itemId);\n\n // Remove translations\n this._survey.translations?.onItemDeleted(itemId);\n\n if (!nested) {\n parentItem.removeChild(itemId);\n this.touchItemModifiedMetadata(parentItem.id, timestamp);\n }\n return true;\n }\n\n // Move an item to a different position\n moveItem(itemId: string, newTarget: Target): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n // Check if item exists\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Check if new target exists and is a group\n const targetItem = this._survey.surveyItems.get(newTarget.parentId);\n if (!targetItem) {\n throw new Error(`Target parent with id '${newTarget.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Target parent '${newTarget.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n // Check if new target is not a child of the current item (prevent circular reference)\n if (this._survey.isDescendantOf(newTarget.parentId, itemId)) {\n throw new Error(`Cannot move item '${itemId}' to its descendant '${newTarget.parentId}'`);\n }\n\n // If the item is already in the target parent\n const currentParentItem = this._survey.getParentItem(itemId);\n if (currentParentItem?.id === newTarget.parentId) {\n throw new Error(`Item '${itemId}' is already in the target parent '${newTarget.parentId}'`);\n }\n\n // Remove item from current parent's items array\n if (currentParentItem) {\n const currentParentGroup = currentParentItem as GroupItemCore;\n currentParentGroup.removeChild(itemId);\n this.touchItemModifiedMetadata(currentParentGroup.id, timestamp);\n }\n\n // Add item to new parent's items array\n const targetGroup = targetItem as GroupItemCore;\n\n // ensure that item's key not already used within the group\n const siblings = Array.from(this._survey.surveyItems.values()).filter((sItem) =>\n targetGroup.hasChild(sItem.id),\n );\n let counter = 1;\n let uniqueKey = item.key;\n while (siblings.some((sibling) => sibling.key === uniqueKey)) {\n uniqueKey = `${item.key}_${counter}`;\n counter++;\n }\n if (uniqueKey !== item.key) {\n item.updateRawItem({\n ...item.rawItem,\n key: uniqueKey,\n });\n }\n\n const insertIndex =\n newTarget.index !== undefined\n ? Math.min(newTarget.index, targetGroup.items.length)\n : targetGroup.items.length;\n\n targetGroup.addChild(itemId, insertIndex);\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n this.touchItemModifiedMetadata(itemId, timestamp);\n\n return true;\n }\n\n /** Move several independent item subtrees as one ordered block. */\n moveItems(itemIds: readonly string[], newTarget: Target): boolean {\n const requestedIds = [...new Set(itemIds)];\n const selectedIds = requestedIds.filter(\n (itemId) =>\n !requestedIds.some(\n (candidateId) =>\n candidateId !== itemId && this._survey.isDescendantOf(itemId, candidateId),\n ),\n );\n if (selectedIds.length === 0) return false;\n\n const targetGroup = this._survey.surveyItems.get(newTarget.parentId);\n if (!(targetGroup instanceof GroupItemCore)) {\n throw new Error(`Target parent '${newTarget.parentId}' is not a group item`);\n }\n\n const entries = selectedIds.map((itemId) => {\n const item = this._survey.surveyItems.get(itemId);\n const parent = this._survey.getParentItem(itemId);\n if (!item || !(parent instanceof GroupItemCore)) {\n throw new Error(`Item '${itemId}' cannot be moved`);\n }\n if (itemId === newTarget.parentId || this._survey.isDescendantOf(newTarget.parentId, itemId)) {\n throw new Error(`Cannot move item '${itemId}' into its own subtree`);\n }\n return { item, parent, index: parent.items.indexOf(itemId) };\n });\n\n // Preserve the survey's structural order, regardless of click order.\n const order = new Map<string, number>();\n let orderIndex = 0;\n const visit = (group: GroupItemCore) => {\n for (const childId of group.items) {\n order.set(childId, orderIndex++);\n const child = this._survey.surveyItems.get(childId);\n if (child instanceof GroupItemCore) visit(child);\n }\n };\n const root = this._survey.rootItem;\n if (root) visit(root);\n entries.sort((a, b) => (order.get(a.item.id) ?? 0) - (order.get(b.item.id) ?? 0));\n\n const selectedSet = new Set(entries.map(({ item }) => item.id));\n const requestedIndex = newTarget.index ?? targetGroup.items.length;\n const removedBeforeTarget = targetGroup.items\n .slice(0, requestedIndex)\n .filter((id) => selectedSet.has(id)).length;\n const insertionIndex = Math.max(0, requestedIndex - removedBeforeTarget);\n const timestamp = this.createEditorTimestamp();\n\n this.markAsModified();\n for (const { item, parent } of entries) {\n parent.removeChild(item.id);\n this.touchItemModifiedMetadata(parent.id, timestamp);\n }\n\n const siblingKeys = new Set(\n targetGroup.items\n .map((id) => this._survey.surveyItems.get(id)?.key)\n .filter((key): key is string => Boolean(key)),\n );\n entries.forEach(({ item }, offset) => {\n const originalKey = item.key;\n let uniqueKey = originalKey;\n let counter = 1;\n while (siblingKeys.has(uniqueKey)) uniqueKey = `${originalKey}_${counter++}`;\n if (uniqueKey !== item.key) item.updateRawItem({ ...item.rawItem, key: uniqueKey });\n siblingKeys.add(uniqueKey);\n targetGroup.addChild(item.id, insertionIndex + offset);\n this.touchItemModifiedMetadata(item.id, timestamp);\n });\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n return true;\n }\n\n /**\n * Get a deep copy of an item's raw data.\n * The returned object is independent of the survey—mutating it will not affect the survey.\n * Use this when you need to edit an item in a form or pass it to updateItem after modifications.\n *\n * @param itemId - The ID of the item to copy\n * @returns A deep copy of the item's RawSurveyItem data\n * @throws Error if the item is not found\n */\n getItemDataCopy(itemId: string): RawSurveyItem {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n return JSON.parse(JSON.stringify(item.rawItem)) as RawSurveyItem;\n }\n\n /**\n * Update an item's data in the survey.\n * Can update common attributes (displayConditions, disabledConditions, validations, etc.)\n * as well as type-specific config.\n *\n * Use getItemDataCopy to obtain an editable copy, modify it, then pass it here.\n * Alternatively, pass a Partial to merge specific fields (top-level keys only;\n * e.g. config replaces the entire config object).\n *\n * @param itemId - The ID of the item to update (must match data.id if provided)\n * @param rawItemData - Full RawSurveyItem or Partial to merge. The id cannot be changed.\n */\n updateItem(itemId: string, rawItemData: RawSurveyItem | Partial<RawSurveyItem>): void {\n const existingItem = this._survey.surveyItems.get(itemId);\n if (!existingItem) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n if (\"id\" in rawItemData && rawItemData.id !== undefined && rawItemData.id !== itemId) {\n throw new Error(`Cannot change item id from '${itemId}' to '${rawItemData.id}'`);\n }\n\n const currentRaw = existingItem.rawItem;\n const merged: RawSurveyItem = {\n ...currentRaw,\n ...rawItemData,\n id: itemId, // Ensure id is never changed\n };\n\n // Reject key change if it would collide with a sibling\n const newKey = merged.key ?? existingItem.key;\n const parentGroup = this._survey.getParentItem(itemId);\n if (parentGroup) {\n const siblingWithSameKey = (parentGroup.items ?? [])\n .filter((id) => id !== itemId)\n .map((id) => this._survey.surveyItems.get(id))\n .find((s) => s !== undefined && s.key === newKey);\n if (siblingWithSameKey) {\n throw new Error(\n `Key '${newKey}' is already in use by sibling item '${siblingWithSameKey.id}'`,\n );\n }\n }\n\n const newItem = this._survey.createItemFromRaw({\n ...merged,\n editorMetadata: existingItem.rawItem.editorMetadata,\n });\n newItem.setModifiedAt(this.createEditorTimestamp());\n this._survey.surveyItems.set(itemId, newItem);\n this.markAsModified();\n }\n\n // TODO: add also to update component translations (updating part of the item)\n // Update item translations\n updateItemTranslations(itemId: string, updatedContent?: SurveyItemTranslations): boolean {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n this.markAsModified();\n item.setModifiedAt(this.createEditorTimestamp());\n this._survey.translations.setItemTranslations(itemId, updatedContent);\n\n return true;\n }\n\n /**\n * Update survey-level translations that are not tied to specific items.\n * Use these for survey card, navigation, validation messages, etc.\n */\n updateSurveyTranslations(updates: {\n surveyCard?: { locale: string; content?: SurveyCardContent };\n navigation?: { locale: string; content?: NavigationContent };\n validationMessages?: { locale: string; content?: { invalidResponse?: Content } };\n }): void {\n this.markAsModified();\n if (updates.surveyCard) {\n this._survey.translations.setSurveyCardContent(\n updates.surveyCard.locale,\n updates.surveyCard.content,\n );\n }\n if (updates.navigation) {\n this._survey.translations.setNavigationContent(\n updates.navigation.locale,\n updates.navigation.content,\n );\n }\n if (updates.validationMessages) {\n this._survey.translations.setValidationMessages(\n updates.validationMessages.locale,\n updates.validationMessages.content,\n );\n }\n }\n\n /** Add an empty survey locale so it can be authored before translated content exists. */\n addLocale(locale: string): boolean {\n const added = this._survey.translations.addLocale(locale);\n if (added) {\n this.markAsModified();\n }\n return added;\n }\n\n /** Remove a locale and every survey- and item-level translation stored for it. */\n removeLocale(locale: string): boolean {\n if (!this._survey.locales.includes(locale)) {\n return false;\n }\n\n this._survey.translations.removeLocale(locale);\n this.markAsModified();\n return true;\n }\n\n /**\n * Get maxItemsPerPage immutably (returns a copy).\n */\n getMaxItemsPerPage(): { large: number; small: number } | undefined {\n const val = this._survey.maxItemsPerPage;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update maxItemsPerPage.\n */\n updateMaxItemsPerPage(value: { large: number; small: number } | undefined): void {\n this.markAsModified();\n this._survey.maxItemsPerPage = value ? { ...value } : undefined;\n }\n\n /**\n * Get metadata immutably (returns a copy).\n */\n getMetadata(): { [key: string]: string } | undefined {\n const val = this._survey.metadata;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update metadata.\n */\n updateMetadata(metadata: { [key: string]: string } | undefined): void {\n this.markAsModified();\n this._survey.metadata = metadata ? { ...metadata } : undefined;\n }\n\n /**\n * Get a template value immutably (returns a deep copy).\n */\n getTemplateValue(key: string): TemplateValueDefinition | undefined {\n const val = this._survey.getTemplateValue(key);\n return val ? structuredCloneMethod(val) : undefined;\n }\n\n /**\n * Get all template values immutably (returns a new Map with deep-copied values).\n */\n getTemplateValues(): Map<string, TemplateValueDefinition> {\n const keys = this._survey.getTemplateValueKeys();\n const result = new Map<string, TemplateValueDefinition>();\n for (const key of keys) {\n const val = this._survey.getTemplateValue(key);\n if (val) {\n result.set(key, structuredCloneMethod(val));\n }\n }\n return result;\n }\n\n /**\n * Add or replace a template value.\n */\n setTemplateValue(key: string, templateValue: TemplateValueDefinition): void {\n this.markAsModified();\n this._survey.setTemplateValue(key, structuredCloneMethod(templateValue));\n }\n\n /**\n * Remove a template value.\n */\n removeTemplateValue(key: string): void {\n this.markAsModified();\n this._survey.deleteTemplateValue(key);\n }\n\n /**\n * Get a survey asset immutably.\n */\n getAsset(assetId: string): RawSurveyAsset | undefined {\n const asset = this._survey.getAsset(assetId);\n return asset ? structuredCloneMethod(asset) : undefined;\n }\n\n /**\n * Get all survey assets immutably.\n */\n getAssets(): Map<string, RawSurveyAsset> {\n return this._survey.getAssets();\n }\n\n /**\n * Add or replace a survey asset.\n */\n setAsset(assetId: string, asset: RawSurveyAsset): void {\n const previousAsset = this._survey.getAsset(assetId);\n this._survey.setAsset(assetId, structuredCloneMethod(asset));\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n next: structuredCloneMethod(asset),\n },\n ],\n {\n label: `Update asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Remove a survey asset.\n */\n removeAsset(assetId: string): void {\n const previousAsset = this._survey.getAsset(assetId);\n if (!previousAsset) {\n return;\n }\n this._survey.deleteAsset(assetId);\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n },\n ],\n {\n label: `Remove asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * @param itemId - The ID of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const copyPaste = new ItemCopyPaste(this._survey);\n return copyPaste.copyItem(itemId);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * @param clipboardData - The clipboard data containing the item to paste\n * @param target - Target location where to paste the item\n * @returns The ID of the pasted item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n const itemIdsBeforePaste = new Set(this._survey.surveyItems.keys());\n const copyPaste = new ItemCopyPaste(this._survey);\n const newItemId = copyPaste.pasteItem(clipboardData, target);\n const pastedItemIds = Array.from(this._survey.surveyItems.keys()).filter(\n (itemId) => !itemIdsBeforePaste.has(itemId),\n );\n\n for (const itemId of pastedItemIds) {\n const item = this._survey.surveyItems.get(itemId);\n if (item) {\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n }\n }\n this.touchItemModifiedMetadata(target.parentId, timestamp);\n\n return newItemId;\n }\n}\n"],"mappings":";;AA2BA,IAAa,gBAAb,MAAa,cAAc;CACzB;CAEA,YAAY,QAAgB;AAC1B,OAAK,SAAS;;;;;;;;CAShB,SAAS,QAAyC;AAEhD,MAAI,CADS,KAAK,OAAO,YAAY,IAAI,OAChC,CACP,OAAM,IAAI,MAAM,iBAAiB,OAAO,aAAa;EAIvD,MAAM,cAAc,KAAK,oBAAoB,OAAO;EAGpD,MAAM,QAAQ,YAAY,KAAK,OAAO;GACpC,MAAM,OAAO,KAAK,OAAO,YAAY,IAAI,GAAG;AAC5C,OAAI,CAAC,KAAM,OAAM,IAAI,MAAM,iBAAiB,GAAG,yBAAyB;AACxE,UAAO;IAAE,QAAQ;IAAI,UAAU,KAAK;IAAS;IAC7C;EAGF,MAAM,eAA6D,EAAE;AACrE,cAAY,SAAS,OAAO;AAC1B,OAAI;IACF,MAAM,mBAAmB,KAAK,OAAO,oBAAoB,GAAG;AAC5D,QAAI,kBAAkB,SAAS,QAAQ;KACrC,MAAM,yBAAiD,EAAE;AACzD,sBAAiB,QAAQ,SAAS,WAAW;MAC3C,MAAM,gBAAgB,iBAAiB,gBAAgB,OAAO;AAC9D,UAAI,cACF,wBAAuB,UAAU;OAEnC;AACF,kBAAa,M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AM;GACN,MAAM,sBAAsB,MAAM;GACnC,CACF,EACD;GACE,OAAO,iBAAiB;GACxB,QAAQ,aAAa;GACtB,CACF;;;;;CAMH,YAAY,SAAuB;EACjC,MAAM,gBAAgB,KAAK,QAAQ,SAAS,QAAQ;AACpD,MAAI,CAAC,cACH;AAEF,OAAK,QAAQ,YAAY,QAAQ;AACjC,OAAK,UAAU,kBACb,CACE;GACE;GACA,MAAM;GACP,CACF,EACD;GACE,OAAO,iBAAiB;GACxB,QAAQ,aAAa;GACtB,CACF;;;;;;;CAQH,SAAS,QAAyC;AAEhD,SAAO,IADe,cAAc,KAAK,QACzB,CAAC,SAAS,OAAO;;;;;;;;CASnC,UAAU,eAAwC,QAAwB;AACxE,OAAK,gBAAgB;EACrB,MAAM,YAAY,KAAK,uBAAuB;EAC9C,MAAM,qBAAqB,IAAI,IAAI,KAAK,QAAQ,YAAY,MAAM,CAAC;EAEnE,MAAM,YAAY,IADI,cAAc,KAAK,QACd,CAAC,UAAU,eAAe,OAAO;EAC5D,MAAM,gBAAgB,MAAM,KAAK,KAAK,QAAQ,YAAY,MAAM,CAAC,CAAC,QAC/D,WAAW,CAAC,mBAAmB,IAAI,OAAO,CAC5C;AAED,OAAK,MAAM,UAAU,eAAe;GAClC,MAAM,OAAO,KAAK,QAAQ,YAAY,IAAI,OAAO;AACjD,OAAI,MAAM;AACR,SAAK,aAAa,UAAU;AAC5B,SAAK,cAAc,UAAU;;;AAGjC,OAAK,0BAA0B,OAAO,UAAU,UAAU;AAE1D,SAAO"}
1
+ {"version":3,"file":"editor.mjs","names":[],"sources":["../src/editor/response-naming.ts","../src/editor/item-copy-paste.ts","../src/editor/undo-redo.ts","../src/editor/survey-editor.ts"],"sourcesContent":["import { getDefaultProjectionIssues, projectSlot } from \"../response-exporter/projection\";\nimport { Survey } from \"../survey/survey\";\nimport type { SurveyItemCore } from \"../survey/items\";\nimport {\n allocateResponseVariableName,\n isValidResponseVariableName,\n type OwnedResponseSlotDefinition,\n} from \"../survey/responses\";\n\nexport interface ResponseNameChange {\n slotId: string;\n itemId: string;\n before: string;\n after: string;\n}\nexport type ResponseNamingEdit =\n | { slotId: string; variableName: string }\n | {\n primitiveId: string;\n prefix?: string;\n rows?: Record<string, string>;\n columns?: Record<string, string>;\n };\n\nfunction readPath(config: unknown, path: readonly (string | number)[]): unknown {\n let current = config;\n for (const key of path) current = (current as Record<string | number, unknown>)?.[key];\n return current;\n}\nfunction writePath(config: unknown, path: readonly (string | number)[], value: string): void {\n if (\n !path.length ||\n path.some((key) => key === \"__proto__\" || key === \"constructor\" || key === \"prototype\")\n )\n throw new Error(\"Invalid response naming path\");\n const parent = readPath(config, path.slice(0, -1));\n if (!parent || typeof parent !== \"object\")\n throw new Error(\"Response naming declaration does not match its config\");\n (parent as Record<string | number, unknown>)[path.at(-1)!] = value;\n}\nconst assertName = (name: string) => {\n if (!isValidResponseVariableName(name))\n throw new Error(\n `Invalid variable name \"${name}\". Use lowercase snake_case, starting with a letter, at most 32 characters.`,\n );\n};\n\n/** Detached, validated preview; applying it uses the editor's ordinary mutation/history path. */\nfunction previewNaming(survey: Survey, edits: readonly ResponseNamingEdit[]) {\n const registry = survey.getResponseSlotRegistry();\n const raw = structuredClone(survey.serialize());\n const config = (slot: OwnedResponseSlotDefinition) =>\n raw.surveyItems.find((item) => item.id === slot.itemId)!.config;\n for (const edit of edits) {\n if (\"slotId\" in edit) {\n const slot = registry.get(edit.slotId);\n if (!slot) throw new Error(`Unknown response variable \"${edit.slotId}\"`);\n if (slot.naming?.kind === \"matrix\")\n throw new Error(\n \"Matrix cell names are derived; edit the matrix prefix or row/column coding names\",\n );\n if (!slot.naming)\n throw new Error(`The input owning \"${edit.slotId}\" does not expose a naming mutation`);\n assertName(edit.variableName);\n writePath(config(slot), slot.naming.path, edit.variableName);\n } else {\n const slots = registry.definitions.filter(\n (slot) => slot.primitiveId === edit.primitiveId && slot.naming?.kind === \"matrix\",\n );\n if (!slots.length) throw new Error(`Unknown matrix primitive \"${edit.primitiveId}\"`);\n for (const [ids, kind] of [\n [edit.rows, \"row\"],\n [edit.columns, \"column\"],\n ] as const) {\n for (const [id, name] of Object.entries(ids ?? {})) {\n assertName(name);\n const slot = slots.find((slot) =>\n kind === \"row\" ? slot.rowId === id : slot.columnId === id,\n );\n const naming = slot?.naming;\n const path =\n naming?.kind === \"matrix\"\n ? kind === \"row\"\n ? naming.rowPath\n : naming.columnPath\n : undefined;\n if (!slot || !path) throw new Error(`Unknown matrix ${kind} \"${id}\"`);\n writePath(config(slot), path, name);\n }\n }\n if (edit.prefix !== undefined) {\n assertName(edit.prefix);\n const slot = slots[0],\n naming = slot.naming;\n if (naming?.kind === \"matrix\") writePath(config(slot), naming.prefixPath, edit.prefix);\n }\n }\n }\n const next = Survey.fromJson(raw, survey.getPluginRegistry());\n const nextRegistry = next.getResponseSlotRegistry();\n const beforeIssues = new Set(registry.diagnostics.map((issue) => JSON.stringify(issue)));\n const issues = nextRegistry.diagnostics.filter(\n (issue) => !beforeIssues.has(JSON.stringify(issue)),\n );\n if (issues.length) throw new Error(issues.map((issue) => issue.message).join(\"\\n\"));\n const changes: ResponseNameChange[] = nextRegistry.definitions.flatMap((slot) => {\n const before = registry.get(slot.slotId)!.variableName;\n return before === slot.variableName\n ? []\n : [{ slotId: slot.slotId, itemId: slot.itemId, before, after: slot.variableName }];\n });\n return { survey: next.serialize(), changes };\n}\n\nfunction assertProjectionChanges(before: Survey, after: Survey): void {\n const existing = new Set(getDefaultProjectionIssues(before));\n const introduced = getDefaultProjectionIssues(after).filter((issue) => !existing.has(issue));\n if (introduced.length) throw new Error(introduced.join(\"\\n\"));\n}\n\nexport function previewResponseNaming(survey: Survey, edits: readonly ResponseNamingEdit[]) {\n const preview = previewNaming(survey, edits);\n assertProjectionChanges(survey, Survey.fromJson(preview.survey, survey.getPluginRegistry()));\n return preview;\n}\n\n/** Allocate whole matrix prefixes and individual names in deterministic declaration order. */\nexport function allocateCopiedResponseNames(\n survey: Survey,\n items: SurveyItemCore[],\n): ResponseNameChange[] {\n // Read declarations, including IDs omitted from an already ambiguous registry.\n const existingIds = new Set(\n survey.getResponseSlotDefinitions().flatMap(({ slots }) => slots.map((slot) => slot.slotId)),\n );\n for (const item of items)\n for (const slot of item.getResponseSlotDefinitions()) {\n if (existingIds.has(slot.slotId))\n throw new Error(`Inserted input must allocate a fresh slot identity: ${slot.slotId}`);\n existingIds.add(slot.slotId);\n }\n const used = new Set(\n survey.getResponseSlotRegistry().definitions.map((slot) => slot.variableName),\n );\n const usedPrefixes = new Set(\n survey\n .getResponseSlotRegistry()\n .definitions.flatMap((slot) =>\n slot.naming?.kind === \"matrix\"\n ? [String(readPath(survey.surveyItems.get(slot.itemId)!.config, slot.naming.prefixPath))]\n : [],\n ),\n );\n const changes: ResponseNameChange[] = [];\n for (const item of items) {\n const initial = item.getResponseSlotDefinitions();\n const groups = new Map<string, typeof initial>();\n for (const slot of initial) {\n const key =\n slot.naming?.kind === \"matrix\" ? JSON.stringify(slot.naming.prefixPath) : slot.slotId;\n groups.set(key, [...(groups.get(key) ?? []), slot]);\n }\n for (const group of groups.values()) {\n const first = group[0],\n naming = first.naming;\n const raw = structuredClone(item.rawItem);\n if (naming?.kind === \"matrix\") {\n const prefix = String(readPath(raw.config, naming.prefixPath));\n assertName(prefix);\n const tails = group.map((slot) => slot.variableName.slice(prefix.length));\n if (new Set(tails).size !== tails.length)\n throw new Error(\"Matrix coding components produce duplicate variable names\");\n let candidate = prefix;\n const blocked = new Set<string>();\n while (\n usedPrefixes.has(candidate) ||\n tails.some((tail) => used.has(`${candidate}${tail}`))\n ) {\n blocked.add(candidate);\n const longestTail = Math.max(...tails.map((tail) => tail.length));\n try {\n candidate = allocateResponseVariableName(prefix, blocked, 32 - longestTail);\n } catch {\n const longest = group[tails.findIndex((tail) => tail.length === longestTail)];\n throw new Error(\n `Cannot allocate a unique matrix prefix for \"${longest.variableName}\". Shorten its row or column coding name to leave room for a unique prefix within 32 characters.`,\n );\n }\n }\n usedPrefixes.add(candidate);\n if (candidate !== prefix) {\n writePath(raw.config, naming.prefixPath, candidate);\n item.updateRawItem(raw);\n }\n } else {\n assertName(first.variableName);\n const name = allocateResponseVariableName(first.variableName, used);\n if (name !== first.variableName) {\n if (!naming)\n throw new Error(\n `Cannot allocate a unique name for plugin variable \"${first.variableName}\"`,\n );\n writePath(raw.config, naming.path, name);\n item.updateRawItem(raw);\n }\n }\n for (const slot of item\n .getResponseSlotDefinitions()\n .filter((slot) => group.some((original) => original.slotId === slot.slotId))) {\n assertName(slot.variableName);\n used.add(slot.variableName);\n const before = initial.find((original) => original.slotId === slot.slotId)!.variableName;\n if (before !== slot.variableName)\n changes.push({ slotId: slot.slotId, itemId: item.id, before, after: slot.variableName });\n }\n }\n }\n return changes;\n}\n\nexport interface ResponseSettingsEdit {\n slotId: string;\n optionCodes?: Record<string, string>;\n exportSettings?: import(\"../response-exporter/types\").SlotTransformConfig;\n}\n\n/** Naming, categorical codes, and formats share one detached, atomic preview. */\nexport function previewResponseSettings(\n survey: Survey,\n naming: readonly ResponseNamingEdit[],\n settings: readonly ResponseSettingsEdit[],\n) {\n const preview = previewNaming(survey, naming);\n const raw = preview.survey;\n const registry = survey.getResponseSlotRegistry();\n const codeWrites = new Map<string, { code: string; slotId: string }>();\n for (const edit of settings) {\n const slot = registry.get(edit.slotId);\n if (!slot) throw new Error(`Unknown response variable \"${edit.slotId}\"`);\n const item = raw.surveyItems.find((item) => item.id === slot.itemId)!;\n for (const [id, code] of Object.entries(edit.optionCodes ?? {})) {\n const path = slot.optionCodePaths?.[id];\n if (!path) throw new Error(`Option \"${id}\" does not expose an export-code mutation`);\n if (!code.trim()) throw new Error(\"Option export codes cannot be empty\");\n const target = JSON.stringify([slot.itemId, path]);\n const previous = codeWrites.get(target);\n if (previous && previous.code !== code)\n throw new Error(\n `Conflicting export codes for shared option \"${id}\" on variables \"${registry.get(previous.slotId)!.variableName}\" and \"${slot.variableName}\". Supply one code for this shared option.`,\n );\n codeWrites.set(target, { code, slotId: slot.slotId });\n writePath(item.config, path, code);\n }\n if (edit.exportSettings)\n item.responseSettings = {\n ...item.responseSettings,\n [slot.slotId]: structuredClone(edit.exportSettings),\n };\n }\n const next = Survey.fromJson(raw, survey.getPluginRegistry());\n // Validate only affected variables so another unfinished input cannot block this edit.\n for (const slot of next\n .getResponseSlotRegistry()\n .definitions.filter((slot) => settings.some((edit) => edit.slotId === slot.slotId))) {\n projectSlot(slot, { mode: \"default\", ...slot.exportSettings });\n }\n assertProjectionChanges(survey, next);\n return { ...preview, survey: next.serialize() };\n}\n","import { allocateCopiedResponseNames, type ResponseNameChange } from \"./response-naming\";\nimport type { JsonExpression } from \"../expressions/expression\";\nimport { Survey } from \"../survey/survey\";\nimport { SurveyItemCore } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport { ReservedSurveyItemTypes } from \"../survey/items/types\";\nimport { SurveyItemTranslations, JsonComponentContent } from \"../survey/utils\";\nimport { RawSurveyItem } from \"../survey/items/survey-item-json\";\nimport { Target } from \"./types\";\nimport { generateId } from \"../utils\";\nimport { ValueType } from \"../survey/responses/value-types\";\nimport { ExpressionType } from \"../expressions/expression\";\n\n// Serialized translation data format for clipboard\nexport type SerializedTranslations = {\n [locale: string]: JsonComponentContent;\n};\n\n// Clipboard data structure for copy-paste functionality\nexport interface SurveyItemClipboardData {\n type: \"survey-item\";\n version: string;\n items: Array<{\n itemId: string;\n itemData: RawSurveyItem;\n }>;\n translations: { [itemId: string]: SerializedTranslations };\n rootItemId: string; // The id of the main item being copied\n timestamp: number;\n}\n\nexport class ItemCopyPaste {\n lastResponseNameChanges: ResponseNameChange[] = [];\n private survey: Survey;\n\n constructor(survey: Survey) {\n this.survey = survey;\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * When copying a group, automatically includes all items in the subtree\n * @param itemId - The id of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const item = this.survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Collect all items to copy (including subtree for groups)\n const itemsToCopy = this.collectItemsForCopy(itemId);\n\n // Create items array with their data\n const items = itemsToCopy.map((id) => {\n const item = this.survey.surveyItems.get(id);\n if (!item) throw new Error(`Item with id '${id}' not found during copy`);\n return { itemId: id, itemData: item.rawItem };\n });\n\n // Collect translations for all items\n const translations: { [itemId: string]: SerializedTranslations } = Object.create(null);\n itemsToCopy.forEach((id) => {\n try {\n const itemTranslations = this.survey.getItemTranslations(id);\n if (itemTranslations?.locales?.length) {\n const serializedTranslations: SerializedTranslations = Object.create(null);\n itemTranslations.locales.forEach((locale) => {\n const localeContent = itemTranslations.getAllForLocale(locale);\n if (localeContent) {\n serializedTranslations[locale] = localeContent;\n }\n });\n translations[id] = serializedTranslations;\n } else {\n translations[id] = {};\n }\n } catch {\n translations[id] = {};\n }\n });\n\n // Create clipboard data\n const clipboardData: SurveyItemClipboardData = {\n type: \"survey-item\",\n version: \"1.0.0\",\n items: items,\n translations: translations,\n rootItemId: itemId,\n timestamp: Date.now(),\n };\n\n return clipboardData;\n }\n\n /**\n * Collect all items that should be copied, including subtree for groups\n * @param itemId - The root item id\n * @returns Array of item keys to copy\n */\n private collectItemsForCopy(itemId: string): string[] {\n const itemsToCopy: string[] = [itemId];\n const item = this.survey.surveyItems.get(itemId);\n\n if (!item) {\n return [];\n }\n\n // If this is a group item, collect all child items recursively\n if (item instanceof GroupItemCore) {\n const childIds = item.items;\n if (childIds.length > 0) {\n childIds.forEach((childId) => {\n const childItems = this.collectItemsForCopy(childId);\n itemsToCopy.push(...childItems);\n });\n }\n }\n\n return itemsToCopy;\n }\n\n /**\n * Add an item to its parent group.\n * Ensures key uniqueness among siblings.\n * @param target - Target location information\n * @param item - The item to add (may have key adjusted for uniqueness)\n */\n private addItemToParentGroup(target: Target, item: SurveyItemCore): void {\n const parentGroup = this.survey.surveyItems.get(target.parentId);\n\n if (!parentGroup) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(parentGroup instanceof GroupItemCore)) {\n throw new Error(`Parent item '${target.parentId}' is not a group item`);\n }\n\n const insertIndex =\n target.index !== undefined\n ? Math.min(target.index, parentGroup.items.length)\n : parentGroup.items.length;\n\n parentGroup.addChild(item.id, insertIndex);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * Handles multiple items and subtrees from the clipboard data\n * @param clipboardData - The clipboard data containing the item(s) to paste\n * @param target - Target location where to paste the item\n * @returns The id of the pasted root item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n // Validate clipboard data\n if (!ItemCopyPaste.isValidClipboardData(clipboardData)) {\n throw new Error(\"Invalid clipboard data format\");\n }\n\n const itemIds = new Set<string>();\n for (const { itemId, itemData } of clipboardData.items) {\n if (itemIds.has(itemId) || itemId !== itemData.id)\n throw new Error(`Ambiguous clipboard item identity: ${itemId}`);\n itemIds.add(itemId);\n }\n if (!itemIds.has(clipboardData.rootItemId)) throw new Error(\"Clipboard root item is missing\");\n const parent = this.survey.surveyItems.get(target.parentId);\n if (!(parent instanceof GroupItemCore))\n throw new Error(`Paste target '${target.parentId}' must be a group item`);\n\n // Create id mapping for all items in the subtree\n const idMapping: { [oldId: string]: string } = Object.create(null);\n clipboardData.items.forEach(({ itemId }) => {\n idMapping[itemId] = generateId();\n });\n\n const componentMapping: Record<string, string> = Object.create(null);\n const copiedSlotIds = new Set<string>();\n clipboardData.items.forEach(({ itemData }) => {\n const item = this.survey.createItemFromRaw(itemData);\n for (const slot of item.getResponseSlotDefinitions()) {\n if (copiedSlotIds.has(slot.slotId))\n throw new Error(`Duplicate copied slot ID: ${slot.slotId}`);\n copiedSlotIds.add(slot.slotId);\n }\n const declaredIds = item\n .getResponseSlotDefinitions()\n .flatMap((slot) =>\n [slot.slotId, slot.primitiveId, slot.rowId, slot.columnId].filter(\n (id): id is string => !!id,\n ),\n );\n for (const id of new Set(\n [...item.getOwnedComponentIds(), ...declaredIds].filter((id) => id !== item.id),\n )) {\n if (componentMapping[id]) throw new Error(`Duplicate owned component ID: ${id}`);\n componentMapping[id] = generateId();\n }\n });\n // Parse every copied item before mutating the destination survey.\n const stagedItems = clipboardData.items.map(({ itemId, itemData }) => {\n const newId = idMapping[itemId];\n if (newId) {\n const updatedItemData = this.updateItemIdsInData(itemData, idMapping, componentMapping);\n updatedItemData.id = newId;\n\n const newItem = this.survey.createItemFromRaw(updatedItemData);\n return newItem;\n }\n throw new Error(`Missing copied identity for '${itemId}'`);\n });\n this.lastResponseNameChanges = allocateCopiedResponseNames(this.survey, stagedItems);\n for (const item of stagedItems) this.survey.surveyItems.set(item.id, item);\n this.addItemToParentGroup(\n target,\n stagedItems.find((item) => item.id === idMapping[clipboardData.rootItemId])!,\n );\n\n // Update translations with new IDs\n const updatedTranslations = this.updateTranslations(\n clipboardData.translations,\n idMapping,\n componentMapping,\n );\n Object.keys(updatedTranslations).forEach((itemId) => {\n // Convert serialized translations back to SurveyItemTranslations instance\n const itemTranslations = new SurveyItemTranslations();\n const serializedData = updatedTranslations[itemId];\n Object.keys(serializedData).forEach((locale) => {\n itemTranslations.setAllForLocale(locale, serializedData[locale]);\n });\n this.survey.translations.setItemTranslations(itemId, itemTranslations);\n });\n\n return idMapping[clipboardData.rootItemId];\n }\n\n // PRIVATE HELPER METHODS\n /**\n * Update all item ids in the raw item data recursively\n */\n private updateItemIdsInData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n componentMapping: Record<string, string>,\n ): RawSurveyItem {\n const updatedData = JSON.parse(JSON.stringify(itemData));\n\n if (updatedData.itemType === ReservedSurveyItemTypes.Group && updatedData.config) {\n const config = updatedData.config as { items?: string[] };\n if (config.items) {\n config.items = config.items.map((childId: string) => idMapping[childId] ?? childId);\n }\n }\n\n // Only declared component identities are rewritten, including slot/option references.\n const remap = (value: unknown, key?: string): unknown => {\n if (typeof value === \"string\") {\n if (\n [\n \"key\",\n \"prefix\",\n \"variableName\",\n \"rowName\",\n \"columnName\",\n \"code\",\n \"label\",\n \"description\",\n \"errorMessage\",\n \"placeholder\",\n \"unit\",\n ].includes(key ?? \"\")\n )\n return value;\n if ((key === \"id\" || key === \"slotId\") && idMapping[value]) return idMapping[value];\n return componentMapping[value] ?? value;\n }\n if (Array.isArray(value)) return value.map((entry) => remap(entry));\n if (\n value &&\n typeof value === \"object\" &&\n (value as { type?: string }).type === \"previousResponse\"\n )\n return structuredClone(value);\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n componentMapping[name] ?? idMapping[name] ?? name,\n // Stored strings (including dropdown codes) are values, not component references.\n name === \"value\" &&\n (typeof entry === \"string\" || Array.isArray(entry)) &&\n (value as { type?: unknown }).type !== ValueType.reference &&\n (value as { type?: unknown }).type !== ValueType.referenceArray\n ? entry\n : remap(entry, name),\n ]),\n );\n return value;\n };\n updatedData.config = remap(updatedData.config);\n if (updatedData.responseSettings)\n updatedData.responseSettings = Object.fromEntries(\n Object.entries(updatedData.responseSettings).map(([slotId, settings]) => {\n const value = structuredClone(\n settings,\n ) as import(\"../response-exporter/types\").SlotTransformConfig;\n for (const name of [\"optionCodes\", \"optionLabels\"] as const)\n if (value[name])\n value[name] = Object.fromEntries(\n Object.entries(value[name]!).map(([id, code]) => [\n componentMapping[id] ?? id,\n code,\n ]),\n );\n return [componentMapping[slotId] ?? idMapping[slotId] ?? slotId, value];\n }),\n );\n if (Object.keys(componentMapping).length) {\n updatedData.displayConditions = remap(updatedData.displayConditions);\n updatedData.disabledConditions = remap(updatedData.disabledConditions);\n updatedData.validations = remap(updatedData.validations);\n updatedData.prefills = remap(updatedData.prefills);\n }\n this.updateExpressionsInItemData(updatedData, idMapping);\n return updatedData;\n }\n\n /**\n * Update expressions in item data that reference the old ids\n */\n private updateExpressionsInItemData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n ): void {\n const visitBounds = (value: unknown): void => {\n if (!value || typeof value !== \"object\") return;\n for (const [key, child] of Object.entries(value)) {\n if (key === \"valueExpression\" && child && typeof child === \"object\")\n this.updateExpressionReferences(child as JsonExpression, idMapping);\n else visitBounds(child);\n }\n };\n visitBounds(itemData.config);\n // Update display conditions\n if (itemData.displayConditions?.root) {\n this.updateExpressionReferences(itemData.displayConditions.root, idMapping);\n }\n if (itemData.displayConditions?.components) {\n Object.values(itemData.displayConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update disabled conditions\n if (itemData.disabledConditions?.components) {\n Object.values(itemData.disabledConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update validations\n if (itemData.validations) {\n Object.values(itemData.validations).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n if (itemData.prefills) {\n itemData.prefills.forEach((prefill) => {\n if (prefill.when) {\n this.updateExpressionReferences(prefill.when, idMapping);\n }\n\n if (prefill.source.type === \"expression\") {\n this.updateExpressionReferences(prefill.source.expression, idMapping);\n }\n\n // Previous-response sources belong to a host-supplied historical schema.\n // Copying a draft must preserve those external slot identities.\n });\n }\n }\n\n /**\n * Update references in a single expression (recursive)\n */\n private updateExpressionReferences(\n expression: unknown,\n idMapping: { [oldId: string]: string },\n ): void {\n if (!expression || typeof expression !== \"object\") {\n return;\n }\n\n const expr = expression as Record<string, unknown>;\n if (\n expr.type === ExpressionType.ResponseVariable &&\n expr.variableRef &&\n typeof expr.variableRef === \"object\"\n ) {\n const reference = expr.variableRef as { slotId?: string };\n if (reference.slotId && Object.prototype.hasOwnProperty.call(idMapping, reference.slotId))\n reference.slotId = idMapping[reference.slotId];\n }\n if (Array.isArray(expr.data)) {\n expr.data.forEach((arg: unknown) => {\n if (arg && typeof arg === \"object\" && arg !== null && \"str\" in arg) {\n const argObj = arg as { str?: string };\n if (\n typeof argObj.str === \"string\" &&\n Object.prototype.hasOwnProperty.call(idMapping, argObj.str)\n ) {\n argObj.str = idMapping[argObj.str];\n }\n this.updateExpressionReferences(arg, idMapping);\n }\n });\n }\n\n Object.keys(expr).forEach((key) => {\n const val = expr[key];\n if (val && typeof val === \"object\") {\n this.updateExpressionReferences(val, idMapping);\n }\n });\n }\n\n /**\n * Update translation keys for the pasted item\n */\n private updateTranslations(\n translations: { [itemId: string]: SerializedTranslations },\n idMapping: { [oldId: string]: string },\n componentMapping: Record<string, string>,\n ): { [itemId: string]: SerializedTranslations } {\n const newTranslations: { [itemId: string]: SerializedTranslations } = Object.create(null);\n\n // Update ids for all items in the translation data\n Object.keys(translations).forEach((itemId) => {\n const itemTranslations = translations[itemId];\n\n // Determine the new key for this item (update the key mapping)\n const newItemId = idMapping[itemId];\n\n // Copy the serialized translations as-is (content is preserved, only keys change)\n newTranslations[newItemId] = Object.fromEntries(\n Object.entries(itemTranslations).map(([locale, content]) => [\n locale,\n Object.fromEntries(\n Object.entries(content).map(([key, value]) => [\n key\n .split(\".\")\n .map((part) => componentMapping[part] ?? part)\n .join(\".\"),\n value,\n ]),\n ),\n ]),\n );\n });\n\n return newTranslations;\n }\n\n /**\n * Validate clipboard data format\n */\n static isValidClipboardData(data: unknown): data is SurveyItemClipboardData {\n if (typeof data !== \"object\" || data === null || data === undefined) return false;\n const clipboardData = data as SurveyItemClipboardData;\n\n if (\n clipboardData.rootItemId === undefined ||\n typeof clipboardData.rootItemId !== \"string\" ||\n !Array.isArray(clipboardData.items) ||\n clipboardData.items.length === 0 ||\n typeof clipboardData.translations !== \"object\" ||\n clipboardData.translations === null ||\n Array.isArray(clipboardData.translations)\n ) {\n return false;\n }\n\n return (\n clipboardData.type === \"survey-item\" &&\n clipboardData.version === \"1.0.0\" &&\n clipboardData.items.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n typeof item.itemId === \"string\" &&\n item.itemId.length > 0 &&\n typeof item.itemData === \"object\" &&\n item.itemData !== null &&\n !Array.isArray(item.itemData) &&\n typeof item.itemData.itemType === \"string\",\n ) &&\n clipboardData.items.some((item) => item.itemId === clipboardData.rootItemId)\n );\n }\n}\n","import { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { generateId, structuredCloneMethod } from \"../utils\";\n\nexport interface UndoRedoConfig {\n maxTotalMemoryMB: number;\n minHistorySize: number;\n maxHistorySize: number;\n}\n\nexport const CommitSource = {\n USER: \"user\",\n SYSTEM: \"system\",\n ASSISTANT: \"assistant\",\n} as const;\nexport type CommitSource = (typeof CommitSource)[keyof typeof CommitSource];\n\nexport interface CommitMeta {\n label: string;\n source?: CommitSource;\n}\n\nexport interface AssetPatch {\n assetId: string;\n prev?: RawSurveyAsset;\n next?: RawSurveyAsset;\n}\n\ninterface BaseHistoryEntry {\n id?: string;\n timestamp: number;\n meta: CommitMeta;\n memorySize: number;\n}\n\ninterface SurveySnapshotHistoryEntry extends BaseHistoryEntry {\n kind: \"survey-snapshot\";\n survey: RawSurvey;\n}\n\ninterface AssetChangeHistoryEntry extends BaseHistoryEntry {\n kind: \"asset-change\";\n changes: AssetPatch[];\n}\n\ntype HistoryEntry = SurveySnapshotHistoryEntry | AssetChangeHistoryEntry;\ntype PendingHistoryEntry =\n | Omit<SurveySnapshotHistoryEntry, \"timestamp\" | \"memorySize\">\n | Omit<AssetChangeHistoryEntry, \"timestamp\" | \"memorySize\">;\n\nexport interface SurveyEditorHistoryCommit {\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n}\n\ntype SerializedHistoryEntry =\n | SurveySnapshotHistoryEntry\n | AssetChangeHistoryEntry\n | (BaseHistoryEntry & { survey: RawSurvey });\n\n// Memory calculation utilities\nclass MemoryCalculator {\n private static encoder = new TextEncoder();\n\n static calculateSize(obj: object): number {\n const jsonString = JSON.stringify(obj);\n return this.encoder.encode(jsonString).length;\n }\n\n static formatBytes(bytes: number): string {\n const units = [\"B\", \"KB\", \"MB\", \"GB\"];\n let size = bytes;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n}\n\nfunction cloneAssets(\n assets?: Record<string, RawSurveyAsset>,\n): Record<string, RawSurveyAsset> | undefined {\n if (!assets || Object.keys(assets).length === 0) {\n return undefined;\n }\n return structuredCloneMethod(assets);\n}\n\nfunction normalizeHistoryEntry(entry: SerializedHistoryEntry): HistoryEntry {\n if (\"kind\" in entry) {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: structuredCloneMethod(entry.changes),\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n}\n\nexport class SurveyEditorUndoRedo {\n private history: HistoryEntry[] = [];\n private currentIndex: number = -1;\n private _config: UndoRedoConfig;\n private baseAssetSize?: number;\n private _initialAssets?: Record<string, RawSurveyAsset>;\n\n constructor(\n initialSurvey: RawSurvey,\n config: Partial<UndoRedoConfig> = {},\n meta: CommitMeta = { label: \"Initial state\", source: CommitSource.SYSTEM },\n initialAssets?: Record<string, RawSurveyAsset>,\n ) {\n this._config = {\n maxTotalMemoryMB: 50,\n minHistorySize: 10,\n maxHistorySize: 200,\n ...config,\n };\n this._initialAssets = cloneAssets(initialAssets);\n\n this.saveSnapshot(initialSurvey, meta);\n }\n\n private saveEntry(entry: PendingHistoryEntry): void {\n const payload =\n entry.kind === \"survey-snapshot\"\n ? { kind: entry.kind, survey: entry.survey }\n : { kind: entry.kind, changes: entry.changes };\n\n const memorySize = MemoryCalculator.calculateSize(payload);\n\n // Remove any history after current index\n this.history = this.history.slice(0, this.currentIndex + 1);\n\n this.history.push({\n ...structuredCloneMethod(entry),\n id: generateId(),\n timestamp: Date.now(),\n memorySize,\n } as HistoryEntry);\n\n this.currentIndex++;\n\n // Clean up history based on memory usage\n this.cleanupHistory();\n }\n\n private saveSnapshot(survey: RawSurvey, meta: CommitMeta): void {\n this.saveEntry({\n kind: \"survey-snapshot\",\n survey,\n meta,\n });\n }\n\n private getBaseAssetsSize(): number {\n return (this.baseAssetSize ??= this._initialAssets\n ? MemoryCalculator.calculateSize(this._initialAssets)\n : 0);\n }\n\n private cleanupHistory(): void {\n const maxMemoryBytes = this._config.maxTotalMemoryMB * 1024 * 1024;\n\n // Remove oldest states while preserving minimum.\n while (\n this.history.length > this._config.minHistorySize &&\n (this.getTotalMemoryUsage() > maxMemoryBytes ||\n this.history.length > this._config.maxHistorySize)\n ) {\n if (this.dropOldestState() <= 0) {\n break;\n }\n }\n }\n\n private dropOldestState(): number {\n if (this.history.length <= 1) {\n return 0;\n }\n\n const nextStateIndex = 1;\n const nextStateSurvey = this.getStateAtIndex(nextStateIndex);\n const nextStateAssets = this.getAssetsAtIndex(nextStateIndex);\n const nextEntry = this.history[nextStateIndex];\n\n const newFirstEntry: SurveySnapshotHistoryEntry = {\n kind: \"survey-snapshot\",\n id: nextEntry.id,\n survey: nextStateSurvey,\n meta: nextEntry.meta,\n timestamp: nextEntry.timestamp,\n memorySize: MemoryCalculator.calculateSize({\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n }),\n };\n\n const removedBytes = this.history[0].memorySize;\n\n this._initialAssets = nextStateAssets;\n this.baseAssetSize = undefined;\n this.history = [newFirstEntry, ...this.history.slice(nextStateIndex + 1)];\n this.currentIndex--;\n\n return removedBytes;\n }\n\n private getTotalMemoryUsage(): number {\n return (\n this.getBaseAssetsSize() + this.history.reduce((total, entry) => total + entry.memorySize, 0)\n );\n }\n\n private getStateAtIndex(index: number): RawSurvey {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n for (let i = index; i >= 0; i--) {\n const entry = this.history[i];\n if (entry.kind === \"survey-snapshot\") {\n return structuredCloneMethod(entry.survey);\n }\n }\n\n throw new Error(\"Invalid history state\");\n }\n\n private applyAssetPatch(\n assets: Record<string, RawSurveyAsset>,\n patch: AssetPatch,\n ): Record<string, RawSurveyAsset> {\n const nextAssets = assets;\n if (patch.next) {\n nextAssets[patch.assetId] = structuredCloneMethod(patch.next);\n } else {\n delete nextAssets[patch.assetId];\n }\n return nextAssets;\n }\n\n private getAssetsAtIndex(index: number): Record<string, RawSurveyAsset> | undefined {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n let assets = cloneAssets(this._initialAssets) ?? {};\n\n for (let i = 1; i <= index; i++) {\n const entry = this.history[i];\n if (entry.kind !== \"asset-change\") {\n continue;\n }\n\n for (const patch of entry.changes) {\n assets = this.applyAssetPatch(assets, patch);\n }\n }\n\n return Object.keys(assets).length > 0 ? assets : undefined;\n }\n\n getEntryId(index: number): string | undefined {\n return this.history[index]?.id;\n }\n\n findEntryIndex(id: string): number {\n return this.history.findIndex((entry) => entry.id === id);\n }\n\n // Commit a change to history\n commit(survey: RawSurvey, meta: CommitMeta): void {\n this.saveSnapshot(survey, meta);\n }\n\n commitAssetChange(changes: AssetPatch[], meta: CommitMeta): void {\n if (changes.length === 0) {\n return;\n }\n\n this.saveEntry({\n kind: \"asset-change\",\n changes: structuredCloneMethod(changes),\n meta,\n });\n }\n\n // Get current committed state\n getCurrentState(): RawSurvey {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getStateAtIndex(this.currentIndex);\n }\n\n getCurrentAssets(): Record<string, RawSurveyAsset> | undefined {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getAssetsAtIndex(this.currentIndex);\n }\n\n undo(): RawSurvey | null {\n if (!this.canUndo()) return null;\n\n this.currentIndex--;\n return this.getCurrentState();\n }\n\n redo(): RawSurvey | null {\n if (!this.canRedo()) return null;\n\n this.currentIndex++;\n return this.getCurrentState();\n }\n\n canUndo(): boolean {\n return this.currentIndex > 0;\n }\n\n canRedo(): boolean {\n return this.currentIndex < this.history.length - 1;\n }\n\n getUndoMeta(): CommitMeta | null {\n if (!this.canUndo()) return null;\n return this.history[this.currentIndex].meta;\n }\n\n getRedoMeta(): CommitMeta | null {\n if (!this.canRedo()) return null;\n return this.history[this.currentIndex + 1].meta;\n }\n\n getMemoryUsage(): { totalMB: number; entries: number } {\n return {\n totalMB: this.getTotalMemoryUsage() / (1024 * 1024),\n entries: this.history.length,\n };\n }\n\n getConfig(): UndoRedoConfig {\n return { ...this._config };\n }\n\n /**\n * Get the full history list with metadata\n */\n getHistory(): Array<{\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n }> {\n return this.history.map((entry, index) => ({\n index,\n kind: entry.kind,\n meta: entry.meta,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n }));\n }\n\n /**\n * Get committed history entries after the initial state up to the current index.\n *\n * Redo-only future entries are intentionally omitted so the returned list describes the active\n * change chain from the initial state to the current editor state.\n */\n getCommitsSinceInitial(): SurveyEditorHistoryCommit[] {\n return this.history.slice(1, this.currentIndex + 1).map((entry, offset) => {\n const index = offset + 1;\n return {\n index,\n kind: entry.kind,\n meta: entry.meta,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n };\n });\n }\n\n /**\n * Get the current index in the history\n */\n getCurrentIndex(): number {\n return this.currentIndex;\n }\n\n /**\n * Get the total number of history entries\n */\n getHistoryLength(): number {\n return this.history.length;\n }\n\n /**\n * Jump to a specific index in the history (can go forward or backward)\n * @param targetIndex The index to jump to\n * @returns The survey state at the target index, or null if invalid\n */\n jumpToIndex(targetIndex: number): RawSurvey | null {\n if (\n targetIndex < 0 ||\n targetIndex >= this.history.length ||\n targetIndex === this.currentIndex\n ) {\n return null;\n }\n\n this.currentIndex = targetIndex;\n return this.getCurrentState();\n }\n\n /**\n * Check if we can jump to a specific index\n */\n canJumpToIndex(targetIndex: number): boolean {\n return (\n targetIndex >= 0 && targetIndex < this.history.length && targetIndex !== this.currentIndex\n );\n }\n\n /**\n * Serialize the undo/redo state to JSON\n * @returns A JSON-serializable object containing the complete state\n */\n serialize(): {\n history: Array<HistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n } {\n return {\n history: this.history.map((entry) => {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: entry.survey,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: entry.changes,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }),\n currentIndex: this.currentIndex,\n config: { ...this._config },\n initialAssets: cloneAssets(this._initialAssets),\n };\n }\n\n /**\n * Create a new SurveyEditorUndoRedo instance from JSON data\n * @param jsonData The serialized undo/redo state\n * @returns A new SurveyEditorUndoRedo instance with the restored state\n */\n static deserialize(\n jsonData: {\n history: Array<SerializedHistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n },\n initialAssetsOverride?: Record<string, RawSurveyAsset>,\n ): SurveyEditorUndoRedo {\n if (!jsonData.history || !Array.isArray(jsonData.history) || jsonData.history.length === 0) {\n throw new Error(\"Invalid object: history must be an array and must not be empty\");\n }\n\n if (\n typeof jsonData.currentIndex !== \"number\" ||\n jsonData.currentIndex < 0 ||\n jsonData.currentIndex >= jsonData.history.length\n ) {\n throw new Error(\n \"Invalid object: currentIndex must be a valid index within the history array\",\n );\n }\n\n if (!jsonData.config) {\n throw new Error(\"Invalid object: config is required\");\n }\n\n const normalizedHistory = jsonData.history.map(normalizeHistoryEntry);\n\n // Create a new instance with the first survey and config\n const firstEntry = normalizedHistory[0];\n const firstSurvey =\n firstEntry.kind === \"survey-snapshot\"\n ? firstEntry.survey\n : (() => {\n throw new Error(\n \"Invalid object: first history entry must resolve to a survey snapshot\",\n );\n })();\n\n const instance = new SurveyEditorUndoRedo(\n firstSurvey,\n jsonData.config,\n firstEntry.meta,\n initialAssetsOverride ?? jsonData.initialAssets,\n );\n\n // Clear the default initial state and restore the full history\n instance.history = normalizedHistory;\n instance.currentIndex = jsonData.currentIndex;\n instance._initialAssets = cloneAssets(initialAssetsOverride ?? jsonData.initialAssets);\n\n return instance;\n }\n}\n","import { getDefaultProjectionIssues } from \"../response-exporter/projection\";\nimport {\n allocateCopiedResponseNames,\n previewResponseNaming,\n previewResponseSettings,\n type ResponseSettingsEdit,\n type ResponseNamingEdit,\n type ResponseNameChange,\n} from \"./response-naming\";\nimport { Survey } from \"../survey/survey\";\nimport { CommitMeta, CommitSource, SurveyEditorUndoRedo, type UndoRedoConfig } from \"./undo-redo\";\nimport {\n SurveyItemTranslations,\n SurveyCardContent,\n NavigationContent,\n Content,\n} from \"../survey/utils\";\nimport { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { ItemCopyPaste, SurveyItemClipboardData } from \"./item-copy-paste\";\nimport { Target } from \"./types\";\nimport { SurveyItemCore, RawSurveyItem } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport type { ItemTypeRegistry } from \"../survey/registry/item-registry\";\nimport type { TemplateValueDefinition } from \"../expressions/template-value\";\nimport { structuredCloneMethod } from \"../utils\";\n\n// Interface for serializing SurveyEditor state\nexport interface SerializedSurveyEditor {\n version: string;\n survey: RawSurvey;\n undoRedo: ReturnType<SurveyEditorUndoRedo[\"serialize\"]>;\n hasUncommittedChanges: boolean;\n}\n\nexport interface SurveyEditorConfig extends Partial<UndoRedoConfig> {\n /** Plugin registry for deserializing survey state during undo/redo. Required when survey contains custom item types. */\n pluginRegistry?: ItemTypeRegistry;\n}\n\nfunction stripAssetsFromSurveySnapshot(survey: RawSurvey): RawSurvey {\n const { assets: _assets, ...snapshot } = survey;\n void _assets;\n return snapshot;\n}\n\nfunction mergeSurveySnapshotWithAssets(\n snapshot: RawSurvey,\n assets?: RawSurvey[\"assets\"],\n): RawSurvey {\n const merged = structuredCloneMethod(snapshot);\n\n if (assets && Object.keys(assets).length > 0) {\n merged.assets = structuredCloneMethod(assets);\n } else {\n delete merged.assets;\n }\n\n return merged;\n}\n\nexport class SurveyEditor {\n lastResponseNameChanges: ResponseNameChange[] = [];\n\n renameResponseVariables(edits: readonly ResponseNamingEdit[]): ResponseNameChange[] {\n const preview = previewResponseNaming(this._survey, edits);\n if (!preview.changes.length) return [];\n const next = Survey.fromJson(preview.survey, this._survey.getPluginRegistry());\n this._survey = next;\n for (const id of new Set(preview.changes.map((change) => change.itemId)))\n this.touchItemModifiedMetadata(id, this.createEditorTimestamp());\n this.lastResponseNameChanges = preview.changes;\n this.markAsModified();\n return preview.changes;\n }\n\n updateResponseSettings(\n naming: readonly ResponseNamingEdit[],\n settings: readonly ResponseSettingsEdit[],\n ): ResponseNameChange[] {\n const preview = previewResponseSettings(this._survey, naming, settings);\n this._survey = Survey.fromJson(preview.survey, this._survey.getPluginRegistry());\n const changedItems = new Set([\n ...preview.changes.map((change) => change.itemId),\n ...settings.map((edit) => this._survey.getResponseSlotRegistry().get(edit.slotId)!.itemId),\n ]);\n for (const itemId of changedItems)\n this.touchItemModifiedMetadata(itemId, this.createEditorTimestamp());\n this.lastResponseNameChanges = preview.changes;\n this.markAsModified();\n return preview.changes;\n }\n\n private _survey: Survey;\n private _undoRedo: SurveyEditorUndoRedo;\n private _hasUncommittedChanges: boolean = false;\n private mutationEpoch = 0;\n private pendingAssets = new Map<string, { prev?: RawSurveyAsset; next?: RawSurveyAsset }>();\n private _pluginRegistry?: ItemTypeRegistry;\n\n constructor(survey: Survey, config: SurveyEditorConfig = {}, meta?: CommitMeta) {\n this._survey = survey;\n const { pluginRegistry, ...undoRedoConfig } = config;\n this._pluginRegistry = pluginRegistry ?? survey.getPluginRegistry();\n const serialized = survey.serialize();\n this._undoRedo = new SurveyEditorUndoRedo(\n stripAssetsFromSurveySnapshot(serialized),\n undoRedoConfig,\n meta,\n serialized.assets,\n );\n }\n\n /**\n * An isolated field edit owns only its field value (held by the caller) and\n * affected item metadata. Any intervening core action invalidates this handle.\n * The caller must finish pre-existing work before opening a handle.\n */\n beginFieldEdit(itemId?: string): {\n run: <T>(write: () => T) => T;\n reconcile: (restoreValue?: () => void) => boolean;\n } {\n if (this.hasUncommittedChanges)\n throw new Error(\"Finish pending changes before editing a field\");\n let expectedEpoch = this.mutationEpoch;\n const history = this._undoRedo;\n const index = history.getCurrentIndex();\n const locales = this._survey.translations.locales;\n const metadata = itemId\n ? structuredCloneMethod(this._survey.surveyItems.get(itemId)?.rawItem.editorMetadata)\n : undefined;\n const owns = () =>\n this.mutationEpoch === expectedEpoch &&\n this._undoRedo === history &&\n history.getCurrentIndex() === index;\n return {\n run: <T>(write: () => T): T => {\n if (!owns()) throw new Error(\"Field edit was superseded by another action\");\n const result = write();\n expectedEpoch = this.mutationEpoch;\n return result;\n },\n reconcile: (restoreValue) => {\n if (!owns()) return false;\n restoreValue?.();\n if (itemId) {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) return false;\n this._survey.surveyItems.set(\n itemId,\n this._survey.createItemFromRaw({\n ...item.rawItem,\n editorMetadata: structuredCloneMethod(metadata),\n }),\n );\n }\n for (const locale of this._survey.translations.locales) {\n if (!locales.includes(locale)) {\n const data = this._survey.translations.serialize()?.[locale];\n if (\n data &&\n !data.surveyCardContent &&\n !data.navigationContent &&\n !data.validationMessages &&\n Object.keys(data.itemTranslations ?? {}).length === 0\n )\n this._survey.translations.removeLocale(locale);\n }\n }\n this._hasUncommittedChanges = false;\n this.mutationEpoch++;\n expectedEpoch = this.mutationEpoch;\n return true;\n },\n };\n }\n\n get hasCommittedChanges(): boolean {\n return this._undoRedo.getCurrentIndex() > 0;\n }\n\n /** Returns an immutable copy of the current survey state. */\n get survey(): Survey {\n const serialized = structuredCloneMethod(this._survey.serialize());\n const registry = this._pluginRegistry ?? this._survey.getPluginRegistry();\n return Survey.fromJson(serialized, registry);\n }\n\n get hasUncommittedChanges(): boolean {\n return this._hasUncommittedChanges || this.pendingAssets.size > 0;\n }\n\n // Expose the undo-redo instance directly\n get undoRedo(): SurveyEditorUndoRedo {\n return this._undoRedo;\n }\n\n // Commit current changes to undo/redo history\n commit(meta: CommitMeta): void {\n if (!this.hasUncommittedChanges) return;\n this.mutationEpoch++;\n if (this._hasUncommittedChanges) {\n this._undoRedo.commit(stripAssetsFromSurveySnapshot(this._survey.serialize()), meta);\n }\n if (this.pendingAssets.size) {\n this._undoRedo.commitAssetChange(\n [...this.pendingAssets].map(([assetId, patch]) => ({ assetId, ...patch })),\n meta,\n );\n this.pendingAssets.clear();\n }\n this._hasUncommittedChanges = false;\n }\n\n private restoreHistoryState(snapshot: RawSurvey, assets?: RawSurvey[\"assets\"]): void {\n this.mutationEpoch++;\n this.lastResponseNameChanges = [];\n this.pendingAssets.clear();\n this._survey = Survey.fromJson(\n mergeSurveySnapshotWithAssets(snapshot, assets),\n this._pluginRegistry,\n );\n }\n\n commitIfNeeded(): void {\n if (this.hasUncommittedChanges) {\n this.commit({\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n });\n }\n }\n\n // Undo to previous state\n undo(): boolean {\n if (this.hasUncommittedChanges) {\n // If there are uncommitted changes, revert to last committed state\n this.restoreHistoryState(this._undoRedo.getCurrentState(), this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n } else {\n // Normal undo operation\n const previousState = this._undoRedo.undo();\n if (previousState) {\n this.restoreHistoryState(previousState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n }\n\n // Redo to next state\n redo(): boolean {\n if (this.hasUncommittedChanges) {\n // Cannot redo when there are uncommitted changes\n return false;\n }\n\n const nextState = this._undoRedo.redo();\n if (nextState) {\n this.restoreHistoryState(nextState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n // Enhanced undo/redo methods that use the exposed instance\n /**\n * Jump to a specific index in the history (can go forward or backward)\n */\n jumpToIndex(targetIndex: number): boolean {\n if (this.hasUncommittedChanges) {\n // Cannot jump to specific index with uncommitted changes\n return false;\n }\n\n const targetState = this._undoRedo.jumpToIndex(targetIndex);\n if (targetState) {\n this.restoreHistoryState(targetState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n canUndo(): boolean {\n return this.hasUncommittedChanges || this._undoRedo.canUndo();\n }\n\n canRedo(): boolean {\n return !this.hasUncommittedChanges && this._undoRedo.canRedo();\n }\n\n getUndoMeta(): CommitMeta | null {\n if (this.hasUncommittedChanges) {\n return {\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n };\n }\n return this._undoRedo.getUndoMeta();\n }\n\n getRedoMeta(): CommitMeta | null {\n if (this.hasUncommittedChanges) {\n return null;\n }\n return this._undoRedo.getRedoMeta();\n }\n\n // Get memory usage statistics\n getMemoryUsage(): { totalMB: number; entries: number } {\n return this._undoRedo.getMemoryUsage();\n }\n\n // Get undo/redo configuration\n getUndoRedoConfig(): UndoRedoConfig {\n return this._undoRedo.getConfig();\n }\n\n /**\n * Get committed changes after the initial editor state up to the current undo/redo position.\n */\n getCommitsSinceInitial() {\n return this._undoRedo.getCommitsSinceInitial();\n }\n\n /**\n * Serialize the SurveyEditor state to JSON\n * @returns A JSON-serializable object containing the complete editor state\n */\n toJson(): SerializedSurveyEditor {\n return {\n version: \"1.0.0\",\n survey: structuredCloneMethod(this._survey.serialize()),\n undoRedo: this._undoRedo.serialize(),\n hasUncommittedChanges: this.hasUncommittedChanges,\n };\n }\n\n /**\n * Create a new SurveyEditor instance from JSON data\n * @param jsonData The serialized editor state\n * @param pluginRegistry Optional plugin registry for deserializing survey state (required when survey contains custom item types)\n * @returns A new SurveyEditor instance with the restored state\n */\n static fromJson(\n jsonData: SerializedSurveyEditor,\n pluginRegistry?: ItemTypeRegistry,\n ): SurveyEditor {\n if (!jsonData.survey) {\n throw new Error(\"Invalid object: survey is required\");\n }\n\n if (!jsonData.undoRedo) {\n throw new Error(\"Invalid object: undoRedo is required\");\n }\n\n if (typeof jsonData.hasUncommittedChanges !== \"boolean\") {\n throw new Error(\"Invalid object: hasUncommittedChanges must be a boolean\");\n }\n\n // Validate version (for future compatibility)\n if (jsonData.version && !jsonData.version.startsWith(\"1.\")) {\n console.warn(\n `Warning: Loading SurveyEditor with version ${jsonData.version}, current version is 1.0.0`,\n );\n }\n\n // Create survey from JSON\n const survey = Survey.fromJson(jsonData.survey, pluginRegistry);\n\n // Create a new editor instance\n const editor = new SurveyEditor(survey, { pluginRegistry });\n\n // Restore undo/redo state\n editor._undoRedo = SurveyEditorUndoRedo.deserialize(\n {\n ...jsonData.undoRedo,\n history: jsonData.undoRedo.history.map((entry) =>\n \"survey\" in entry\n ? {\n ...entry,\n survey: stripAssetsFromSurveySnapshot(entry.survey),\n }\n : entry,\n ),\n },\n jsonData.survey.assets,\n );\n\n // Infer whether the live survey contains uncommitted survey changes by comparing\n // the current survey content to the current history entry, ignoring assets.\n editor._hasUncommittedChanges =\n JSON.stringify(stripAssetsFromSurveySnapshot(jsonData.survey)) !==\n JSON.stringify(editor._undoRedo.getCurrentState());\n\n const baselineAssets = editor._undoRedo.getCurrentAssets() ?? {};\n const liveAssets = jsonData.survey.assets ?? {};\n for (const assetId of new Set([...Object.keys(baselineAssets), ...Object.keys(liveAssets)])) {\n if (JSON.stringify(baselineAssets[assetId]) !== JSON.stringify(liveAssets[assetId])) {\n editor.pendingAssets.set(assetId, {\n prev: structuredCloneMethod(baselineAssets[assetId]),\n next: structuredCloneMethod(liveAssets[assetId]),\n });\n }\n }\n return editor;\n }\n\n private markAsModified(): void {\n this.mutationEpoch++;\n this._hasUncommittedChanges = true;\n }\n\n private createEditorTimestamp(): string {\n return new Date().toISOString();\n }\n\n private touchItemModifiedMetadata(\n itemId: string,\n timestamp = this.createEditorTimestamp(),\n ): void {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return;\n }\n\n item.setModifiedAt(timestamp);\n }\n\n addItem(target: Target, item: SurveyItemCore, content?: SurveyItemTranslations): void {\n if (this._survey.surveyItems.has(item.id)) {\n throw new Error(`Item with id '${item.id}' already exists in the survey`);\n }\n\n const timestamp = this.createEditorTimestamp();\n\n // Find the parent group item\n let parentGroup: GroupItemCore;\n\n if (!target) {\n // If no target provided, add to root\n\n const rootItem = this._survey.rootItem;\n if (!rootItem) {\n throw new Error(\"No root group found in survey\");\n }\n if (!(rootItem instanceof GroupItemCore)) {\n throw new Error(\"Root item is not a group item\");\n }\n parentGroup = rootItem;\n } else {\n // Find the target parent group\n const targetItem = this._survey.surveyItems.get(target.parentId);\n\n if (!targetItem) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Parent item '${target.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n parentGroup = targetItem;\n }\n\n if (parentGroup.hasChild(item.id)) {\n throw new Error(`Item ${item.id} already in this group`);\n }\n\n // Determine insertion index\n let insertIndex: number;\n if (target?.index !== undefined) {\n // Insert at specified index, or at end if index is larger than array length\n insertIndex = Math.min(target.index, parentGroup.items.length);\n } else {\n // Insert at the end\n insertIndex = parentGroup.items.length;\n }\n\n this.lastResponseNameChanges = allocateCopiedResponseNames(this._survey, [item]);\n this.markAsModified();\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n\n // Add the item to the survey items collection\n this._survey.surveyItems.set(item.id, item);\n\n // Add the item to the parent group (uses addChild for proper persistence)\n parentGroup.addChild(item.id, insertIndex);\n this.touchItemModifiedMetadata(parentGroup.id, timestamp);\n\n // Update translations in the survey\n if (content) {\n this._survey.translations.setItemTranslations(item.id, content);\n }\n }\n\n // Remove an item from the survey\n removeItem(itemId: string, nested: boolean = false): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n // Find parent group and remove from its items array\n const parentItem = this._survey.getParentItem(itemId);\n if (!parentItem) {\n throw new Error(`Item with id '${itemId}' is the root item`);\n }\n\n if (item instanceof GroupItemCore) {\n for (const childId of item.getChildrenIds()) {\n this.removeItem(childId, true);\n }\n }\n\n // Remove from survey items\n this._survey.surveyItems.delete(itemId);\n\n // Remove translations\n this._survey.translations?.onItemDeleted(itemId);\n\n if (!nested) {\n parentItem.removeChild(itemId);\n this.touchItemModifiedMetadata(parentItem.id, timestamp);\n }\n return true;\n }\n\n // Move an item to a different position\n moveItem(itemId: string, newTarget: Target): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n // Check if item exists\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Check if new target exists and is a group\n const targetItem = this._survey.surveyItems.get(newTarget.parentId);\n if (!targetItem) {\n throw new Error(`Target parent with id '${newTarget.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Target parent '${newTarget.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n // Check if new target is not a child of the current item (prevent circular reference)\n if (this._survey.isDescendantOf(newTarget.parentId, itemId)) {\n throw new Error(`Cannot move item '${itemId}' to its descendant '${newTarget.parentId}'`);\n }\n\n // If the item is already in the target parent\n const currentParentItem = this._survey.getParentItem(itemId);\n if (currentParentItem?.id === newTarget.parentId) {\n throw new Error(`Item '${itemId}' is already in the target parent '${newTarget.parentId}'`);\n }\n\n // Remove item from current parent's items array\n if (currentParentItem) {\n const currentParentGroup = currentParentItem as GroupItemCore;\n currentParentGroup.removeChild(itemId);\n this.touchItemModifiedMetadata(currentParentGroup.id, timestamp);\n }\n\n // Add item to new parent's items array\n const targetGroup = targetItem as GroupItemCore;\n\n const insertIndex =\n newTarget.index !== undefined\n ? Math.min(newTarget.index, targetGroup.items.length)\n : targetGroup.items.length;\n\n targetGroup.addChild(itemId, insertIndex);\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n this.touchItemModifiedMetadata(itemId, timestamp);\n\n return true;\n }\n\n /** Move several independent item subtrees as one ordered block. */\n moveItems(itemIds: readonly string[], newTarget: Target): boolean {\n const requestedIds = [...new Set(itemIds)];\n const selectedIds = requestedIds.filter(\n (itemId) =>\n !requestedIds.some(\n (candidateId) =>\n candidateId !== itemId && this._survey.isDescendantOf(itemId, candidateId),\n ),\n );\n if (selectedIds.length === 0) return false;\n\n const targetGroup = this._survey.surveyItems.get(newTarget.parentId);\n if (!(targetGroup instanceof GroupItemCore)) {\n throw new Error(`Target parent '${newTarget.parentId}' is not a group item`);\n }\n\n const entries = selectedIds.map((itemId) => {\n const item = this._survey.surveyItems.get(itemId);\n const parent = this._survey.getParentItem(itemId);\n if (!item || !(parent instanceof GroupItemCore)) {\n throw new Error(`Item '${itemId}' cannot be moved`);\n }\n if (\n itemId === newTarget.parentId ||\n this._survey.isDescendantOf(newTarget.parentId, itemId)\n ) {\n throw new Error(`Cannot move item '${itemId}' into its own subtree`);\n }\n return { item, parent, index: parent.items.indexOf(itemId) };\n });\n\n // Preserve the survey's structural order, regardless of click order.\n const order = new Map<string, number>();\n let orderIndex = 0;\n const visit = (group: GroupItemCore) => {\n for (const childId of group.items) {\n order.set(childId, orderIndex++);\n const child = this._survey.surveyItems.get(childId);\n if (child instanceof GroupItemCore) visit(child);\n }\n };\n const root = this._survey.rootItem;\n if (root) visit(root);\n entries.sort((a, b) => (order.get(a.item.id) ?? 0) - (order.get(b.item.id) ?? 0));\n\n const selectedSet = new Set(entries.map(({ item }) => item.id));\n const requestedIndex = newTarget.index ?? targetGroup.items.length;\n const removedBeforeTarget = targetGroup.items\n .slice(0, requestedIndex)\n .filter((id) => selectedSet.has(id)).length;\n const insertionIndex = Math.max(0, requestedIndex - removedBeforeTarget);\n const timestamp = this.createEditorTimestamp();\n\n this.markAsModified();\n for (const { item, parent } of entries) {\n parent.removeChild(item.id);\n this.touchItemModifiedMetadata(parent.id, timestamp);\n }\n\n entries.forEach(({ item }, offset) => {\n targetGroup.addChild(item.id, insertionIndex + offset);\n this.touchItemModifiedMetadata(item.id, timestamp);\n });\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n return true;\n }\n\n /**\n * Get a deep copy of an item's raw data.\n * The returned object is independent of the survey—mutating it will not affect the survey.\n * Use this when you need to edit an item in a form or pass it to updateItem after modifications.\n *\n * @param itemId - The ID of the item to copy\n * @returns A deep copy of the item's RawSurveyItem data\n * @throws Error if the item is not found\n */\n getItemDataCopy(itemId: string): RawSurveyItem {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n return JSON.parse(JSON.stringify(item.rawItem)) as RawSurveyItem;\n }\n\n /**\n * Update an item's data in the survey.\n * Can update common attributes (displayConditions, disabledConditions, validations, etc.)\n * as well as type-specific config.\n *\n * Use getItemDataCopy to obtain an editable copy, modify it, then pass it here.\n * Alternatively, pass a Partial to merge specific fields (top-level keys only;\n * e.g. config replaces the entire config object).\n *\n * @param itemId - The ID of the item to update (must match data.id if provided)\n * @param rawItemData - Full RawSurveyItem or Partial to merge. The id cannot be changed.\n */\n updateItem(itemId: string, rawItemData: RawSurveyItem | Partial<RawSurveyItem>): void {\n const existingItem = this._survey.surveyItems.get(itemId);\n if (!existingItem) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n if (\"id\" in rawItemData && rawItemData.id !== undefined && rawItemData.id !== itemId) {\n throw new Error(`Cannot change item id from '${itemId}' to '${rawItemData.id}'`);\n }\n\n const currentRaw = existingItem.rawItem;\n const merged: RawSurveyItem = {\n ...currentRaw,\n ...rawItemData,\n id: itemId, // Ensure id is never changed\n };\n\n if (merged.responseSettings) {\n merged.responseSettings = { ...merged.responseSettings };\n const nextSlotIds = new Set(\n this._survey\n .createItemFromRaw(merged)\n .getResponseSlotDefinitions()\n .map((slot) => slot.slotId),\n );\n for (const slot of existingItem.getResponseSlotDefinitions())\n if (!nextSlotIds.has(slot.slotId)) delete merged.responseSettings[slot.slotId];\n }\n const stagedRaw = this._survey.serialize();\n stagedRaw.surveyItems = stagedRaw.surveyItems.map((item) =>\n item.id === itemId ? merged : item,\n );\n const beforeIssues = new Set(\n this._survey.getResponseSlotRegistry().diagnostics.map((issue) => JSON.stringify(issue)),\n );\n const stagedSurvey = Survey.fromJson(stagedRaw, this._survey.getPluginRegistry());\n const introduced = stagedSurvey\n .getResponseSlotRegistry()\n .diagnostics.filter((issue) => !beforeIssues.has(JSON.stringify(issue)));\n if (introduced.length) throw new Error(introduced.map((issue) => issue.message).join(\"\\n\"));\n const previousProjectionIssues = new Set(getDefaultProjectionIssues(this._survey));\n const projectionIssues = getDefaultProjectionIssues(stagedSurvey).filter(\n (issue) => !previousProjectionIssues.has(issue),\n );\n if (projectionIssues.length) throw new Error(projectionIssues.join(\"\\n\"));\n\n const newItem = this._survey.createItemFromRaw({\n ...merged,\n editorMetadata: existingItem.rawItem.editorMetadata,\n });\n newItem.setModifiedAt(this.createEditorTimestamp());\n this._survey.surveyItems.set(itemId, newItem);\n this.markAsModified();\n }\n\n /** Detached field read; does not construct a Survey or visit other locales. */\n getItemTranslationContent(\n itemId: string,\n locale: string,\n contentKey: string,\n fallbackLocale?: string,\n ): Content | undefined {\n return this._survey.translations.getItemTranslationContent(\n itemId,\n locale,\n contentKey,\n fallbackLocale,\n );\n }\n\n /** Publish accepted content without committing history. Equivalent writes are no-ops. */\n setItemTranslationContent(\n itemId: string,\n locale: string,\n contentKey: string,\n content?: Content,\n ): boolean {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) return false;\n const changed = this._survey.translations.setItemTranslationContent(\n itemId,\n locale,\n contentKey,\n content,\n );\n if (!changed) return false;\n item.setModifiedAt(this.createEditorTimestamp());\n this.markAsModified();\n return true;\n }\n\n // Update item translations\n updateItemTranslations(itemId: string, updatedContent?: SurveyItemTranslations): boolean {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n this.markAsModified();\n item.setModifiedAt(this.createEditorTimestamp());\n this._survey.translations.setItemTranslations(itemId, updatedContent);\n\n return true;\n }\n\n /**\n * Update survey-level translations that are not tied to specific items.\n * Use these for survey card, navigation, validation messages, etc.\n */\n updateSurveyTranslations(updates: {\n surveyCard?: { locale: string; content?: SurveyCardContent };\n navigation?: { locale: string; content?: NavigationContent };\n validationMessages?: { locale: string; content?: { invalidResponse?: Content } };\n }): void {\n this.markAsModified();\n if (updates.surveyCard) {\n this._survey.translations.setSurveyCardContent(\n updates.surveyCard.locale,\n updates.surveyCard.content,\n );\n }\n if (updates.navigation) {\n this._survey.translations.setNavigationContent(\n updates.navigation.locale,\n updates.navigation.content,\n );\n }\n if (updates.validationMessages) {\n this._survey.translations.setValidationMessages(\n updates.validationMessages.locale,\n updates.validationMessages.content,\n );\n }\n }\n\n /** Add an empty survey locale so it can be authored before translated content exists. */\n addLocale(locale: string): boolean {\n const added = this._survey.translations.addLocale(locale);\n if (added) {\n this.markAsModified();\n }\n return added;\n }\n\n /** Remove a locale and every survey- and item-level translation stored for it. */\n removeLocale(locale: string): boolean {\n if (!this._survey.locales.includes(locale)) {\n return false;\n }\n\n this._survey.translations.removeLocale(locale);\n this.markAsModified();\n return true;\n }\n\n /**\n * Get maxItemsPerPage immutably (returns a copy).\n */\n getMaxItemsPerPage(): { large: number; small: number } | undefined {\n const val = this._survey.maxItemsPerPage;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update maxItemsPerPage.\n */\n updateMaxItemsPerPage(value: { large: number; small: number } | undefined): void {\n this.markAsModified();\n this._survey.maxItemsPerPage = value ? { ...value } : undefined;\n }\n\n /**\n * Get metadata immutably (returns a copy).\n */\n getMetadata(): { [key: string]: string } | undefined {\n const val = this._survey.metadata;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update metadata.\n */\n updateMetadata(metadata: { [key: string]: string } | undefined): void {\n this.markAsModified();\n this._survey.metadata = metadata ? { ...metadata } : undefined;\n }\n\n /**\n * Get a template value immutably (returns a deep copy).\n */\n getTemplateValue(key: string): TemplateValueDefinition | undefined {\n const val = this._survey.getTemplateValue(key);\n return val ? structuredCloneMethod(val) : undefined;\n }\n\n /**\n * Get all template values immutably (returns a new Map with deep-copied values).\n */\n getTemplateValues(): Map<string, TemplateValueDefinition> {\n const keys = this._survey.getTemplateValueKeys();\n const result = new Map<string, TemplateValueDefinition>();\n for (const key of keys) {\n const val = this._survey.getTemplateValue(key);\n if (val) {\n result.set(key, structuredCloneMethod(val));\n }\n }\n return result;\n }\n\n /**\n * Add or replace a template value.\n */\n setTemplateValue(key: string, templateValue: TemplateValueDefinition): void {\n this.markAsModified();\n this._survey.setTemplateValue(key, structuredCloneMethod(templateValue));\n }\n\n /**\n * Remove a template value.\n */\n removeTemplateValue(key: string): void {\n this.markAsModified();\n this._survey.deleteTemplateValue(key);\n }\n\n /**\n * Get a survey asset immutably.\n */\n getAsset(assetId: string): RawSurveyAsset | undefined {\n const asset = this._survey.getAsset(assetId);\n return asset ? structuredCloneMethod(asset) : undefined;\n }\n\n /**\n * Get all survey assets immutably.\n */\n getAssets(): Map<string, RawSurveyAsset> {\n return this._survey.getAssets();\n }\n\n /**\n * Add or replace a survey asset.\n */\n /** Stage one live asset delta. Default setAsset/removeAsset remain immediate. */\n stageAsset(assetId: string, asset?: RawSurveyAsset): void {\n const previous = this.pendingAssets.get(assetId)?.prev ?? this._survey.getAsset(assetId);\n const baseline = this.pendingAssets.has(assetId)\n ? this.pendingAssets.get(assetId)!.prev\n : previous;\n if (asset) this._survey.setAsset(assetId, structuredCloneMethod(asset));\n else this._survey.deleteAsset(assetId);\n if (JSON.stringify(baseline) === JSON.stringify(asset)) this.pendingAssets.delete(assetId);\n else this.pendingAssets.set(assetId, { prev: baseline, next: structuredCloneMethod(asset) });\n this.mutationEpoch++;\n }\n\n setAsset(assetId: string, asset: RawSurveyAsset): void {\n this.mutationEpoch++;\n const previousAsset = this._survey.getAsset(assetId);\n this._survey.setAsset(assetId, structuredCloneMethod(asset));\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n next: structuredCloneMethod(asset),\n },\n ],\n {\n label: `Update asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Remove a survey asset.\n */\n removeAsset(assetId: string): void {\n this.mutationEpoch++;\n const previousAsset = this._survey.getAsset(assetId);\n if (!previousAsset) {\n return;\n }\n this._survey.deleteAsset(assetId);\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n },\n ],\n {\n label: `Remove asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * @param itemId - The ID of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const copyPaste = new ItemCopyPaste(this._survey);\n return copyPaste.copyItem(itemId);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * @param clipboardData - The clipboard data containing the item to paste\n * @param target - Target location where to paste the item\n * @returns The ID of the pasted item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n const timestamp = this.createEditorTimestamp();\n const itemIdsBeforePaste = new Set(this._survey.surveyItems.keys());\n const copyPaste = new ItemCopyPaste(this._survey);\n const newItemId = copyPaste.pasteItem(clipboardData, target);\n this.lastResponseNameChanges = copyPaste.lastResponseNameChanges;\n this.markAsModified();\n const pastedItemIds = Array.from(this._survey.surveyItems.keys()).filter(\n (itemId) => !itemIdsBeforePaste.has(itemId),\n );\n\n for (const itemId of pastedItemIds) {\n const item = this._survey.surveyItems.get(itemId);\n if (item) {\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n }\n }\n this.touchItemModifiedMetadata(target.parentId, timestamp);\n\n return newItemId;\n }\n}\n"],"mappings":";;AAwBA,SAAS,SAAS,QAAiB,MAA6C;CAC9E,IAAI,UAAU;CACd,KAAK,MAAM,OAAO,MAAM,UAAW,UAA+C;CAClF,OAAO;AACT;AACA,SAAS,UAAU,QAAiB,MAAoC,OAAqB;CAC3F,IACE,CAAC,KAAK,UACN,KAAK,MAAM,QAAQ,QAAQ,eAAe,QAAQ,iBAAiB,QAAQ,WAAW,GAEtF,MAAM,IAAI,MAAM,8BAA8B;CAChD,MAAM,SAAS,SAAS,QAAQ,KAAK,MAAM,GAAG,EAAE,CAAC;CACjD,IAAI,CAAC,UAAU,OAAO,WAAW,UAC/B,MAAM,IAAI,MAAM,uDAAuD;CACzE,OAA6C,KAAK,GAAG,EAAE,KAAM;AAC/D;AACA,MAAM,cAAc,SAAiB;CACnC,IAAI,CAAC,4BAA4B,IAAI,GACnC,MAAM,IAAI,MACR,0BAA0B,KAAK,4EACjC;AACJ;;AAGA,SAAS,cAAc,QAAgB,OAAsC;CAC3E,MAAM,WAAW,OAAO,wBAAwB;CAChD,MAAM,MAAM,gBAAgB,OAAO,UAAU,CAAC;CAC9C,MAAM,UAAU,SACd,IAAI,YAAY,MAAM,SAAS,KAAK,OAAO,KAAK,MAAM,CAAC,CAAE;CAC3D,KAAK,MAAM,QAAQ,OACjB,IAAI,YAAY,MAAM;EACpB,MAAM,OAAO,SAAS,IAAI,KAAK,MAAM;EACrC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,8BAA8B,KAAK,OAAO,EAAE;EACvE,IAAI,KAAK,QAAQ,SAAS,UACxB,MAAM,IAAI,MACR,kFACF;EACF,IAAI,CAAC,KAAK,QACR,MAAM,IAAI,MAAM,qBAAqB,KAAK,OAAO,oCAAoC;EACvF,WAAW,KAAK,YAAY;EAC5B,UAAU,OAAO,IAAI,GAAG,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