1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2024-10-30 15:42:41 +01:00

Merge pull request #3875 from BookStackApp/md_editor_updates

Markdown Editor Updates
This commit is contained in:
Dan Brown 2022-11-28 12:21:33 +00:00 committed by GitHub
commit b786ed07be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 1041 additions and 629 deletions

View File

@ -29,6 +29,8 @@ return [
'ui-shortcuts' => '{}',
'ui-shortcuts-enabled' => false,
'dark-mode-enabled' => env('APP_DEFAULT_DARK_MODE', false),
'md-show-preview' => true,
'md-scroll-sync' => true,
'bookshelves_view_type' => env('APP_VIEWS_BOOKSHELVES', 'grid'),
'bookshelf_view_type' => env('APP_VIEWS_BOOKSHELF', 'grid'),
'books_view_type' => env('APP_VIEWS_BOOKS', 'grid'),

View File

@ -115,6 +115,9 @@ class UserPreferencesController extends Controller
return response('', 204);
}
/**
* Update the favorite status for a code language.
*/
public function updateCodeLanguageFavourite(Request $request)
{
$validated = $this->validate($request, [
@ -134,5 +137,27 @@ class UserPreferencesController extends Controller
}
setting()->putForCurrentUser('code-language-favourites', implode(',', $currentFavorites));
return response('', 204);
}
/**
* Update a boolean user preference setting.
*/
public function updateBooleanPreference(Request $request)
{
$allowedKeys = ['md-scroll-sync', 'md-show-preview'];
$validated = $this->validate($request, [
'name' => ['required', 'string'],
'value' => ['required'],
]);
if (!in_array($validated['name'], $allowedKeys)) {
return response('Invalid boolean preference', 500);
}
$value = $validated['value'] === 'true' ? 'true' : 'false';
setting()->putForCurrentUser($validated['name'], $value);
return response('', 204);
}
}

View File

@ -1,4 +1 @@
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86l-3 3.87L9 13.14 6 17h12l-3.86-5.14z"/></svg>

Before

Width:  |  Height:  |  Size: 246 B

After

Width:  |  Height:  |  Size: 216 B

View File

