1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2024-11-23 19:32:29 +01:00

Merge pull request #3617 from BookStackApp/codemirror6

Upgrade to codemirror 6
This commit is contained in:
Dan Brown 2023-04-18 15:35:39 +01:00 committed by GitHub
commit 69d03042c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 1775 additions and 2731 deletions

4
.gitignore vendored
View File

@ -21,8 +21,10 @@ yarn.lock
nbproject
.buildpath
.project
.nvmrc
.settings/
webpack-stats.json
.phpunit.result.cache
.DS_Store
phpstan.neon
phpstan.neon
esbuild-meta.json

View File

@ -1,32 +1,35 @@
#!/usr/bin/env node
const esbuild = require('esbuild');
const fs = require('fs');
const path = require('path');
const fs = require('fs');
// Check if we're building for production
// (Set via passing `production` as first argument)
const isProd = process.argv[2] === 'production';
// Gather our input files
const jsInDir = path.join(__dirname, '../../resources/js');
const jsInDirFiles = fs.readdirSync(jsInDir, 'utf8');
const entryFiles = jsInDirFiles
.filter(f => f.endsWith('.js') || f.endsWith('.mjs'))
.map(f => path.join(jsInDir, f));
const entryPoints = {
app: path.join(__dirname, '../../resources/js/app.js'),
code: path.join(__dirname, '../../resources/js/code/index.mjs'),
'legacy-modes': path.join(__dirname, '../../resources/js/code/legacy-modes.mjs'),
};
// Locate our output directory
const outDir = path.join(__dirname, '../../public/dist');
const outdir = path.join(__dirname, '../../public/dist');
// Build via esbuild
esbuild.build({
bundle: true,
entryPoints: entryFiles,
outdir: outDir,
metafile: true,
entryPoints,
outdir,
sourcemap: true,
target: 'es2020',
mainFields: ['module', 'main'],
format: 'esm',
minify: isProd,
logLevel: "info",
}).then(result => {
fs.writeFileSync('esbuild-meta.json', JSON.stringify(result.metafile));
}).catch(() => process.exit(1));

