/** * Hilfsfunktionen für den Blockbaum im Editor. */ export function uid() { return Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-6); } export function clone(value) { return JSON.parse(JSON.stringify(value)); } function itemCount(type, data) { if (!type.container) return 0; if (type.key === 'columns') return (data.layout ?? '1-1').split('-').length; if (type.key === 'tabs') return 2; if (type.key === 'accordion') return 3; return type.container.min; } export function createBlock(type) { const data = clone(type.defaults ?? {}); const block = { id: uid(), type: type.key, data }; if (type.container) { block.items = Array.from({ length: itemCount(type, data) }, (_, index) => ({ id: uid(), title: type.container.titled ? `${type.container.label} ${index + 1}` : undefined, blocks: [], })); } return block; } /** Kopie mit neuen IDs (Duplizieren, Vorlagen). */ export function duplicate(block) { const copy = clone(block); const renew = (b) => { b.id = uid(); (b.items ?? []).forEach((item) => { item.id = uid(); item.blocks.forEach(renew); }); }; renew(copy); return copy; } /** Block im Baum finden: liefert Block, Liste und Position. */ export function locate(blocks, id, parent = null) { for (let index = 0; index < blocks.length; index++) { const block = blocks[index]; if (block.id === id) return { block, list: blocks, index, parent }; for (const item of block.items ?? []) { const found = locate(item.blocks, id, block); if (found) return found; } } return null; } export function walk(blocks, callback) { for (const block of blocks) { callback(block); (block.items ?? []).forEach((item) => walk(item.blocks, callback)); } } /** Anzahl der Spalten an die Aufteilung anpassen, ohne Inhalte zu verlieren. */ export function syncColumns(block) { const count = (block.data.layout ?? '1-1').split('-').length; while (block.items.length < count) { block.items.push({ id: uid(), blocks: [] }); } if (block.items.length > count) { const overflow = block.items.splice(count).flatMap((item) => item.blocks); block.items[count - 1].blocks.push(...overflow); } }