Add functionality to expand the markdown editor

The editor will now have a default height of 300px but a button will let
the user expand the editor. It will expand it to fit all content (or up
to 400px if the content was not exceeding 300px). In the expanded mode
the editor will keep growing as the user types more content.
This commit is contained in:
Julia Casamitjana
2024-04-15 13:23:00 +02:00
committed by Dominic Sauer
parent f10bcb96a6
commit 749074fec0
5 changed files with 95 additions and 3 deletions

View File

@ -1,7 +1,7 @@
/**
* ToastUi editor initializer
*
* This script transforms form textareas created with
* This script transforms form textareas created with
* "MarkdownFormBuilder" into ToastUi markdown editors.
*
*/
@ -25,7 +25,7 @@ const initializeMarkdownEditors = () => {
target: "_blank",
},
previewHighlight: false,
height: "400px",
height: "300px",
autofocus: false,
usageStatistics: false,
language: I18n.locale,
@ -45,6 +45,8 @@ const initializeMarkdownEditors = () => {
},
});
setResizeBtn(formInput, toastEditor);
// Prevent user from drag'n'dropping images in the editor
toastEditor.removeHook("addImageBlobHook");
@ -82,6 +84,48 @@ const setMarkdownEditorTheme = (theme) => {
});
};
const hasScrollBar = (el) => el.scrollHeight > el.clientHeight;
const toggleScrollbarModifier = (btn, el) => {
if (el.clientHeight === 0) return;
btn.classList.toggle(
"markdown-editor__resize-btn--with-scrollbar",
hasScrollBar(el)
);
};
const setResizeBtn = (formInput, editor) => {
const resizeBtn = document.querySelector(`#${formInput.id}-resize`);
if (!resizeBtn) return;
const editorTextArea = editor
.getEditorElements()
.mdEditor.querySelector('[contenteditable="true"]');
toggleScrollbarModifier(resizeBtn, editorTextArea);
new MutationObserver(() => {
toggleScrollbarModifier(resizeBtn, editorTextArea);
}).observe(editorTextArea, {
attributes: true,
});
resizeBtn.addEventListener("click", () => {
const height = editor.getHeight();
if (height && height === "300px") {
editor.setHeight("auto");
editor.setMinHeight("400px");
resizeBtn.classList.add("markdown-editor__resize-btn--collapse");
resizeBtn.title = I18n.t("markdown_editor.collapse");
resizeBtn.ariaLabel = I18n.t("markdown_editor.collapse");
} else {
editor.setHeight("300px");
editor.setMinHeight("300px");
resizeBtn.classList.remove("markdown-editor__resize-btn--collapse");
resizeBtn.title = I18n.t("markdown_editor.expand");
resizeBtn.ariaLabel = I18n.t("markdown_editor.expand");
}
});
};
$(document).on("turbolinks:load", function () {
initializeMarkdownEditors();
disableImageUpload();