BookStack/resources/js/services/code.js

341 lines
9.2 KiB
JavaScript
Raw Normal View History

import CodeMirror from "codemirror";
2018-11-11 00:08:33 +08:00
import Clipboard from "clipboard/dist/clipboard.min";
// Modes
import 'codemirror/mode/css/css';
import 'codemirror/mode/clike/clike';
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/perl/perl';
import 'codemirror/mode/pascal/pascal';
import 'codemirror/mode/php/php';
import 'codemirror/mode/powershell/powershell';
2019-09-16 08:20:11 +08:00
import 'codemirror/mode/properties/properties';
import 'codemirror/mode/python/python';
import 'codemirror/mode/ruby/ruby';
import 'codemirror/mode/rust/rust';
import 'codemirror/mode/shell/shell';
import 'codemirror/mode/sql/sql';
import 'codemirror/mode/toml/toml';
2020-10-02 21:14:29 +08:00
import 'codemirror/mode/vbscript/vbscript';
import 'codemirror/mode/xml/xml';
import 'codemirror/mode/yaml/yaml';
2017-05-28 20:16:21 +08:00
// Addons
import 'codemirror/addon/scroll/scrollpastend';
2017-05-28 20:16:21 +08:00
// 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.
2017-06-17 19:41:18 +08:00
const modeMap = {
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',
diff: 'diff',
for: 'fortran',
fortran: 'fortran',
2017-06-17 19:41:18 +08:00
go: 'go',
haskell: 'haskell',
hs: 'haskell',
2017-06-17 19:41:18 +08:00
html: 'htmlmixed',
ini: 'properties',
2017-06-17 19:41:18 +08:00
javascript: 'javascript',
json: {name: 'javascript', json: true},
js: 'javascript',
jl: 'julia',
julia: 'julia',
lua: 'lua',
2017-06-17 19:41:18 +08:00
md: 'markdown',
mdown: 'markdown',
markdown: 'markdown',
ml: 'mllike',
2017-06-17 19:41:18 +08:00
nginx: 'nginx',
perl: 'perl',
pl: 'perl',
2017-06-17 19:41:18 +08:00
powershell: 'powershell',
2019-09-16 08:24:47 +08:00
properties: 'properties',
ocaml: 'mllike',
pascal: 'text/x-pascal',
pas: 'text/x-pascal',
php: (content) => {
return content.includes('<?php') ? 'php' : 'text/x-php';
},
2017-06-17 19:41:18 +08:00
py: 'python',
python: 'python',
ruby: 'ruby',
rust: 'rust',
2017-06-17 19:41:18 +08:00
rb: 'ruby',
rs: 'rust',
2017-06-17 19:41:18 +08:00
shell: 'shell',
sh: 'shell',
2017-06-17 19:41:18 +08:00
bash: 'shell',
toml: 'toml',
sql: 'text/x-sql',
2020-10-14 05:44:33 +08:00
vbs: 'vbscript',
2020-10-02 21:14:29 +08:00
vbscript: 'vbscript',
2017-06-17 19:41:18 +08:00
xml: 'xml',
yaml: 'yaml',
yml: 'yaml',
};
/**
* Highlight pre elements on a page
*/
function highlight() {
2020-01-16 04:18:02 +08:00
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
*/
function highlightWithin(parent) {
const codeBlocks = parent.querySelectorAll('pre');
for (const codeBlock of codeBlocks) {
highlightElem(codeBlock);
2017-06-17 22:07:55 +08:00
}
}
2017-05-28 20:16:21 +08:00
/**
* Add code highlighting to a single element.
* @param {HTMLElement} elem
*/
2017-06-17 22:07:55 +08:00
function highlightElem(elem) {
const innerCodeElem = elem.querySelector('code[class^=language-]');
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
const content = elem.textContent.trimEnd();
2017-06-17 22:07:55 +08:00
let mode = '';
if (innerCodeElem !== null) {
const langName = innerCodeElem.className.replace('language-', '');
mode = getMode(langName, content);
2017-05-28 20:16:21 +08:00
}
2017-06-17 22:07:55 +08:00
const cm = CodeMirror(function(elt) {
2017-06-17 22:07:55 +08:00
elem.parentNode.replaceChild(elt, elem);
}, {
value: content,
mode: mode,
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
2017-06-17 22:07:55 +08:00
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);
});
2017-06-17 22:07:55 +08:00
}
/**
* 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');
}
2017-05-28 20:16:21 +08:00
/**
* Create a CodeMirror instance for showing inside the WYSIWYG editor.
* Manages a textarea element to hold code content.
* @param {HTMLElement} elem
* @returns {{wrap: Element, editor: *}}
*/
function wysiwygView(elem) {
const doc = elem.ownerDocument;
const codeElem = elem.querySelector('code');
let lang = (elem.className || '').replace('language-', '');
if (lang === '' && codeElem) {
lang = (codeElem.className || '').replace('language-', '')
}
2017-06-17 22:07:55 +08:00
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
const content = elem.textContent;
const newWrap = doc.createElement('div');
const newTextArea = doc.createElement('textarea');
2017-06-17 22:07:55 +08:00
newWrap.className = 'CodeMirrorContainer';
newWrap.setAttribute('data-lang', lang);
newWrap.setAttribute('dir', 'ltr');
2017-06-17 22:07:55 +08:00
newTextArea.style.display = 'none';
elem.parentNode.replaceChild(newWrap, elem);
newWrap.appendChild(newTextArea);
newWrap.contentEditable = false;
newTextArea.textContent = content;
let cm = CodeMirror(function(elt) {
newWrap.appendChild(elt);
}, {
value: content,
mode: getMode(lang, content),
2017-06-17 22:07:55 +08:00
lineNumbers: true,
lineWrapping: false,
theme: getTheme(),
2017-06-17 22:07:55 +08:00
readOnly: true
});
setTimeout(() => {
cm.refresh();
}, 300);
return {wrap: newWrap, editor: cm};
}
2017-05-28 20:16:21 +08:00
/**
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor
* @param {HTMLElement} elem
* @param {String} modeSuggestion
* @returns {*}
*/
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()
});
}
/**
* Set the mode of a codemirror instance.
* @param cmInstance
* @param modeSuggestion
*/
function setMode(cmInstance, modeSuggestion, content) {
cmInstance.setOption('mode', getMode(modeSuggestion, content));
}
/**
* Set the content of a cm instance.
* @param cmInstance
* @param codeContent
*/
function setContent(cmInstance, codeContent) {
cmInstance.setValue(codeContent);
setTimeout(() => {
updateLayout(cmInstance);
}, 10);
}
2017-06-17 22:07:55 +08:00
/**
* Update the layout (codemirror refresh) of a cm instance.
* @param cmInstance
*/
function updateLayout(cmInstance) {
cmInstance.refresh();
}
/**
* Get a CodeMirror instance to use for the markdown editor.
* @param {HTMLElement} elem
* @returns {*}
*/
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 dependant on the user's system.
* @returns {string}
*/
function getMetaKey() {
let mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
return mac ? "Cmd" : "Ctrl";
}
export default {
highlight: highlight,
2020-01-16 04:18:02 +08:00
highlightWithin: highlightWithin,
wysiwygView: wysiwygView,
popupEditor: popupEditor,
setMode: setMode,
setContent: setContent,
updateLayout: updateLayout,
markdownEditor: markdownEditor,
getMetaKey: getMetaKey,
};