2273
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
"build:css:watch": "sass ./resources/sass:./public/dist --watch --embed-sources",
"build:css:production": "sass ./resources/sass:./public/dist -s compressed",
"build:js:dev": "node dev/build/esbuild.js",
"build:js:watch": "chokidar --initial \"./resources/**/*.js\" -c \"npm run build:js:dev\"",
"build:js:watch": "chokidar --initial \"./resources/**/*.js\" \"./resources/**/*.mjs\" -c \"npm run build:js:dev\"",
"build:js:production": "node dev/build/esbuild.js production",
"build": "npm-run-all --parallel build:*:dev",
"production": "npm-run-all --parallel build:*:production",
@ -15,16 +15,31 @@
"permissions": "chown -R $USER:$USER bootstrap/cache storage public/uploads"
},
"devDependencies": {
"@lezer/generator": "^1.2.2",
"chokidar-cli": "^3.0",
"esbuild": "^0.17.3",
"esbuild": "^0.17.16",
"livereload": "^0.9.3",
"npm-run-all": "^4.1.5",
"punycode": "^2.3.0",
"sass": "^1.57.0"
"sass": "^1.62.0"
},
"dependencies": {
"clipboard": "^2.0.11",
"codemirror": "^5.65.5",
"@codemirror/commands": "^6.2.2",
"@codemirror/lang-css": "^6.1.1",
"@codemirror/lang-html": "^6.4.3",
"@codemirror/lang-javascript": "^6.1.6",
"@codemirror/lang-json": "^6.0.1",
"@codemirror/lang-markdown": "^6.1.1",
"@codemirror/lang-php": "^6.0.1",
"@codemirror/lang-xml": "^6.0.2",
"@codemirror/language": "^6.6.0",
"@codemirror/legacy-modes": "^6.3.2",
"@codemirror/state": "^6.2.0",
"@codemirror/theme-one-dark": "^6.1.1",
"@codemirror/view": "^6.9.4",
"@ssddanbrown/codemirror-lang-smarty": "^1.0.0",
"@ssddanbrown/codemirror-lang-twig": "^1.0.0",
"codemirror": "^6.0.1",
"dropzone": "^5.9.3",
"markdown-it": "^13.0.1",
"markdown-it-task-lists": "^2.1.1",

View File

@ -134,7 +134,6 @@ Note: This is not an exhaustive list of all libraries and projects that would be
* [Sortable](https://github.com/SortableJS/Sortable) - _[MIT](https://github.com/SortableJS/Sortable/blob/master/LICENSE)_
* [Google Material Icons](https://github.com/google/material-design-icons) - _[Apache-2.0](https://github.com/google/material-design-icons/blob/master/LICENSE)_
* [Dropzone.js](http://www.dropzonejs.com/) - _[MIT](https://github.com/dropzone/dropzone/blob/main/LICENSE)_
* [clipboard.js](https://clipboardjs.com/) - _[MIT](https://github.com/zenorocha/clipboard.js/blob/master/LICENSE)_
* [markdown-it](https://github.com/markdown-it/markdown-it) and [markdown-it-task-lists](https://github.com/revin/markdown-it-task-lists) - _[MIT](https://github.com/markdown-it/markdown-it/blob/master/LICENSE) and [ISC](https://github.com/revin/markdown-it-task-lists/blob/master/LICENSE)_
* [Dompdf](https://github.com/dompdf/dompdf) - _[LGPL v2.1](https://github.com/dompdf/dompdf/blob/master/LICENSE.LGPL)_
* [BarryVD/Dompdf](https://github.com/barryvdh/laravel-dompdf) - _[MIT](https://github.com/barryvdh/laravel-dompdf/blob/master/LICENSE)_

View File

@ -1,346 +0,0 @@
import CodeMirror from "codemirror";
import Clipboard from "clipboard/dist/clipboard.min";
// Modes
import 'codemirror/mode/css/css';
import 'codemirror/mode/clike/clike';
import 'codemirror/mode/dart/dart';
import 'codemirror/mode/diff/diff';
import 'codemirror/mode/fortran/fortran';
import 'codemirror/mode/go/go';
import 'codemirror/mode/haskell/haskell';
import 'codemirror/mode/htmlmixed/htmlmixed';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/julia/julia';
import 'codemirror/mode/lua/lua';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/mode/mllike/mllike';
import 'codemirror/mode/nginx/nginx';
import 'codemirror/mode/octave/octave';
import 'codemirror/mode/perl/perl';
import 'codemirror/mode/pascal/pascal';
import 'codemirror/mode/php/php';
import 'codemirror/mode/powershell/powershell';
import 'codemirror/mode/properties/properties';
import 'codemirror/mode/python/python';
import 'codemirror/mode/ruby/ruby';
import 'codemirror/mode/rust/rust';
import 'codemirror/mode/scheme/scheme';
import 'codemirror/mode/shell/shell';
import 'codemirror/mode/smarty/smarty';
import 'codemirror/mode/sql/sql';
import 'codemirror/mode/stex/stex';
import 'codemirror/mode/swift/swift';
import 'codemirror/mode/toml/toml';
import 'codemirror/mode/twig/twig';
import 'codemirror/mode/vb/vb';
import 'codemirror/mode/vbscript/vbscript';
import 'codemirror/mode/xml/xml';
import 'codemirror/mode/yaml/yaml';
// Addons
import 'codemirror/addon/scroll/scrollpastend';
// Mapping of possible languages or formats from user input to their codemirror modes.
// Value can be a mode string or a function that will receive the code content & return the mode string.
// The function option is used in the event the exact mode could be dynamic depending on the code.
const modeMap = {
bash: 'shell',
css: 'css',
c: 'text/x-csrc',
java: 'text/x-java',
scala: 'text/x-scala',
kotlin: 'text/x-kotlin',
'c++': 'text/x-c++src',
'c#': 'text/x-csharp',
csharp: 'text/x-csharp',
dart: 'application/dart',
diff: 'diff',
for: 'fortran',
fortran: 'fortran',
'f#': 'text/x-fsharp',
fsharp: 'text/x-fsharp',
go: 'go',
haskell: 'haskell',
hs: 'haskell',
html: 'htmlmixed',
ini: 'properties',
javascript: 'text/javascript',
json: 'application/json',
js: 'text/javascript',
jl: 'text/x-julia',
julia: 'text/x-julia',
latex: 'text/x-stex',
lua: 'lua',
matlab: 'text/x-octave',
md: 'markdown',
mdown: 'markdown',
markdown: 'markdown',
ml: 'mllike',
mssql: 'text/x-mssql',
mysql: 'text/x-mysql',
nginx: 'nginx',
octave: 'text/x-octave',
perl: 'perl',
pl: 'perl',
powershell: 'powershell',
properties: 'properties',
ocaml: 'text/x-ocaml',
pascal: 'text/x-pascal',
pas: 'text/x-pascal',
php: (content) => {
return content.includes('<?php') ? 'php' : 'text/x-php';
},
pgsql: 'text/x-pgsql',
'pl/sql': 'text/x-plsql',
postgresql: 'text/x-pgsql',
py: 'python',
python: 'python',
ruby: 'ruby',
rust: 'rust',
rb: 'ruby',
rs: 'rust',
scheme: 'scheme',
shell: 'shell',
sh: 'shell',
smarty: 'smarty',
sql: 'text/x-sql',
sqlite: 'text/x-sqlite',
stext: 'text/x-stex',
swift: 'text/x-swift',
toml: 'toml',
ts: 'text/typescript',
twig: 'twig',
typescript: 'text/typescript',
vbs: 'vbscript',
vbscript: 'vbscript',
'vb.net': 'text/x-vb',
vbnet: 'text/x-vb',
xml: 'xml',
yaml: 'yaml',
yml: 'yaml',
};
/**
* Highlight pre elements on a page
*/
export function highlight() {
const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
for (const codeBlock of codeBlocks) {
highlightElem(codeBlock);
}
}
/**
* Highlight all code blocks within the given parent element
* @param {HTMLElement} parent
*/
export function highlightWithin(parent) {
const codeBlocks = parent.querySelectorAll('pre');
for (const codeBlock of codeBlocks) {
highlightElem(codeBlock);
}
}
/**
* Add code highlighting to a single element.
* @param {HTMLElement} elem
*/
function highlightElem(elem) {
const innerCodeElem = elem.querySelector('code[class^=language-]');
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
const content = elem.textContent.trimEnd();
let mode = '';
if (innerCodeElem !== null) {
const langName = innerCodeElem.className.replace('language-', '');
mode = getMode(langName, content);
}
const cm = CodeMirror(function(elt) {
elem.parentNode.replaceChild(elt, elem);
}, {
value: content,
mode: mode,
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
readOnly: true
});
addCopyIcon(cm);
}
/**
* Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
* @param cmInstance
*/
function addCopyIcon(cmInstance) {
const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
const copyButton = document.createElement('div');
copyButton.classList.add('CodeMirror-copy');
copyButton.innerHTML = copyIcon;
cmInstance.display.wrapper.appendChild(copyButton);
const clipboard = new Clipboard(copyButton, {
text: function(trigger) {
return cmInstance.getValue()
}
});
clipboard.on('success', event => {
copyButton.classList.add('success');
setTimeout(() => {
copyButton.classList.remove('success');
}, 240);
});
}
/**
* Search for a codemirror code based off a user suggestion
* @param {String} suggestion
* @param {String} content
* @returns {string}
*/
function getMode(suggestion, content) {
suggestion = suggestion.trim().replace(/^\./g, '').toLowerCase();
const modeMapType = typeof modeMap[suggestion];
if (modeMapType === 'undefined') {
return '';
}
if (modeMapType === 'function') {
return modeMap[suggestion](content);
}
return modeMap[suggestion];
}
/**
* Ge the theme to use for CodeMirror instances.
* @returns {*|string}
*/
function getTheme() {
const darkMode = document.documentElement.classList.contains('dark-mode');
return window.codeTheme || (darkMode ? 'darcula' : 'default');
}
/**
* Create a CodeMirror instance for showing inside the WYSIWYG editor.
* Manages a textarea element to hold code content.
* @param {HTMLElement} cmContainer
* @param {String} content
* @param {String} language
* @returns {{wrap: Element, editor: *}}
*/
export function wysiwygView(cmContainer, content, language) {
return CodeMirror(cmContainer, {
value: content,
mode: getMode(language, content),
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
readOnly: true
});
}
/**
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor
* @param {HTMLElement} elem
* @param {String} modeSuggestion
* @returns {*}
*/
export function popupEditor(elem, modeSuggestion) {
const content = elem.textContent;
return CodeMirror(function(elt) {
elem.parentNode.insertBefore(elt, elem);
elem.style.display = 'none';
}, {
value: content,
mode: getMode(modeSuggestion, content),
lineNumbers: true,
lineWrapping: false,
theme: getTheme()
});
}
/**
* Create an inline editor to replace the given textarea.
* @param {HTMLTextAreaElement} textArea
* @param {String} mode
* @returns {CodeMirror3}
*/
export function inlineEditor(textArea, mode) {
return CodeMirror.fromTextArea(textArea, {
mode: getMode(mode, textArea.value),
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
});
}
/**
* Set the mode of a codemirror instance.
* @param cmInstance
* @param modeSuggestion
*/
export function setMode(cmInstance, modeSuggestion, content) {
cmInstance.setOption('mode', getMode(modeSuggestion, content));
}
/**
* Set the content of a cm instance.
* @param cmInstance
* @param codeContent
*/
export function setContent(cmInstance, codeContent) {
cmInstance.setValue(codeContent);
setTimeout(() => {
updateLayout(cmInstance);
}, 10);
}
/**
* Update the layout (codemirror refresh) of a cm instance.
* @param cmInstance
*/
export function updateLayout(cmInstance) {
cmInstance.refresh();
}
/**
* Get a CodeMirror instance to use for the markdown editor.
* @param {HTMLElement} elem
* @returns {*}
*/
export function markdownEditor(elem) {
const content = elem.textContent;
const config = {
value: content,
mode: "markdown",
lineNumbers: true,
lineWrapping: true,
theme: getTheme(),
scrollPastEnd: true,
};
window.$events.emitPublic(elem, 'editor-markdown-cm::pre-init', {config});
return CodeMirror(function (elt) {
elem.parentNode.insertBefore(elt, elem);
elem.style.display = 'none';
}, config);
}
/**
* Get the 'meta' key dependent on the user's system.
* @returns {string}
*/
export function getMetaKey() {
let mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
return mac ? "Cmd" : "Ctrl";
}

207
resources/js/code/index.mjs Normal file
View File

@ -0,0 +1,207 @@
import {EditorView, keymap} from "@codemirror/view";
import {copyTextToClipboard} from "../services/clipboard.js"
import {viewerExtensions, editorExtensions} from "./setups.js";
import {createView} from "./views.js";
import {SimpleEditorInterface} from "./simple-editor-interface.js";
/**
* Highlight pre elements on a page
*/
export function highlight() {
const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
for (const codeBlock of codeBlocks) {
highlightElem(codeBlock);
}
}
/**
* Highlight all code blocks within the given parent element
* @param {HTMLElement} parent
*/
export function highlightWithin(parent) {
const codeBlocks = parent.querySelectorAll('pre');
for (const codeBlock of codeBlocks) {
highlightElem(codeBlock);
}
}
/**
* Add code highlighting to a single element.
* @param {HTMLElement} elem
*/
function highlightElem(elem) {
const innerCodeElem = elem.querySelector('code[class^=language-]');
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
const content = elem.textContent.trimEnd();
let langName = '';
if (innerCodeElem !== null) {
langName = innerCodeElem.className.replace('language-', '');
}
const wrapper = document.createElement('div');
elem.parentNode.insertBefore(wrapper, elem);
const ev = createView({
parent: wrapper,
doc: content,
extensions: viewerExtensions(wrapper),
});
const editor = new SimpleEditorInterface(ev);
editor.setMode(langName, content);
elem.remove();
addCopyIcon(ev);
}
/**
* Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
* @param {EditorView} editorView
*/
function addCopyIcon(editorView) {
const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
const checkIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`;
const copyButton = document.createElement('button');
copyButton.setAttribute('type', 'button')
copyButton.classList.add('cm-copy-button');
copyButton.innerHTML = copyIcon;
editorView.dom.appendChild(copyButton);
const notifyTime = 620;
const transitionTime = 60;
copyButton.addEventListener('click', event => {
copyTextToClipboard(editorView.state.doc.toString());
copyButton.classList.add('success');
setTimeout(() => {
copyButton.innerHTML = checkIcon;
}, transitionTime / 2);
setTimeout(() => {
copyButton.classList.remove('success');
}, notifyTime);
setTimeout(() => {
copyButton.innerHTML = copyIcon;
}, notifyTime + (transitionTime / 2));
});
}
/**
* Create a CodeMirror instance for showing inside the WYSIWYG editor.
* Manages a textarea element to hold code content.
* @param {HTMLElement} cmContainer
* @param {ShadowRoot} shadowRoot
* @param {String} content
* @param {String} language
* @returns {SimpleEditorInterface}
*/
export function wysiwygView(cmContainer, shadowRoot, content, language) {
const ev = createView({
parent: cmContainer,
doc: content,
extensions: viewerExtensions(cmContainer),
root: shadowRoot,
});
const editor = new SimpleEditorInterface(ev);
editor.setMode(language, content);
return editor;
}
/**
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor
* @param {HTMLElement} elem
* @param {String} modeSuggestion
* @returns {SimpleEditorInterface}
*/
export function popupEditor(elem, modeSuggestion) {
const content = elem.textContent;
const config = {
parent: elem.parentElement,
doc: content,
extensions: [
...editorExtensions(elem.parentElement),
EditorView.updateListener.of((v) => {
if (v.docChanged) {
// textArea.value = v.state.doc.toString();
}
}),
],
};
// Create editor, hide original input
const editor = new SimpleEditorInterface(createView(config));
editor.setMode(modeSuggestion, content);
elem.style.display = 'none';
return editor;
}
/**
* Create an inline editor to replace the given textarea.
* @param {HTMLTextAreaElement} textArea
* @param {String} mode
* @returns {SimpleEditorInterface}
*/
export function inlineEditor(textArea, mode) {
const content = textArea.value;
const config = {
parent: textArea.parentElement,
doc: content,
extensions: [
...editorExtensions(textArea.parentElement),
EditorView.updateListener.of((v) => {
if (v.docChanged) {
textArea.value = v.state.doc.toString();
}
}),
],
};
// Create editor view, hide original input
const ev = createView(config);
const editor = new SimpleEditorInterface(ev);
editor.setMode(mode, content);
textArea.style.display = 'none';
return editor;
}
/**
* Get a CodeMirror instance to use for the markdown editor.
* @param {HTMLElement} elem
* @param {function} onChange
* @param {object} domEventHandlers
* @param {Array} keyBindings
* @returns {EditorView}
*/
export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
const content = elem.textContent;
const config = {
parent: elem.parentElement,
doc: content,
extensions: [
keymap.of(keyBindings),
...editorExtensions(elem.parentElement),
EditorView.updateListener.of((v) => {
onChange(v);
}),
EditorView.domEventHandlers(domEventHandlers),
],
};
// Emit a pre-event public event to allow tweaking of the configure before view creation.
window.$events.emitPublic(elem, 'editor-markdown-cm6::pre-init', {editorViewConfig: config});
// Create editor view, hide original input
const ev = createView(config);
(new SimpleEditorInterface(ev)).setMode('markdown', '');
elem.style.display = 'none';
return ev;
}

View File

@ -0,0 +1,116 @@
import {StreamLanguage} from "@codemirror/language"
import {css} from '@codemirror/lang-css';
import {json} from '@codemirror/lang-json';
import {javascript} from '@codemirror/lang-javascript';
import {html} from "@codemirror/lang-html";
import {markdown} from '@codemirror/lang-markdown';
import {php} from '@codemirror/lang-php';
import {twig} from "@ssddanbrown/codemirror-lang-twig";
import {xml} from "@codemirror/lang-xml";
const legacyLoad = async (mode) => {
const modes = await window.importVersioned('legacy-modes');
return StreamLanguage.define(modes[mode]);
};
// Mapping of possible languages or formats from user input to their codemirror modes.
// Value can be a mode string or a function that will receive the code content & return the mode string.
// The function option is used in the event the exact mode could be dynamic depending on the code.
const modeMap = {
bash: () => legacyLoad('shell'),
c: () => legacyLoad('c'),
css: async () => css(),
'c++': () => legacyLoad('cpp'),
'c#': () => legacyLoad('csharp'),
csharp: () => legacyLoad('csharp'),
dart: () => legacyLoad('dart'),
diff: () => legacyLoad('diff'),
for: () => legacyLoad('fortran'),
fortran: () => legacyLoad('fortran'),
'f#': () => legacyLoad('fSharp'),
fsharp: () => legacyLoad('fSharp'),
go: () => legacyLoad('go'),
haskell: () => legacyLoad('haskell'),
hs: () => legacyLoad('haskell'),
html: async () => html(),
ini: () => legacyLoad('properties'),
java: () => legacyLoad('java'),
javascript: async () => javascript(),
json: async () => json(),
js: async () => javascript(),
jl: () => legacyLoad('julia'),
julia: () => legacyLoad('julia'),
kotlin: () => legacyLoad('kotlin'),
latex: () => legacyLoad('stex'),
lua: () => legacyLoad('lua'),
markdown: async () => markdown(),
matlab: () => legacyLoad('octave'),
md: async () => markdown(),
mdown: async () => markdown(),
ml: () => legacyLoad('sml'),
mssql: () => legacyLoad('msSQL'),
mysql: () => legacyLoad('mySQL'),
nginx: () => legacyLoad('nginx'),
octave: () => legacyLoad('octave'),
pas: () => legacyLoad('pascal'),
pascal: () => legacyLoad('pascal'),
perl: () => legacyLoad('perl'),
pgsql: () => legacyLoad('pgSQL'),
php: async (code) => {
const hasTags = code.includes('<?php');
return php({plain: !hasTags});
},
pl: () => legacyLoad('perl'),
'pl/sql': () => legacyLoad('plSQL'),
postgresql: () => legacyLoad('pgSQL'),
powershell: () => legacyLoad('powerShell'),
properties: () => legacyLoad('properties'),
ocaml: () => legacyLoad('oCaml'),
py: () => legacyLoad('python'),
python: () => legacyLoad('python'),
rb: () => legacyLoad('ruby'),
rs: () => legacyLoad('rust'),
ruby: () => legacyLoad('ruby'),
rust: () => legacyLoad('rust'),
scala: () => legacyLoad('scala'),
scheme: () => legacyLoad('scheme'),
shell: () => legacyLoad('shell'),
sh: () => legacyLoad('shell'),
smarty: () => legacyLoad('smarty'),
stext: () => legacyLoad('stex'),
swift: () => legacyLoad('swift'),
toml: () => legacyLoad('toml'),
ts: async () => javascript({typescript: true}),
twig: async () => twig(),
typescript: async () => javascript({typescript: true}),
sql: () => legacyLoad('standardSQL'),
sqlite: () => legacyLoad('sqlite'),
vbs: () => legacyLoad('vbScript'),
vbscript: () => legacyLoad('vbScript'),
'vb.net': () => legacyLoad('vb'),
vbnet: () => legacyLoad('vb'),
xml: async () => xml(),
yaml: () => legacyLoad('yaml'),
yml: () => legacyLoad('yaml'),
};
/**
* Get the relevant codemirror language extension based upon the given language
* suggestion and content.
* @param {String} langSuggestion
* @param {String} content
* @returns {Promise<StreamLanguage|LanguageSupport>}
*/
export function getLanguageExtension(langSuggestion, content) {
const suggestion = langSuggestion.trim().replace(/^\./g, '').toLowerCase();
const language = modeMap[suggestion];
if (typeof language === 'undefined') {
return undefined;
}
return language(content);
}

View File

@ -0,0 +1,27 @@
export {c, cpp, csharp, java, kotlin, scala, dart} from '@codemirror/legacy-modes/mode/clike';
export {diff} from '@codemirror/legacy-modes/mode/diff';
export {fortran} from '@codemirror/legacy-modes/mode/fortran';
export {go} from '@codemirror/legacy-modes/mode/go';
export {haskell} from '@codemirror/legacy-modes/mode/haskell';
export {julia} from '@codemirror/legacy-modes/mode/julia';
export {lua} from '@codemirror/legacy-modes/mode/lua';
export {oCaml, fSharp, sml} from '@codemirror/legacy-modes/mode/mllike';
export {nginx} from '@codemirror/legacy-modes/mode/nginx';
export {octave} from '@codemirror/legacy-modes/mode/octave';
export {perl} from '@codemirror/legacy-modes/mode/perl';
export {pascal} from '@codemirror/legacy-modes/mode/pascal';
export {powerShell} from '@codemirror/legacy-modes/mode/powershell';
export {properties} from '@codemirror/legacy-modes/mode/properties';
export {python} from '@codemirror/legacy-modes/mode/python';
export {ruby} from '@codemirror/legacy-modes/mode/ruby';
export {rust} from '@codemirror/legacy-modes/mode/rust';
export {scheme} from '@codemirror/legacy-modes/mode/scheme';
export {shell} from '@codemirror/legacy-modes/mode/shell';
export {standardSQL, pgSQL, msSQL, mySQL, sqlite, plSQL} from '@codemirror/legacy-modes/mode/sql';
export {stex} from '@codemirror/legacy-modes/mode/stex';
export {swift} from "@codemirror/legacy-modes/mode/swift";
export {toml} from '@codemirror/legacy-modes/mode/toml';
export {vb} from '@codemirror/legacy-modes/mode/vb';
export {vbScript} from '@codemirror/legacy-modes/mode/vbscript';
export {yaml} from '@codemirror/legacy-modes/mode/yaml';
export {smarty} from "@ssddanbrown/codemirror-lang-smarty";

View File

@ -0,0 +1,54 @@
import {EditorView, keymap, drawSelection, highlightActiveLine, dropCursor,
rectangularSelection, lineNumbers, highlightActiveLineGutter} from "@codemirror/view"
import {bracketMatching} from "@codemirror/language"
import {defaultKeymap, history, historyKeymap, indentWithTab} from "@codemirror/commands"
import {EditorState} from "@codemirror/state"
import {getTheme} from "./themes";
/**
* @param {Element} parentEl
* @return {(Extension[]|{extension: Extension}|readonly Extension[])[]}
*/
function common(parentEl) {
return [
getTheme(parentEl),
lineNumbers(),
highlightActiveLineGutter(),
drawSelection(),
dropCursor(),
bracketMatching(),
rectangularSelection(),
highlightActiveLine(),
];
}
/**
* @param {Element} parentEl
* @return {*[]}
*/
export function viewerExtensions(parentEl) {
return [
...common(parentEl),
keymap.of([
...defaultKeymap,
]),
EditorState.readOnly.of(true),
];
}
/**
* @param {Element} parentEl
* @return {*[]}
*/
export function editorExtensions(parentEl) {
return [
...common(parentEl),
history(),
keymap.of([
...defaultKeymap,
...historyKeymap,
indentWithTab,
]),
EditorView.lineWrapping,
];
}

View File

@ -0,0 +1,46 @@
import {updateViewLanguage} from "./views";
export class SimpleEditorInterface {
/**
* @param {EditorView} editorView
*/
constructor(editorView) {
this.ev = editorView;
}
/**
* Get the contents of an editor instance.
* @return {string}
*/
getContent() {
return this.ev.state.doc.toString();
}
/**
* Set the contents of an editor instance.
* @param content
*/
setContent(content) {
const doc = this.ev.state.doc;
this.ev.dispatch({
changes: {from: 0, to: doc.length, insert: content}
});
}
/**
* Return focus to the editor instance.
*/
focus() {
this.ev.focus();
}
/**
* Set the language mode of the editor instance.
* @param {String} mode
* @param {String} content
*/
setMode(mode, content = '') {
updateViewLanguage(this.ev, mode, content);
}
}

View File

@ -0,0 +1,91 @@
import {tags} from "@lezer/highlight";
import {HighlightStyle, syntaxHighlighting} from "@codemirror/language";
import {EditorView} from "@codemirror/view";
import {oneDarkHighlightStyle, oneDarkTheme} from "@codemirror/theme-one-dark";
const defaultLightHighlightStyle = HighlightStyle.define([
{ tag: tags.meta,
color: "#388938" },
{ tag: tags.link,
textDecoration: "underline" },
{ tag: tags.heading,
textDecoration: "underline",
fontWeight: "bold" },
{ tag: tags.emphasis,
fontStyle: "italic" },
{ tag: tags.strong,
fontWeight: "bold" },
{ tag: tags.strikethrough,
textDecoration: "line-through" },
{ tag: tags.keyword,
color: "#708" },
{ tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
color: "#219" },
{ tag: [tags.literal, tags.inserted],
color: "#164" },
{ tag: [tags.string, tags.deleted],
color: "#a11" },
{ tag: [tags.regexp, tags.escape, tags.special(tags.string)],
color: "#e40" },
{ tag: tags.definition(tags.variableName),
color: "#00f" },
{ tag: tags.local(tags.variableName),
color: "#30a" },
{ tag: [tags.typeName, tags.namespace],
color: "#085" },
{ tag: tags.className,
color: "#167" },
{ tag: [tags.special(tags.variableName), tags.macroName],
color: "#256" },
{ tag: tags.definition(tags.propertyName),
color: "#00c" },
{ tag: tags.compareOperator,
color: "#708" },
{ tag: tags.comment,
color: "#940" },
{ tag: tags.invalid,
color: "#f00" }
]);
const defaultThemeSpec = {
"&": {
backgroundColor: "#FFF",
color: "#000",
},
"&.cm-focused": {
outline: "none",
},
".cm-line": {
lineHeight: "1.6",
},
};
/**
* Get the theme extension to use for editor view instance.
* @returns {Extension[]}
*/
export function getTheme(viewParentEl) {
const darkMode = document.documentElement.classList.contains('dark-mode');
let viewTheme = darkMode ? oneDarkTheme : EditorView.theme(defaultThemeSpec);
let highlightStyle = darkMode ? oneDarkHighlightStyle : defaultLightHighlightStyle;
const eventData = {
darkModeActive: darkMode,
registerViewTheme(builder) {
const spec = builder();
if (spec) {
viewTheme = EditorView.theme(spec);
}
},
registerHighlightStyle(builder) {
const tagStyles = builder(tags) || [];
if (tagStyles.length) {
highlightStyle = HighlightStyle.define(tagStyles);
}
}
};
window.$events.emitPublic(viewParentEl, 'library-cm6::configure-theme', eventData);
return [viewTheme, syntaxHighlighting(highlightStyle)];
}

View File

@ -0,0 +1,38 @@
import {Compartment} from "@codemirror/state";
import {EditorView} from "@codemirror/view";
import {getLanguageExtension} from "./languages";
const viewLangCompartments = new WeakMap();
/**
* Create a new editor view.
*
* @param {{parent: Element, doc: String, extensions: Array}} config
* @returns {EditorView}
*/
export function createView(config) {
const langCompartment = new Compartment();
config.extensions.push(langCompartment.of([]));
const ev = new EditorView(config);
viewLangCompartments.set(ev, langCompartment);
return ev;
}
/**
* Set the language mode of an EditorView.
*
* @param {EditorView} ev
* @param {string} modeSuggestion
* @param {string} content
*/
export async function updateViewLanguage(ev, modeSuggestion, content) {
const compartment = viewLangCompartments.get(ev);
const language = await getLanguageExtension(modeSuggestion, content);
ev.dispatch({
effects: compartment.reconfigure(language ? language : [])
});
}

View File

@ -4,6 +4,15 @@ import {Component} from "./component";
export class CodeEditor extends Component {
/**
* @type {null|SimpleEditorInterface}
*/
editor = null;
callback = null;
history = {};
historyKey = 'code_history';
setup() {
this.container = this.$refs.container;
this.popup = this.$el;
@ -16,10 +25,6 @@ export class CodeEditor extends Component {
this.historyList = this.$refs.historyList;
this.favourites = new Set(this.$opts.favourites.split(','));
this.callback = null;
this.editor = null;
this.history = {};
this.historyKey = 'code_history';
this.setupListeners();
this.setupFavourites();
}
@ -45,7 +50,7 @@ export class CodeEditor extends Component {
event.preventDefault();
const historyTime = elem.dataset.time;
if (this.editor) {
this.editor.setValue(this.history[historyTime]);
this.editor.setContent(this.history[historyTime]);
}
});
}
@ -104,19 +109,18 @@ export class CodeEditor extends Component {
save() {
if (this.callback) {
this.callback(this.editor.getValue(), this.languageInput.value);
this.callback(this.editor.getContent(), this.languageInput.value);
}
this.hide();
}
open(code, language, callback) {
async open(code, language, callback) {
this.languageInput.value = language;
this.callback = callback;
this.show()
.then(() => this.languageInputChange(language))
.then(() => window.importVersioned('code'))
.then(Code => Code.setContent(this.editor, code));
await this.show();
this.languageInputChange(language);
this.editor.setContent(code);
}
async show() {
@ -127,7 +131,6 @@ export class CodeEditor extends Component {
this.loadHistory();
this.getPopup().show(() => {
Code.updateLayout(this.editor);
this.editor.focus();
}, () => {
this.addHistory()
@ -147,8 +150,7 @@ export class CodeEditor extends Component {
}
async updateEditorMode(language) {
const Code = await window.importVersioned('code');
Code.setMode(this.editor, language, this.editor.getValue());
this.editor.setMode(language, this.editor.getContent());
}
languageInputChange(language) {
@ -177,7 +179,7 @@ export class CodeEditor extends Component {
addHistory() {
if (!this.editor) return;
const code = this.editor.getValue();
const code = this.editor.getContent();
if (!code) return;
// Stop if we'd be storing the same as the last item

View File

@ -1,4 +1,3 @@
import {debounce} from "../services/util";
import {Component} from "./component";
import {init as initEditor} from "../markdown/editor";
@ -45,7 +44,7 @@ export class MarkdownEditor extends Component {
window.$events.emitPublic(this.elem, 'editor-markdown::setup', {
markdownIt: this.editor.markdown.getRenderer(),
displayEl: this.display,
codeMirrorInstance: this.editor.cm,
cmEditorView: this.editor.cm,
});
}
@ -57,7 +56,7 @@ export class MarkdownEditor extends Component {
if (button === null) return;
const action = button.getAttribute('data-action');
if (action === 'insertImage') this.editor.actions.insertImage();
if (action === 'insertImage') this.editor.actions.showImageInsert();
if (action === 'insertLink') this.editor.actions.showLinkSelector();
if (action === 'insertDrawing' && (event.ctrlKey || event.metaKey)) {
this.editor.actions.showImageManager();
@ -80,11 +79,6 @@ export class MarkdownEditor extends Component {
toolbarLabel.closest('.markdown-editor-wrap').classList.add('active');
});
// Refresh CodeMirror on container resize
const resizeDebounced = debounce(() => this.editor.cm.refresh(), 100, false);
const observer = new ResizeObserver(resizeDebounced);
observer.observe(this.elem);
this.handleDividerDrag();
}
@ -102,7 +96,6 @@ export class MarkdownEditor extends Component {
window.removeEventListener('pointerup', upListener);
this.display.style.pointerEvents = null;
document.body.style.userSelect = null;
this.editor.cm.refresh();
};
this.display.style.pointerEvents = 'none';

View File

@ -22,7 +22,7 @@ export class PageEditor extends Component {
this.draftDisplayIcon = this.$refs.draftDisplayIcon;
this.changelogInput = this.$refs.changelogInput;
this.changelogDisplay = this.$refs.changelogDisplay;
this.changeEditorButtons = this.$manyRefs.changeEditor;
this.changeEditorButtons = this.$manyRefs.changeEditor || [];
this.switchDialogContainer = this.$refs.switchDialog;
// Translations

View File

@ -1,12 +1,14 @@
import * as DOM from "../services/dom";
import Clipboard from "clipboard/dist/clipboard.min";
import {Component} from "./component";
import {copyTextToClipboard} from "../services/clipboard";
export class Pointer extends Component {
setup() {
this.container = this.$el;
this.input = this.$refs.input;
this.button = this.$refs.button;
this.pageId = this.$opts.pageId;
// Instance variables
@ -16,15 +18,17 @@ export class Pointer extends Component {
this.pointerSectionId = '';
this.setupListeners();
// Set up clipboard
new Clipboard(this.container.querySelector('button'));
}
setupListeners() {
// Copy on copy button click
this.button.addEventListener('click', event => {
copyTextToClipboard(this.input.value);
});
// Select all contents on input click
DOM.onChildEvent(this.container, 'input', 'click', (event, input) => {
input.select();
this.input.addEventListener('click', event => {
this.input.select();
event.stopPropagation();
});
@ -112,7 +116,7 @@ export class Pointer extends Component {
inputText = window.location.protocol + "//" + window.location.host + inputText;
}
this.container.querySelector('input').value = inputText;
this.input.value = inputText;
// Update anchor if present
const editAnchor = this.container.querySelector('#pointer-edit');

View File

@ -13,7 +13,7 @@ export class Actions {
}
updateAndRender() {
const content = this.editor.cm.getValue();
const content = this.#getText();
this.editor.config.inputEl.value = content;
const html = this.editor.markdown.render(content);
@ -28,50 +28,49 @@ export class Actions {
return this.lastContent;
}
insertImage() {
const cursorPos = this.editor.cm.getCursor('from');
showImageInsert() {
/** @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);
const selectedText = this.#getSelectionText();
const newText = "[![" + (selectedText || image.name) + "](" + imageUrl + ")](" + image.url + ")";
this.#replaceSelection(newText, newText.length);
}, 'gallery');
}
insertImage() {
const newText = `![${this.#getSelectionText()}](http://)`;
this.#replaceSelection(newText, newText.length - 1);
}
insertLink() {
const cursorPos = this.editor.cm.getCursor('from');
const selectedText = this.editor.cm.getSelection() || '';
const selectedText = this.#getSelectionText();
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);
this.#replaceSelection(newText, newText.length+cursorPosDiff);
}
showImageManager() {
const cursorPos = this.editor.cm.getCursor('from');
const selectionRange = this.#getSelectionRange();
/** @type {ImageManager} **/
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
this.insertDrawing(image, cursorPos);
this.#insertDrawing(image, selectionRange);
}, 'drawio');
}
// Show the popup link selector and insert a link when finished
showLinkSelector() {
const cursorPos = this.editor.cm.getCursor('from');
const selectionRange = this.#getSelectionRange();
/** @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);
const selectedText = this.#getSelectionText(selectionRange) || entity.name;
const newText = `[${selectedText}](${entity.link})`;
this.#replaceSelection(newText, newText.length, selectionRange);
});
}
@ -80,7 +79,7 @@ export class Actions {
const url = this.editor.config.drawioUrl;
if (!url) return;
const cursorPos = this.editor.cm.getCursor('from');
const selectionRange = this.#getSelectionRange();
DrawIO.show(url,() => {
return Promise.resolve('');
@ -92,7 +91,7 @@ export class Actions {
};
window.$http.post("/images/drawio", data).then(resp => {
this.insertDrawing(resp.data, cursorPos);
this.#insertDrawing(resp.data, selectionRange);
DrawIO.close();
}).catch(err => {
this.handleDrawingUploadError(err);
@ -100,11 +99,9 @@ export class Actions {
});
}
insertDrawing(image, originalCursor) {
#insertDrawing(image, originalSelectionRange) {
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);
this.#replaceSelection(newText, newText.length, originalSelectionRange);
}
// Show draw.io if enabled and handle save.
@ -114,7 +111,7 @@ export class Actions {
return;
}
const cursorPos = this.editor.cm.getCursor('from');
const selectionRange = this.#getSelectionRange();
const drawingId = imgContainer.getAttribute('drawio-diagram');
DrawIO.show(drawioUrl, () => {
@ -128,15 +125,13 @@ export class Actions {
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 => {
const newContent = this.#getText().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();
this.#setText(newContent, selectionRange);
DrawIO.close();
}).catch(err => {
this.handleDrawingUploadError(err);
@ -167,29 +162,30 @@ export class Actions {
return;
}
const content = this.editor.cm.getValue();
const lines = content.split(/\r?\n/);
let lineNumber = lines.findIndex(line => {
return line && line.indexOf(searchText) !== -1;
});
const text = this.editor.cm.state.doc;
let lineCount = 1;
let scrollToLine = -1;
for (const line of text.iterLines()) {
if (line.includes(searchText)) {
scrollToLine = lineCount;
break;
}
lineCount++;
}
if (lineNumber === -1) {
if (scrollToLine === -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
})
const line = text.line(scrollToLine);
this.#setSelection(line.from, line.to, true);
this.focus();
}
focus() {
this.editor.cm.focus();
if (!this.editor.cm.hasFocus) {
this.editor.cm.focus();
}
}
/**
@ -197,7 +193,7 @@ export class Actions {
* @param {String} content
*/
insertContent(content) {
this.editor.cm.replaceSelection(content);
this.#replaceSelection(content, content.length);
}
/**
@ -205,11 +201,11 @@ export class Actions {
* @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);
content = this.#cleanTextForEditor(content);
const selectionRange = this.#getSelectionRange();
const selectFrom = selectionRange.from + content.length + 1;
this.#dispatchChange(0, 0, content + '\n', selectFrom);
this.focus();
}
/**
@ -217,10 +213,9 @@ export class Actions {
* @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);
content = this.#cleanTextForEditor(content);
this.#dispatchChange(this.editor.cm.state.doc.length, '\n' + content);
this.focus();
}
/**
@ -228,18 +223,7 @@ export class Actions {
* @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);
this.#setText(content)
}
/**
@ -247,51 +231,30 @@ export class Actions {
* @param {String} newStart
*/
replaceLineStart(newStart) {
const cursor = this.editor.cm.getCursor();
let lineContent = this.editor.cm.getLine(cursor.line);
const lineLen = lineContent.length;
const selectionRange = this.#getSelectionRange();
const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
const lineContent = line.text;
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)});
const newLineContent = lineContent.replace(`${newStart} `, '');
const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
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}`;
const alreadySymbol = /^[#>`]/.test(lineStart);
if (alreadySymbol) {
newLineContent = lineContent.replace(lineStart, newStart).trim();
} else if (newStart !== '') {
newLineContent = newStart + ' ' + lineContent;
}
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});
const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
this.#dispatchChange(line.from, line.to, newLineContent, selectFrom);
}
/**
@ -300,33 +263,30 @@ export class Actions {
* @param {String} end
*/
wrapSelection(start, end) {
const selection = this.editor.cm.getSelection();
if (selection === '') return this.wrapLine(start, end);
const selectionRange = this.#getSelectionRange();
const selectionText = this.#getSelectionText(selectionRange);
if (!selectionText) return this.#wrapLine(start, end);
let newSelection = selection;
const frontDiff = 0;
let endDiff;
let newSelectionText = selectionText;
let newRange;
if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
newSelection = selection.slice(start.length, selection.length - end.length);
endDiff = -(end.length + start.length);
if (selectionText.startsWith(start) && selectionText.endsWith(end)) {
newSelectionText = selectionText.slice(start.length, selectionText.length - end.length);
newRange = selectionRange.extend(selectionRange.from, selectionRange.to - (start.length + end.length));
} else {
newSelection = `${start}${selection}${end}`;
endDiff = start.length + end.length;
newSelectionText = `${start}${selectionText}${end}`;
newRange = selectionRange.extend(selectionRange.from, selectionRange.to + (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]);
this.#dispatchChange(selectionRange.from, selectionRange.to, newSelectionText, newRange.anchor, newRange.head);
}
replaceLineStartForOrderedList() {
const cursor = this.editor.cm.getCursor();
const prevLineContent = this.editor.cm.getLine(cursor.line - 1) || '';
const listMatch = prevLineContent.match(/^(\s*)(\d)([).])\s/) || [];
const selectionRange = this.#getSelectionRange();
const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
const prevLine = this.editor.cm.state.doc.line(line.number - 1);
const listMatch = prevLine.text.match(/^(\s*)(\d)([).])\s/) || [];
const number = (Number(listMatch[2]) || 0) + 1;
const whiteSpace = listMatch[1] || '';
@ -341,87 +301,39 @@ export class Actions {
* 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 selectionRange = this.#getSelectionRange();
const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
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 matches = regex.exec(line.text);
const format = (matches ? (matches[2] || matches[3]) : '').toLowerCase();
if (format === formats[formats.length - 1]) {
this.wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
this.#wrapLine(`<p class="callout ${formats[formats.length - 1]}">`, '</p>');
} else if (format === '') {
this.wrapLine('<p class="callout info">', '</p>');
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);
const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
const lineDiff = newContent.length - line.text.length;
this.#dispatchChange(line.from, line.to, newContent, selectionRange.anchor + lineDiff, selectionRange.head + lineDiff);
}
}
/**
* 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() {
syncDisplayPosition(event) {
// 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;
const scrollEl = event.target;
const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
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 blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
const parser = new DOMParser();
const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
const totalLines = doc.documentElement.querySelectorAll('body > *');
@ -435,24 +347,190 @@ export class Actions {
* @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);
});
async insertTemplate(templateId, posX, posY) {
const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
const {data} = await window.$http.get(`/templates/${templateId}`);
const content = data.markdown || data.html;
this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
}
/**
* Insert multiple images from the clipboard.
* Insert multiple images from the clipboard from an event at the provided
* screen coordinates (Typically form a paste event).
* @param {File[]} images
* @param {Number} posX
* @param {Number} posY
*/
insertClipboardImages(images) {
const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
this.editor.cm.setCursor(cursorPos);
insertClipboardImages(images, posX, posY) {
const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
for (const image of images) {
this.uploadImage(image);
this.uploadImage(image, cursorPos);
}
}
/**
* Handle image upload and add image into markdown content
* @param {File} file
* @param {?Number} position
*/
async uploadImage(file, position= null) {
if (file === null || file.type.indexOf('image') !== 0) return;
let ext = 'png';
if (position === null) {
position = this.#getSelectionRange().from;
}
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 placeHolderText = `![](${placeholderImage})`;
this.#dispatchChange(position, position, placeHolderText, position);
const remoteFilename = "image-" + Date.now() + "." + ext;
const formData = new FormData();
formData.append('file', file, remoteFilename);
formData.append('uploaded_to', this.editor.config.pageId);
try {
const {data} = await window.$http.post('/images/gallery', formData);
const newContent = `[![](${data.thumbs.display})](${data.url})`;
this.#findAndReplaceContent(placeHolderText, newContent);
} catch (err) {
window.$events.emit('error', this.editor.config.text.imageUploadError);
this.#findAndReplaceContent(placeHolderText, '');
console.log(err);
}
}
/**
* Get the current text of the editor instance.
* @return {string}
*/
#getText() {
return this.editor.cm.state.doc.toString();
}
/**
* Set the text of the current editor instance.
* @param {String} text
* @param {?SelectionRange} selectionRange
*/
#setText(text, selectionRange = null) {
selectionRange = selectionRange || this.#getSelectionRange();
this.#dispatchChange(0, this.editor.cm.state.doc.length, text, selectionRange.from);
this.focus();
}
/**
* Replace the current selection and focus the editor.
* Takes an offset for the cursor, after the change, relative to the start of the provided string.
* Can be provided a selection range to use instead of the current selection range.
* @param {String} newContent
* @param {Number} cursorOffset
* @param {?SelectionRange} selectionRange
*/
#replaceSelection(newContent, cursorOffset = 0, selectionRange = null) {
selectionRange = selectionRange || this.editor.cm.state.selection.main;
this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectionRange.from + cursorOffset);
this.focus();
}
/**
* Get the text content of the main current selection.
* @param {SelectionRange} selectionRange
* @return {string}
*/
#getSelectionText(selectionRange = null) {
selectionRange = selectionRange || this.#getSelectionRange();
return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
}
/**
* Get the range of the current main selection.
* @return {SelectionRange}
*/
#getSelectionRange() {
return this.editor.cm.state.selection.main;
}
/**
* Cleans the given text to work with the editor.
* Standardises line endings to what's expected.
* @param {String} text
* @return {String}
*/
#cleanTextForEditor(text) {
return text.replace(/\r\n|\r/g, "\n");
}
/**
* Find and replace the first occurrence of [search] with [replace]
* @param {String} search
* @param {String} replace
*/
#findAndReplaceContent(search, replace) {
const newText = this.#getText().replace(search, replace);
this.#setText(newText);
}
/**
* Wrap the line in the given start and end contents.
* @param {String} start
* @param {String} end
*/
#wrapLine(start, end) {
const selectionRange = this.#getSelectionRange();
const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
const lineContent = line.text;
let newLineContent;
let lineOffset = 0;
if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
lineOffset = -(start.length);
} else {
newLineContent = `${start}${lineContent}${end}`;
lineOffset = start.length;
}
this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
}
/**
* Dispatch changes to the editor.
* @param {Number} from
* @param {?Number} to
* @param {?String} text
* @param {?Number} selectFrom
* @param {?Number} selectTo
*/
#dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
const tr = {changes: {from, to: to, insert: text}};
if (selectFrom) {
tr.selection = {anchor: selectFrom};
}
this.editor.cm.dispatch(tr);
}
/**
* Set the current selection range.
* Optionally will scroll the new range into view.
* @param {Number} from
* @param {Number} to
* @param {Boolean} scrollIntoView
*/
#setSelection(from, to, scrollIntoView = false) {
this.editor.cm.dispatch({
selection: {anchor: from, head: to},
scrollIntoView,
});
}
}