@ -1,10 +1,6 @@
import MarkdownIt from "markdown-it";
import mdTasksLists from 'markdown-it-task-lists';
import Clipboard from "../services/clipboard";
import {debounce} from "../services/util";
import {patchDomFromHtmlString} from "../services/vdom";
import DrawIO from "../services/drawio";
import {Component} from "./component";
import {init as initEditor} from "../markdown/editor";
export class MarkdownEditor extends Component {
@ -16,80 +12,55 @@ export class MarkdownEditor extends Component {
this.imageUploadErrorText = this.$opts.imageUploadErrorText;
this.serverUploadLimitText = this.$opts.serverUploadLimitText;
this.markdown = new MarkdownIt({html: true});
this.markdown.use(mdTasksLists, {label: true});
this.display = this.$refs.display;
this.input = this.$refs.input;
this.settingContainer = this.$refs.settingContainer;
this.display = this.elem.querySelector('.markdown-display');
this.displayStylesLoaded = false;
this.input = this.elem.querySelector('textarea');
this.cm = null;
this.Code = null;
const cmLoadPromise = window.importVersioned('code').then(Code => {
this.cm = Code.markdownEditor(this.input);
this.Code = Code;
return this.cm;
});
this.onMarkdownScroll = this.onMarkdownScroll.bind(this);
const displayLoad = () => {
this.displayDoc = this.display.contentDocument;
this.init(cmLoadPromise);
};
if (this.display.contentDocument.readyState === 'complete') {
displayLoad();
} else {
this.display.addEventListener('load', displayLoad.bind(this));
}
window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
markdownIt: this.markdown,
this.editor = null;
initEditor({
pageId: this.pageId,
container: this.elem,
displayEl: this.display,
codeMirrorInstance: this.cm,
inputEl: this.input,
drawioUrl: this.getDrawioUrl(),
text: {
serverUploadLimit: this.serverUploadLimitText,
imageUploadError: this.imageUploadErrorText,
},
settings: this.loadSettings(),
}).then(editor => {
this.editor = editor;
this.setupListeners();
this.emitEditorEvents();
this.scrollToTextIfNeeded();
this.editor.actions.updateAndRender();
});
}
init(cmLoadPromise) {
let lastClick = 0;
// Prevent markdown display link click redirect
this.displayDoc.addEventListener('click', event => {
let isDblClick = Date.now() - lastClick < 300;
let link = event.target.closest('a');
if (link !== null) {
event.preventDefault();
window.open(link.getAttribute('href'));
return;
}
let drawing = event.target.closest('[drawio-diagram]');
if (drawing !== null && isDblClick) {
this.actionEditDrawing(drawing);
return;
}
lastClick = Date.now();
emitEditorEvents() {
window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
markdownIt: this.editor.markdown.getRenderer(),
displayEl: this.display,
codeMirrorInstance: this.editor.cm,
});
}
setupListeners() {
// Button actions
this.elem.addEventListener('click', event => {
let button = event.target.closest('button[data-action]');
if (button === null) return;
let action = button.getAttribute('data-action');
if (action === 'insertImage') this.actionInsertImage();
if (action === 'insertLink') this.actionShowLinkSelector();
const action = button.getAttribute('data-action');
if (action === 'insertImage') this.editor.actions.insertImage();
if (action === 'insertLink') this.editor.actions.showLinkSelector();
if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
this.actionShowImageManager();
this.editor.actions.showImageManager();
return;
}
if (action === 'insertDrawing') this.actionStartDrawing();
if (action === 'fullscreen') this.actionFullScreen();
if (action === 'insertDrawing') this.editor.actions.startDrawing();
if (action === 'fullscreen') this.editor.actions.fullScreen();
});
// Mobile section toggling
@ -98,531 +69,58 @@ export class MarkdownEditor extends Component {
if (!toolbarLabel) return;
const currentActiveSections = this.elem.querySelectorAll('.markdown-editor-wrap');
for (let activeElem of currentActiveSections) {
for (const activeElem of currentActiveSections) {
activeElem.classList.remove('active');
}
toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
});
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);
// Setting changes
this.settingContainer.addEventListener('change', e => {
const actualInput = e.target.parentNode.querySelector('input[type="hidden"]');
const name = actualInput.getAttribute('name');
const value = actualInput.getAttribute('value');
window.$http.patch('/preferences/update-boolean', {name, value});
this.editor.settings.set(name, value === 'true');
});
this.listenForBookStackEditorEvents();
// Refresh CodeMirror on container resize
const resizeDebounced = debounce(() => this.editor.cm.refresh(), 100, false);
const observer = new ResizeObserver(resizeDebounced);
observer.observe(this.elem);
}
// Scroll to text if needed.
loadSettings() {
const settings = {};
const inputs = this.settingContainer.querySelectorAll('input[type="hidden"]');
for (const input of inputs) {
settings[input.getAttribute('name')] = input.value === 'true';
}
return settings;
}
scrollToTextIfNeeded() {
const queryParams = (new URL(window.location)).searchParams;
const scrollText = queryParams.get('content-text');
if (scrollText) {
this.scrollToText(scrollText);
this.editor.actions.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 = `![${selectedText}](http://)`;
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>');};
extraKeys[`${metaKey}-P`] = cm => {replaceLineStart('-')}
extraKeys[`${metaKey}-O`] = cm => {replaceLineStartForOrderedList()}
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];
// Remove symbol if already set
if (lineStart === newStart) {
lineContent = lineContent.replace(`${newStart} `, '');
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
return;
}
let 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;
}
cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
}
function wrapLine(start, end) {
let cursor = cm.getCursor();
let lineContent = cm.getLine(cursor.line);
let 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}`;
}
cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
cm.setCursor({line: cursor.line, ch: cursor.ch + start.length});
}
function wrapSelection(start, end) {
let selection = cm.getSelection();
if (selection === '') return wrapLine(start, end);
let newSelection = selection;
let frontDiff = 0;
let endDiff = 0;
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;
}
let selections = cm.listSelections()[0];
cm.replaceSelection(newSelection);
let headFirst = selections.head.ch <= selections.anchor.ch;
selections.head.ch += headFirst ? frontDiff : endDiff;
selections.anchor.ch += headFirst ? endDiff : frontDiff;
cm.setSelections([selections]);
}
function replaceLineStartForOrderedList() {
const cursor = cm.getCursor();
const prevLineContent = 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 replaceLineStart(prefix);
}
// Handle image upload and add image into markdown content
function 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 = cm.getSelection();
const placeHolderText = `![${selectedText}](${placeholderImage})`;
const cursor = cm.getCursor();
cm.replaceSelection(placeHolderText);
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', context.pageId);
window.$http.post('/images/gallery', formData).then(resp => {
const newContent = `[![${selectedText}](${resp.data.thumbs.display})](${resp.data.url})`;
replaceContent(placeHolderText, newContent);
}).catch(err => {
window.$events.emit('error', context.imageUploadErrorText);
replaceContent(placeHolderText, selectedText);
console.log(err);
});
}
function insertLink() {
let cursorPos = cm.getCursor('from');
let selectedText = cm.getSelection() || '';
let newText = `[${selectedText}]()`;
cm.focus();
cm.replaceSelection(newText);
let cursorPosDiff = (selectedText === '') ? -3 : -1;
cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
}
this.updateAndRender();
}
actionInsertImage() {
const cursorPos = this.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.cm.getSelection();
let newText = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
this.cm.focus();
this.cm.replaceSelection(newText);
this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
}, 'gallery');
}
actionShowImageManager() {
const cursorPos = this.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
actionShowLinkSelector() {
const cursorPos = this.cm.getCursor('from');
/** @type {EntitySelectorPopup} **/
const selector = window.$components.first('entity-selector-popup');
selector.show(entity => {
let selectedText = this.cm.getSelection() || entity.name;
let newText = `[${selectedText}](${entity.link})`;
this.cm.focus();
this.cm.replaceSelection(newText);
this.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
});
}
/**
* Get the URL for the configured drawio instance.
* @returns {String}
*/
getDrawioUrl() {
const drawioUrlElem = document.querySelector('[drawio-url]');
return drawioUrlElem ? drawioUrlElem.getAttribute('drawio-url') : false;
}
// Show draw.io if enabled and handle save.
actionStartDrawing() {
const url = this.getDrawioUrl();
if (!url) return;
const cursorPos = this.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.cm.focus();
this.cm.replaceSelection(newText);
this.cm.setCursor(originalCursor.line, originalCursor.ch + newText.length);
}
// Show draw.io if enabled and handle save.
actionEditDrawing(imgContainer) {
const drawioUrl = this.getDrawioUrl();
if (!drawioUrl) {
return;
const drawioAttrEl = document.querySelector('[drawio-url]');
if (!drawioAttrEl) {
return '';
}
const cursorPos = this.cm.getCursor('from');
const drawingId = imgContainer.getAttribute('drawio-diagram');
DrawIO.show(drawioUrl, () => {
return DrawIO.load(drawingId);
}, (pngData) => {
let data = {
image: pngData,
uploaded_to: Number(this.pageId),
};
window.$http.post("/images/drawio", data).then(resp => {
let newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
let newContent = this.cm.getValue().split('\n').map(line => {
if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
return newText;
}
return line;
}).join('\n');
this.cm.setValue(newContent);
this.cm.setCursor(cursorPos);
this.cm.focus();
DrawIO.close();
}).catch(err => {
this.handleDrawingUploadError(err);
});
});
return drawioAttrEl.getAttribute('drawio-url') || '';
}
handleDrawingUploadError(error) {
if (error.status === 413) {
window.$events.emit('error', this.serverUploadLimitText);
} else {
window.$events.emit('error', this.imageUploadErrorText);
}
console.log(error);
}
// Make the editor full screen
actionFullScreen() {
const alreadyFullscreen = this.elem.classList.contains('fullscreen');
this.elem.classList.toggle('fullscreen', !alreadyFullscreen);
document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
}
// Scroll to a specified text
scrollToText(searchText) {
if (!searchText) {
return;
}
const content = this.cm.getValue();
const lines = content.split(/\r?\n/);
let lineNumber = lines.findIndex(line => {
return line && line.indexOf(searchText) !== -1;
});
if (lineNumber === -1) {
return;
}
this.cm.scrollIntoView({
line: lineNumber,
}, 200);
this.cm.focus();
// set the cursor location.
this.cm.setCursor({
line: lineNumber,
char: lines[lineNumber].length
})
}
listenForBookStackEditorEvents() {
function getContentToInsert({html, markdown}) {
return markdown || html;
}
// Replace editor content
window.$events.listen('editor::replace', (eventContent) => {
const markdown = getContentToInsert(eventContent);
this.cm.setValue(markdown);
});
// Append editor content
window.$events.listen('editor::append', (eventContent) => {
const cursorPos = this.cm.getCursor('from');
const markdown = getContentToInsert(eventContent);
const content = this.cm.getValue() + '\n' + markdown;
this.cm.setValue(content);
this.cm.setCursor(cursorPos.line, cursorPos.ch);
});
// Prepend editor content
window.$events.listen('editor::prepend', (eventContent) => {
const cursorPos = this.cm.getCursor('from');
const markdown = getContentToInsert(eventContent);
const content = markdown + '\n' + this.cm.getValue();
this.cm.setValue(content);
const prependLineCount = markdown.split('\n').length;
this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
});
// Insert editor content at the current location
window.$events.listen('editor::insert', (eventContent) => {
const markdown = getContentToInsert(eventContent);
this.cm.replaceSelection(markdown);
});
// Focus on editor
window.$events.listen('editor::focus', () => {
this.cm.focus();
});
}
}

View File

@ -0,0 +1,448 @@
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 = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + 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.editor.config.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);
}
/**
* Cycles through the type of callout block within the selection.
* Creates a callout block if none existing, and removes it if cycling past the danger type.
*/
cycleCalloutTypeAtSelection() {
const selectionRange = this.editor.cm.listSelections()[0];
const lineContent = this.editor.cm.getLine(selectionRange.anchor.line);
const lineLength = lineContent.length;
const contentRange = {
anchor: {line: selectionRange.anchor.line, ch: 0},
head: {line: selectionRange.anchor.line, ch: lineLength},
};
const formats = ['info', 'success', 'warning', 'danger'];
const joint = formats.join('|');
const regex = new RegExp(`class="((${joint})\\s+callout|callout\\s+(${joint}))"`, 'i');
const matches = regex.exec(lineContent);
const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
if (format === formats[formats.length - 1]) {
this.wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
} else if (format === '') {
this.wrapLine('<p class="callout info">', '</p>');
} else {
const newFormatIndex = formats.indexOf(format) + 1;
const newFormat = formats[newFormatIndex];
const newContent = lineContent.replace(matches[0], matches[0].replace(format, newFormat));
this.editor.cm.replaceRange(newContent, contentRange.anchor, contentRange.head);
const chDiff = newContent.length - lineContent.length;
selectionRange.anchor.ch += chDiff;
if (selectionRange.anchor !== selectionRange.head) {
selectionRange.head.ch += chDiff;
}
this.editor.cm.setSelection(selectionRange.anchor, selectionRange.head);
}
}
/**
* 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 = `![${selectedText}](${placeholderImage})`;
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 = `[![${selectedText}](${resp.data.thumbs.display})](${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) {
this.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 > *');
this.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) {
this.uploadImage(image);
}
}
}

