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