From 4eac09f3045dc49703097de8df546345febd592b Mon Sep 17 00:00:00 2001 From: Lephe Date: Wed, 27 Apr 2022 11:43:35 +0100 Subject: [PATCH] editor: basic markup insertion around selection --- app/static/scripts/editor.js | 45 +++++++++++++++++++++++++++---- app/templates/widgets/editor.html | 8 +++--- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/app/static/scripts/editor.js b/app/static/scripts/editor.js index 4304b4f..df09d14 100644 --- a/app/static/scripts/editor.js +++ b/app/static/scripts/editor.js @@ -1,13 +1,48 @@ /* Add callbacks on text formatting buttons */ -function editor_bold(e) { - let ta = document.querySelector(".editor textarea"); +function editor_insert_around(e) { + let button = undefined; + let editor = undefined; + + /* Grab the button and the parent editor block. The onclick event itself + usually reports the SVG in the button as the source */ + let node = e.target || e.srcElement; + while(node != document.body) { + if(node.tagName == "BUTTON" && !button) + button = node; + if(node.classList.contains("editor") && !editor) { + editor = node; + break; + } + node = node.parentNode; + } + if(!button || !editor) return; + + /* Find the textarea */ + const ta = editor.querySelector("textarea"); + ta.focus(); let indexStart = ta.selectionStart; let indexEnd = ta.selectionEnd; - let txt = ta.value.substring(indexStart, indexEnd); - ta.value += '\n' + 'bold'; -} + const before = button.dataset.before || ""; + const after = button.dataset.after || ""; + + ta.value = ta.value.substring(0, indexStart) + + before + + ta.value.substring(indexStart, indexEnd) + + after + + ta.value.substring(indexEnd); + + /* Restore selection */ + if(indexStart != indexEnd) { + ta.selectionStart = indexStart; + ta.selectionEnd = indexEnd + before.length + after.length; + } + else { + ta.selectionStart = indexStart + before.length; + ta.selectionEnd = ta.selectionStart; + } +} // Tab insert some spaces // Ctrl+Enter send the form diff --git a/app/templates/widgets/editor.html b/app/templates/widgets/editor.html index a0363cf..363ced9 100644 --- a/app/templates/widgets/editor.html +++ b/app/templates/widgets/editor.html @@ -3,22 +3,22 @@
- - - -