]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-comment-reference.ts
5a71f0c513b8c176182aa64e30b16c278acaa62b
[bookstack] / resources / js / components / page-comment-reference.ts
1 import {Component} from "./component";
2 import {findTargetNodeAndOffset, hashElement} from "../services/dom";
3 import {el} from "../wysiwyg/utils/dom";
4 import commentIcon from "@icons/comment.svg";
5 import closeIcon from "@icons/close.svg";
6 import {debounce, scrollAndHighlightElement} from "../services/util";
7
8 /**
9  * Track the close function for the current open marker so it can be closed
10  * when another is opened so we only show one marker comment thread at one time.
11  */
12 let openMarkerClose: Function|null = null;
13
14 export class PageCommentReference extends Component {
15     protected link: HTMLLinkElement;
16     protected reference: string;
17     protected markerWrap: HTMLElement|null = null;
18
19     protected viewCommentText: string;
20     protected jumpToThreadText: string;
21     protected closeText: string;
22
23     setup() {
24         this.link = this.$el as HTMLLinkElement;
25         this.reference = this.$opts.reference;
26         this.viewCommentText = this.$opts.viewCommentText;
27         this.jumpToThreadText = this.$opts.jumpToThreadText;
28         this.closeText = this.$opts.closeText;
29
30         // Show within page display area if seen
31         this.showForDisplay();
32
33         // Handle editor view to show on comments toolbox view
34         window.addEventListener('editor-toolbox-change', (event) => {
35              const tabName: string = (event as {detail: {tab: string, open: boolean}}).detail.tab;
36              const isOpen = (event as {detail: {tab: string, open: boolean}}).detail.open;
37              if (tabName === 'comments' && isOpen) {
38                  this.showForEditor();
39              } else {
40                  this.hideMarker();
41              }
42         });
43
44         // Handle comments tab changes to hide/show markers & indicators
45         window.addEventListener('tabs-change', event => {
46             const sectionId = (event as {detail: {showing: string}}).detail.showing;
47             if (!sectionId.startsWith('comment-tab-panel')) {
48                 return;
49             }
50
51             const panel = document.getElementById(sectionId);
52             if (panel?.contains(this.link)) {
53                 this.showForDisplay();
54             } else {
55                 this.hideMarker();
56             }
57         });
58     }
59
60     public showForDisplay() {
61         const pageContentArea = document.querySelector('.page-content');
62         if (pageContentArea instanceof HTMLElement && this.link.checkVisibility()) {
63             this.updateMarker(pageContentArea);
64         }
65     }
66
67     protected showForEditor() {
68         const contentWrap = document.querySelector('.editor-content-wrap');
69         if (contentWrap instanceof HTMLElement) {
70             this.updateMarker(contentWrap);
71         }
72
73         const onChange = () => {
74             this.hideMarker();
75             setTimeout(() => {
76                 window.$events.remove('editor-html-change', onChange);
77             }, 1);
78         };
79
80         window.$events.listen('editor-html-change', onChange);
81     }
82
83     protected updateMarker(contentContainer: HTMLElement) {
84         // Reset link and existing marker
85         this.link.classList.remove('outdated', 'missing');
86         if (this.markerWrap) {
87             this.markerWrap.remove();
88         }
89
90         const [refId, refHash, refRange] = this.reference.split(':');
91         const refEl = document.getElementById(refId);
92         if (!refEl) {
93             this.link.classList.add('outdated', 'missing');
94             return;
95         }
96
97         const actualHash = hashElement(refEl);
98         if (actualHash !== refHash) {
99             this.link.classList.add('outdated');
100         }
101
102         const marker = el('button', {
103             type: 'button',
104             class: 'content-comment-marker',
105             title: this.viewCommentText,
106         });
107         marker.innerHTML = <string>commentIcon;
108         marker.addEventListener('click', event => {
109             this.showCommentAtMarker(marker);
110         });
111
112         this.markerWrap = el('div', {
113             class: 'content-comment-highlight',
114         }, [marker]);
115
116         contentContainer.append(this.markerWrap);
117         this.positionMarker(refEl, refRange);
118
119         this.link.href = `#${refEl.id}`;
120         this.link.addEventListener('click', (event: MouseEvent) => {
121             event.preventDefault();
122             scrollAndHighlightElement(refEl);
123         });
124
125         const debouncedReposition = debounce(() => {
126             this.positionMarker(refEl, refRange);
127         }, 50, false).bind(this);
128         window.addEventListener('resize', debouncedReposition);
129     }
130
131     protected positionMarker(targetEl: HTMLElement, range: string) {
132         if (!this.markerWrap) {
133             return;
134         }
135
136         const markerParent = this.markerWrap.parentElement as HTMLElement;
137         const parentBounds = markerParent.getBoundingClientRect();
138         let targetBounds = targetEl.getBoundingClientRect();
139         const [rangeStart, rangeEnd] = range.split('-');
140         if (rangeStart && rangeEnd) {
141             const range = new Range();
142             const relStart = findTargetNodeAndOffset(targetEl, Number(rangeStart));
143             const relEnd = findTargetNodeAndOffset(targetEl, Number(rangeEnd));
144             if (relStart && relEnd) {
145                 range.setStart(relStart.node, relStart.offset);
146                 range.setEnd(relEnd.node, relEnd.offset);
147                 targetBounds = range.getBoundingClientRect();
148             }
149         }
150
151         const relLeft = targetBounds.left - parentBounds.left;
152         const relTop = (targetBounds.top - parentBounds.top) + markerParent.scrollTop;
153
154         this.markerWrap.style.left = `${relLeft}px`;
155         this.markerWrap.style.top = `${relTop}px`;
156         this.markerWrap.style.width = `${targetBounds.width}px`;
157         this.markerWrap.style.height = `${targetBounds.height}px`;
158     }
159
160     public hideMarker() {
161         // Hide marker and close existing marker windows
162         if (openMarkerClose) {
163             openMarkerClose();
164         }
165         this.markerWrap?.remove();
166         this.markerWrap = null;
167     }
168
169     protected showCommentAtMarker(marker: HTMLElement): void {
170         // Hide marker and close existing marker windows
171         if (openMarkerClose) {
172             openMarkerClose();
173         }
174         marker.hidden = true;
175
176         // Locate relevant comment
177         const commentBox = this.link.closest('.comment-box') as HTMLElement;
178
179         // Build comment window
180         const readClone = (commentBox.closest('.comment-branch') as HTMLElement).cloneNode(true) as HTMLElement;
181         const toRemove = readClone.querySelectorAll('.actions, form');
182         for (const el of toRemove) {
183             el.remove();
184         }
185
186         const close = el('button', {type: 'button', title: this.closeText});
187         close.innerHTML = (closeIcon as string);
188         const jump = el('button', {type: 'button', 'data-action': 'jump'}, [this.jumpToThreadText]);
189
190         const commentWindow = el('div', {
191             class: 'content-comment-window'
192         }, [
193             el('div', {
194                 class: 'content-comment-window-actions',
195             }, [jump, close]),
196             el('div', {
197                 class: 'content-comment-window-content comment-container-compact comment-container-super-compact',
198             }, [readClone]),
199         ]);
200
201         marker.parentElement?.append(commentWindow);
202
203         // Handle interaction within window
204         const closeAction = () => {
205             commentWindow.remove();
206             marker.hidden = false;
207             window.removeEventListener('click', windowCloseAction);
208             openMarkerClose = null;
209         };
210
211         const windowCloseAction = (event: MouseEvent) => {
212             if (!(marker.parentElement as HTMLElement).contains(event.target as HTMLElement)) {
213                 closeAction();
214             }
215         };
216         window.addEventListener('click', windowCloseAction);
217
218         openMarkerClose = closeAction;
219         close.addEventListener('click', closeAction.bind(this));
220         jump.addEventListener('click', () => {
221             closeAction();
222             commentBox.scrollIntoView({behavior: 'smooth'});
223             const highlightTarget = commentBox.querySelector('.header') as HTMLElement;
224             highlightTarget.classList.add('anim-highlight');
225             highlightTarget.addEventListener('animationend', () => highlightTarget.classList.remove('anim-highlight'))
226         });
227
228         // Position window within bounds
229         const commentWindowBounds = commentWindow.getBoundingClientRect();
230         const contentBounds = document.querySelector('.page-content')?.getBoundingClientRect();
231         if (contentBounds && commentWindowBounds.right > contentBounds.right) {
232             const diff = commentWindowBounds.right - contentBounds.right;
233             commentWindow.style.left = `-${diff}px`;
234         }
235     }
236 }