View File

@ -0,0 +1,70 @@
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.bind(editor.actions), 100, false);
let syncActive = editor.settings.get('scrollSync');
editor.settings.onChange('scrollSync', val => syncActive = val);
cm.on('scroll', instance => {
if (syncActive) {
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;
}

View 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();
});
}

View File

@ -0,0 +1,109 @@
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));
}
this.updateVisibility(editor.settings.get('showPreview'));
editor.settings.onChange('showPreview', show => this.updateVisibility(show));
}
updateVisibility(show) {
const wrap = this.container.closest('.markdown-editor-wrap');
wrap.style.display = show ? null : 'none';
}
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.bind(this));
}
/**
* @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[0]?.children;
if (elems && elems.length <= index) return;
const topElem = (index === -1) ? elems[elems.length-1] : elems[index];
topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
}
}

View File

@ -0,0 +1,54 @@
import {Markdown} from "./markdown";
import {Display} from "./display";
import {Actions} from "./actions";
import {Settings} from "./settings";
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(),
settings: new Settings(config.settings),
};
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
* @property {Object<String, any>} settings
*/
/**
* @typedef MarkdownEditor
* @property {MarkdownEditorConfig} config
* @property {Display} display
* @property {Markdown} markdown
* @property {Actions} actions
* @property {CodeMirror} cm
* @property {Settings} settings
*/

