From 158613f5fd0a7dd6f8fac39ac809919952afda46 Mon Sep 17 00:00:00 2001 From: Joel Schlotterer <103943917+schlotterer@users.noreply.github.com> Date: Sat, 24 Aug 2024 17:20:59 -0500 Subject: [PATCH] Create shortcode-paste-handler.js --- shortcode-paste-handler.js | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 shortcode-paste-handler.js diff --git a/shortcode-paste-handler.js b/shortcode-paste-handler.js new file mode 100644 index 0000000..db8b079 --- /dev/null +++ b/shortcode-paste-handler.js @@ -0,0 +1,52 @@ +wp.domReady(() => { + const allowedPlainTextBlocks = [ + 'core/paragraph', + 'core/heading', + 'core/quote', + 'core/list', + 'core/preformatted' + ]; + + wp.data.subscribe(() => { + const { isTyping, getSelectedBlock } = wp.data.select('core/block-editor'); + + if (!isTyping()) { + const block = getSelectedBlock(); + if (block && allowedPlainTextBlocks.includes(block.name)) { + const blockElement = document.querySelector(`[data-block="${block.clientId}"]`); + + if (blockElement) { + // Remove any existing paste listener first to avoid duplicates + blockElement.removeEventListener('paste', handlePaste); + + // Add the paste event listener + blockElement.addEventListener('paste', handlePaste, { once: true }); + } + } + } + }); + + function handlePaste(event) { + const clipboardData = event.clipboardData.getData('text'); + + // Check if the pasted content contains a shortcode + if (/\[[^\]]+\]/.test(clipboardData)) { + event.preventDefault(); + + const selection = window.getSelection(); + if (selection.rangeCount > 0) { + const range = selection.getRangeAt(0); + range.deleteContents(); + range.insertNode(document.createTextNode(clipboardData)); + + // Trigger the block content update + const blockId = event.target.closest('[data-block]').dataset.block; + const blockElement = document.querySelector(`[data-block="${blockId}"]`); + + wp.data.dispatch('core/block-editor').updateBlockAttributes(blockId, { + content: blockElement.innerText + }); + } + } + } +});