From 83afbf077801e872c61e0943181725fd9a9a68bc Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Wed, 24 Aug 2022 08:21:57 +0100 Subject: [PATCH] Update block map structure for better ejection --- packages/client/src/components/Block.svelte | 26 ++++++++++++--------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/packages/client/src/components/Block.svelte b/packages/client/src/components/Block.svelte index 0ebb5e4483..b382062787 100644 --- a/packages/client/src/components/Block.svelte +++ b/packages/client/src/components/Block.svelte @@ -10,34 +10,36 @@ const registerBlockComponent = (id, order, parentId, instance) => { // Ensure child array exists if (!structureLookupMap[parentId]) { - structureLookupMap[parentId] = [] + structureLookupMap[parentId] = {} } - // Remove existing instance of this component in case props changed - structureLookupMap[parentId] = structureLookupMap[parentId].filter( - blockComponent => blockComponent.order !== order - ) - // Add new instance of this component - structureLookupMap[parentId].push({ order, instance }) + // Add this instance in this order, overwriting any existing instance in + // this order in case of repeaters + structureLookupMap[parentId][order] = instance } const eject = () => { // Start the new structure with the first top level component - let definition = structureLookupMap[$component.id][0].instance + let definition = structureLookupMap[$component.id][0] attachChildren(definition, structureLookupMap) builderStore.actions.ejectBlock($component.id, definition) } const attachChildren = (rootComponent, map) => { + // Transform map into children array let id = rootComponent._id - if (!map[id]?.length) { + const children = Object.entries(map[id] || {}).map(([order, instance]) => ({ + order, + instance, + })) + if (!children.length) { return } // Sort children by order - map[id].sort((a, b) => (a.order < b.order ? -1 : 1)) + children.sort((a, b) => (a.order < b.order ? -1 : 1)) // Attach all children of this component - rootComponent._children = map[id].map(x => x.instance) + rootComponent._children = children.map(x => x.instance) // Recurse for each child rootComponent._children.forEach(child => { @@ -57,6 +59,8 @@ }) onMount(() => { + // We register and unregister blocks to the block store when inside the + // builder preview to allow for block ejection if ($builderStore.inBuilder) { blockStore.actions.registerBlock($component.id, { eject }) }