mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-07-30 04:23:11 +03:00
Refactored markdown editor logic
Split out the markdown editor logic into seperate components to provide a more orgranised heirachy with feature-specific files.
This commit is contained in:
410
resources/js/markdown/actions.js
Normal file
410
resources/js/markdown/actions.js
Normal file
@ -0,0 +1,410 @@
|
||||
import DrawIO from "../services/drawio";
|
||||
|
||||
export class Actions {
|
||||
/**
|
||||
* @param {MarkdownEditor} editor
|
||||
*/
|
||||
constructor(editor) {
|
||||
this.editor = editor;
|
||||
}
|
||||
|
||||
updateAndRender() {
|
||||
const content = this.editor.cm.getValue();
|
||||
this.editor.config.inputEl.value = content;
|
||||
|
||||
const html = this.editor.markdown.render(content);
|
||||
window.$events.emit('editor-html-change', html);
|
||||
window.$events.emit('editor-markdown-change', content);
|
||||
this.editor.display.patchWithHtml(html);
|
||||
}
|
||||
|
||||
insertImage() {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
/** @type {ImageManager} **/
|
||||
const imageManager = window.$components.first('image-manager');
|
||||
imageManager.show(image => {
|
||||
const imageUrl = image.thumbs.display || image.url;
|
||||
let selectedText = this.editor.cm.getSelection();
|
||||
let newText = "[](" + image.url + ")";
|
||||
this.editor.cm.focus();
|
||||
this.editor.cm.replaceSelection(newText);
|
||||
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
}, 'gallery');
|
||||
}
|
||||
|
||||
insertLink() {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
const selectedText = this.editor.cm.getSelection() || '';
|
||||
const newText = `[${selectedText}]()`;
|
||||
this.editor.cm.focus();
|
||||
this.editor.cm.replaceSelection(newText);
|
||||
const cursorPosDiff = (selectedText === '') ? -3 : -1;
|
||||
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
|
||||
}
|
||||
|
||||
showImageManager() {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
/** @type {ImageManager} **/
|
||||
const imageManager = window.$components.first('image-manager');
|
||||
imageManager.show(image => {
|
||||
this.insertDrawing(image, cursorPos);
|
||||
}, 'drawio');
|
||||
}
|
||||
|
||||
// Show the popup link selector and insert a link when finished
|
||||
showLinkSelector() {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
/** @type {EntitySelectorPopup} **/
|
||||
const selector = window.$components.first('entity-selector-popup');
|
||||
selector.show(entity => {
|
||||
let selectedText = this.editor.cm.getSelection() || entity.name;
|
||||
let newText = `[${selectedText}](${entity.link})`;
|
||||
this.editor.cm.focus();
|
||||
this.editor.cm.replaceSelection(newText);
|
||||
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
|
||||
});
|
||||
}
|
||||
|
||||
// Show draw.io if enabled and handle save.
|
||||
startDrawing() {
|
||||
const url = this.editor.config.drawioUrl;
|
||||
if (!url) return;
|
||||
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
|
||||
DrawIO.show(url,() => {
|
||||
return Promise.resolve('');
|
||||
}, (pngData) => {
|
||||
|
||||
const data = {
|
||||
image: pngData,
|
||||
uploaded_to: Number(this.pageId),
|
||||
};
|
||||
|
||||
window.$http.post("/images/drawio", data).then(resp => {
|
||||
this.insertDrawing(resp.data, cursorPos);
|
||||
DrawIO.close();
|
||||
}).catch(err => {
|
||||
this.handleDrawingUploadError(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
insertDrawing(image, originalCursor) {
|
||||
const newText = `<div drawio-diagram="${image.id}"><img src="${image.url}"></div>`;
|
||||
this.editor.cm.focus();
|
||||
this.editor.cm.replaceSelection(newText);
|
||||
this.editor.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
|
||||
}
|
||||
|
||||
// Show draw.io if enabled and handle save.
|
||||
editDrawing(imgContainer) {
|
||||
const drawioUrl = this.editor.config.drawioUrl;
|
||||
if (!drawioUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
const drawingId = imgContainer.getAttribute('drawio-diagram');
|
||||
|
||||
DrawIO.show(drawioUrl, () => {
|
||||
return DrawIO.load(drawingId);
|
||||
}, (pngData) => {
|
||||
|
||||
const data = {
|
||||
image: pngData,
|
||||
uploaded_to: Number(this.editor.config.pageId),
|
||||
};
|
||||
|
||||
window.$http.post("/images/drawio", data).then(resp => {
|
||||
const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
|
||||
const newContent = this.editor.cm.getValue().split('\n').map(line => {
|
||||
if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
|
||||
return newText;
|
||||
}
|
||||
return line;
|
||||
}).join('\n');
|
||||
this.editor.cm.setValue(newContent);
|
||||
this.editor.cm.setCursor(cursorPos);
|
||||
this.editor.cm.focus();
|
||||
DrawIO.close();
|
||||
}).catch(err => {
|
||||
this.handleDrawingUploadError(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
handleDrawingUploadError(error) {
|
||||
if (error.status === 413) {
|
||||
window.$events.emit('error', this.editor.config.text.serverUploadLimit);
|
||||
} else {
|
||||
window.$events.emit('error', this.editor.config.text.imageUploadError);
|
||||
}
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
// Make the editor full screen
|
||||
fullScreen() {
|
||||
const container = this.editor.config.container;
|
||||
const alreadyFullscreen = container.classList.contains('fullscreen');
|
||||
container.classList.toggle('fullscreen', !alreadyFullscreen);
|
||||
document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
|
||||
}
|
||||
|
||||
// Scroll to a specified text
|
||||
scrollToText(searchText) {
|
||||
if (!searchText) {
|
||||
return;
|
||||
}
|
||||
|
||||
const content = this.editor.cm.getValue();
|
||||
const lines = content.split(/\r?\n/);
|
||||
let lineNumber = lines.findIndex(line => {
|
||||
return line && line.indexOf(searchText) !== -1;
|
||||
});
|
||||
|
||||
if (lineNumber === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.editor.cm.scrollIntoView({
|
||||
line: lineNumber,
|
||||
}, 200);
|
||||
this.editor.cm.focus();
|
||||
// set the cursor location.
|
||||
this.editor.cm.setCursor({
|
||||
line: lineNumber,
|
||||
char: lines[lineNumber].length
|
||||
})
|
||||
}
|
||||
|
||||
focus() {
|
||||
this.editor.cm.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert content into the editor.
|
||||
* @param {String} content
|
||||
*/
|
||||
insertContent(content) {
|
||||
this.editor.cm.replaceSelection(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepend content to the editor.
|
||||
* @param {String} content
|
||||
*/
|
||||
prependContent(content) {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
const newContent = content + '\n' + this.editor.cm.getValue();
|
||||
this.editor.cm.setValue(newContent);
|
||||
const prependLineCount = content.split('\n').length;
|
||||
this.editor.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Append content to the editor.
|
||||
* @param {String} content
|
||||
*/
|
||||
appendContent(content) {
|
||||
const cursorPos = this.editor.cm.getCursor('from');
|
||||
const newContent = this.editor.cm.getValue() + '\n' + content;
|
||||
this.editor.cm.setValue(newContent);
|
||||
this.editor.cm.setCursor(cursorPos.line, cursorPos.ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the editor's contents
|
||||
* @param {String} content
|
||||
*/
|
||||
replaceContent(content) {
|
||||
this.editor.cm.setValue(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String|RegExp} search
|
||||
* @param {String} replace
|
||||
*/
|
||||
findAndReplaceContent(search, replace) {
|
||||
const text = this.editor.cm.getValue();
|
||||
const cursor = this.editor.cm.listSelections();
|
||||
this.editor.cm.setValue(text.replace(search, replace));
|
||||
this.editor.cm.setSelections(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the start of the line
|
||||
* @param {String} newStart
|
||||
*/
|
||||
replaceLineStart(newStart) {
|
||||
const cursor = this.editor.cm.getCursor();
|
||||
let lineContent = this.editor.cm.getLine(cursor.line);
|
||||
const lineLen = lineContent.length;
|
||||
const lineStart = lineContent.split(' ')[0];
|
||||
|
||||
// Remove symbol if already set
|
||||
if (lineStart === newStart) {
|
||||
lineContent = lineContent.replace(`${newStart} `, '');
|
||||
this.editor.cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
|
||||
return;
|
||||
}
|
||||
|
||||
const alreadySymbol = /^[#>`]/.test(lineStart);
|
||||
let posDif = 0;
|
||||
if (alreadySymbol) {
|
||||
posDif = newStart.length - lineStart.length;
|
||||
lineContent = lineContent.replace(lineStart, newStart).trim();
|
||||
} else if (newStart !== '') {
|
||||
posDif = newStart.length + 1;
|
||||
lineContent = newStart + ' ' + lineContent;
|
||||
}
|
||||
this.editor.cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the line in the given start and end contents.
|
||||
* @param {String} start
|
||||
* @param {String} end
|
||||
*/
|
||||
wrapLine(start, end) {
|
||||
const cursor = this.editor.cm.getCursor();
|
||||
const lineContent = this.editor.cm.getLine(cursor.line);
|
||||
const lineLen = lineContent.length;
|
||||
let newLineContent = lineContent;
|
||||
|
||||
if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
|
||||
newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
|
||||
} else {
|
||||
newLineContent = `${start}${lineContent}${end}`;
|
||||
}
|
||||
|
||||
this.editor.cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
|
||||
this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the selection in the given contents start and end contents.
|
||||
* @param {String} start
|
||||
* @param {String} end
|
||||
*/
|
||||
wrapSelection(start, end) {
|
||||
const selection = this.editor.cm.getSelection();
|
||||
if (selection === '') return this.wrapLine(start, end);
|
||||
|
||||
let newSelection = selection;
|
||||
const frontDiff = 0;
|
||||
let endDiff;
|
||||
|
||||
if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
|
||||
newSelection = selection.slice(start.length, selection.length - end.length);
|
||||
endDiff = -(end.length + start.length);
|
||||
} else {
|
||||
newSelection = `${start}${selection}${end}`;
|
||||
endDiff = start.length + end.length;
|
||||
}
|
||||
|
||||
const selections = this.editor.cm.listSelections()[0];
|
||||
this.editor.cm.replaceSelection(newSelection);
|
||||
const headFirst = selections.head.ch <= selections.anchor.ch;
|
||||
selections.head.ch += headFirst ? frontDiff : endDiff;
|
||||
selections.anchor.ch += headFirst ? endDiff : frontDiff;
|
||||
this.editor.cm.setSelections([selections]);
|
||||
}
|
||||
|
||||
replaceLineStartForOrderedList() {
|
||||
const cursor = this.editor.cm.getCursor();
|
||||
const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
|
||||
const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
|
||||
|
||||
const number = (Number(listMatch[2]) || 0) + 1;
|
||||
const whiteSpace = listMatch[1] || '';
|
||||
const listMark = listMatch[3] || '.'
|
||||
|
||||
const prefix = `${whiteSpace}${number}${listMark}`;
|
||||
return this.replaceLineStart(prefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle image upload and add image into markdown content
|
||||
* @param {File} file
|
||||
*/
|
||||
uploadImage(file) {
|
||||
if (file === null || file.type.indexOf('image') !== 0) return;
|
||||
let ext = 'png';
|
||||
|
||||
if (file.name) {
|
||||
let fileNameMatches = file.name.match(/\.(.+)$/);
|
||||
if (fileNameMatches.length > 1) ext = fileNameMatches[1];
|
||||
}
|
||||
|
||||
// Insert image into markdown
|
||||
const id = "image-" + Math.random().toString(16).slice(2);
|
||||
const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
|
||||
const selectedText = this.editor.cm.getSelection();
|
||||
const placeHolderText = ``;
|
||||
const cursor = this.editor.cm.getCursor();
|
||||
this.editor.cm.replaceSelection(placeHolderText);
|
||||
this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
|
||||
|
||||
const remoteFilename = "image-" + Date.now() + "." + ext;
|
||||
const formData = new FormData();
|
||||
formData.append('file', file, remoteFilename);
|
||||
formData.append('uploaded_to', this.editor.config.pageId);
|
||||
|
||||
window.$http.post('/images/gallery', formData).then(resp => {
|
||||
const newContent = `[](${resp.data.url})`;
|
||||
this.findAndReplaceContent(placeHolderText, newContent);
|
||||
}).catch(err => {
|
||||
window.$events.emit('error', this.editor.config.text.imageUploadError);
|
||||
this.findAndReplaceContent(placeHolderText, selectedText);
|
||||
console.log(err);
|
||||
});
|
||||
}
|
||||
|
||||
syncDisplayPosition() {
|
||||
// Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
|
||||
const scroll = this.editor.cm.getScrollInfo();
|
||||
const atEnd = scroll.top + scroll.clientHeight === scroll.height;
|
||||
if (atEnd) {
|
||||
editor.display.scrollToIndex(-1);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineNum = this.editor.cm.lineAtHeight(scroll.top, 'local');
|
||||
const range = this.editor.cm.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
|
||||
const totalLines = doc.documentElement.querySelectorAll('body > *');
|
||||
editor.display.scrollToIndex(totalLines.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and insert the template of the given ID.
|
||||
* The page-relative position provided can be used to determine insert location if possible.
|
||||
* @param {String} templateId
|
||||
* @param {Number} posX
|
||||
* @param {Number} posY
|
||||
*/
|
||||
insertTemplate(templateId, posX, posY) {
|
||||
const cursorPos = this.editor.cm.coordsChar({left: posX, top: posY});
|
||||
this.editor.cm.setCursor(cursorPos);
|
||||
window.$http.get(`/templates/${templateId}`).then(resp => {
|
||||
const content = resp.data.markdown || resp.data.html;
|
||||
this.editor.cm.replaceSelection(content);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert multiple images from the clipboard.
|
||||
* @param {File[]} images
|
||||
*/
|
||||
insertClipboardImages(images) {
|
||||
const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
|
||||
this.editor.cm.setCursor(cursorPos);
|
||||
for (const image of images) {
|
||||
editor.actions.uploadImage(image);
|
||||
}
|
||||
}
|
||||
}
|
64
resources/js/markdown/codemirror.js
Normal file
64
resources/js/markdown/codemirror.js
Normal file
@ -0,0 +1,64 @@
|
||||
import {provide as provideShortcuts} from "./shortcuts";
|
||||
import {debounce} from "../services/util";
|
||||
import Clipboard from "../services/clipboard";
|
||||
|
||||
/**
|
||||
* Initiate the codemirror instance for the markdown editor.
|
||||
* @param {MarkdownEditor} editor
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function init(editor) {
|
||||
const Code = await window.importVersioned('code');
|
||||
const cm = Code.markdownEditor(editor.config.inputEl);
|
||||
|
||||
// Will force to remain as ltr for now due to issues when HTML is in editor.
|
||||
cm.setOption('direction', 'ltr');
|
||||
// Register shortcuts
|
||||
cm.setOption('extraKeys', provideShortcuts(editor, Code.getMetaKey()));
|
||||
|
||||
|
||||
// Register codemirror events
|
||||
|
||||
// Update data on content change
|
||||
cm.on('change', (instance, changeObj) => editor.actions.updateAndRender());
|
||||
|
||||
// Handle scroll to sync display view
|
||||
const onScrollDebounced = debounce(editor.actions.syncDisplayPosition, 100, false);
|
||||
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) {
|
||||
editor.actions.uploadImage(image);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle image & content drag n drop
|
||||
cm.on('drop', (cm, event) => {
|
||||
|
||||
const templateId = event.dataTransfer.getData('bookstack/template');
|
||||
if (templateId) {
|
||||
event.preventDefault();
|
||||
editor.actions.insertTemplate(templateId, event.pageX, event.pageY);
|
||||
}
|
||||
|
||||
const clipboard = new Clipboard(event.dataTransfer);
|
||||
const clipboardImages = clipboard.getImages();
|
||||
if (clipboardImages.length > 0) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
editor.actions.insertClipboardImages(clipboardImages);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
return cm;
|
||||
}
|
33
resources/js/markdown/common-events.js
Normal file
33
resources/js/markdown/common-events.js
Normal file
@ -0,0 +1,33 @@
|
||||
function getContentToInsert({html, markdown}) {
|
||||
return markdown || html;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {MarkdownEditor} editor
|
||||
*/
|
||||
export function listen(editor) {
|
||||
|
||||
window.$events.listen('editor::replace', (eventContent) => {
|
||||
const markdown = getContentToInsert(eventContent);
|
||||
editor.actions.replaceContent(markdown);
|
||||
});
|
||||
|
||||
window.$events.listen('editor::append', (eventContent) => {
|
||||
const markdown = getContentToInsert(eventContent);
|
||||
editor.actions.appendContent(markdown);
|
||||
});
|
||||
|
||||
window.$events.listen('editor::prepend', (eventContent) => {
|
||||
const markdown = getContentToInsert(eventContent);
|
||||
editor.actions.prependContent(markdown);
|
||||
});
|
||||
|
||||
window.$events.listen('editor::insert', (eventContent) => {
|
||||
const markdown = getContentToInsert(eventContent);
|
||||
editor.actions.insertContent(markdown);
|
||||
});
|
||||
|
||||
window.$events.listen('editor::focus', () => {
|
||||
editor.actions.focus();
|
||||
});
|
||||
}
|
101
resources/js/markdown/display.js
Normal file
101
resources/js/markdown/display.js
Normal file
@ -0,0 +1,101 @@
|
||||
import {patchDomFromHtmlString} from "../services/vdom";
|
||||
|
||||
export class Display {
|
||||
|
||||
/**
|
||||
* @param {MarkdownEditor} editor
|
||||
*/
|
||||
constructor(editor) {
|
||||
this.editor = editor;
|
||||
this.container = editor.config.displayEl;
|
||||
|
||||
this.doc = null;
|
||||
this.lastDisplayClick = 0;
|
||||
|
||||
if (this.container.contentDocument.readyState === 'complete') {
|
||||
this.onLoad();
|
||||
} else {
|
||||
this.container.addEventListener('load', this.onLoad.bind(this));
|
||||
}
|
||||
}
|
||||
|
||||
onLoad() {
|
||||
this.doc = this.container.contentDocument;
|
||||
|
||||
this.loadStylesIntoDisplay();
|
||||
this.doc.body.className = 'page-content';
|
||||
|
||||
// Prevent markdown display link click redirect
|
||||
this.doc.addEventListener('click', this.onDisplayClick)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {MouseEvent} event
|
||||
*/
|
||||
onDisplayClick(event) {
|
||||
const isDblClick = Date.now() - this.lastDisplayClick < 300;
|
||||
|
||||
const link = event.target.closest('a');
|
||||
if (link !== null) {
|
||||
event.preventDefault();
|
||||
window.open(link.getAttribute('href'));
|
||||
return;
|
||||
}
|
||||
|
||||
const drawing = event.target.closest('[drawio-diagram]');
|
||||
if (drawing !== null && isDblClick) {
|
||||
this.editor.actions.editDrawing(drawing);
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastDisplayClick = Date.now();
|
||||
}
|
||||
|
||||
loadStylesIntoDisplay() {
|
||||
this.doc.documentElement.classList.add('markdown-editor-display');
|
||||
|
||||
// Set display to be dark mode if parent is
|
||||
if (document.documentElement.classList.contains('dark-mode')) {
|
||||
this.doc.documentElement.style.backgroundColor = '#222';
|
||||
this.doc.documentElement.classList.add('dark-mode');
|
||||
}
|
||||
|
||||
this.doc.head.innerHTML = '';
|
||||
const styles = document.head.querySelectorAll('style,link[rel=stylesheet]');
|
||||
for (const style of styles) {
|
||||
const copy = style.cloneNode(true);
|
||||
this.doc.head.appendChild(copy);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch the display DOM with the given HTML content.
|
||||
* @param {String} html
|
||||
*/
|
||||
patchWithHtml(html) {
|
||||
const body = this.doc.body;
|
||||
|
||||
if (body.children.length === 0) {
|
||||
const wrap = document.createElement('div');
|
||||
this.doc.body.append(wrap);
|
||||
}
|
||||
|
||||
const target = body.children[0];
|
||||
|
||||
patchDomFromHtmlString(target, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll to the given block index within the display content.
|
||||
* Will scroll to the end if the index is -1.
|
||||
* @param {Number} index
|
||||
*/
|
||||
scrollToIndex(index) {
|
||||
const elems = this.doc.body.children;
|
||||
if (elems.length <= index) return;
|
||||
|
||||
const topElem = (index === -1) ? elems[elems.length-1] : elems[index];
|
||||
topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
|
||||
}
|
||||
|
||||
}
|
50
resources/js/markdown/editor.js
Normal file
50
resources/js/markdown/editor.js
Normal file
@ -0,0 +1,50 @@
|
||||
import {Markdown} from "./markdown";
|
||||
import {Display} from "./display";
|
||||
import {Actions} from "./actions";
|
||||
import {listen} from "./common-events";
|
||||
import {init as initCodemirror} from "./codemirror";
|
||||
|
||||
|
||||
/**
|
||||
* Initiate a new markdown editor instance.
|
||||
* @param {MarkdownEditorConfig} config
|
||||
* @returns {Promise<MarkdownEditor>}
|
||||
*/
|
||||
export async function init(config) {
|
||||
|
||||
/**
|
||||
* @type {MarkdownEditor}
|
||||
*/
|
||||
const editor = {
|
||||
config,
|
||||
markdown: new Markdown(),
|
||||
};
|
||||
|
||||
editor.actions = new Actions(editor);
|
||||
editor.display = new Display(editor);
|
||||
editor.cm = await initCodemirror(editor);
|
||||
|
||||
listen(editor);
|
||||
|
||||
return editor;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @typedef MarkdownEditorConfig
|
||||
* @property {String} pageId
|
||||
* @property {Element} container
|
||||
* @property {Element} displayEl
|
||||
* @property {HTMLTextAreaElement} inputEl
|
||||
* @property {String} drawioUrl
|
||||
* @property {Object<String, String>} text
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef MarkdownEditor
|
||||
* @property {MarkdownEditorConfig} config
|
||||
* @property {Display} display
|
||||
* @property {Markdown} markdown
|
||||
* @property {Actions} actions
|
||||
* @property {CodeMirror} cm
|
||||
*/
|
30
resources/js/markdown/markdown.js
Normal file
30
resources/js/markdown/markdown.js
Normal file
@ -0,0 +1,30 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import mdTasksLists from 'markdown-it-task-lists';
|
||||
|
||||
export class Markdown {
|
||||
|
||||
constructor() {
|
||||
this.renderer = new MarkdownIt({html: true});
|
||||
this.renderer.use(mdTasksLists, {label: true});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the front-end render used to convert markdown to HTML.
|
||||
* @returns {MarkdownIt}
|
||||
*/
|
||||
getRenderer() {
|
||||
return this.renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the given Markdown to HTML.
|
||||
* @param {String} markdown
|
||||
* @returns {String}
|
||||
*/
|
||||
render(markdown) {
|
||||
return this.renderer.render(markdown);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
48
resources/js/markdown/shortcuts.js
Normal file
48
resources/js/markdown/shortcuts.js
Normal file
@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Provide shortcuts for the given codemirror instance.
|
||||
* @param {MarkdownEditor} editor
|
||||
* @param {String} metaKey
|
||||
* @returns {Object<String, Function>}
|
||||
*/
|
||||
export function provide(editor, metaKey) {
|
||||
const shortcuts = {};
|
||||
|
||||
// Insert Image shortcut
|
||||
shortcuts[`${metaKey}-Alt-I`] = function(cm) {
|
||||
const selectedText = cm.getSelection();
|
||||
const newText = ``;
|
||||
const cursorPos = cm.getCursor('from');
|
||||
cm.replaceSelection(newText);
|
||||
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
|
||||
};
|
||||
|
||||
// Save draft
|
||||
shortcuts[`${metaKey}-S`] = cm => window.$events.emit('editor-save-draft');
|
||||
|
||||
// Save page
|
||||
shortcuts[`${metaKey}-Enter`] = cm => window.$events.emit('editor-save-page');
|
||||
|
||||
// Show link selector
|
||||
shortcuts[`Shift-${metaKey}-K`] = cm => editor.actions.showLinkSelector();
|
||||
|
||||
// Insert Link
|
||||
shortcuts[`${metaKey}-K`] = cm => editor.actions.insertLink();
|
||||
|
||||
// FormatShortcuts
|
||||
shortcuts[`${metaKey}-1`] = cm => editor.actions.replaceLineStart('##');
|
||||
shortcuts[`${metaKey}-2`] = cm => editor.actions.replaceLineStart('###');
|
||||
shortcuts[`${metaKey}-3`] = cm => editor.actions.replaceLineStart('####');
|
||||
shortcuts[`${metaKey}-4`] = cm => editor.actions.replaceLineStart('#####');
|
||||
shortcuts[`${metaKey}-5`] = cm => editor.actions.replaceLineStart('');
|
||||
shortcuts[`${metaKey}-D`] = cm => editor.actions.replaceLineStart('');
|
||||
shortcuts[`${metaKey}-6`] = cm => editor.actions.replaceLineStart('>');
|
||||
shortcuts[`${metaKey}-Q`] = cm => editor.actions.replaceLineStart('>');
|
||||
shortcuts[`${metaKey}-7`] = cm => editor.actions.wrapSelection('\n```\n', '\n```');
|
||||
shortcuts[`${metaKey}-8`] = cm => editor.actions.wrapSelection('`', '`');
|
||||
shortcuts[`Shift-${metaKey}-E`] = cm => editor.actions.wrapSelection('`', '`');
|
||||
shortcuts[`${metaKey}-9`] = cm => editor.actions.wrapSelection('<p class="callout info">', '</p>');
|
||||
shortcuts[`${metaKey}-P`] = cm => editor.actions.replaceLineStart('-')
|
||||
shortcuts[`${metaKey}-O`] = cm => editor.actions.replaceLineStartForOrderedList()
|
||||
|
||||
return shortcuts;
|
||||
}
|
Reference in New Issue
Block a user