]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/page-display.js
Merge branch 'Copy-For-View-Only' of git://github.com/mark-james/BookStack into mark...
[bookstack] / resources / assets / js / components / page-display.js
1 import Clipboard from "clipboard/dist/clipboard.min";
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 = ($elem) => {
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             // update anchor if present
84             const $editAnchor = $pointer.find('#pointer-edit');
85             if ($editAnchor.length !== 0 && $elem) {
86                 const editHref = $editAnchor.data('editHref');
87                 const element = $elem[0];
88                 const elementId = element.id;
89
90                 // get the first 50 characters.
91                 let queryContent = element.textContent && element.textContent.substring(0, 50);
92                 $editAnchor[0].href = `${editHref}?content-id=${elementId}&content-text=${encodeURIComponent(queryContent)}`;
93             }
94         };
95
96         // Show pointer when selecting a single block of tagged content
97         $('.page-content [id^="bkmrk"]').on('mouseup keyup', function (e) {
98             e.stopPropagation();
99             let selection = window.getSelection();
100             if (selection.toString().length === 0) return;
101
102             // Show pointer and set link
103             let $elem = $(this);
104             pointerSectionId = $elem.attr('id');
105             updatePointerContent($elem);
106
107             $elem.before($pointer);
108             $pointer.show();
109             pointerShowing = true;
110
111             // Set pointer to sit near mouse-up position
112             let pointerLeftOffset = (e.pageX - $elem.offset().left - ($pointerInner.width() / 2));
113             if (pointerLeftOffset < 0) pointerLeftOffset = 0;
114             let pointerLeftOffsetPercent = (pointerLeftOffset / $elem.width()) * 100;
115             $pointerInner.css('left', pointerLeftOffsetPercent + '%');
116
117             isSelection = true;
118             setTimeout(() => {
119                 isSelection = false;
120             }, 100);
121         });
122     }
123
124     setupStickySidebar() {
125         // Make the sidebar stick in view on scroll
126         const $window = $(window);
127         const $sidebar = $("#sidebar .scroll-body");
128         const $sidebarContainer = $sidebar.parent();
129         const sidebarHeight = $sidebar.height() + 32;
130
131         // Check the page is scrollable and the content is taller than the tree
132         const pageScrollable = ($(document).height() > ($window.height() + 40)) && (sidebarHeight < $('.page-content').height());
133
134         // Get current tree's width and header height
135         const headerHeight = $("#header").height() + $(".toolbar").height();
136         let isFixed = $window.scrollTop() > headerHeight;
137
138         // Fix the tree as a sidebar
139         function stickTree() {
140             $sidebar.width($sidebarContainer.width() + 15);
141             $sidebar.addClass("fixed");
142             isFixed = true;
143         }
144
145         // Un-fix the tree back into position
146         function unstickTree() {
147             $sidebar.css('width', 'auto');
148             $sidebar.removeClass("fixed");
149             isFixed = false;
150         }
151
152         // Checks if the tree stickiness state should change
153         function checkTreeStickiness(skipCheck) {
154             let shouldBeFixed = $window.scrollTop() > headerHeight;
155             if (shouldBeFixed && (!isFixed || skipCheck)) {
156                 stickTree();
157             } else if (!shouldBeFixed && (isFixed || skipCheck)) {
158                 unstickTree();
159             }
160         }
161         // The event ran when the window scrolls
162         function windowScrollEvent() {
163             checkTreeStickiness(false);
164         }
165
166         // If the page is scrollable and the window is wide enough listen to scroll events
167         // and evaluate tree stickiness.
168         if (pageScrollable && $window.width() > 1000) {
169             $window.on('scroll', windowScrollEvent);
170             checkTreeStickiness(true);
171         }
172
173         // Handle window resizing and switch between desktop/mobile views
174         $window.on('resize', event => {
175             if (pageScrollable && $window.width() > 1000) {
176                 $window.on('scroll', windowScrollEvent);
177                 checkTreeStickiness(true);
178             } else {
179                 $window.off('scroll', windowScrollEvent);
180                 unstickTree();
181             }
182         });
183     }
184
185     setupNavHighlighting() {
186         // Check if support is present for IntersectionObserver
187         if (!'IntersectionObserver' in window ||
188             !'IntersectionObserverEntry' in window ||
189             !'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
190             return;
191         }
192
193         let pageNav = document.querySelector('.sidebar-page-nav');
194
195         // fetch all the headings.
196         let headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
197         // if headings are present, add observers.
198         if (headings.length > 0 && pageNav !== null) {
199             addNavObserver(headings);
200         }
201
202         function addNavObserver(headings) {
203             // Setup the intersection observer.
204             let intersectOpts = {
205                 rootMargin: '0px 0px 0px 0px',
206                 threshold: 1.0
207             };
208             let pageNavObserver = new IntersectionObserver(headingVisibilityChange, intersectOpts);
209
210             // observe each heading
211             for (let i = 0; i !== headings.length; ++i) {
212                 pageNavObserver.observe(headings[i]);
213             }
214         }
215
216         function headingVisibilityChange(entries, observer) {
217             for (let entry of entries) {
218                 let isVisible = (entry.intersectionRatio === 1);
219                 toggleAnchorHighlighting(entry.target.id, isVisible);
220             }
221         }
222
223         function toggleAnchorHighlighting(elementId, shouldHighlight) {
224             let anchorsToHighlight = pageNav.querySelectorAll('a[href="#' + elementId + '"]');
225             for (let i = 0; i < anchorsToHighlight.length; i++) {
226                 // Change below to use classList.toggle when IE support is dropped.
227                 if (shouldHighlight) {
228                     anchorsToHighlight[i].classList.add('current-heading');
229                 } else {
230                     anchorsToHighlight[i].classList.remove('current-heading');
231                 }
232             }
233         }
234     }
235 }
236
237 export default PageDisplay;