From 29c430b92a4bf9ef5799976e87708d686fa248fb Mon Sep 17 00:00:00 2001 From: jacobtoppm Date: Thu, 1 Sep 2022 17:51:02 +0100 Subject: [PATCH] Postpone add comment widget initialisation until after comments are enabled. (#9124) This prevents errors when comments.js is loaded but a view does not use the commenting functionality, which caused issues for StructBlocks containing FieldBlocks on non page-models. In future we should only load comments.js where it is actually needed as well. --- client/src/entrypoints/admin/comments.js | 36 +++++++++++++++--------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/client/src/entrypoints/admin/comments.js b/client/src/entrypoints/admin/comments.js index 9423908ed3..cb14babdb8 100644 --- a/client/src/entrypoints/admin/comments.js +++ b/client/src/entrypoints/admin/comments.js @@ -264,6 +264,27 @@ window.comments = (() => { } } + function onNextEnable(fn) { + // Run a function once, when comments are enabled + const { selectEnabled } = commentApp.selectors; + const getEnabled = () => selectEnabled(commentApp.store.getState()); + let enabled = getEnabled(); + if (enabled) { + // If we're starting off enabled, run the function immediately + fn(); + return; + } + const unsubscribe = commentApp.store.subscribe(() => { + // Otherwise, subscribe to updates and run the function when comments change to enabled + const newEnabled = getEnabled(); + if (newEnabled && !enabled) { + enabled = newEnabled; + unsubscribe(); + fn(); + } + }); + } + function initAddCommentButton(buttonElement) { const initWidget = () => { const widget = new FieldLevelCommentWidget({ @@ -275,19 +296,8 @@ window.comments = (() => { widget.register(); } }; - try { - initWidget(); - } catch (e) { - if ( - e.name === 'MissingElementError' && - document.readyState === 'loading' - ) { - // Our template node doesn't exist yet - let's hold off until the DOM loads - document.addEventListener('DOMContentLoaded', initWidget); - } else { - throw e; - } - } + // Our template node may not exist yet - let's hold off until comments are loaded and enabled + onNextEnable(initWidget); } function initCommentsInterface(formElement) {