]> BookStack Code Mirror - bookstack/blob - resources/js/components/code-editor.js
ESLINT: Added GH action and details to dev docs
[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, () => this.save());
47         this.languageInput.addEventListener('input', () => this.languageInputChange(this.languageInput.value));
48         onSelect(this.saveButton, () => 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             const action = isFavorite ? this.favourites.add : this.favourites.delete;
78             action(language);
79             button.setAttribute('data-favourite', isFavorite ? 'true' : 'false');
80
81             window.$http.patch('/preferences/update-code-language-favourite', {
82                 language,
83                 active: isFavorite,
84             });
85
86             this.sortLanguageList();
87             if (isFavorite) {
88                 button.scrollIntoView({block: 'center', behavior: 'smooth'});
89             }
90         });
91     }
92
93     sortLanguageList() {
94         const sortedParents = this.languageButtons.sort((a, b) => {
95             const aFav = a.dataset.favourite === 'true';
96             const bFav = b.dataset.favourite === 'true';
97
98             if (aFav && !bFav) {
99                 return -1;
100             } if (bFav && !aFav) {
101                 return 1;
102             }
103
104             return a.dataset.lang > b.dataset.lang ? 1 : -1;
105         }).map(button => button.parentElement);
106
107         for (const parent of sortedParents) {
108             this.languageOptionsContainer.append(parent);
109         }
110     }
111
112     save() {
113         if (this.callback) {
114             this.callback(this.editor.getContent(), this.languageInput.value);
115         }
116         this.hide();
117     }
118
119     async open(code, language, callback) {
120         this.languageInput.value = language;
121         this.callback = callback;
122
123         await this.show();
124         this.languageInputChange(language);
125         this.editor.setContent(code);
126     }
127
128     async show() {
129         const Code = await window.importVersioned('code');
130         if (!this.editor) {
131             this.editor = Code.popupEditor(this.editorInput, this.languageInput.value);
132         }
133
134         this.loadHistory();
135         this.getPopup().show(() => {
136             this.editor.focus();
137         }, () => {
138             this.addHistory();
139         });
140     }
141
142     hide() {
143         this.getPopup().hide();
144         this.addHistory();
145     }
146
147     /**
148      * @returns {Popup}
149      */
150     getPopup() {
151         return window.$components.firstOnElement(this.popup, 'popup');
152     }
153
154     async updateEditorMode(language) {
155         this.editor.setMode(language, this.editor.getContent());
156     }
157
158     languageInputChange(language) {
159         this.updateEditorMode(language);
160         const inputLang = language.toLowerCase();
161
162         for (const link of this.languageButtons) {
163             const lang = link.dataset.lang.toLowerCase().trim();
164             const isMatch = inputLang === lang;
165             link.classList.toggle('active', isMatch);
166             if (isMatch) {
167                 link.scrollIntoView({block: 'center', behavior: 'smooth'});
168             }
169         }
170     }
171
172     loadHistory() {
173         this.history = JSON.parse(window.sessionStorage.getItem(this.historyKey) || '{}');
174         const historyKeys = Object.keys(this.history).reverse();
175         this.historyDropDown.classList.toggle('hidden', historyKeys.length === 0);
176         this.historyList.innerHTML = historyKeys.map(key => {
177             const localTime = (new Date(parseInt(key, 10))).toLocaleTimeString();
178             return `<li><button type="button" data-time="${key}" class="text-item">${localTime}</button></li>`;
179         }).join('');
180     }
181
182     addHistory() {
183         if (!this.editor) return;
184         const code = this.editor.getContent();
185         if (!code) return;
186
187         // Stop if we'd be storing the same as the last item
188         const lastHistoryKey = Object.keys(this.history).pop();
189         if (this.history[lastHistoryKey] === code) return;
190
191         this.history[String(Date.now())] = code;
192         const historyString = JSON.stringify(this.history);
193         window.sessionStorage.setItem(this.historyKey, historyString);
194     }
195
196 }