sandy/static/script/editor.js

79 lines
2.3 KiB
JavaScript

require.config({ paths: { 'vs': 'https://unpkg.com/monaco-editor@0.8.3/min/vs' }});
window.MonacoEnvironment = { getWorkerUrl: () => proxy };
window.code = '';
let proxy = URL.createObjectURL(new Blob([`
self.MonacoEnvironment = {
baseUrl: 'https://unpkg.com/monaco-editor@0.8.3/min/'
};
importScripts('https://unpkg.com/monaco-editor@0.8.3/min/vs/base/worker/workerMain.js');
`], { type: 'text/javascript' }));
require(["vs/editor/editor.main"], function () {
/** @type {string[]} */
const supported_langs = get_langs();
const code_key = 'sandy-cached-code';
const lang_key = 'sandy-cached-lang';
const storage = window.localStorage;
const init_lang = storage.getItem(lang_key) ?? 'python';
const init_code = storage.getItem(code_key) ?? '# put code here';
let editor = monaco.editor.create(document.getElementById('container'), {
value: init_code,
language: init_lang,
theme: 'vs-dark'
});
let model = editor.getModel();
function upd_code() {
window.code = editor.getValue();
storage.setItem(code_key, window.code);
}
function timer_code() {
setTimeout(() => {
timer_code()
upd_code();
}, 500);
}
editor.addListener('didType', () => upd_code);
timer_code();
monaco.languages.getLanguages().forEach(x => {
if (supported_langs.indexOf(x.id) === -1) return
let el = document.createElement('option');
el.id = x.id;
el.innerText = x.id;
if (x.id == init_lang) el.selected = true;
document.getElementById('lang').appendChild(el);
})
document.getElementById('lang').onchange = (e) => {
e = e.target;
const lang = e.options[e.selectedIndex].id;
monaco.editor.setModelLanguage(editor.getModel(), lang);
storage.setItem(lang_key, lang);
}
document.getElementById('run').onclick = (e) => {
executeCode(window.code, editor.getModel().getLanguageIdentifier().language)
}
document.getElementById('reset').onclick = (_) => {
storage.removeItem(lang_key);
storage.removeItem(code_key);
lang = 'python';
monaco.editor.setModelLanguage(editor.getModel(), 'python');
window.code = init_code;
model.setValue(init_code);
}
});