View 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);
}
}

View File

@ -0,0 +1,40 @@
import {kebabToCamel} from "../services/text";
export class Settings {
constructor(initialSettings) {
this.settingMap = {};
this.changeListeners = {};
this.merge(initialSettings);
}
set(key, value) {
key = this.normaliseKey(key);
this.settingMap[key] = value;
for (const listener of (this.changeListeners[key] || [])) {
listener(value);
}
}
get(key) {
return this.settingMap[this.normaliseKey(key)] || null;
}
merge(settings) {
for (const [key, value] of Object.entries(settings)) {
this.set(key, value);
}
}
onChange(key, callback) {
key = this.normaliseKey(key);
const listeners = this.changeListeners[this.normaliseKey(key)] || [];
listeners.push(callback);
this.changeListeners[this.normaliseKey(key)] = listeners;
}
normaliseKey(key) {
return kebabToCamel(key.replace('md-', ''));
}
}

View 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 = `![${selectedText}](http://)`;
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.cycleCalloutTypeAtSelection();
shortcuts[`${metaKey}-P`] = cm => editor.actions.replaceLineStart('-')
shortcuts[`${metaKey}-O`] = cm => editor.actions.replaceLineStartForOrderedList()
return shortcuts;
}

View File

@ -1,3 +1,5 @@
import {kebabToCamel, camelToKebab} from "./text";
/**
* A mapping of active components keyed by name, with values being arrays of component
* instances since there can be multiple components of the same type.
@ -107,17 +109,6 @@ function parseOpts(name, element) {
return opts;
}
/**
* Convert a kebab-case string to camelCase
* @param {String} kebab
* @returns {string}
*/
function kebabToCamel(kebab) {
const ucFirst = (word) => word.slice(0,1).toUpperCase() + word.slice(1);
const words = kebab.split('-');
return words[0] + words.slice(1).map(ucFirst).join('');
}
/**
* Initialize all components found within the given element.
* @param {Element|Document} parentElement
@ -171,8 +162,4 @@ export function get(name) {
export function firstOnElement(element, name) {
const elComponents = elementComponentMap.get(element) || {};
return elComponents[name] || null;
}
function camelToKebab(camelStr) {
return camelStr.replace(/[A-Z]/g, (str, offset) => (offset > 0 ? '-' : '') + str.toLowerCase());
}

View File

@ -0,0 +1,19 @@
/**
* Convert a kebab-case string to camelCase
* @param {String} kebab
* @returns {string}
*/
export function kebabToCamel(kebab) {
const ucFirst = (word) => word.slice(0,1).toUpperCase() + word.slice(1);
const words = kebab.split('-');
return words[0] + words.slice(1).map(ucFirst).join('');
}
/**
* Convert a camelCase string to a kebab-case string.
* @param {String} camelStr
* @returns {String}
*/
export function camelToKebab(camelStr) {
return camelStr.replace(/[A-Z]/g, (str, offset) => (offset > 0 ? '-' : '') + str.toLowerCase());
}