View File

@ -1,4 +1,4 @@
import {provide as provideShortcuts} from "./shortcuts";
import {provideKeyBindings} from "./shortcuts";
import {debounce} from "../services/util";
import Clipboard from "../services/clipboard";
@ -9,62 +9,65 @@ import Clipboard from "../services/clipboard";
*/
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()));
/**
* @param {ViewUpdate} v
*/
function onViewUpdate(v) {
if (v.docChanged) {
editor.actions.updateAndRender();
}
}
// 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);
const domEventHandlers = {
// Handle scroll to sync display view
scroll: (event) => syncActive && onScrollDebounced(event),
// Handle image & content drag n drop
drop: (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, event.pageX, event.pageY);
}
},
// Handle image paste
paste: (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 paste
cm.on('paste', (cm, event) => {
const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
const cm = Code.markdownEditor(
editor.config.inputEl,
onViewUpdate,
domEventHandlers,
provideKeyBindings(editor),
);
// 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);
}
});
// Add editor view to window for easy access/debugging.
// Not part of official API/Docs
window.mdEditorView = cm;
return cm;
}

View File

@ -49,6 +49,6 @@ export async function init(config) {
* @property {Display} display
* @property {Markdown} markdown
* @property {Actions} actions
* @property {CodeMirror} cm
* @property {EditorView} cm
* @property {Settings} settings
*/

View File

@ -1,48 +1,64 @@
/**
* Provide shortcuts for the given codemirror instance.
* Provide shortcuts for the editor instance.
* @param {MarkdownEditor} editor
* @param {String} metaKey
* @returns {Object<String, Function>}
*/
export function provide(editor, metaKey) {
function provide(editor) {
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);
};
shortcuts['Shift-Mod-i'] = cm => editor.actions.insertImage();
// Save draft
shortcuts[`${metaKey}-S`] = cm => window.$events.emit('editor-save-draft');
shortcuts['Mod-s'] = cm => window.$events.emit('editor-save-draft');
// Save page
shortcuts[`${metaKey}-Enter`] = cm => window.$events.emit('editor-save-page');
shortcuts['Mod-Enter'] = cm => window.$events.emit('editor-save-page');
// Show link selector
shortcuts[`Shift-${metaKey}-K`] = cm => editor.actions.showLinkSelector();
shortcuts['Shift-Mod-k'] = cm => editor.actions.showLinkSelector();
// Insert Link
shortcuts[`${metaKey}-K`] = cm => editor.actions.insertLink();
shortcuts['Mod-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()
shortcuts['Mod-1'] = cm => editor.actions.replaceLineStart('##');
shortcuts['Mod-2'] = cm => editor.actions.replaceLineStart('###');
shortcuts['Mod-3'] = cm => editor.actions.replaceLineStart('####');
shortcuts['Mod-4'] = cm => editor.actions.replaceLineStart('#####');
shortcuts['Mod-5'] = cm => editor.actions.replaceLineStart('');
shortcuts['Mod-d'] = cm => editor.actions.replaceLineStart('');
shortcuts['Mod-6'] = cm => editor.actions.replaceLineStart('>');
shortcuts['Mod-q'] = cm => editor.actions.replaceLineStart('>');
shortcuts['Mod-7'] = cm => editor.actions.wrapSelection('\n```\n', '\n```');
shortcuts['Mod-8'] = cm => editor.actions.wrapSelection('`', '`');
shortcuts['Shift-Mod-e'] = cm => editor.actions.wrapSelection('`', '`');
shortcuts['Mod-9'] = cm => editor.actions.cycleCalloutTypeAtSelection();
shortcuts['Mod-p'] = cm => editor.actions.replaceLineStart('-')
shortcuts['Mod-o'] = cm => editor.actions.replaceLineStartForOrderedList()
return shortcuts;
}
/**
* Get the editor shortcuts in CodeMirror keybinding format.
* @param {MarkdownEditor} editor
* @return {{key: String, run: function, preventDefault: boolean}[]}
*/
export function provideKeyBindings(editor) {
const shortcuts= provide(editor);
const keyBindings = [];
const wrapAction = (action) => {
return () => {
action();
return true;
};
};
for (const [shortcut, action] of Object.entries(shortcuts)) {
keyBindings.push({key: shortcut, run: wrapAction(action), preventDefault: true});
}
return keyBindings;
}

View File

@ -1,5 +1,5 @@
class Clipboard {
export class Clipboard {
/**
* Constructor
@ -51,4 +51,20 @@ class Clipboard {
}
}
export async function copyTextToClipboard(text) {
if (window.isSecureContext && navigator.clipboard) {
await navigator.clipboard.writeText(text);
return;
}
// Backup option where we can't use the navigator.clipboard API
const tempInput = document.createElement("textarea");
tempInput.style = "position: absolute; left: -1000px; top: -1000px;";
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
}
export default Clipboard;

View File

@ -36,6 +36,12 @@ function defineCodeBlockCustomElement(editor) {
const win = doc.defaultView;
class CodeBlockElement extends win.HTMLElement {
/**
* @type {?SimpleEditorInterface}
*/
editor = null;
constructor() {
super();
this.attachShadow({mode: 'open'});
@ -47,6 +53,7 @@ function defineCodeBlockCustomElement(editor) {
cmContainer.style.pointerEvents = 'none';
cmContainer.contentEditable = 'false';
cmContainer.classList.add('CodeMirrorContainer');
cmContainer.classList.toggle('dark-mode', document.documentElement.classList.contains('dark-mode'));
this.shadowRoot.append(...copiedStyles, cmContainer);
}
@ -63,11 +70,9 @@ function defineCodeBlockCustomElement(editor) {
}
setContent(content, language) {
if (this.cm) {
importVersioned('code').then(Code => {
Code.setContent(this.cm, content);
Code.setMode(this.cm, language, content);
});
if (this.editor) {
this.editor.setContent(content);
this.editor.setMode(language, content);
}
let pre = this.querySelector('pre');
@ -98,7 +103,7 @@ function defineCodeBlockCustomElement(editor) {
connectedCallback() {
const connectedTime = Date.now();
if (this.cm) {
if (this.editor) {
return;
}
@ -109,15 +114,14 @@ function defineCodeBlockCustomElement(editor) {
this.style.height = `${height}px`;
const container = this.shadowRoot.querySelector('.CodeMirrorContainer');
const renderCodeMirror = (Code) => {
this.cm = Code.wysiwygView(container, content, this.getLanguage());
setTimeout(() => Code.updateLayout(this.cm), 10);
const renderEditor = (Code) => {
this.editor = Code.wysiwygView(container, this.shadowRoot, content, this.getLanguage());
setTimeout(() => this.style.height = null, 12);
};
window.importVersioned('code').then((Code) => {
const timeout = (Date.now() - connectedTime < 20) ? 20 : 0;
setTimeout(() => renderCodeMirror(Code), timeout);
setTimeout(() => renderEditor(Code), timeout);
});
}

View File

@ -1,480 +1,64 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor-mark {
background-color: rgba(20, 255, 20, 0.5);
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
background-color: #7e7;
}
@-moz-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@-webkit-keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
@keyframes blink {
0% {}
50% { background-color: transparent; }
100% {}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-rulers {
position: absolute;
left: 0; right: 0; top: -50px; bottom: 0;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0; bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 50px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -50px; margin-right: -50px;
padding-bottom: 50px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 50px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
outline: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -50px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0; bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre.CodeMirror-line,
.CodeMirror-wrap pre.CodeMirror-line-like {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
.CodeMirror-widget {}
.CodeMirror-rtl pre { direction: rtl; }
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre { position: static; }
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, .4);
}
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }
/* STOP */
/**
* Codemirror Darcula theme
* Custom CodeMirror BookStack overrides
*/
/**
Name: IntelliJ IDEA darcula theme
From IntelliJ IDEA by JetBrains
*/
.cm-s-darcula { font-family: Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif;}
.cm-s-darcula.CodeMirror { background: #2B2B2B; color: #A9B7C6; }
.cm-s-darcula span.cm-meta { color: #BBB529; }
.cm-s-darcula span.cm-number { color: #6897BB; }
.cm-s-darcula span.cm-keyword { color: #CC7832; line-height: 1em; font-weight: bold; }
.cm-s-darcula span.cm-def { color: #A9B7C6; font-style: italic; }
.cm-s-darcula span.cm-variable { color: #A9B7C6; }
.cm-s-darcula span.cm-variable-2 { color: #A9B7C6; }
.cm-s-darcula span.cm-variable-3 { color: #9876AA; }
.cm-s-darcula span.cm-type { color: #AABBCC; font-weight: bold; }
.cm-s-darcula span.cm-property { color: #FFC66D; }
.cm-s-darcula span.cm-operator { color: #A9B7C6; }
.cm-s-darcula span.cm-string { color: #6A8759; }
.cm-s-darcula span.cm-string-2 { color: #6A8759; }
.cm-s-darcula span.cm-comment { color: #61A151; font-style: italic; }
.cm-s-darcula span.cm-link { color: #CC7832; }
.cm-s-darcula span.cm-atom { color: #CC7832; }
.cm-s-darcula span.cm-error { color: #BC3F3C; }
.cm-s-darcula span.cm-tag { color: #629755; font-weight: bold; font-style: italic; text-decoration: underline; }
.cm-s-darcula span.cm-attribute { color: #6897bb; }
.cm-s-darcula span.cm-qualifier { color: #6A8759; }
.cm-s-darcula span.cm-bracket { color: #A9B7C6; }
.cm-s-darcula span.cm-builtin { color: #FF9E59; }
.cm-s-darcula span.cm-special { color: #FF9E59; }
.cm-s-darcula span.cm-matchhighlight { color: #FFFFFF; background-color: rgba(50, 89, 48, .7); font-weight: normal;}
.cm-s-darcula span.cm-searching { color: #FFFFFF; background-color: rgba(61, 115, 59, .7); font-weight: normal;}
.cm-s-darcula .CodeMirror-cursor { border-left: 1px solid #A9B7C6; }
.cm-s-darcula .CodeMirror-activeline-background { background: #323232; }
.cm-s-darcula .CodeMirror-gutters { background: #313335; border-right: 1px solid #313335; }
.cm-s-darcula .CodeMirror-guttermarker { color: #FFEE80; }
.cm-s-darcula .CodeMirror-guttermarker-subtle { color: #D0D0D0; }
.cm-s-darcula .CodeMirrir-linenumber { color: #606366; }
.cm-s-darcula .CodeMirror-matchingbracket { background-color: #3B514D; color: #FFEF28 !important; font-weight: bold; }
.cm-s-darcula div.CodeMirror-selected { background: #214283; }
.CodeMirror-hints.darcula {
font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;
color: #9C9E9E;
background-color: #3B3E3F !important;
}
.CodeMirror-hints.darcula .CodeMirror-hint-active {
background-color: #494D4E !important;
color: #9C9E9E !important;
}
/**
* Custom BookStack overrides
*/
.CodeMirror, .CodeMirror pre {
.cm-editor {
font-size: 12px;
}
.CodeMirror {
font-size: 12px;
height: auto;
border: 1px solid #ddd;
line-height: 1.4;
margin-bottom: $-l;
border: 1px solid;
@include lightDark(border-color, #DDD, #111);
}
.CodeMirror pre::after {
display: none;
}
html.dark-mode .CodeMirror pre {
background-color: transparent;
}
.cm-s-mdn-like .CodeMirror-gutters { background: #f8f8f8; border-left: 0; color: #333; }
.page-content .cm-editor,
.CodeMirrorContainer .cm-editor {
border-radius: 4px;
}
.code-fill .CodeMirror {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
margin-bottom: 0;
border: 0;
// Manual dark-mode definition so that it applies to code blocks within the shadow
// dom which are used within the WYSIWYG editor, as the .dark-mode on the parent
// <html> node are not applies so instead we have the class on the parent element.
.dark-mode .cm-editor {
border-color: #444;
}
/**
* Custom Copy Button
*/
.CodeMirror-copy {
.cm-copy-button {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
top: -1px;
right: -1px;
background-color: #EEE;
border: 1px solid #DDD;
border-radius: 0 4px 0 0;
@include lightDark(background-color, #eee, #333);
@include lightDark(border-color, #ddd, #444);
@include lightDark(fill, #444, #888);
padding: $-xs;
@include lightDark(color, #444, #888);
line-height: 0;
cursor: pointer;
z-index: 5;
user-select: none;
opacity: 0;
pointer-events: none;
width: 32px;
height: 32px;
transition: background-color linear 60ms, color linear 60ms;
svg {
transition: all ease-in 240ms;
transform: translateY(0);
fill: currentColor;
}
&.success {
background-color: lighten($positive, 10%);
svg {
fill: #FFF;
transform: translateY(-3px);
}
background: $positive;
color: #FFF;
}
&:focus {
outline: 0 !important;
}
}
.CodeMirror:hover .CodeMirror-copy {
.cm-editor:hover .cm-copy-button {
user-select: all;
opacity: 1;
opacity: .6;
pointer-events: all;
}

View File

@ -730,7 +730,7 @@ body.flexbox-support #entity-selector-wrap .popup-body .form-group {
.code-editor-main {
flex: 1;
min-width: 0;
.CodeMirror {
.cm-editor {
margin-bottom: 0;
z-index: 1;
max-width: 100%;

View File

@ -75,6 +75,7 @@
@include lightDark(border-color, #ddd, #000);
position: relative;
flex: 1;
min-width: 0;
}
.markdown-editor-wrap + .markdown-editor-wrap {
flex-basis: 50%;
@ -82,6 +83,13 @@
flex-grow: 0;
}
.markdown-editor-wrap .cm-editor {
flex: 1;
max-width: 100%;
border: 0;
margin: 0;
}
.markdown-panel-divider {
width: 2px;
@include lightDark(background-color, #ddd, #000);

View File

@ -178,6 +178,10 @@ body.tox-fullscreen, body.markdown-fullscreen {
white-space: pre-wrap;
}
}
.cm-editor {
margin-bottom: 1.375em;
}
}
// Page content pointers

View File

@ -178,18 +178,19 @@ sub, .subscript {
pre {
font-size: 12px;
border: 1px solid #DDD;
@include lightDark(background-color, #f5f5f5, #2B2B2B);
@include lightDark(background-color, #FFF, #2B2B2B);
@include lightDark(border-color, #DDD, #111);
padding-left: 31px;
border-radius: 4px;
padding-left: 26px;
position: relative;
padding-top: 3px;
padding-bottom: 3px;
&:after {
&:before {
content: '';
display: block;
position: absolute;
top: 0;
width: 29px;
width: 22.4px;
left: 0;
height: 100%;
@include lightDark(background-color, #f5f5f5, #313335);

View File

@ -30,7 +30,7 @@
</div>
</div>
<div markdown-input class="flex flex-fill">
<div class="flex flex-fill" dir="ltr">
<textarea id="markdown-editor-input"
refs="markdown-editor@input"
@if($errors->has('markdown')) class="text-neg" @endif

View File

@ -5,8 +5,8 @@
<div class="pointer anim {{ userCan('page-update', $page) ? 'is-page-editable' : ''}}" >
<span class="icon mr-xxs">@icon('link') @icon('include', ['style' => 'display:none;'])</span>
<div class="input-group inline block">
<input readonly="readonly" type="text" id="pointer-url" placeholder="url">
<button class="button outline icon" data-clipboard-target="#pointer-url" type="button" title="{{ trans('entities.pages_copy_link') }}">@icon('copy')</button>
<input refs="pointer@input" readonly="readonly" type="text" id="pointer-url" placeholder="url">
<button refs="pointer@button" class="button outline icon" data-clipboard-target="#pointer-url" type="button" title="{{ trans('entities.pages_copy_link') }}">@icon('copy')</button>
</div>
@if(userCan('page-update', $page))
<a href="{{ $page->getUrl('/edit') }}" id="pointer-edit" data-edit-href="{{ $page->getUrl('/edit') }}"