Skip to content

Commit

Permalink
Instead of relying on the button class name, switch to detect post-st…
Browse files Browse the repository at this point in the history
…atus 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.
  • Loading branch information
rgomezp committed Jan 15, 2025
1 parent 6309413 commit b9585fc
Showing 1 changed file with 32 additions and 18 deletions.
50 changes: 32 additions & 18 deletions v3/onesignal-metabox/onesignal-metabox.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
});
});

0 comments on commit b9585fc

Please sign in to comment.