]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/page-display.js
Fixes undefined error when clicking on page navigation links.
[bookstack] / resources / assets / js / components / page-display.js
1 import Clipboard from "clipboard";
2 import Code from "../services/code";
3
4 class PageDisplay {
5
6     constructor(elem) {
7         this.elem = elem;
8         this.pageId = elem.getAttribute('page-display');
9
10         Code.highlight();
11         this.setupPointer();
12         this.setupStickySidebar();
13         this.setupNavHighlighting();
14
15         // Check the hash on load
16         if (window.location.hash) {
17             let text = window.location.hash.replace(/\%20/g, ' ').substr(1);
18             this.goToText(text);
19         }
20
21         // Sidebar page nav click event
22         $('.sidebar-page-nav').on('click', 'a', event => {
23             this.goToText(event.target.getAttribute('href').substr(1));
24         });
25     }
26
27     goToText(text) {
28         let idElem = document.getElementById(text);
29         $('.page-content [data-highlighted]').attr('data-highlighted', '').css('background-color', '');
30         if (idElem !== null) {
31             window.scrollAndHighlight(idElem);
32         } else {
33             $('.page-content').find(':contains("' + text + '")').smoothScrollTo();
34         }
35     }
36
37     setupPointer() {
38         if (document.getElementById('pointer') === null) return;
39         // Set up pointer
40         let $pointer = $('#pointer').detach();
41         let pointerShowing = false;
42         let $pointerInner = $pointer.children('div.pointer').first();
43         let isSelection = false;
44         let pointerModeLink = true;
45         let pointerSectionId = '';
46
47         // Select all contents on input click
48         $pointer.on('click', 'input', event => {
49             $(this).select();
50             event.stopPropagation();
51         });
52
53         $pointer.on('click focus', event => {
54             event.stopPropagation();
55         });
56
57         // Pointer mode toggle
58         $pointer.on('click', 'span.icon', event => {
59             event.stopPropagation();
60             let $icon = $(event.currentTarget);
61             pointerModeLink = !pointerModeLink;
62             $icon.find('[data-icon="include"]').toggle(!pointerModeLink);
63             $icon.find('[data-icon="link"]').toggle(pointerModeLink);
64             updatePointerContent();
65         });
66
67         // Set up clipboard
68         let clipboard = new Clipboard($pointer[0].querySelector('button'));
69
70         // Hide pointer when clicking away
71         $(document.body).find('*').on('click focus', event => {
72             if (!pointerShowing || isSelection) return;
73             $pointer.detach();
74             pointerShowing = false;
75         });
76
77         let updatePointerContent = () => {
78             let inputText = pointerModeLink ? window.baseUrl(`/link/${this.pageId}#${pointerSectionId}`) : `{{@${this.pageId}#${pointerSectionId}}}`;
79             if (pointerModeLink && inputText.indexOf('http') !== 0) inputText = window.location.protocol + "//" + window.location.host + inputText;
80
81             $pointer.find('input').val(inputText);
82         };
83
84         // Show pointer when selecting a single block of tagged content
85         $('.page-content [id^="bkmrk"]').on('mouseup keyup', function (e) {
86             e.stopPropagation();
87             let selection = window.getSelection();
88             if (selection.toString().length === 0) return;
89
90             // Show pointer and set link
91             let $elem = $(this);
92             pointerSectionId = $elem.attr('id');
93             updatePointerContent();
94
95             $elem.before($pointer);
96             $pointer.show();
97             pointerShowing = true;
98
99             // Set pointer to sit near mouse-up position
100             let pointerLeftOffset = (e.pageX - $elem.offset().left - ($pointerInner.width() / 2));
101             if (pointerLeftOffset < 0) pointerLeftOffset = 0;
102             let pointerLeftOffsetPercent = (pointerLeftOffset / $elem.width()) * 100;
103             $pointerInner.css('left', pointerLeftOffsetPercent + '%');
104
105             isSelection = true;
106             setTimeout(() => {
107                 isSelection = false;
108             }, 100);
109         });
110     }
111
112     setupStickySidebar() {
113         // Make the sidebar stick in view on scroll
114         let $window = $(window);
115         let $sidebar = $("#sidebar .scroll-body");
116         let $bookTreeParent = $sidebar.parent();
117
118         // Check the page is scrollable and the content is taller than the tree
119         let pageScrollable = ($(document).height() > $window.height()) && ($sidebar.height() < $('.page-content').height());
120
121         // Get current tree's width and header height
122         let headerHeight = $("#header").height() + $(".toolbar").height();
123         let isFixed = $window.scrollTop() > headerHeight;
124
125         // Fix the tree as a sidebar
126         function stickTree() {
127             $sidebar.width($bookTreeParent.width() + 15);
128             $sidebar.addClass("fixed");
129             isFixed = true;
130         }
131
132         // Un-fix the tree back into position
133         function unstickTree() {
134             $sidebar.css('width', 'auto');
135             $sidebar.removeClass("fixed");
136             isFixed = false;
137         }
138
139         // Checks if the tree stickiness state should change
140         function checkTreeStickiness(skipCheck) {
141             let shouldBeFixed = $window.scrollTop() > headerHeight;
142             if (shouldBeFixed && (!isFixed || skipCheck)) {
143                 stickTree();
144             } else if (!shouldBeFixed && (isFixed || skipCheck)) {
145                 unstickTree();
146             }
147         }
148         // The event ran when the window scrolls
149         function windowScrollEvent() {
150             checkTreeStickiness(false);
151         }
152
153         // If the page is scrollable and the window is wide enough listen to scroll events
154         // and evaluate tree stickiness.
155         if (pageScrollable && $window.width() > 1000) {
156             $window.on('scroll', windowScrollEvent);
157             checkTreeStickiness(true);
158         }
159
160         // Handle window resizing and switch between desktop/mobile views
161         $window.on('resize', event => {
162             if (pageScrollable && $window.width() > 1000) {
163                 $window.on('scroll', windowScrollEvent);
164                 checkTreeStickiness(true);
165             } else {
166                 $window.off('scroll', windowScrollEvent);
167                 unstickTree();
168             }
169         });
170     }
171
172     setupNavHighlighting() {
173         // Check if support is present for IntersectionObserver
174         if (!'IntersectionObserver' in window ||
175             !'IntersectionObserverEntry' in window ||
176             !'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
177             return;
178         }
179
180         let pageNav = document.querySelector('.sidebar-page-nav');
181
182         // fetch all the headings.
183         let headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
184         // if headings are present, add observers.
185         if (headings.length > 0 && pageNav !== null) {
186             addNavObserver(headings);
187         }
188
189         function addNavObserver(headings) {
190             // Setup the intersection observer.
191             let intersectOpts = {
192                 rootMargin: '0px 0px 0px 0px',
193                 threshold: 1.0
194             };
195             let pageNavObserver = new IntersectionObserver(headingVisibilityChange, intersectOpts);
196
197             // observe each heading
198             for (let i = 0; i !== headings.length; ++i) {
199                 pageNavObserver.observe(headings[i]);
200             }
201         }
202
203         function headingVisibilityChange(entries, observer) {
204             for (let entry of entries) {
205                 let isVisible = (entry.intersectionRatio === 1);
206                 toggleAnchorHighlighting(entry.target.id, isVisible);
207             }
208         }
209
210         function toggleAnchorHighlighting(elementId, shouldHighlight) {
211             let anchorsToHighlight = pageNav.querySelectorAll('a[href="#' + elementId + '"]');
212             for (let i = 0; i < anchorsToHighlight.length; i++) {
213                 // Change below to use classList.toggle when IE support is dropped.
214                 if (shouldHighlight) {
215                     anchorsToHighlight[i].classList.add('current-heading');
216                 } else {
217                     anchorsToHighlight[i].classList.remove('current-heading');
218                 }
219             }
220         }
221     }
222
223 }
224
225 module.exports = PageDisplay;