From b9585fc4249ab251a58d36396db4aff0c0653b6c Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Wed, 15 Jan 2025 12:44:26 -0600 Subject: [PATCH] Instead of relying on the button class name, switch to detect post-status changes in JS Motivation: it's fragile to rely on a 3rd party button class name to listen to. Especially since this can potentially change between WP versions. Instead, we can use the 'core/editor' API on `wp.data` to listen to changes in the post status and uncheck the checkbox that way. --- v3/onesignal-metabox/onesignal-metabox.js | 50 +++++++++++++++-------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/v3/onesignal-metabox/onesignal-metabox.js b/v3/onesignal-metabox/onesignal-metabox.js index 5233ba4..23a9280 100644 --- a/v3/onesignal-metabox/onesignal-metabox.js +++ b/v3/onesignal-metabox/onesignal-metabox.js @@ -33,24 +33,38 @@ window.addEventListener("DOMContentLoaded", () => { setDisabled(customiseWrapChild, !customisePost.checked); }); - // Watch for the Publish button to be added to the DOM - const observer = new MutationObserver((mutations, obs) => { - const publishButton = document.querySelector('.editor-post-publish-button__button'); - - if (publishButton) { - publishButton.addEventListener('click', function() { - setTimeout(() => { - if (sendPost && sendPost.checked) { - sendPost.click(); - } - }, 1000); - }); - obs.disconnect(); // Stop observing once we've found and handled the button - } - }); - observer.observe(document.body, { - childList: true, - subtree: true + // make sure WordPress editor and API are available + if (typeof wp === 'undefined' || !wp.data || !wp.data.select) { + console.warn('wp.data is not available.'); + return; + } + + const editorStore = wp.data.select('core/editor'); + + // track initial state of checkbox + const osUpdateCheckbox = document.querySelector('#os_update'); + const wasCheckedInitially = osUpdateCheckbox ? osUpdateCheckbox.checked : false; + + // track previous post status to detect changes + let previousStatus = editorStore.getCurrentPostAttribute('status'); + + // subscribe to state changes + wp.data.subscribe(() => { + const currentStatus = editorStore.getCurrentPostAttribute('status'); + + // check if the post status changed to "publish" + if (previousStatus !== currentStatus && currentStatus === 'publish') { + previousStatus = currentStatus; + + if (wasCheckedInitially) { + // uncheck the os_update checkbox + if (osUpdateCheckbox && osUpdateCheckbox.checked) { + osUpdateCheckbox.checked = false; + } + } + } else { + previousStatus = currentStatus; + } }); });