From 34168716fe824f372665e447c99aee5cfb2a3eda Mon Sep 17 00:00:00 2001 From: thecodrr Date: Thu, 4 Nov 2021 10:13:53 +0500 Subject: [PATCH] fix: refresh highlighting on all keys with 500 debounce --- packages/tinymce-plugins/codeblock/index.js | 34 ++++++++++++++++----- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/packages/tinymce-plugins/codeblock/index.js b/packages/tinymce-plugins/codeblock/index.js index 3d988c644..b26ef91fa 100644 --- a/packages/tinymce-plugins/codeblock/index.js +++ b/packages/tinymce-plugins/codeblock/index.js @@ -214,14 +214,14 @@ var registerHandlers = function (api, editor) { } function onKeyUp(e) { - // perf: only apply highlighting on whitespace characters - if ( + debounce( + () => refreshHighlighting(editor), + 500, e.code === "Enter" || - e.code === "Space" || - e.code === "Backspace" || - e.code === "Tab" - ) - refreshHighlighting(editor); + e.code === "Space" || + e.code === "Backspace" || + e.code === "Tab" + ); } editor.on("BeforeExecCommand", onBeforeExecCommand); @@ -270,3 +270,23 @@ function processPastedContent(node) { } module.exports = { processPastedContent }; + +// Returns a function, that, as long as it continues to be invoked, will not +// be triggered. The function will be called after it stops being called for +// N milliseconds. If `immediate` is passed, trigger the function on the +// leading edge, instead of the trailing. +function debounce(func, wait, immediate) { + var timeout; + return function () { + var context = this, + args = arguments; + var later = function () { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +}