- cmLoadPromise.then(cm => {
- this.codeMirrorSetup(cm);
-
- // Refresh CodeMirror on container resize
- const resizeDebounced = debounce(() => this.Code.updateLayout(cm), 100, false);
- const observer = new ResizeObserver(resizeDebounced);
- observer.observe(this.elem);
- });
-
- this.listenForBookStackEditorEvents();
-
- // Scroll to text if needed.
- const queryParams = (new URL(window.location)).searchParams;
- const scrollText = queryParams.get('content-text');
- if (scrollText) {
- this.scrollToText(scrollText);
- }
- }
-
- // Update the input content and render the display.
- updateAndRender() {
- const content = this.cm.getValue();
- this.input.value = content;
-
- const html = this.markdown.render(content);
- window.$events.emit('editor-html-change', html);
- window.$events.emit('editor-markdown-change', content);
-
- // Set body content
- const target = this.getDisplayTarget();
- this.displayDoc.body.className = 'page-content';
- patchDomFromHtmlString(target, html);
-
- // Copy styles from page head and set custom styles for editor
- this.loadStylesIntoDisplay();
- }
-
- getDisplayTarget() {
- const body = this.displayDoc.body;
-
- if (body.children.length === 0) {
- const wrap = document.createElement('div');
- this.displayDoc.body.append(wrap);
- }
-
- return body.children[0];
- }
-
- loadStylesIntoDisplay() {
- if (this.displayStylesLoaded) return;
- this.displayDoc.documentElement.classList.add('markdown-editor-display');
- // Set display to be dark mode if parent is
-
- if (document.documentElement.classList.contains('dark-mode')) {
- this.displayDoc.documentElement.style.backgroundColor = '#222';
- this.displayDoc.documentElement.classList.add('dark-mode');
- }
-
- this.displayDoc.head.innerHTML = '';
- const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
- for (let style of styles) {
- const copy = style.cloneNode(true);
- this.displayDoc.head.appendChild(copy);
- }
-
- this.displayStylesLoaded = true;
- }
-
- onMarkdownScroll(lineCount) {
- const elems = this.displayDoc.body.children;
- if (elems.length <= lineCount) return;
-
- const topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
- topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
- }
-
- codeMirrorSetup(cm) {
- const context = this;
-
- // Text direction
- // cm.setOption('direction', this.textDirection);
- cm.setOption('direction', 'ltr'); // Will force to remain as ltr for now due to issues when HTML is in editor.
- // Custom key commands
- let metaKey = this.Code.getMetaKey();
- const extraKeys = {};
- // Insert Image shortcut
- extraKeys[`${metaKey}-Alt-I`] = function(cm) {
- let selectedText = cm.getSelection();
- let newText = ``;
- let cursorPos = cm.getCursor('from');
- cm.replaceSelection(newText);
- cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
- };
- // Save draft
- extraKeys[`${metaKey}-S`] = cm => {window.$events.emit('editor-save-draft')};
- // Save page
- extraKeys[`${metaKey}-Enter`] = cm => {window.$events.emit('editor-save-page')};
- // Show link selector
- extraKeys[`Shift-${metaKey}-K`] = cm => {this.actionShowLinkSelector()};
- // Insert Link
- extraKeys[`${metaKey}-K`] = cm => {insertLink()};
- // FormatShortcuts
- extraKeys[`${metaKey}-1`] = cm => {replaceLineStart('##');};
- extraKeys[`${metaKey}-2`] = cm => {replaceLineStart('###');};
- extraKeys[`${metaKey}-3`] = cm => {replaceLineStart('####');};
- extraKeys[`${metaKey}-4`] = cm => {replaceLineStart('#####');};
- extraKeys[`${metaKey}-5`] = cm => {replaceLineStart('');};
- extraKeys[`${metaKey}-d`] = cm => {replaceLineStart('');};
- extraKeys[`${metaKey}-6`] = cm => {replaceLineStart('>');};
- extraKeys[`${metaKey}-q`] = cm => {replaceLineStart('>');};
- extraKeys[`${metaKey}-7`] = cm => {wrapSelection('\n```\n', '\n```');};
- extraKeys[`${metaKey}-8`] = cm => {wrapSelection('`', '`');};
- extraKeys[`Shift-${metaKey}-E`] = cm => {wrapSelection('`', '`');};
- extraKeys[`${metaKey}-9`] = cm => {wrapSelection('<p class="callout info">', '</p>');};
- cm.setOption('extraKeys', extraKeys);
-
- // Update data on content change
- cm.on('change', (instance, changeObj) => {
- this.updateAndRender();
- });
-
- const onScrollDebounced = debounce((instance) => {
- // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
- let scroll = instance.getScrollInfo();
- let atEnd = scroll.top + scroll.clientHeight === scroll.height;
- if (atEnd) {
- this.onMarkdownScroll(-1);
- return;
- }
-
- let lineNum = instance.lineAtHeight(scroll.top, 'local');
- let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
- let parser = new DOMParser();
- let doc = parser.parseFromString(this.markdown.render(range), 'text/html');
- let totalLines = doc.documentElement.querySelectorAll('body > *');
- this.onMarkdownScroll(totalLines.length);
- }, 100);
-
- // Handle scroll to sync display view
- cm.on('scroll', instance => {
- onScrollDebounced(instance);
- });
-
- // Handle image paste
- cm.on('paste', (cm, event) => {
- const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
-
- // Don't handle the event ourselves if no items exist of contains table-looking data
- if (!clipboard.hasItems() || clipboard.containsTabularData()) {
- return;
- }
-
- const images = clipboard.getImages();
- for (const image of images) {
- uploadImage(image);
- }
- });
-
- // Handle image & content drag n drop
- cm.on('drop', (cm, event) => {
-
- const templateId = event.dataTransfer.getData('bookstack/template');
- if (templateId) {
- const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
- cm.setCursor(cursorPos);
- event.preventDefault();
- window.$http.get(`/templates/${templateId}`).then(resp => {
- const content = resp.data.markdown || resp.data.html;
- cm.replaceSelection(content);
- });
- }
-
- const clipboard = new Clipboard(event.dataTransfer);
- if (clipboard.hasItems() && clipboard.getImages().length > 0) {
- const cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
- cm.setCursor(cursorPos);
- event.stopPropagation();
- event.preventDefault();
- const images = clipboard.getImages();
- for (const image of images) {
- uploadImage(image);
- }
- }
-
- });
-
- // Helper to replace editor content
- function replaceContent(search, replace) {
- let text = cm.getValue();
- let cursor = cm.listSelections();
- cm.setValue(text.replace(search, replace));
- cm.setSelections(cursor);
- }
-
- // Helper to replace the start of the line
- function replaceLineStart(newStart) {
- let cursor = cm.getCursor();
- let lineContent = cm.getLine(cursor.line);
- let lineLen = lineContent.length;
- let lineStart = lineContent.split(' ')[0];