1 import Code from "../services/code";
2 import {onChildEvent, onEnterPress, onSelect} from "../services/dom";
11 this.container = this.$refs.container;
12 this.popup = this.$el;
13 this.editorInput = this.$refs.editor;
14 this.languageLinks = this.$manyRefs.languageLink;
15 this.saveButton = this.$refs.saveButton;
16 this.languageInput = this.$refs.languageInput;
17 this.historyDropDown = this.$refs.historyDropDown;
18 this.historyList = this.$refs.historyList;
23 this.historyKey = 'code_history';
24 this.setupListeners();
28 this.container.addEventListener('keydown', event => {
29 if (event.ctrlKey && event.key === 'Enter') {
34 onSelect(this.languageLinks, event => {
35 const language = event.target.dataset.lang;
36 this.languageInput.value = language;
37 this.updateEditorMode(language);
40 onEnterPress(this.languageInput, e => this.save());
41 onSelect(this.saveButton, e => this.save());
43 onChildEvent(this.historyList, 'button', 'click', (event, elem) => {
44 event.preventDefault();
45 const historyTime = elem.dataset.time;
47 this.editor.setValue(this.history[historyTime]);
54 this.callback(this.editor.getValue(), this.languageInput.value);
59 open(code, language, callback) {
60 this.languageInput.value = language;
61 this.callback = callback;
64 this.updateEditorMode(language);
66 Code.setContent(this.editor, code);
71 this.editor = Code.popupEditor(this.editorInput, this.languageInput.value);
74 this.popup.components.popup.show(() => {
75 Code.updateLayout(this.editor);
83 this.popup.components.popup.hide();
87 updateEditorMode(language) {
88 Code.setMode(this.editor, language, this.editor.getValue());
92 this.history = JSON.parse(window.sessionStorage.getItem(this.historyKey) || '{}');
93 const historyKeys = Object.keys(this.history).reverse();
94 this.historyDropDown.classList.toggle('hidden', historyKeys.length === 0);
95 this.historyList.innerHTML = historyKeys.map(key => {
96 const localTime = (new Date(parseInt(key))).toLocaleTimeString();
97 return `<li><button type="button" data-time="${key}">${localTime}</button></li>`;
102 if (!this.editor) return;
103 const code = this.editor.getValue();
106 // Stop if we'd be storing the same as the last item
107 const lastHistoryKey = Object.keys(this.history).pop();
108 if (this.history[lastHistoryKey] === code) return;
110 this.history[String(Date.now())] = code;
111 const historyString = JSON.stringify(this.history);
112 window.sessionStorage.setItem(this.historyKey, historyString);
117 export default CodeEditor;