1
0
Fork 0
mirror of synced 2024-07-02 13:01:09 +12:00

Update block map structure for better ejection

This commit is contained in:
Andrew Kingston 2022-08-24 08:21:57 +01:00
parent 2f2c28cf4d
commit 5525f29a57

View file

@ -10,34 +10,36 @@
const registerBlockComponent = (id, order, parentId, instance) => { const registerBlockComponent = (id, order, parentId, instance) => {
// Ensure child array exists // Ensure child array exists
if (!structureLookupMap[parentId]) { if (!structureLookupMap[parentId]) {
structureLookupMap[parentId] = [] structureLookupMap[parentId] = {}
} }
// Remove existing instance of this component in case props changed // Add this instance in this order, overwriting any existing instance in
structureLookupMap[parentId] = structureLookupMap[parentId].filter( // this order in case of repeaters
blockComponent => blockComponent.order !== order structureLookupMap[parentId][order] = instance
)
// Add new instance of this component
structureLookupMap[parentId].push({ order, instance })
} }
const eject = () => { const eject = () => {
// Start the new structure with the first top level component // 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) attachChildren(definition, structureLookupMap)
builderStore.actions.ejectBlock($component.id, definition) builderStore.actions.ejectBlock($component.id, definition)
} }
const attachChildren = (rootComponent, map) => { const attachChildren = (rootComponent, map) => {
// Transform map into children array
let id = rootComponent._id let id = rootComponent._id
if (!map[id]?.length) { const children = Object.entries(map[id] || {}).map(([order, instance]) => ({
order,
instance,
}))
if (!children.length) {
return return
} }
// Sort children by order // 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 // 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 // Recurse for each child
rootComponent._children.forEach(child => { rootComponent._children.forEach(child => {
@ -57,6 +59,8 @@
}) })
onMount(() => { onMount(() => {
// We register and unregister blocks to the block store when inside the
// builder preview to allow for block ejection
if ($builderStore.inBuilder) { if ($builderStore.inBuilder) {
blockStore.actions.registerBlock($component.id, { eject }) blockStore.actions.registerBlock($component.id, { eject })
} }