]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-comment.ts
9192c7c56afc846605f5a4adbeb3e3f59ade4ce3
[bookstack] / resources / js / components / page-comment.ts
1 import {Component} from './component';
2 import {findTargetNodeAndOffset, getLoading, hashElement, htmlToDom} from '../services/dom.ts';
3 import {buildForInput} from '../wysiwyg-tinymce/config';
4 import {el} from "../wysiwyg/utils/dom";
5
6 import commentIcon from "@icons/comment.svg"
7 import closeIcon from "@icons/close.svg"
8
9 /**
10  * Track the close function for the current open marker so it can be closed
11  * when another is opened so we only show one marker comment thread at one time.
12  */
13 let openMarkerClose: Function|null = null;
14
15 export class PageComment extends Component {
16
17     protected commentId: string;
18     protected commentLocalId: string;
19     protected commentContentRef: string;
20     protected deletedText: string;
21     protected updatedText: string;
22     protected viewCommentText: string;
23     protected jumpToThreadText: string;
24     protected closeText: string;
25
26     protected wysiwygEditor: any = null;
27     protected wysiwygLanguage: string;
28     protected wysiwygTextDirection: string;
29
30     protected container: HTMLElement;
31     protected contentContainer: HTMLElement;
32     protected form: HTMLFormElement;
33     protected formCancel: HTMLElement;
34     protected editButton: HTMLElement;
35     protected deleteButton: HTMLElement;
36     protected replyButton: HTMLElement;
37     protected input: HTMLInputElement;
38
39     setup() {
40         // Options
41         this.commentId = this.$opts.commentId;
42         this.commentLocalId = this.$opts.commentLocalId;
43         this.commentContentRef = this.$opts.commentContentRef;
44         this.deletedText = this.$opts.deletedText;
45         this.updatedText = this.$opts.updatedText;
46         this.viewCommentText = this.$opts.viewCommentText;
47         this.jumpToThreadText = this.$opts.jumpToThreadText;
48         this.closeText = this.$opts.closeText;
49
50         // Editor reference and text options
51         this.wysiwygLanguage = this.$opts.wysiwygLanguage;
52         this.wysiwygTextDirection = this.$opts.wysiwygTextDirection;
53
54         // Element references
55         this.container = this.$el;
56         this.contentContainer = this.$refs.contentContainer;
57         this.form = this.$refs.form as HTMLFormElement;
58         this.formCancel = this.$refs.formCancel;
59         this.editButton = this.$refs.editButton;
60         this.deleteButton = this.$refs.deleteButton;
61         this.replyButton = this.$refs.replyButton;
62         this.input = this.$refs.input as HTMLInputElement;
63
64         this.setupListeners();
65         this.positionForReference();
66     }
67
68     protected setupListeners(): void {
69         if (this.replyButton) {
70             this.replyButton.addEventListener('click', () => this.$emit('reply', {
71                 id: this.commentLocalId,
72                 element: this.container,
73             }));
74         }
75
76         if (this.editButton) {
77             this.editButton.addEventListener('click', this.startEdit.bind(this));
78             this.form.addEventListener('submit', this.update.bind(this));
79             this.formCancel.addEventListener('click', () => this.toggleEditMode(false));
80         }
81
82         if (this.deleteButton) {
83             this.deleteButton.addEventListener('click', this.delete.bind(this));
84         }
85     }
86
87     protected toggleEditMode(show: boolean) : void {
88         this.contentContainer.toggleAttribute('hidden', show);
89         this.form.toggleAttribute('hidden', !show);
90     }
91
92     protected startEdit() : void {
93         this.toggleEditMode(true);
94
95         if (this.wysiwygEditor) {
96             this.wysiwygEditor.focus();
97             return;
98         }
99
100         const config = buildForInput({
101             language: this.wysiwygLanguage,
102             containerElement: this.input,
103             darkMode: document.documentElement.classList.contains('dark-mode'),
104             textDirection: this.wysiwygTextDirection,
105             drawioUrl: '',
106             pageId: 0,
107             translations: {},
108             translationMap: (window as Record<string, Object>).editor_translations,
109         });
110
111         (window as {tinymce: {init: (Object) => Promise<any>}}).tinymce.init(config).then(editors => {
112             this.wysiwygEditor = editors[0];
113             setTimeout(() => this.wysiwygEditor.focus(), 50);
114         });
115     }
116
117     protected async update(event: Event): Promise<void> {
118         event.preventDefault();
119         const loading = this.showLoading();
120         this.form.toggleAttribute('hidden', true);
121
122         const reqData = {
123             html: this.wysiwygEditor.getContent(),
124         };
125
126         try {
127             const resp = await window.$http.put(`/comment/${this.commentId}`, reqData);
128             const newComment = htmlToDom(resp.data as string);
129             this.container.replaceWith(newComment);
130             window.$events.success(this.updatedText);
131         } catch (err) {
132             console.error(err);
133             window.$events.showValidationErrors(err);
134             this.form.toggleAttribute('hidden', false);
135             loading.remove();
136         }
137     }
138
139     protected async delete(): Promise<void> {
140         this.showLoading();
141
142         await window.$http.delete(`/comment/${this.commentId}`);
143         this.$emit('delete');
144         this.container.closest('.comment-branch')?.remove();
145         window.$events.success(this.deletedText);
146     }
147
148     protected showLoading(): HTMLElement {
149         const loading = getLoading();
150         loading.classList.add('px-l');
151         this.container.append(loading);
152         return loading;
153     }
154
155     protected positionForReference() {
156         if (!this.commentContentRef) {
157             return;
158         }
159
160         const [refId, refHash, refRange] = this.commentContentRef.split(':');
161         const refEl = document.getElementById(refId);
162         if (!refEl) {
163             // TODO - Show outdated marker for comment
164             return;
165         }
166
167         const actualHash = hashElement(refEl);
168         if (actualHash !== refHash) {
169             // TODO - Show outdated marker for comment
170             return;
171         }
172
173         const refElBounds = refEl.getBoundingClientRect();
174         let bounds = refElBounds;
175         const [rangeStart, rangeEnd] = refRange.split('-');
176         if (rangeStart && rangeEnd) {
177             const range = new Range();
178             const relStart = findTargetNodeAndOffset(refEl, Number(rangeStart));
179             const relEnd = findTargetNodeAndOffset(refEl, Number(rangeEnd));
180             if (relStart && relEnd) {
181                 range.setStart(relStart.node, relStart.offset);
182                 range.setEnd(relEnd.node, relEnd.offset);
183                 bounds = range.getBoundingClientRect();
184             }
185         }
186
187         const relLeft = bounds.left - refElBounds.left;
188         const relTop = bounds.top - refElBounds.top;
189
190         const marker = el('button', {
191             type: 'button',
192             class: 'content-comment-marker',
193             title: this.viewCommentText,
194         });
195         marker.innerHTML = <string>commentIcon;
196         marker.addEventListener('click', event => {
197             this.showCommentAtMarker(marker);
198         });
199
200         const markerWrap = el('div', {
201             class: 'content-comment-highlight',
202             style: `left: ${relLeft}px; top: ${relTop}px; width: ${bounds.width}px; height: ${bounds.height}px;`
203         }, [marker]);
204
205         refEl.style.position = 'relative';
206         refEl.append(markerWrap);
207     }
208
209     protected showCommentAtMarker(marker: HTMLElement): void {
210         // Hide marker and close existing marker windows
211         if (openMarkerClose) {
212             openMarkerClose();
213         }
214         marker.hidden = true;
215
216         // Build comment window
217         const readClone = (this.container.closest('.comment-branch') as HTMLElement).cloneNode(true) as HTMLElement;
218         const toRemove = readClone.querySelectorAll('.actions, form');
219         for (const el of toRemove) {
220             el.remove();
221         }
222
223         const close = el('button', {type: 'button', title: this.closeText});
224         close.innerHTML = (closeIcon as string);
225         const jump = el('button', {type: 'button', 'data-action': 'jump'}, [this.jumpToThreadText]);
226
227         const commentWindow = el('div', {
228             class: 'content-comment-window'
229         }, [
230             el('div', {
231                 class: 'content-comment-window-actions',
232             }, [jump, close]),
233             el('div', {
234                 class: 'content-comment-window-content comment-container-compact comment-container-super-compact',
235             }, [readClone]),
236         ]);
237
238         marker.parentElement?.append(commentWindow);
239
240         // Handle interaction within window
241         const closeAction = () => {
242             commentWindow.remove();
243             marker.hidden = false;
244             window.removeEventListener('click', windowCloseAction);
245             openMarkerClose = null;
246         };
247
248         const windowCloseAction = (event: MouseEvent) => {
249             if (!(marker.parentElement as HTMLElement).contains(event.target as HTMLElement)) {
250                 closeAction();
251             }
252         };
253         window.addEventListener('click', windowCloseAction);
254
255         openMarkerClose = closeAction;
256         close.addEventListener('click', closeAction.bind(this));
257         jump.addEventListener('click', () => {
258             closeAction();
259             this.container.scrollIntoView({behavior: 'smooth'});
260             const highlightTarget = this.container.querySelector('.header') as HTMLElement;
261             highlightTarget.classList.add('anim-highlight');
262             highlightTarget.addEventListener('animationend', () => highlightTarget.classList.remove('anim-highlight'))
263         });
264
265         // Position window within bounds
266         const commentWindowBounds = commentWindow.getBoundingClientRect();
267         const contentBounds = document.querySelector('.page-content')?.getBoundingClientRect();
268         if (contentBounds && commentWindowBounds.right > contentBounds.right) {
269             const diff = commentWindowBounds.right - contentBounds.right;
270             commentWindow.style.left = `-${diff}px`;
271         }
272     }
273 }