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