1 import {onChildEvent, onEnterPress, onSelect} from "../services/dom";
10 this.container = this.$refs.container;
11 this.popup = this.$el;
12 this.editorInput = this.$refs.editor;
13 this.languageLinks = this.$manyRefs.languageLink;
14 this.saveButton = this.$refs.saveButton;
15 this.languageInput = this.$refs.languageInput;
16 this.historyDropDown = this.$refs.historyDropDown;
17 this.historyList = this.$refs.historyList;
22 this.historyKey = 'code_history';
23 this.setupListeners();
27 this.container.addEventListener('keydown', event => {
28 if (event.ctrlKey && event.key === 'Enter') {
33 onSelect(this.languageLinks, event => {
34 const language = event.target.dataset.lang;
35 this.languageInput.value = language;
36 this.updateEditorMode(language);
39 onEnterPress(this.languageInput, e => this.save());
40 onSelect(this.saveButton, e => this.save());
42 onChildEvent(this.historyList, 'button', 'click', (event, elem) => {
43 event.preventDefault();
44 const historyTime = elem.dataset.time;
46 this.editor.setValue(this.history[historyTime]);
53 this.callback(this.editor.getValue(), this.languageInput.value);
58 open(code, language, callback) {
59 this.languageInput.value = language;
60 this.callback = callback;
63 this.updateEditorMode(language);
65 window.importVersioned('code').then(Code => {
66 Code.setContent(this.editor, code);
71 const Code = await window.importVersioned('code');
73 this.editor = Code.popupEditor(this.editorInput, this.languageInput.value);
77 this.popup.components.popup.show(() => {
78 Code.updateLayout(this.editor);
86 this.popup.components.popup.hide();
90 async updateEditorMode(language) {
91 const Code = await window.importVersioned('code');
92 Code.setMode(this.editor, language, this.editor.getValue());
96 this.history = JSON.parse(window.sessionStorage.getItem(this.historyKey) || '{}');
97 const historyKeys = Object.keys(this.history).reverse();
98 this.historyDropDown.classList.toggle('hidden', historyKeys.length === 0);
99 this.historyList.innerHTML = historyKeys.map(key => {
100 const localTime = (new Date(parseInt(key))).toLocaleTimeString();
101 return `<li><button type="button" data-time="${key}">${localTime}</button></li>`;
106 if (!this.editor) return;
107 const code = this.editor.getValue();
110 // Stop if we'd be storing the same as the last item
111 const lastHistoryKey = Object.keys(this.history).pop();
112 if (this.history[lastHistoryKey] === code) return;
114 this.history[String(Date.now())] = code;
115 const historyString = JSON.stringify(this.history);
116 window.sessionStorage.setItem(this.historyKey, historyString);
121 export default CodeEditor;