View File

@ -224,6 +224,8 @@ return [
'pages_md_insert_image' => 'Insert Image',
'pages_md_insert_link' => 'Insert Entity Link',
'pages_md_insert_drawing' => 'Insert Drawing',
'pages_md_show_preview' => 'Show preview',
'pages_md_sync_scroll' => 'Sync preview scroll',
'pages_not_in_chapter' => 'Page is not in a chapter',
'pages_move' => 'Move Page',
'pages_move_success' => 'Page moved to ":parentName"',

View File

@ -64,14 +64,6 @@
flex: 1;
position: relative;
}
.markdown-editor-wrap {
display: flex;
flex-direction: column;
border: 1px solid #DDD;
@include lightDark(border-color, #ddd, #000);
width: 50%;
max-width: 50%;
}
&.fullscreen {
position: fixed;
top: 0;
@ -81,6 +73,20 @@
}
}
.markdown-editor-wrap {
display: flex;
flex-direction: column;
border-top: 1px solid #DDD;
border-bottom: 1px solid #DDD;
@include lightDark(border-color, #ddd, #000);
width: 50%;
}
.markdown-editor-wrap + .markdown-editor-wrap {
border-inline-start: 1px solid;
@include lightDark(border-color, #ddd, #000);
}
@include smaller-than($m) {
#markdown-editor {
flex-direction: column;
@ -90,15 +96,9 @@
max-width: 100%;
flex-grow: 1;
}
#markdown-editor .editor-toolbar {
padding: 0;
}
#markdown-editor .editor-toolbar > * {
padding: $-xs $-s;
}
.editor-toolbar-label {
float: none !important;
border-bottom: 1px solid #DDD;
@include lightDark(border-color, #DDD, #555);
display: block;
}
.markdown-editor-wrap:not(.active) .editor-toolbar + div,
@ -113,10 +113,6 @@
}
}
.markdown-display {
margin-inline-start: -1px;
}
.markdown-editor-display {
background-color: #fff;
body {
@ -138,8 +134,8 @@ html.markdown-editor-display.dark-mode {
}
.editor-toolbar {
height: 32px;
width: 100%;
padding: $-xs $-m;
font-size: 11px;
line-height: 1.6;
border-bottom: 1px solid #DDD;
@ -147,11 +143,6 @@ html.markdown-editor-display.dark-mode {
@include lightDark(background-color, #eee, #111);
@include lightDark(border-color, #ddd, #000);
flex: none;
&:after {
content: '';
display: block;
clear: both;
}
@include whenDark {
button {
color: #AAA;
@ -159,6 +150,30 @@ html.markdown-editor-display.dark-mode {
}
}
.editor-toolbar .buttons {
font-size: $fs-m;
.dropdown-menu {
padding: 0;
}
.toggle-switch {
margin: $-s 0;
}
}
.editor-toolbar .buttons button {
font-size: .9rem;
width: 2rem;
text-align: center;
border-left: 1px solid;
@include lightDark(border-color, #DDD, #555);
svg {
margin-inline-end: 0;
}
&:hover {
@include lightDark(background-color, #DDD, #222);
}
}
label {
@include lightDark(color, #666, #ddd);

View File

@ -198,6 +198,9 @@ body.flexbox {
.items-center {
align-items: center;
}
.items-stretch {
align-items: stretch;
}
/**
* Min width utilities

View File

@ -5,7 +5,7 @@
body, button, input, select, label, textarea {
font-family: $text;
}
.Codemirror, pre, #markdown-editor-input, .editor-toolbar, .code-base {
.Codemirror, pre, #markdown-editor-input, .text-mono, .code-base {
font-family: $mono;
}

View File

@ -6,23 +6,33 @@
class="flex-fill flex code-fill">
<div class="markdown-editor-wrap active">
<div class="editor-toolbar">
<span class="float left editor-toolbar-label">{{ trans('entities.pages_md_editor') }}</span>
<div class="float right buttons">
<div class="editor-toolbar flex-container-row items-stretch justify-space-between">
<div class="editor-toolbar-label text-mono px-m py-xs flex-container-row items-center flex">
<span>{{ trans('entities.pages_md_editor') }}</span>
</div>
<div component="dropdown" class="buttons flex-container-row items-stretch">
@if(config('services.drawio'))
<button class="text-button" type="button" data-action="insertDrawing">@icon('drawing'){{ trans('entities.pages_md_insert_drawing') }}</button>
<span class="mx-xs text-muted">|</span>
<button class="text-button" type="button" data-action="insertDrawing" title="{{ trans('entities.pages_md_insert_drawing') }}">@icon('drawing')</button>
@endif
<button class="text-button" type="button" data-action="insertImage">@icon('image'){{ trans('entities.pages_md_insert_image') }}</button>
<span class="mx-xs text-muted">|</span>
<button class="text-button" type="button" data-action="insertLink">@icon('link'){{ trans('entities.pages_md_insert_link') }}</button>
<span class="mx-xs text-muted">|</span>
<button class="text-button" type="button" data-action="fullscreen">@icon('fullscreen'){{ trans('common.fullscreen') }}</button>
<button class="text-button" type="button" data-action="insertImage" title="{{ trans('entities.pages_md_insert_image') }}">@icon('image')</button>
<button class="text-button" type="button" data-action="insertLink" title="{{ trans('entities.pages_md_insert_link') }}">@icon('link')</button>
<button class="text-button" type="button" data-action="fullscreen" title="{{ trans('common.fullscreen') }}">@icon('fullscreen')</button>
<button refs="dropdown@toggle" class="text-button" type="button" title="{{ trans('common.more') }}">@icon('more')</button>
<div refs="dropdown@menu markdown-editor@setting-container" class="dropdown-menu" role="menu">
<div class="px-m">
@include('form.toggle-switch', ['name' => 'md-show-preview', 'label' => trans('entities.pages_md_show_preview'), 'value' => setting()->getForCurrentUser('md-show-preview')])
</div>
<hr class="m-none">
<div class="px-m">
@include('form.toggle-switch', ['name' => 'md-scroll-sync', 'label' => trans('entities.pages_md_sync_scroll'), 'value' => setting()->getForCurrentUser('md-scroll-sync')])
</div>
</div>
</div>
</div>
<div markdown-input class="flex flex-fill">
<textarea id="markdown-editor-input"
refs="markdown-editor@input"
@if($errors->has('markdown')) class="text-neg" @endif
name="markdown"
rows="5">@if(isset($model) || old('markdown')){{ old('markdown') ?? ($model->markdown === '' ? $model->html : $model->markdown) }}@endif</textarea>
@ -30,11 +40,14 @@
</div>
<div class="markdown-editor-wrap">
<div class="markdown-editor-wrap" @if(!setting()->getForCurrentUser('md-show-preview')) style="display: none;" @endif>
<div class="editor-toolbar">
<div class="editor-toolbar-label">{{ trans('entities.pages_md_preview') }}</div>
<div class="editor-toolbar-label text-mono px-m py-xs">{{ trans('entities.pages_md_preview') }}</div>
</div>
<iframe src="about:blank" class="markdown-display" sandbox="allow-same-origin"></iframe>
<iframe src="about:blank"
refs="markdown-editor@display"
class="markdown-display"
sandbox="allow-same-origin"></iframe>
</div>
</div>

View File

@ -254,6 +254,7 @@ Route::middleware('auth')->group(function () {
Route::patch('/preferences/change-expansion/{type}', [UserPreferencesController::class, 'changeExpansion']);
Route::patch('/preferences/toggle-dark-mode', [UserPreferencesController::class, 'toggleDarkMode']);
Route::patch('/preferences/update-code-language-favourite', [UserPreferencesController::class, 'updateCodeLanguageFavourite']);
Route::patch('/preferences/update-boolean', [UserPreferencesController::class, 'updateBooleanPreference']);
// User API Tokens
Route::get('/settings/users/{userId}/create-api-token', [UserApiTokenController::class, 'create']);

View File

@ -191,4 +191,22 @@ class UserPreferencesTest extends TestCase
$resp = $this->get($page->getUrl('/edit'));
$resp->assertSee('option:code-editor:favourites="javascript,ruby"', false);
}
public function test_update_boolean()
{
$editor = $this->getEditor();
$this->assertTrue(setting()->getUser($editor, 'md-show-preview'));
$resp = $this->actingAs($editor)->patch('/preferences/update-boolean', ['name' => 'md-show-preview', 'value' => 'false']);
$resp->assertStatus(204);
$this->assertFalse(setting()->getUser($editor, 'md-show-preview'));
}
public function test_update_boolean_rejects_unfamiliar_key()
{
$resp = $this->asEditor()->patch('/preferences/update-boolean', ['name' => 'md-donkey-show', 'value' => 'false']);
$resp->assertStatus(500);
}
}