From 3d2392dc7092419ba0a7c2cbbd8db64ecd4d234a Mon Sep 17 00:00:00 2001 From: linonetwo Date: Sun, 23 Mar 2025 20:24:12 +0800 Subject: [PATCH] feat: debounced on change --- core/modules/utils/debounce.js | 37 +++++++++++++++++++++++++++ plugins/tiddlywiki/editorjs/widget.js | 19 ++++++++++++-- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 core/modules/utils/debounce.js diff --git a/core/modules/utils/debounce.js b/core/modules/utils/debounce.js new file mode 100644 index 000000000..756c162c2 --- /dev/null +++ b/core/modules/utils/debounce.js @@ -0,0 +1,37 @@ +/*\ +title: $:/core/modules/utils/debounce.js +type: application/javascript +module-type: utils + +Debounce function execution. + +Usage: + +- func: function to be debounced +- wait: time to wait before executing the function +- immediate: if true, the function is executed immediately + +\*/ + +"use strict"; + +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); + } + }; +}; + +exports.debounce = debounce; diff --git a/plugins/tiddlywiki/editorjs/widget.js b/plugins/tiddlywiki/editorjs/widget.js index 511921b1c..caecb4ad4 100644 --- a/plugins/tiddlywiki/editorjs/widget.js +++ b/plugins/tiddlywiki/editorjs/widget.js @@ -10,6 +10,7 @@ Text node widget "use strict"; var Widget = require("$:/core/modules/widgets/widget.js").widget; +var debounce = require("$:/core/modules/utils/debounce.js").debounce; var EditorJSWidget = function(parseTreeNode,options) { this.initialise(parseTreeNode,options); @@ -38,20 +39,34 @@ EditorJSWidget.prototype.render = function(parent,nextSibling) { tools: { list: List, header: Header - } + }, + onChange: this.debouncedSaveEditorContent.bind(this) }); + this.editor = editor; editor.isReady .then(() => { - console.log('Editor.js is ready to work!') + console.log('Editor.js is ready to work!', editor.onChange); }) .catch((reason) => { console.log('Editor.js initialization failed because of', reason) }); + parent.insertBefore(container,nextSibling); this.domNodes.push(container); }; +EditorJSWidget.prototype.saveEditorContent = function() { + this.editor.save().then((outputData) => { + console.log('Article data: ', outputData) + }).catch((error) => { + console.log('Saving failed: ', error) + }); +} + +// Debounced save function for performance +EditorJSWidget.prototype.debouncedSaveEditorContent = debounce(EditorJSWidget.prototype.saveEditorContent, 300); + /* Compute the internal state of the widget */