1 import {onSelect} from '../services/dom.ts';
2 import {debounce} from '../services/util.ts';
3 import {Component} from './component';
4 import {utcTimeStampToLocalTime} from '../services/dates.ts';
6 export class PageEditor extends Component {
10 this.draftsEnabled = this.$opts.draftsEnabled === 'true';
11 this.editorType = this.$opts.editorType;
12 this.pageId = Number(this.$opts.pageId);
13 this.isNewDraft = this.$opts.pageNewDraft === 'true';
14 this.hasDefaultTitle = this.$opts.hasDefaultTitle || false;
17 this.container = this.$el;
18 this.titleElem = this.$refs.titleContainer.querySelector('input');
19 this.saveDraftButton = this.$refs.saveDraft;
20 this.discardDraftButton = this.$refs.discardDraft;
21 this.discardDraftWrap = this.$refs.discardDraftWrap;
22 this.deleteDraftButton = this.$refs.deleteDraft;
23 this.deleteDraftWrap = this.$refs.deleteDraftWrap;
24 this.draftDisplay = this.$refs.draftDisplay;
25 this.draftDisplayIcon = this.$refs.draftDisplayIcon;
26 this.changelogInput = this.$refs.changelogInput;
27 this.changelogDisplay = this.$refs.changelogDisplay;
28 this.changeEditorButtons = this.$manyRefs.changeEditor || [];
29 this.switchDialogContainer = this.$refs.switchDialog;
30 this.deleteDraftDialogContainer = this.$refs.deleteDraftDialog;
33 this.draftText = this.$opts.draftText;
34 this.autosaveFailText = this.$opts.autosaveFailText;
35 this.editingPageText = this.$opts.editingPageText;
36 this.draftDiscardedText = this.$opts.draftDiscardedText;
37 this.draftDeleteText = this.$opts.draftDeleteText;
38 this.draftDeleteFailText = this.$opts.draftDeleteFailText;
39 this.setChangelogText = this.$opts.setChangelogText;
48 this.shownWarningsCache = new Set();
50 if (this.pageId !== 0 && this.draftsEnabled) {
51 window.setTimeout(() => {
55 this.draftDisplay.innerHTML = this.draftText;
57 this.setupListeners();
58 this.setInitialFocus();
62 // Listen to save events from editor
63 window.$events.listen('editor-save-draft', this.saveDraft.bind(this));
64 window.$events.listen('editor-save-page', this.savePage.bind(this));
66 // Listen to content changes from the editor
67 const onContentChange = () => {
68 this.autoSave.pendingChange = true;
70 window.$events.listen('editor-html-change', onContentChange);
71 window.$events.listen('editor-markdown-change', onContentChange);
73 // Listen to changes on the title input
74 this.titleElem.addEventListener('input', onContentChange);
77 const updateChangelogDebounced = debounce(this.updateChangelogDisplay.bind(this), 300, false);
78 this.changelogInput.addEventListener('input', updateChangelogDebounced);
81 onSelect(this.saveDraftButton, this.saveDraft.bind(this));
82 onSelect(this.discardDraftButton, this.discardDraft.bind(this));
83 onSelect(this.deleteDraftButton, this.deleteDraft.bind(this));
85 // Change editor controls
86 onSelect(this.changeEditorButtons, this.changeEditor.bind(this));
90 if (this.hasDefaultTitle) {
91 this.titleElem.select();
95 window.setTimeout(() => {
96 window.$events.emit('editor::focus', '');
101 this.autoSave.interval = window.setInterval(this.runAutoSave.bind(this), this.autoSave.frequency);
105 // Stop if manually saved recently to prevent bombarding the server
106 const savedRecently = (Date.now() - this.autoSave.last < (this.autoSave.frequency) / 2);
107 if (savedRecently || !this.autoSave.pendingChange) {
115 this.container.closest('form').requestSubmit();
119 const data = {name: this.titleElem.value.trim()};
121 const editorContent = await this.getEditorComponent().getContent();
122 Object.assign(data, editorContent);
126 const resp = await window.$http.put(`/ajax/page/${this.pageId}/save-draft`, data);
127 if (!this.isNewDraft) {
128 this.discardDraftWrap.toggleAttribute('hidden', false);
129 this.deleteDraftWrap.toggleAttribute('hidden', false);
132 this.draftNotifyChange(`${resp.data.message} ${utcTimeStampToLocalTime(resp.data.timestamp)}`);
133 this.autoSave.last = Date.now();
134 if (resp.data.warning && !this.shownWarningsCache.has(resp.data.warning)) {
135 window.$events.emit('warning', resp.data.warning);
136 this.shownWarningsCache.add(resp.data.warning);
140 this.autoSave.pendingChange = false;
142 // Save the editor content in LocalStorage as a last resort, just in case.
144 const saveKey = `draft-save-fail-${(new Date()).toISOString()}`;
145 window.localStorage.setItem(saveKey, JSON.stringify(data));
147 console.error(lsErr);
150 window.$events.emit('error', this.autosaveFailText);
156 draftNotifyChange(text) {
157 this.draftDisplay.innerText = text;
158 this.draftDisplayIcon.classList.add('visible');
159 window.setTimeout(() => {
160 this.draftDisplayIcon.classList.remove('visible');
164 async discardDraft(notify = true) {
167 response = await window.$http.get(`/ajax/page/${this.pageId}`);
173 if (this.autoSave.interval) {
174 window.clearInterval(this.autoSave.interval);
177 this.draftDisplay.innerText = this.editingPageText;
178 this.discardDraftWrap.toggleAttribute('hidden', true);
179 window.$events.emit('editor::replace', {
180 html: response.data.html,
181 markdown: response.data.markdown,
184 this.titleElem.value = response.data.name;
185 window.setTimeout(() => {
186 this.startAutoSave();
190 window.$events.success(this.draftDiscardedText);
194 async deleteDraft() {
195 /** @var {ConfirmDialog} * */
196 const dialog = window.$components.firstOnElement(this.deleteDraftDialogContainer, 'confirm-dialog');
197 const confirmed = await dialog.show();
203 const discard = this.discardDraft(false);
204 const draftDelete = window.$http.delete(`/page-revisions/user-drafts/${this.pageId}`);
205 await Promise.all([discard, draftDelete]);
206 window.$events.success(this.draftDeleteText);
207 this.deleteDraftWrap.toggleAttribute('hidden', true);
210 window.$events.error(this.draftDeleteFailText);
214 updateChangelogDisplay() {
215 let summary = this.changelogInput.value.trim();
216 if (summary.length === 0) {
217 summary = this.setChangelogText;
218 } else if (summary.length > 16) {
219 summary = `${summary.slice(0, 16)}...`;
221 this.changelogDisplay.innerText = summary;
224 async changeEditor(event) {
225 event.preventDefault();
227 const link = event.target.closest('a').href;
228 /** @var {ConfirmDialog} * */
229 const dialog = window.$components.firstOnElement(this.switchDialogContainer, 'confirm-dialog');
230 const [saved, confirmed] = await Promise.all([this.saveDraft(), dialog.show()]);
232 if (saved && confirmed) {
233 window.location = link;
238 * @return {MarkdownEditor|WysiwygEditor|WysiwygEditorTinymce}
240 getEditorComponent() {
241 return window.$components.first('markdown-editor')
242 || window.$components.first('wysiwyg-editor')
243 || window.$components.first('wysiwyg-editor-tinymce');