0
0
Fork 0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-05-18 14:21:05 +00:00

Revamped workings of WYSIWYG code blocks

Code blocks in tinymce could sometimes end up exploded into the sub
elements of the codemirror display.
This changes the strategy to render codemirror within the shadow dom of
a custom element while preserving the normal pre/code DOM structure.

Still a little instability when moving/adding code blocks within details
blocks but much harder to break things now.
This commit is contained in:
Dan Brown 2022-02-09 19:24:27 +00:00
parent 2b46b00f29
commit 2b3726702d
No known key found for this signature in database
GPG key ID: 46D9F943C24A2EF9
7 changed files with 216 additions and 148 deletions
resources/js

View file

@ -204,56 +204,22 @@ function getTheme() {
/**
* Create a CodeMirror instance for showing inside the WYSIWYG editor.
* Manages a textarea element to hold code content.
* @param {HTMLElement} elem
* @param {HTMLElement} cmContainer
* @param {String} content
* @param {String} language
* @returns {{wrap: Element, editor: *}}
*/
export function wysiwygView(elem) {
const doc = elem.ownerDocument;
const codeElem = elem.querySelector('code');
let lang = getLanguageFromCssClasses(elem.className || '');
if (!lang && codeElem) {
lang = getLanguageFromCssClasses(codeElem.className || '');
}
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
const content = elem.textContent;
const newWrap = doc.createElement('div');
const newTextArea = doc.createElement('textarea');
newWrap.className = 'CodeMirrorContainer';
newWrap.setAttribute('data-lang', lang);
newWrap.setAttribute('dir', 'ltr');
newTextArea.style.display = 'none';
elem.parentNode.replaceChild(newWrap, elem);
newWrap.appendChild(newTextArea);
newWrap.contentEditable = 'false';
newTextArea.textContent = content;
let cm = CodeMirror(function(elt) {
newWrap.appendChild(elt);
}, {
export function wysiwygView(cmContainer, content, language) {
return CodeMirror(cmContainer, {
value: content,
mode: getMode(lang, content),
mode: getMode(language, content),
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
readOnly: true
});
return {wrap: newWrap, editor: cm};
}
/**
* Get the code language from the given css classes.
* @param {String} classes
* @return {String}
*/
function getLanguageFromCssClasses(classes) {
const langClasses = classes.split(' ').filter(cssClass => cssClass.startsWith('language-'));
return (langClasses[0] || '').replace('language-', '');
}
/**
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor