trilium/src/public/javascripts/services/note_detail_code.js

95 lines
2.8 KiB
JavaScript
Raw Normal View History

2018-03-28 10:42:46 +08:00
import libraryLoader from "./library_loader.js";
import bundleService from "./bundle.js";
import infoService from "./info.js";
import server from "./server.js";
import noteDetailService from "./note_detail.js";
let codeEditor = null;
const $noteDetailCode = $('#note-detail-code');
const $executeScriptButton = $("#execute-script-button");
2018-03-28 09:46:38 +08:00
async function show() {
2018-04-08 03:56:46 +08:00
await libraryLoader.requireLibrary(libraryLoader.CODE_MIRROR);
2018-04-08 03:56:46 +08:00
if (!codeEditor) {
CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";
CodeMirror.keyMap.default["Tab"] = "indentMore";
// these conflict with backward/forward navigation shortcuts
delete CodeMirror.keyMap.default["Alt-Left"];
delete CodeMirror.keyMap.default["Alt-Right"];
CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';
2018-04-08 03:56:46 +08:00
codeEditor = CodeMirror($noteDetailCode[0], {
value: "",
viewportMargin: Infinity,
indentUnit: 4,
matchBrackets: true,
matchTags: {bothTags: true},
highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false},
lint: true,
gutters: ["CodeMirror-lint-markers"],
lineNumbers: true,
tabindex: 2 // so that tab from title will lead to code editor focus
});
codeEditor.on('change', noteDetailService.noteChanged);
}
$noteDetailCode.show();
const currentNote = noteDetailService.getCurrentNote();
2018-04-08 03:56:46 +08:00
// this needs to happen after the element is shown, otherwise the editor won't be refreshed
codeEditor.setValue(currentNote.content);
const info = CodeMirror.findModeByMIME(currentNote.mime);
if (info) {
codeEditor.setOption("mode", info.mime);
CodeMirror.autoLoadMode(codeEditor, info.mode);
}
codeEditor.refresh();
}
function getContent() {
return codeEditor.getValue();
}
function focus() {
codeEditor.focus();
}
async function executeCurrentNote() {
if (noteDetailService.getCurrentNoteType() === 'code') {
// make sure note is saved so we load latest changes
await noteDetailService.saveNoteIfChanged();
const currentNote = noteDetailService.getCurrentNote();
if (currentNote.mime.endsWith("env=frontend")) {
2018-04-07 07:41:48 +08:00
const bundle = await server.get('script/bundle/' + noteDetailService.getCurrentNoteId());
bundleService.executeBundle(bundle);
}
if (currentNote.mime.endsWith("env=backend")) {
2018-04-07 07:41:48 +08:00
await server.post('script/run/' + noteDetailService.getCurrentNoteId());
}
infoService.showMessage("Note executed");
}
}
$(document).bind('keydown', "ctrl+return", executeCurrentNote);
$executeScriptButton.click(executeCurrentNote);
export default {
2018-03-28 09:46:38 +08:00
show,
getContent,
focus
}