]> BookStack Code Mirror - bookstack/blob - resources/js/components/code-editor.js
0d8450314cc3115605eec73804812e81b816efa9
[bookstack] / resources / js / components / code-editor.js
1 import {onChildEvent, onEnterPress, onSelect} from '../services/dom';
2 import {Component} from './component';
3
4 export class CodeEditor extends Component {
5
6     /**
7      * @type {null|SimpleEditorInterface}
8      */
9     editor = null;
10
11     callback = null;
12
13     history = {};
14
15     historyKey = 'code_history';
16
17     setup() {
18         this.container = this.$refs.container;
19         this.popup = this.$el;
20         this.editorInput = this.$refs.editor;
21         this.languageButtons = this.$manyRefs.languageButton;
22         this.languageOptionsContainer = this.$refs.languageOptionsContainer;
23         this.saveButton = this.$refs.saveButton;
24         this.languageInput = this.$refs.languageInput;
25         this.historyDropDown = this.$refs.historyDropDown;
26         this.historyList = this.$refs.historyList;
27         this.favourites = new Set(this.$opts.favourites.split(','));
28
29         this.setupListeners();
30         this.setupFavourites();
31     }
32
33     setupListeners() {
34         this.container.addEventListener('keydown', event => {
35             if (event.ctrlKey && event.key === 'Enter') {
36                 this.save();
37             }
38         });
39
40         onSelect(this.languageButtons, event => {
41             const language = event.target.dataset.lang;
42             this.languageInput.value = language;
43             this.languageInputChange(language);
44         });
45
46         onEnterPress(this.languageInput, e => this.save());
47         this.languageInput.addEventListener('input', e => this.languageInputChange(this.languageInput.value));
48         onSelect(this.saveButton, e => this.save());
49
50         onChildEvent(this.historyList, 'button', 'click', (event, elem) => {
51             event.preventDefault();
52             const historyTime = elem.dataset.time;
53             if (this.editor) {
54                 this.editor.setContent(this.history[historyTime]);
55             }
56         });
57     }
58
59     setupFavourites() {
60         for (const button of this.languageButtons) {
61             this.setupFavouritesForButton(button);
62         }
63
64         this.sortLanguageList();
65     }
66
67     /**
68      * @param {HTMLButtonElement} button
69      */
70     setupFavouritesForButton(button) {
71         const language = button.dataset.lang;
72         let isFavorite = this.favourites.has(language);
73         button.setAttribute('data-favourite', isFavorite ? 'true' : 'false');
74
75         onChildEvent(button.parentElement, '.lang-option-favorite-toggle', 'click', () => {
76             isFavorite = !isFavorite;
77             isFavorite ? this.favourites.add(language) : this.favourites.delete(language);
78             button.setAttribute('data-favourite', isFavorite ? 'true' : 'false');
79
80             window.$http.patch('/preferences/update-code-language-favourite', {
81                 language,
82                 active: isFavorite,
83             });
84
85             this.sortLanguageList();
86             if (isFavorite) {
87                 button.scrollIntoView({block: 'center', behavior: 'smooth'});
88             }
89         });
90     }
91
92     sortLanguageList() {
93         const sortedParents = this.languageButtons.sort((a, b) => {
94             const aFav = a.dataset.favourite === 'true';
95             const bFav = b.dataset.favourite === 'true';
96
97             if (aFav && !bFav) {
98                 return -1;
99             } if (bFav && !aFav) {
100                 return 1;
101             }
102
103             return a.dataset.lang > b.dataset.lang ? 1 : -1;
104         }).map(button => button.parentElement);
105
106         for (const parent of sortedParents) {
107             this.languageOptionsContainer.append(parent);
108         }
109     }
110
111     save() {
112         if (this.callback) {
113             this.callback(this.editor.getContent(), this.languageInput.value);
114         }
115         this.hide();
116     }
117
118     async open(code, language, callback) {
119         this.languageInput.value = language;
120         this.callback = callback;
121
122         await this.show();
123         this.languageInputChange(language);
124         this.editor.setContent(code);
125     }
126
127     async show() {
128         const Code = await window.importVersioned('code');
129         if (!this.editor) {
130             this.editor = Code.popupEditor(this.editorInput, this.languageInput.value);
131         }
132
133         this.loadHistory();
134         this.getPopup().show(() => {
135             this.editor.focus();
136         }, () => {
137             this.addHistory();
138         });
139     }
140
141     hide() {
142         this.getPopup().hide();
143         this.addHistory();
144     }
145
146     /**
147      * @returns {Popup}
148      */
149     getPopup() {
150         return window.$components.firstOnElement(this.popup, 'popup');
151     }
152
153     async updateEditorMode(language) {
154         this.editor.setMode(language, this.editor.getContent());
155     }
156
157     languageInputChange(language) {
158         this.updateEditorMode(language);
159         const inputLang = language.toLowerCase();
160
161         for (const link of this.languageButtons) {
162             const lang = link.dataset.lang.toLowerCase().trim();
163             const isMatch = inputLang === lang;
164             link.classList.toggle('active', isMatch);
165             if (isMatch) {
166                 link.scrollIntoView({block: 'center', behavior: 'smooth'});
167             }
168         }
169     }
170
171     loadHistory() {
172         this.history = JSON.parse(window.sessionStorage.getItem(this.historyKey) || '{}');
173         const historyKeys = Object.keys(this.history).reverse();
174         this.historyDropDown.classList.toggle('hidden', historyKeys.length === 0);
175         this.historyList.innerHTML = historyKeys.map(key => {
176             const localTime = (new Date(parseInt(key))).toLocaleTimeString();
177             return `<li><button type="button" data-time="${key}" class="text-item">${localTime}</button></li>`;
178         }).join('');
179     }
180
181     addHistory() {
182         if (!this.editor) return;
183         const code = this.editor.getContent();
184         if (!code) return;
185
186         // Stop if we'd be storing the same as the last item
187         const lastHistoryKey = Object.keys(this.history).pop();
188         if (this.history[lastHistoryKey] === code) return;
189
190         this.history[String(Date.now())] = code;
191         const historyString = JSON.stringify(this.history);
192         window.sessionStorage.setItem(this.historyKey, historyString);
193     }
194
195 }