Last active
December 29, 2022 16:56
-
-
Save vincentorback/364336ef6d75baf2f143385708d2a8a5 to your computer and use it in GitHub Desktop.
Show warning notifications when user, in WordPress gutenberg editor, uses words or phrases in content. For example ' and " when they should be using ` or ”.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const warnAbout = [ | |
{ | |
id: 'single_quote_notice', | |
needle: '"', | |
haystack: 'text', | |
message: "Content includes simple quotation marks: '. Did you mean ’ ?", | |
dispatched: false, | |
}, | |
{ | |
id: 'double_quote_notice', | |
needle: '"', | |
haystack: 'text', | |
message: 'Content includes simple quotation marks: ". Did you mean ” ?', | |
dispatched: false, | |
}, | |
{ | |
id: 'teg-spelling', | |
needle: 'COMPANY name', | |
haystack: 'html', | |
message: 'Company Name should always be written in camel case Company Name', | |
dispatched: false, | |
}, | |
] | |
function extractTextContant(str) { | |
var span = document.createElement('div') | |
span.innerHTML = str | |
return span.textContent || span.innerText | |
} | |
wp.domReady(() => { | |
wp.data.subscribe(() => { | |
if (localStorage.getItem('no_quote_notice')) { | |
return | |
} | |
if (wp.data.select('core/editor').isSavingPost()) { | |
const blocks = wp.blocks.parse( | |
wp.data.select('core/editor').getEditedPostContent() | |
) | |
blocks.forEach((block) => { | |
warnAbout.forEach((warn) => { | |
if (localStorage.getItem(`no_${warn.id}_notice`)) { | |
return | |
} | |
if (!warn.dispatched) { | |
if ( | |
extractTextContant(block.attributes.content).includes(warn.needle) | |
) { | |
warn.dispatched = true | |
wp.data | |
.dispatch('core/notices') | |
.createWarningNotice(warn.message, { | |
id: warn.id, | |
isDismissable: true, | |
actions: [ | |
{ | |
label: 'Visa inte igen', | |
onClick: () => { | |
warn.dispatched = false | |
localStorage.setItem(`no_${warn.id}_notice`, 1) | |
wp.data.dispatch('core/notices').removeNotice(warn.id) | |
}, | |
}, | |
], | |
onDismiss: () => { | |
warn.dispatched = false | |
}, | |
}) | |
} | |
} | |
}) | |
}) | |
// TODO: Remove notices when user saves and quotes are good. | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment