]> BookStack Code Mirror - bookstack/blob - resources/js/components/page-display.js
2be1c1c48b8cc93f5ac147b64023cf910eabc3fa
[bookstack] / resources / js / components / page-display.js
1 import Clipboard from "clipboard/dist/clipboard.min";
2 import Code from "../services/code";
3 import * as DOM from "../services/dom";
4 import {scrollAndHighlightElement} from "../services/util";
5
6 class PageDisplay {
7
8     constructor(elem) {
9         this.elem = elem;
10         this.pageId = elem.getAttribute('page-display');
11
12         Code.highlight();
13         this.setupPointer();
14         this.setupNavHighlighting();
15
16         // Check the hash on load
17         if (window.location.hash) {
18             let text = window.location.hash.replace(/\%20/g, ' ').substr(1);
19             this.goToText(text);
20         }
21
22         // Sidebar page nav click event
23         const sidebarPageNav = document.querySelector('.sidebar-page-nav');
24         if (sidebarPageNav) {
25             DOM.onChildEvent(sidebarPageNav, 'a', 'click', (event, child) => {
26                 event.preventDefault();
27                 window.components['tri-layout'][0].showContent();
28                 const contentId = child.getAttribute('href').substr(1);
29                 this.goToText(contentId);
30                 window.history.pushState(null, null, '#' + contentId);
31             });
32         }
33     }
34
35     goToText(text) {
36         const idElem = document.getElementById(text);
37
38         DOM.forEach('.page-content [data-highlighted]', elem => {
39             elem.removeAttribute('data-highlighted');
40             elem.style.backgroundColor = null;
41         });
42
43         if (idElem !== null) {
44             scrollAndHighlightElement(idElem);
45         } else {
46             const textElem = DOM.findText('.page-content > div > *', text);
47             if (textElem) {
48                 scrollAndHighlightElement(textElem);
49             }
50         }
51     }
52
53     setupPointer() {
54         let pointer = document.getElementById('pointer');
55         if (!pointer) {
56             return;
57         }
58
59         // Set up pointer
60         pointer = pointer.parentNode.removeChild(pointer);
61         const pointerInner = pointer.querySelector('div.pointer');
62
63         // Instance variables
64         let pointerShowing = false;
65         let isSelection = false;
66         let pointerModeLink = true;
67         let pointerSectionId = '';
68
69         // Select all contents on input click
70         DOM.onChildEvent(pointer, 'input', 'click', (event, input) => {
71             input.select();
72             event.stopPropagation();
73         });
74
75         // Prevent closing pointer when clicked or focused
76         DOM.onEvents(pointer, ['click', 'focus'], event => {
77             event.stopPropagation();
78         });
79
80         // Pointer mode toggle
81         DOM.onChildEvent(pointer, 'span.icon', 'click', (event, icon) => {
82             event.stopPropagation();
83             pointerModeLink = !pointerModeLink;
84             icon.querySelector('[data-icon="include"]').style.display = (!pointerModeLink) ? 'inline' : 'none';
85             icon.querySelector('[data-icon="link"]').style.display = (pointerModeLink) ? 'inline' : 'none';
86             updatePointerContent();
87         });
88
89         // Set up clipboard
90         new Clipboard(pointer.querySelector('button'));
91
92         // Hide pointer when clicking away
93         DOM.onEvents(document.body, ['click', 'focus'], event => {
94             if (!pointerShowing || isSelection) return;
95             pointer = pointer.parentElement.removeChild(pointer);
96             pointerShowing = false;
97         });
98
99         let updatePointerContent = (element) => {
100             let inputText = pointerModeLink ? window.baseUrl(`/link/${this.pageId}#${pointerSectionId}`) : `{{@${this.pageId}#${pointerSectionId}}}`;
101             if (pointerModeLink && !inputText.startsWith('http')) {
102                 inputText = window.location.protocol + "//" + window.location.host + inputText;
103             }
104
105             pointer.querySelector('input').value = inputText;
106
107             // Update anchor if present
108             const editAnchor = pointer.querySelector('#pointer-edit');
109             if (editAnchor && element) {
110                 const editHref = editAnchor.dataset.editHref;
111                 const elementId = element.id;
112
113                 // get the first 50 characters.
114                 const queryContent = element.textContent && element.textContent.substring(0, 50);
115                 editAnchor.href = `${editHref}?content-id=${elementId}&content-text=${encodeURIComponent(queryContent)}`;
116             }
117         };
118
119         // Show pointer when selecting a single block of tagged content
120         DOM.forEach('.page-content [id^="bkmrk"]', bookMarkElem => {
121             DOM.onEvents(bookMarkElem, ['mouseup', 'keyup'], event => {
122                 event.stopPropagation();
123                 let selection = window.getSelection();
124                 if (selection.toString().length === 0) return;
125
126                 // Show pointer and set link
127                 pointerSectionId = bookMarkElem.id;
128                 updatePointerContent(bookMarkElem);
129
130                 bookMarkElem.parentNode.insertBefore(pointer, bookMarkElem);
131                 pointer.style.display = 'block';
132                 pointerShowing = true;
133                 isSelection = true;
134
135                 // Set pointer to sit near mouse-up position
136                 requestAnimationFrame(() => {
137                     const bookMarkBounds = bookMarkElem.getBoundingClientRect();
138                     let pointerLeftOffset = (event.pageX - bookMarkBounds.left - 164);
139                     if (pointerLeftOffset < 0) {
140                         pointerLeftOffset = 0
141                     }
142                     const pointerLeftOffsetPercent = (pointerLeftOffset / bookMarkBounds.width) * 100;
143
144                     pointerInner.style.left = pointerLeftOffsetPercent + '%';
145
146                     setTimeout(() => {
147                         isSelection = false;
148                     }, 100);
149                 });
150
151             });
152         });
153     }
154
155     setupNavHighlighting() {
156         // Check if support is present for IntersectionObserver
157         if (!('IntersectionObserver' in window) ||
158             !('IntersectionObserverEntry' in window) ||
159             !('intersectionRatio' in window.IntersectionObserverEntry.prototype)) {
160             return;
161         }
162
163         let pageNav = document.querySelector('.sidebar-page-nav');
164
165         // fetch all the headings.
166         let headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
167         // if headings are present, add observers.
168         if (headings.length > 0 && pageNav !== null) {
169             addNavObserver(headings);
170         }
171
172         function addNavObserver(headings) {
173             // Setup the intersection observer.
174             let intersectOpts = {
175                 rootMargin: '0px 0px 0px 0px',
176                 threshold: 1.0
177             };
178             let pageNavObserver = new IntersectionObserver(headingVisibilityChange, intersectOpts);
179
180             // observe each heading
181             for (let heading of headings) {
182                 pageNavObserver.observe(heading);
183             }
184         }
185
186         function headingVisibilityChange(entries, observer) {
187             for (let entry of entries) {
188                 let isVisible = (entry.intersectionRatio === 1);
189                 toggleAnchorHighlighting(entry.target.id, isVisible);
190             }
191         }
192
193         function toggleAnchorHighlighting(elementId, shouldHighlight) {
194             DOM.forEach('a[href="#' + elementId + '"]', anchor => {
195                 anchor.closest('li').classList.toggle('current-heading', shouldHighlight);
196             });
197         }
198     }
199 }
200
201 export default PageDisplay;