From 34ad59c003e65b17bf9bb24f589592b5ad3787d0 Mon Sep 17 00:00:00 2001 From: Dirk Date: Wed, 7 Feb 2024 09:59:26 +0100 Subject: [PATCH] feat: add editor-support.js --- scripts/editor-support.js | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 scripts/editor-support.js diff --git a/scripts/editor-support.js b/scripts/editor-support.js new file mode 100644 index 000000000..badfd564d --- /dev/null +++ b/scripts/editor-support.js @@ -0,0 +1,42 @@ +import { + decorateBlock, + decorateButtons, + decorateIcons, + loadBlock, +} from './aem.js'; + +const connectionPrefix = 'urn:aemconnection:'; + +async function handleEditorUpdate(event) { + const { detail } = event; + + const resource = detail?.requestData?.target?.resource; + if (!resource) return; + + const element = document.querySelector(`[data-aue-resource="${resource}"]`); + const block = element?.parentElement?.closest('.block') || element?.closest('.block'); + const blockResource = block?.getAttribute('data-aue-resource'); + if (!block || !blockResource?.startsWith(connectionPrefix)) return; + + const updates = detail?.responseData?.updates; + if (updates.length > 0) { + const { content } = updates[0]; + const newBlockDocument = new DOMParser().parseFromString(content, 'text/html'); + const newBlock = newBlockDocument?.querySelector(`[data-aue-resource="${blockResource}"]`); + if (newBlock) { + newBlock.style.display = 'none'; + block.insertAdjacentElement('afterend', newBlock); + // decorate buttons and icons + decorateButtons(newBlock); + decorateIcons(newBlock); + // decorate and load the block + decorateBlock(newBlock); + await loadBlock(newBlock); + // remove the old block and show the new one + block.remove(); + newBlock.style.display = null; + } + } +} + +document.querySelector('main')?.addEventListener('aue:content-patch', handleEditorUpdate);