sandy/static/script/editor.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-02-17 15:53:47 +01:00
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();
2024-02-17 15:53:47 +01:00
const code_key = 'sandy-cached-code';
const lang_key = 'sandy-cached-lang';
2024-02-18 17:48:44 +01:00
const storage = window.localStorage;
const init_lang = storage.getItem(lang_key) ?? 'python';
2024-02-19 07:34:29 +01:00
const init_code = storage.getItem(code_key) ?? '# put code here';
2024-02-17 15:53:47 +01:00
let editor = monaco.editor.create(document.getElementById('container'), {
2024-02-19 07:34:29 +01:00
value: init_code,
2024-02-17 15:53:47 +01:00
language: init_lang,
theme: 'vs-dark'
});
2024-02-19 07:34:29 +01:00
let model = editor.getModel();
2024-02-18 17:48:44 +01:00
function upd_code() {
2024-02-17 15:53:47 +01:00
window.code = editor.getValue();
storage.setItem(code_key, window.code);
2024-02-18 17:48:44 +01:00
}
function timer_code() {
setTimeout(() => {
timer_code()
upd_code();
}, 500);
}
editor.addListener('didType', () => upd_code);
timer_code();
2024-02-17 15:53:47 +01:00
monaco.languages.getLanguages().forEach(x => {
if (supported_langs.indexOf(x.id) === -1) return
2024-02-17 15:53:47 +01:00
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);
2024-02-17 15:53:47 +01:00
}
document.getElementById('run').onclick = (e) => {
executeCode(window.code, editor.getModel().getLanguageIdentifier().language)
}
2024-02-19 07:34:29 +01:00
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);
}
2024-02-17 15:53:47 +01:00
});