]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/page-display.js
Changed the way we were displaying the edit icon.
[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         this.setupEditOnHeader();
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         $('.sidebar-page-nav').on('click', 'a', event => {
24             goToText(event.target.getAttribute('href').substr(1));
25         });
26     }
27
28     goToText(text) {
29         let idElem = document.getElementById(text);
30         $('.page-content [data-highlighted]').attr('data-highlighted', '').css('background-color', '');
31         if (idElem !== null) {
32             window.scrollAndHighlight(idElem);
33         } else {
34             $('.page-content').find(':contains("' + text + '")').smoothScrollTo();
35         }
36     }
37
38     setupPointer() {
39         if (document.getElementById('pointer') === null) return;
40         // Set up pointer
41         let $pointer = $('#pointer').detach();
42         let pointerShowing = false;
43         let $pointerInner = $pointer.children('div.pointer').first();
44         let isSelection = false;
45         let pointerModeLink = true;
46         let pointerSectionId = '';
47
48         // Select all contents on input click
49         $pointer.on('click', 'input', event => {
50             $(this).select();
51             event.stopPropagation();
52         });
53
54         $pointer.on('click focus', event => {
55             event.stopPropagation();
56         });
57
58         // Pointer mode toggle
59         $pointer.on('click', 'span.icon', event => {
60             event.stopPropagation();
61             let $icon = $(event.currentTarget);
62             pointerModeLink = !pointerModeLink;
63             $icon.find('[data-icon="include"]').toggle(!pointerModeLink);
64             $icon.find('[data-icon="link"]').toggle(pointerModeLink);
65             updatePointerContent();
66         });
67
68         // Set up clipboard
69         let clipboard = new Clipboard($pointer[0].querySelector('button'));
70
71         // Hide pointer when clicking away
72         $(document.body).find('*').on('click focus', event => {
73             if (!pointerShowing || isSelection) return;
74             $pointer.detach();
75             pointerShowing = false;
76         });
77
78         let updatePointerContent = ($elem) => {
79             let inputText = pointerModeLink ? window.baseUrl(`/link/${this.pageId}#${pointerSectionId}`) : `{{@${this.pageId}#${pointerSectionId}}}`;
80             if (pointerModeLink && inputText.indexOf('http') !== 0) inputText = window.location.protocol + "//" + window.location.host + inputText;
81
82             $pointer.find('input').val(inputText);
83
84             // update anchor if present
85             const $editAnchor = $pointer.find('#pointer-edit');
86             if ($editAnchor.length !== 0 && $elem) {
87                 const editHref = $editAnchor.data('editHref');
88                 const element = $elem[0];
89                 const elementId = element.id;
90
91                 // get the first 50 characters.
92                 let queryContent = element.textContent && element.textContent.substring(0, 50);
93                 $editAnchor[0].href = `${editHref}?content-id=${elementId}&content-text=${encodeURIComponent(queryContent)}`;
94             }
95         };
96
97         // Show pointer when selecting a single block of tagged content
98         $('.page-content [id^="bkmrk"]').on('mouseup keyup', function (e) {
99             e.stopPropagation();
100             let selection = window.getSelection();
101             if (selection.toString().length === 0) return;
102
103             // Show pointer and set link
104             let $elem = $(this);
105             pointerSectionId = $elem.attr('id');
106             updatePointerContent($elem);
107
108             $elem.before($pointer);
109             $pointer.show();
110             pointerShowing = true;
111
112             // Set pointer to sit near mouse-up position
113             let pointerLeftOffset = (e.pageX - $elem.offset().left - ($pointerInner.width() / 2));
114             if (pointerLeftOffset < 0) pointerLeftOffset = 0;
115             let pointerLeftOffsetPercent = (pointerLeftOffset / $elem.width()) * 100;
116             $pointerInner.css('left', pointerLeftOffsetPercent + '%');
117
118             isSelection = true;
119             setTimeout(() => {
120                 isSelection = false;
121             }, 100);
122         });
123     }
124
125     setupStickySidebar() {
126         // Make the sidebar stick in view on scroll
127         let $window = $(window);
128         let $sidebar = $("#sidebar .scroll-body");
129         let $bookTreeParent = $sidebar.parent();
130
131         // Check the page is scrollable and the content is taller than the tree
132         let pageScrollable = ($(document).height() > $window.height()) && ($sidebar.height() < $('.page-content').height());
133
134         // Get current tree's width and header height
135         let 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($bookTreeParent.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     setupEditOnHeader() {
236         const headingEditIcon = document.querySelector('.heading-edit-icon');
237         if (headingEditIcon === null) {
238             // user does not have permission to edit.
239             return;
240         }
241
242         // Create a clone of the edit icon without the hidden class
243         const visibleHeadingEditIcon = headingEditIcon.cloneNode(true);
244         visibleHeadingEditIcon.style.display = '';
245
246         const headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
247
248         // add an edit icon to each header.
249         for (let i = 0; i !== headings.length; ++i) {
250             const currHeading = headings[i];
251             const headingId = currHeading.id;
252
253             let editIcon = visibleHeadingEditIcon.cloneNode(true);
254
255             // get the first 50 characters.
256             let queryContent = currHeading.textContent && currHeading.textContent.substring(0, 50);
257             editIcon.href += `?content-id=${headingId}&content-text=${encodeURIComponent(queryContent)}`;
258
259             currHeading.appendChild(editIcon);
260         }
261     }
262
263 }
264
265 module.exports = PageDisplay;