]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-editor.js
Improved WYSIWYG code block behaviour via range of fixes
[bookstack] / resources / js / components / page-editor.js
1 import * as Dates from "../services/dates";
2 import {onSelect} from "../services/dom";
3
4 /**
5  * Page Editor
6  * @extends {Component}
7  */
8 class PageEditor {
9     setup() {
10         // Options
11         this.draftsEnabled = this.$opts.draftsEnabled === 'true';
12         this.editorType = this.$opts.editorType;
13         this.pageId = Number(this.$opts.pageId);
14         this.isNewDraft = this.$opts.pageNewDraft === 'true';
15         this.hasDefaultTitle = this.$opts.hasDefaultTitle || false;
16
17         // Elements
18         this.container = this.$el;
19         this.titleElem = this.$refs.titleContainer.querySelector('input');
20         this.saveDraftButton = this.$refs.saveDraft;
21         this.discardDraftButton = this.$refs.discardDraft;
22         this.discardDraftWrap = this.$refs.discardDraftWrap;
23         this.draftDisplay = this.$refs.draftDisplay;
24         this.draftDisplayIcon = this.$refs.draftDisplayIcon;
25         this.changelogInput = this.$refs.changelogInput;
26         this.changelogDisplay = this.$refs.changelogDisplay;
27
28         // Translations
29         this.draftText = this.$opts.draftText;
30         this.autosaveFailText = this.$opts.autosaveFailText;
31         this.editingPageText = this.$opts.editingPageText;
32         this.draftDiscardedText = this.$opts.draftDiscardedText;
33         this.setChangelogText = this.$opts.setChangelogText;
34
35         // State data
36         this.editorHTML = '';
37         this.editorMarkdown = '';
38         this.autoSave = {
39             interval: null,
40             frequency: 30000,
41             last: 0,
42         };
43         this.shownWarningsCache = new Set();
44
45         if (this.pageId !== 0 && this.draftsEnabled) {
46             window.setTimeout(() => {
47                 this.startAutoSave();
48             }, 1000);
49         }
50         this.draftDisplay.innerHTML = this.draftText;
51
52         this.setupListeners();
53         this.setInitialFocus();
54     }
55
56     setupListeners() {
57         // Listen to save events from editor
58         window.$events.listen('editor-save-draft', this.saveDraft.bind(this));
59         window.$events.listen('editor-save-page', this.savePage.bind(this));
60
61         // Listen to content changes from the editor
62         window.$events.listen('editor-html-change', html => {
63             this.editorHTML = html;
64         });
65         window.$events.listen('editor-markdown-change', markdown => {
66             this.editorMarkdown = markdown;
67         });
68
69         // Changelog controls
70         this.changelogInput.addEventListener('change', this.updateChangelogDisplay.bind(this));
71
72         // Draft Controls
73         onSelect(this.saveDraftButton, this.saveDraft.bind(this));
74         onSelect(this.discardDraftButton, this.discardDraft.bind(this));
75     }
76
77     setInitialFocus() {
78         if (this.hasDefaultTitle) {
79             return this.titleElem.select();
80         }
81
82         window.setTimeout(() => {
83             window.$events.emit('editor::focus', '');
84         }, 500);
85     }
86
87     startAutoSave() {
88         let lastContent = this.titleElem.value.trim() + '::' + this.editorHTML;
89         this.autoSaveInterval = window.setInterval(() => {
90             // Stop if manually saved recently to prevent bombarding the server
91             let savedRecently = (Date.now() - this.autoSave.last < (this.autoSave.frequency)/2);
92             if (savedRecently) return;
93             const newContent = this.titleElem.value.trim() + '::' + this.editorHTML;
94             if (newContent !== lastContent) {
95                 lastContent = newContent;
96                 this.saveDraft();
97             }
98
99         }, this.autoSave.frequency);
100     }
101
102     savePage() {
103         this.container.closest('form').submit();
104     }
105
106     async saveDraft() {
107         const data = {
108             name: this.titleElem.value.trim(),
109             html: this.editorHTML,
110         };
111
112         if (this.editorType === 'markdown') {
113             data.markdown = this.editorMarkdown;
114         }
115
116         try {
117             const resp = await window.$http.put(`/ajax/page/${this.pageId}/save-draft`, data);
118             if (!this.isNewDraft) {
119                 this.toggleDiscardDraftVisibility(true);
120             }
121             this.draftNotifyChange(`${resp.data.message} ${Dates.utcTimeStampToLocalTime(resp.data.timestamp)}`);
122             this.autoSave.last = Date.now();
123             if (resp.data.warning && !this.shownWarningsCache.has(resp.data.warning)) {
124                 window.$events.emit('warning', resp.data.warning);
125                 this.shownWarningsCache.add(resp.data.warning);
126             }
127         } catch (err) {
128             // Save the editor content in LocalStorage as a last resort, just in case.
129             try {
130                 const saveKey = `draft-save-fail-${(new Date()).toISOString()}`;
131                 window.localStorage.setItem(saveKey, JSON.stringify(data));
132             } catch (err) {}
133
134             window.$events.emit('error', this.autosaveFailText);
135         }
136
137     }
138
139     draftNotifyChange(text) {
140         this.draftDisplay.innerText = text;
141         this.draftDisplayIcon.classList.add('visible');
142         window.setTimeout(() => {
143             this.draftDisplayIcon.classList.remove('visible');
144         }, 2000);
145     }
146
147     async discardDraft() {
148         let response;
149         try {
150             response = await window.$http.get(`/ajax/page/${this.pageId}`);
151         } catch (e) {
152             return console.error(e);
153         }
154
155         if (this.autoSave.interval) {
156             window.clearInterval(this.autoSave.interval);
157         }
158
159         this.draftDisplay.innerText = this.editingPageText;
160         this.toggleDiscardDraftVisibility(false);
161         window.$events.emit('editor::replace', {
162             html: response.data.html,
163             markdown: response.data.markdown,
164         });
165
166         this.titleElem.value = response.data.name;
167         window.setTimeout(() => {
168             this.startAutoSave();
169         }, 1000);
170         window.$events.emit('success', this.draftDiscardedText);
171
172     }
173
174     updateChangelogDisplay() {
175         let summary = this.changelogInput.value.trim();
176         if (summary.length === 0) {
177             summary = this.setChangelogText;
178         } else if (summary.length > 16) {
179             summary = summary.slice(0, 16) + '...';
180         }
181         this.changelogDisplay.innerText = summary;
182     }
183
184     toggleDiscardDraftVisibility(show) {
185         this.discardDraftWrap.classList.toggle('hidden', !show);
186     }
187
188 }
189
190 export default PageEditor;