aboutsummaryrefslogtreecommitdiffhomepage
path: root/assets/default/js/base.js
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2018-02-24 18:30:30 +0100
committerArthurHoaro <arthur@hoa.ro>2018-03-26 19:29:20 +0200
commitd42da5435024b4270d5abac11e6fcfa38354f3e9 (patch)
treecfd340e25ab7e1b88fe943541ce4f882a315617b /assets/default/js/base.js
parentd78c23e00d3007c3fee8c3603acac00efc1ce14e (diff)
downloadShaarli-d42da5435024b4270d5abac11e6fcfa38354f3e9.tar.gz
Shaarli-d42da5435024b4270d5abac11e6fcfa38354f3e9.tar.zst
Shaarli-d42da5435024b4270d5abac11e6fcfa38354f3e9.zip
Webpack / Rewrite all JS to ES6 Syntax
Diffstat (limited to 'assets/default/js/base.js')
-rw-r--r--assets/default/js/base.js1172
1 files changed, 557 insertions, 615 deletions
diff --git a/assets/default/js/base.js b/assets/default/js/base.js
index cf628e87..5cf037c2 100644
--- a/assets/default/js/base.js
+++ b/assets/default/js/base.js
@@ -1,532 +1,4 @@
1/** @licstart The following is the entire license notice for the 1import Awesomplete from 'awesomplete';
2 * JavaScript code in this page.
3 *
4 * Copyright: (c) 2011-2015 Sébastien SAUVAGE <sebsauvage@sebsauvage.net>
5 * (c) 2011-2017 The Shaarli Community, see AUTHORS
6 *
7 * This software is provided 'as-is', without any express or implied warranty.
8 * In no event will the authors be held liable for any damages arising from
9 * the use of this software.
10 *
11 * Permission is granted to anyone to use this software for any purpose,
12 * including commercial applications, and to alter it and redistribute it
13 * freely, subject to the following restrictions:
14 *
15 * 1. The origin of this software must not be misrepresented; you must not
16 * claim that you wrote the original software. If you use this software
17 * in a product, an acknowledgment in the product documentation would
18 * be appreciated but is not required.
19 *
20 * 2. Altered source versions must be plainly marked as such, and must
21 * not be misrepresented as being the original software.
22 *
23 * 3. This notice may not be removed or altered from any source distribution.
24 *
25 * @licend The above is the entire license notice
26 * for the JavaScript code in this page.
27 */
28
29window.onload = function () {
30
31 /**
32 * Retrieve an element up in the tree from its class name.
33 */
34 function getParentByClass(el, className) {
35 var p = el.parentNode;
36 if (p == null || p.classList.contains(className)) {
37 return p;
38 }
39 return getParentByClass(p, className);
40 }
41
42
43 /**
44 * Handle responsive menu.
45 * Source: http://purecss.io/layouts/tucked-menu-vertical/
46 */
47 (function (window, document) {
48 var menu = document.getElementById('shaarli-menu'),
49 WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange':'resize';
50
51 function toggleHorizontal() {
52 [].forEach.call(
53 document.getElementById('shaarli-menu').querySelectorAll('.menu-transform'),
54 function(el){
55 el.classList.toggle('pure-menu-horizontal');
56 }
57 );
58 };
59
60 function toggleMenu() {
61 // set timeout so that the panel has a chance to roll up
62 // before the menu switches states
63 if (menu.classList.contains('open')) {
64 setTimeout(toggleHorizontal, 500);
65 }
66 else {
67 toggleHorizontal();
68 }
69 menu.classList.toggle('open');
70 document.getElementById('menu-toggle').classList.toggle('x');
71 };
72
73 function closeMenu() {
74 if (menu.classList.contains('open')) {
75 toggleMenu();
76 }
77 }
78
79 var menuToggle = document.getElementById('menu-toggle');
80 if (menuToggle != null) {
81 menuToggle.addEventListener('click', function (e) {
82 toggleMenu();
83 });
84 }
85
86 window.addEventListener(WINDOW_CHANGE_EVENT, closeMenu);
87 })(this, this.document);
88
89 /**
90 * Fold/Expand shaares description and thumbnail.
91 */
92 var foldAllButtons = document.getElementsByClassName('fold-all');
93 var foldButtons = document.getElementsByClassName('fold-button');
94
95 [].forEach.call(foldButtons, function (foldButton) {
96 // Retrieve description
97 var description = null;
98 var thumbnail = null;
99 var linklistItem = getParentByClass(foldButton, 'linklist-item');
100 if (linklistItem != null) {
101 description = linklistItem.querySelector('.linklist-item-description');
102 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
103 if (description != null || thumbnail != null) {
104 foldButton.style.display = 'inline';
105 }
106 }
107
108 foldButton.addEventListener('click', function (event) {
109 event.preventDefault();
110 toggleFold(event.target, description, thumbnail);
111 });
112 });
113
114 if (foldAllButtons != null) {
115 [].forEach.call(foldAllButtons, function (foldAllButton) {
116 foldAllButton.addEventListener('click', function (event) {
117 event.preventDefault();
118 var state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') != -1 ? 'down' : 'up';
119 [].forEach.call(foldButtons, function (foldButton) {
120 if (foldButton.firstElementChild.classList.contains('fa-chevron-up') && state == 'down'
121 || foldButton.firstElementChild.classList.contains('fa-chevron-down') && state == 'up'
122 ) {
123 return;
124 }
125 // Retrieve description
126 var description = null;
127 var thumbnail = null;
128 var linklistItem = getParentByClass(foldButton, 'linklist-item');
129 if (linklistItem != null) {
130 description = linklistItem.querySelector('.linklist-item-description');
131 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
132 if (description != null || thumbnail != null) {
133 foldButton.style.display = 'inline';
134 }
135 }
136
137 toggleFold(foldButton.firstElementChild, description, thumbnail);
138 });
139 foldAllButton.firstElementChild.classList.toggle('fa-chevron-down');
140 foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
141 foldAllButton.title = state === 'down'
142 ? document.getElementById('translation-fold-all').innerHTML
143 : document.getElementById('translation-expand-all').innerHTML
144 });
145 });
146 }
147
148 function toggleFold(button, description, thumb)
149 {
150 // Switch fold/expand - up = fold
151 if (button.classList.contains('fa-chevron-up')) {
152 button.title = document.getElementById('translation-expand').innerHTML;
153 if (description != null) {
154 description.style.display = 'none';
155 }
156 if (thumb != null) {
157 thumb.style.display = 'none';
158 }
159 }
160 else {
161 button.title = document.getElementById('translation-fold').innerHTML;
162 if (description != null) {
163 description.style.display = 'block';
164 }
165 if (thumb != null) {
166 thumb.style.display = 'block';
167 }
168 }
169 button.classList.toggle('fa-chevron-down');
170 button.classList.toggle('fa-chevron-up');
171 }
172
173 /**
174 * Confirmation message before deletion.
175 */
176 var deleteLinks = document.querySelectorAll('.confirm-delete');
177 [].forEach.call(deleteLinks, function(deleteLink) {
178 deleteLink.addEventListener('click', function(event) {
179 if(! confirm(document.getElementById('translation-delete-link').innerHTML)) {
180 event.preventDefault();
181 }
182 });
183 });
184
185 /**
186 * Close alerts
187 */
188 var closeLinks = document.querySelectorAll('.pure-alert-close');
189 [].forEach.call(closeLinks, function(closeLink) {
190 closeLink.addEventListener('click', function(event) {
191 var alert = getParentByClass(event.target, 'pure-alert-closable');
192 alert.style.display = 'none';
193 });
194 });
195
196 /**
197 * New version dismiss.
198 * Hide the message for one week using localStorage.
199 */
200 var newVersionDismiss = document.getElementById('new-version-dismiss');
201 var newVersionMessage = document.querySelector('.new-version-message');
202 if (newVersionMessage != null
203 && localStorage.getItem('newVersionDismiss') != null
204 && parseInt(localStorage.getItem('newVersionDismiss')) + 7*24*60*60*1000 > (new Date()).getTime()
205 ) {
206 newVersionMessage.style.display = 'none';
207 }
208 if (newVersionDismiss != null) {
209 newVersionDismiss.addEventListener('click', function () {
210 localStorage.setItem('newVersionDismiss', (new Date()).getTime());
211 });
212 }
213
214 var hiddenReturnurl = document.getElementsByName('returnurl');
215 if (hiddenReturnurl != null) {
216 hiddenReturnurl.value = window.location.href;
217 }
218
219 /**
220 * Autofocus text fields
221 */
222 var autofocusElements = document.querySelectorAll('.autofocus');
223 var breakLoop = false;
224 [].forEach.call(autofocusElements, function(autofocusElement) {
225 if (autofocusElement.value == '' && ! breakLoop) {
226 autofocusElement.focus();
227 breakLoop = true;
228 }
229 });
230
231 /**
232 * Handle sub menus/forms
233 */
234 var openers = document.getElementsByClassName('subheader-opener');
235 if (openers != null) {
236 [].forEach.call(openers, function(opener) {
237 opener.addEventListener('click', function(event) {
238 event.preventDefault();
239
240 var id = opener.getAttribute('data-open-id');
241 var sub = document.getElementById(id);
242
243 if (sub != null) {
244 [].forEach.call(document.getElementsByClassName('subheader-form'), function (element) {
245 if (element != sub) {
246 removeClass(element, 'open')
247 }
248 });
249
250 sub.classList.toggle('open');
251 }
252 });
253 });
254 }
255
256 function removeClass(element, classname) {
257 element.className = element.className.replace(new RegExp('(?:^|\\s)'+ classname + '(?:\\s|$)'), ' ');
258 }
259
260 /**
261 * Remove CSS target padding (for fixed bar)
262 */
263 if (location.hash != '') {
264 var anchor = document.getElementById(location.hash.substr(1));
265 if (anchor != null) {
266 var padsize = anchor.clientHeight;
267 this.window.scroll(0, this.window.scrollY - padsize);
268 anchor.style.paddingTop = 0;
269 }
270 }
271
272 /**
273 * Text area resizer
274 */
275 var description = document.getElementById('lf_description');
276 var observe = function (element, event, handler) {
277 element.addEventListener(event, handler, false);
278 };
279 function init () {
280 function resize () {
281 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
282 var scrollTop = window.pageYOffset ||
283 (document.documentElement || document.body.parentNode || document.body).scrollTop;
284
285 description.style.height = 'auto';
286 description.style.height = description.scrollHeight+10+'px';
287
288 window.scrollTo(0, scrollTop);
289 }
290 /* 0-timeout to get the already changed text */
291 function delayedResize () {
292 window.setTimeout(resize, 0);
293 }
294 observe(description, 'change', resize);
295 observe(description, 'cut', delayedResize);
296 observe(description, 'paste', delayedResize);
297 observe(description, 'drop', delayedResize);
298 observe(description, 'keydown', delayedResize);
299
300 resize();
301 }
302
303 if (description != null) {
304 init();
305 // Submit editlink form with CTRL + Enter in the text area.
306 description.addEventListener('keydown', function (event) {
307 if (event.ctrlKey && event.keyCode === 13) {
308 document.getElementById('button-save-edit').click();
309 }
310 });
311 }
312
313 /**
314 * Awesomplete trigger.
315 */
316 var tags = document.getElementById('lf_tags');
317 if (tags != null) {
318 awesompleteUniqueTag('#lf_tags');
319 }
320
321 /**
322 * bLazy trigger
323 */
324 var picwall = document.getElementById('picwall_container');
325 if (picwall != null) {
326 var bLazy = new Blazy();
327 }
328
329 /**
330 * Bookmarklet alert
331 */
332 var bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
333 var bkmMessage = document.getElementById('bookmarklet-alert');
334 [].forEach.call(bookmarkletLinks, function(link) {
335 link.addEventListener('click', function(event) {
336 event.preventDefault();
337 alert(bkmMessage.value);
338 });
339 });
340
341 /**
342 * Firefox Social
343 */
344 var ffButton = document.getElementById('ff-social-button');
345 if (ffButton != null) {
346 ffButton.addEventListener('click', function(event) {
347 activateFirefoxSocial(event.target);
348 });
349 }
350
351 /**
352 * Plugin admin order
353 */
354 var orderPA = document.querySelectorAll('.order');
355 [].forEach.call(orderPA, function(link) {
356 link.addEventListener('click', function(event) {
357 event.preventDefault();
358 if (event.target.classList.contains('order-up')) {
359 return orderUp(event.target.parentNode.parentNode.getAttribute('data-order'));
360 } else if (event.target.classList.contains('order-down')) {
361 return orderDown(event.target.parentNode.parentNode.getAttribute('data-order'));
362 }
363 });
364 });
365
366 var continent = document.getElementById('continent');
367 var city = document.getElementById('city');
368 if (continent != null && city != null) {
369 continent.addEventListener('change', function (event) {
370 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
371 });
372 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
373 }
374
375 /**
376 * Bulk actions
377 */
378 var linkCheckboxes = document.querySelectorAll('.delete-checkbox');
379 var bar = document.getElementById('actions');
380 [].forEach.call(linkCheckboxes, function(checkbox) {
381 checkbox.style.display = 'inline-block';
382 checkbox.addEventListener('click', function(event) {
383 var count = 0;
384 var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
385 [].forEach.call(linkCheckedCheckboxes, function(checkbox) {
386 count++;
387 });
388 if (count == 0 && bar.classList.contains('open')) {
389 bar.classList.toggle('open');
390 } else if (count > 0 && ! bar.classList.contains('open')) {
391 bar.classList.toggle('open');
392 }
393 });
394 });
395
396 var deleteButton = document.getElementById('actions-delete');
397 var token = document.querySelector('input[type="hidden"][name="token"]');
398 if (deleteButton != null && token != null) {
399 deleteButton.addEventListener('click', function(event) {
400 event.preventDefault();
401
402 var links = [];
403 var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
404 [].forEach.call(linkCheckedCheckboxes, function(checkbox) {
405 links.push({
406 'id': checkbox.value,
407 'title': document.querySelector('.linklist-item[data-id="'+ checkbox.value +'"] .linklist-link').innerHTML
408 });
409 });
410
411 var message = 'Are you sure you want to delete '+ links.length +' links?\n';
412 message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
413 var ids = [];
414 links.forEach(function(item) {
415 message += ' - '+ item['title'] +'\n';
416 ids.push(item['id']);
417 });
418
419 if (window.confirm(message)) {
420 window.location = '?delete_link&lf_linkdate='+ ids.join('+') +'&token='+ token.value;
421 }
422 });
423 }
424
425 /**
426 * Tag list operations
427 *
428 * TODO: support error code in the backend for AJAX requests
429 */
430 var tagList = document.querySelector('input[name="taglist"]');
431 var existingTags = tagList ? tagList.value.split(' ') : [];
432 var awesomepletes = [];
433
434 // Display/Hide rename form
435 var renameTagButtons = document.querySelectorAll('.rename-tag');
436 [].forEach.call(renameTagButtons, function(rename) {
437 rename.addEventListener('click', function(event) {
438 event.preventDefault();
439 var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
440 var form = block.querySelector('.rename-tag-form');
441 if (form.style.display == 'none' || form.style.display == '') {
442 form.style.display = 'block';
443 } else {
444 form.style.display = 'none';
445 }
446 block.querySelector('input').focus();
447 });
448 });
449
450 // Rename a tag with an AJAX request
451 var renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
452 [].forEach.call(renameTagSubmits, function(rename) {
453 rename.addEventListener('click', function(event) {
454 event.preventDefault();
455 var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
456 var input = block.querySelector('.rename-tag-input');
457 var totag = input.value.replace('/"/g', '\\"');
458 if (totag.trim() == '') {
459 return;
460 }
461 var fromtag = block.getAttribute('data-tag');
462 var token = document.getElementById('token').value;
463
464 xhr = new XMLHttpRequest();
465 xhr.open('POST', '?do=changetag');
466 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
467 xhr.onload = function() {
468 if (xhr.status !== 200) {
469 alert('An error occurred. Return code: '+ xhr.status);
470 location.reload();
471 } else {
472 block.setAttribute('data-tag', totag);
473 input.setAttribute('name', totag);
474 input.setAttribute('value', totag);
475 findParent(input, 'div', {'class': 'rename-tag-form'}).style.display = 'none';
476 block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
477 block.querySelector('a.tag-link').setAttribute('href', '?searchtags='+ encodeURIComponent(totag));
478 block.querySelector('a.rename-tag').setAttribute('href', '?do=changetag&fromtag='+ encodeURIComponent(totag));
479
480 // Refresh awesomplete values
481 for (var key in existingTags) {
482 if (existingTags[key] == fromtag) {
483 existingTags[key] = totag;
484 }
485 }
486 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
487 }
488 };
489 xhr.send('renametag=1&fromtag='+ encodeURIComponent(fromtag) +'&totag='+ encodeURIComponent(totag) +'&token='+ token);
490 refreshToken();
491 });
492 });
493
494 // Validate input with enter key
495 var renameTagInputs = document.querySelectorAll('.rename-tag-input');
496 [].forEach.call(renameTagInputs, function(rename) {
497
498 rename.addEventListener('keypress', function(event) {
499 if (event.keyCode === 13) { // enter
500 findParent(event.target, 'div', {'class': 'tag-list-item'}).querySelector('.validate-rename-tag').click();
501 }
502 });
503 });
504
505 // Delete a tag with an AJAX query (alert popup confirmation)
506 var deleteTagButtons = document.querySelectorAll('.delete-tag');
507 [].forEach.call(deleteTagButtons, function(rename) {
508 rename.style.display = 'inline';
509 rename.addEventListener('click', function(event) {
510 event.preventDefault();
511 var block = findParent(event.target, 'div', {'class': 'tag-list-item'});
512 var tag = block.getAttribute('data-tag');
513 var token = document.getElementById('token').value;
514
515 if (confirm('Are you sure you want to delete the tag "'+ tag +'"?')) {
516 xhr = new XMLHttpRequest();
517 xhr.open('POST', '?do=changetag');
518 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
519 xhr.onload = function() {
520 block.remove();
521 };
522 xhr.send(encodeURI('deletetag=1&fromtag='+ tag +'&token='+ token));
523 refreshToken();
524 }
525 });
526 });
527
528 updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
529};
530 2
531/** 3/**
532 * Find a parent element according to its tag and its attributes 4 * Find a parent element according to its tag and its attributes
@@ -537,41 +9,60 @@ window.onload = function () {
537 * 9 *
538 * @returns Found element or null. 10 * @returns Found element or null.
539 */ 11 */
540function findParent(element, tagName, attributes) 12function findParent(element, tagName, attributes) {
541{ 13 const parentMatch = key => attributes[key] !== '' && element.getAttribute(key).indexOf(attributes[key]) !== -1;
542 while (element) { 14 while (element) {
543 if (element.tagName.toLowerCase() == tagName) { 15 if (element.tagName.toLowerCase() === tagName) {
544 var match = true; 16 if (Object.keys(attributes).find(parentMatch)) {
545 for (var key in attributes) { 17 return element;
546 if (! element.hasAttribute(key) 18 }
547 || (attributes[key] != '' && element.getAttribute(key).indexOf(attributes[key]) == -1)
548 ) {
549 match = false;
550 break;
551 }
552 }
553
554 if (match) {
555 return element;
556 }
557 }
558 element = element.parentElement;
559 } 19 }
560 return null; 20 element = element.parentElement;
21 }
22 return null;
561} 23}
562 24
563/** 25/**
564 * Ajax request to refresh the CSRF token. 26 * Ajax request to refresh the CSRF token.
565 */ 27 */
566function refreshToken() 28function refreshToken() {
567{ 29 const xhr = new XMLHttpRequest();
568 var xhr = new XMLHttpRequest(); 30 xhr.open('GET', '?do=token');
569 xhr.open('GET', '?do=token'); 31 xhr.onload = () => {
570 xhr.onload = function() { 32 const token = document.getElementById('token');
571 var token = document.getElementById('token'); 33 token.setAttribute('value', xhr.responseText);
572 token.setAttribute('value', xhr.responseText); 34 };
573 }; 35 xhr.send();
574 xhr.send(); 36}
37
38function createAwesompleteInstance(element, tags = []) {
39 const awesome = new Awesomplete(Awesomplete.$(element));
40 // Tags are separated by a space
41 awesome.filter = (text, input) => Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
42 // Insert new selected tag in the input
43 awesome.replace = (text) => {
44 const before = awesome.input.value.match(/^.+ \s*|/)[0];
45 awesome.input.value = `${before}${text} `;
46 };
47 // Highlight found items
48 awesome.item = (text, input) => Awesomplete.ITEM(text, input.match(/[^ ]*$/)[0]);
49 // Don't display already selected items
50 const reg = /(\w+) /g;
51 let match;
52 awesome.data = (item, input) => {
53 while ((match = reg.exec(input))) {
54 if (item === match[1]) {
55 return '';
56 }
57 }
58 return item;
59 };
60 awesome.minChars = 1;
61 if (tags.length) {
62 awesome.list = tags;
63 }
64
65 return awesome;
575} 66}
576 67
577/** 68/**
@@ -581,24 +72,21 @@ function refreshToken()
581 * @param tags Array of tags 72 * @param tags Array of tags
582 * @param instances List of existing awesomplete instances 73 * @param instances List of existing awesomplete instances
583 */ 74 */
584function updateAwesompleteList(selector, tags, instances) 75function updateAwesompleteList(selector, tags, instances) {
585{ 76 if (instances.length === 0) {
586 // First load: create Awesomplete instances 77 // First load: create Awesomplete instances
587 if (instances.length == 0) { 78 const elements = document.querySelectorAll(selector);
588 var elements = document.querySelectorAll(selector); 79 [...elements].forEach((element) => {
589 [].forEach.call(elements, function (element) { 80 instances.push(createAwesompleteInstance(element, tags));
590 instances.push(new Awesomplete( 81 });
591 element, 82 } else {
592 {'list': tags} 83 // Update awesomplete tag list
593 )); 84 instances.map((item) => {
594 }); 85 item.list = tags;
595 } else { 86 return item;
596 // Update awesomplete tag list 87 });
597 for (var key in instances) { 88 }
598 instances[key].list = tags; 89 return instances;
599 }
600 }
601 return instances;
602} 90}
603 91
604/** 92/**
@@ -606,36 +94,31 @@ function updateAwesompleteList(selector, tags, instances)
606 * 94 *
607 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript 95 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
608 */ 96 */
609function htmlEntities(str) 97function htmlEntities(str) {
610{ 98 return str.replace(/[\u00A0-\u9999<>&]/gim, i => `&#${i.charCodeAt(0)};`);
611 return str.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
612 return '&#'+i.charCodeAt(0)+';';
613 });
614} 99}
615 100
616function activateFirefoxSocial(node) { 101function activateFirefoxSocial(node) {
617 var loc = location.href; 102 const loc = location.href;
618 var baseURL = loc.substring(0, loc.lastIndexOf("/") + 1); 103 const baseURL = loc.substring(0, loc.lastIndexOf('/') + 1);
619 var title = document.title; 104
620 105 const data = {
621 // Keeping the data separated (ie. not in the DOM) so that it's maintainable and diffable. 106 name: document.title,
622 var data = { 107 description: document.getElementById('translation-delete-link').innerHTML,
623 name: title, 108 author: 'Shaarli',
624 description: document.getElementById('translation-delete-link').innerHTML, 109 version: '1.0.0',
625 author: "Shaarli", 110
626 version: "1.0.0", 111 iconURL: `${baseURL}/images/favicon.ico`,
627 112 icon32URL: `${baseURL}/images/favicon.ico`,
628 iconURL: baseURL + "/images/favicon.ico", 113 icon64URL: `${baseURL}/images/favicon.ico`,
629 icon32URL: baseURL + "/images/favicon.ico", 114
630 icon64URL: baseURL + "/images/favicon.ico", 115 shareURL: `${baseURL}?post=%{url}&title=%{title}&description=%{text}&source=firefoxsocialapi`,
631 116 homepageURL: baseURL,
632 shareURL: baseURL + "?post=%{url}&title=%{title}&description=%{text}&source=firefoxsocialapi", 117 };
633 homepageURL: baseURL 118 node.setAttribute('data-service', JSON.stringify(data));
634 }; 119
635 node.setAttribute("data-service", JSON.stringify(data)); 120 const activate = new CustomEvent('ActivateSocialFeature');
636 121 node.dispatchEvent(activate);
637 var activate = new CustomEvent("ActivateSocialFeature");
638 node.dispatchEvent(activate);
639} 122}
640 123
641/** 124/**
@@ -645,20 +128,479 @@ function activateFirefoxSocial(node) {
645 * @param currentContinent Current selected continent 128 * @param currentContinent Current selected continent
646 * @param reset Set to true to reset the selected value 129 * @param reset Set to true to reset the selected value
647 */ 130 */
648function hideTimezoneCities(cities, currentContinent) { 131function hideTimezoneCities(cities, currentContinent, reset = null) {
649 var first = true; 132 let first = true;
650 if (reset == null) { 133 if (reset == null) {
651 reset = false; 134 reset = false;
135 }
136 [...cities].forEach((option) => {
137 if (option.getAttribute('data-continent') !== currentContinent) {
138 option.className = 'hidden';
139 } else {
140 option.className = '';
141 if (reset === true && first === true) {
142 option.setAttribute('selected', 'selected');
143 first = false;
144 }
652 } 145 }
653 [].forEach.call(cities, function (option) { 146 });
654 if (option.getAttribute('data-continent') != currentContinent) { 147}
655 option.className = 'hidden'; 148
656 } else { 149/**
657 option.className = ''; 150 * Retrieve an element up in the tree from its class name.
658 if (reset === true && first === true) { 151 */
659 option.setAttribute('selected', 'selected'); 152function getParentByClass(el, className) {
660 first = false; 153 const p = el.parentNode;
154 if (p == null || p.classList.contains(className)) {
155 return p;
156 }
157 return getParentByClass(p, className);
158}
159
160function toggleHorizontal() {
161 [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
162 el.classList.toggle('pure-menu-horizontal');
163 });
164}
165
166function toggleMenu(menu) {
167 // set timeout so that the panel has a chance to roll up
168 // before the menu switches states
169 if (menu.classList.contains('open')) {
170 setTimeout(toggleHorizontal, 500);
171 } else {
172 toggleHorizontal();
173 }
174 menu.classList.toggle('open');
175 document.getElementById('menu-toggle').classList.toggle('x');
176}
177
178function closeMenu(menu) {
179 if (menu.classList.contains('open')) {
180 toggleMenu(menu);
181 }
182}
183
184function toggleFold(button, description, thumb) {
185 // Switch fold/expand - up = fold
186 if (button.classList.contains('fa-chevron-up')) {
187 button.title = document.getElementById('translation-expand').innerHTML;
188 if (description != null) {
189 description.style.display = 'none';
190 }
191 if (thumb != null) {
192 thumb.style.display = 'none';
193 }
194 } else {
195 button.title = document.getElementById('translation-fold').innerHTML;
196 if (description != null) {
197 description.style.display = 'block';
198 }
199 if (thumb != null) {
200 thumb.style.display = 'block';
201 }
202 }
203 button.classList.toggle('fa-chevron-down');
204 button.classList.toggle('fa-chevron-up');
205}
206
207function removeClass(element, classname) {
208 element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
209}
210
211function init(description) {
212 function resize() {
213 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
214 const scrollTop = window.pageYOffset ||
215 (document.documentElement || document.body.parentNode || document.body).scrollTop;
216
217 description.style.height = 'auto';
218 description.style.height = `${description.scrollHeight + 10}px`;
219
220 window.scrollTo(0, scrollTop);
221 }
222
223 /* 0-timeout to get the already changed text */
224 function delayedResize() {
225 window.setTimeout(resize, 0);
226 }
227
228 const observe = (element, event, handler) => {
229 element.addEventListener(event, handler, false);
230 };
231 observe(description, 'change', resize);
232 observe(description, 'cut', delayedResize);
233 observe(description, 'paste', delayedResize);
234 observe(description, 'drop', delayedResize);
235 observe(description, 'keydown', delayedResize);
236
237 resize();
238}
239
240(() => {
241 /**
242 * Handle responsive menu.
243 * Source: http://purecss.io/layouts/tucked-menu-vertical/
244 */
245 const menu = document.getElementById('shaarli-menu');
246 const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
247
248 const menuToggle = document.getElementById('menu-toggle');
249 if (menuToggle != null) {
250 menuToggle.addEventListener('click', () => toggleMenu(menu));
251 }
252
253 window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
254
255 /**
256 * Fold/Expand shaares description and thumbnail.
257 */
258 const foldAllButtons = document.getElementsByClassName('fold-all');
259 const foldButtons = document.getElementsByClassName('fold-button');
260
261 [...foldButtons].forEach((foldButton) => {
262 // Retrieve description
263 let description = null;
264 let thumbnail = null;
265 const linklistItem = getParentByClass(foldButton, 'linklist-item');
266 if (linklistItem != null) {
267 description = linklistItem.querySelector('.linklist-item-description');
268 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
269 if (description != null || thumbnail != null) {
270 foldButton.style.display = 'inline';
271 }
272 }
273
274 foldButton.addEventListener('click', (event) => {
275 event.preventDefault();
276 toggleFold(event.target, description, thumbnail);
277 });
278 });
279
280 if (foldAllButtons != null) {
281 [].forEach.call(foldAllButtons, (foldAllButton) => {
282 foldAllButton.addEventListener('click', (event) => {
283 event.preventDefault();
284 const state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
285 [].forEach.call(foldButtons, (foldButton) => {
286 if ((foldButton.firstElementChild.classList.contains('fa-chevron-up') && state === 'down')
287 || (foldButton.firstElementChild.classList.contains('fa-chevron-down') && state === 'up')
288 ) {
289 return;
290 }
291 // Retrieve description
292 let description = null;
293 let thumbnail = null;
294 const linklistItem = getParentByClass(foldButton, 'linklist-item');
295 if (linklistItem != null) {
296 description = linklistItem.querySelector('.linklist-item-description');
297 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
298 if (description != null || thumbnail != null) {
299 foldButton.style.display = 'inline';
300 }
301 }
302
303 toggleFold(foldButton.firstElementChild, description, thumbnail);
304 });
305 foldAllButton.firstElementChild.classList.toggle('fa-chevron-down');
306 foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
307 foldAllButton.title = state === 'down'
308 ? document.getElementById('translation-fold-all').innerHTML
309 : document.getElementById('translation-expand-all').innerHTML;
310 });
311 });
312 }
313
314 /**
315 * Confirmation message before deletion.
316 */
317 const deleteLinks = document.querySelectorAll('.confirm-delete');
318 [...deleteLinks].forEach((deleteLink) => {
319 deleteLink.addEventListener('click', (event) => {
320 if (!confirm(document.getElementById('translation-delete-link').innerHTML)) {
321 event.preventDefault();
322 }
323 });
324 });
325
326 /**
327 * Close alerts
328 */
329 const closeLinks = document.querySelectorAll('.pure-alert-close');
330 [...closeLinks].forEach((closeLink) => {
331 closeLink.addEventListener('click', (event) => {
332 const alert = getParentByClass(event.target, 'pure-alert-closable');
333 alert.style.display = 'none';
334 });
335 });
336
337 /**
338 * New version dismiss.
339 * Hide the message for one week using localStorage.
340 */
341 const newVersionDismiss = document.getElementById('new-version-dismiss');
342 const newVersionMessage = document.querySelector('.new-version-message');
343 if (newVersionMessage != null
344 && localStorage.getItem('newVersionDismiss') != null
345 && parseInt(localStorage.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
346 ) {
347 newVersionMessage.style.display = 'none';
348 }
349 if (newVersionDismiss != null) {
350 newVersionDismiss.addEventListener('click', () => {
351 localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
352 });
353 }
354
355 const hiddenReturnurl = document.getElementsByName('returnurl');
356 if (hiddenReturnurl != null) {
357 hiddenReturnurl.value = window.location.href;
358 }
359
360 /**
361 * Autofocus text fields
362 */
363 const autofocusElements = document.querySelectorAll('.autofocus');
364 let breakLoop = false;
365 [].forEach.call(autofocusElements, (autofocusElement) => {
366 if (autofocusElement.value === '' && !breakLoop) {
367 autofocusElement.focus();
368 breakLoop = true;
369 }
370 });
371
372 /**
373 * Handle sub menus/forms
374 */
375 const openers = document.getElementsByClassName('subheader-opener');
376 if (openers != null) {
377 [...openers].forEach((opener) => {
378 opener.addEventListener('click', (event) => {
379 event.preventDefault();
380
381 const id = opener.getAttribute('data-open-id');
382 const sub = document.getElementById(id);
383
384 if (sub != null) {
385 [...document.getElementsByClassName('subheader-form')].forEach((element) => {
386 if (element !== sub) {
387 removeClass(element, 'open');
661 } 388 }
389 });
390
391 sub.classList.toggle('open');
662 } 392 }
393 });
663 }); 394 });
664} 395 }
396
397 /**
398 * Remove CSS target padding (for fixed bar)
399 */
400 if (location.hash !== '') {
401 const anchor = document.getElementById(location.hash.substr(1));
402 if (anchor != null) {
403 const padsize = anchor.clientHeight;
404 window.scroll(0, window.scrollY - padsize);
405 anchor.style.paddingTop = '0';
406 }
407 }
408
409 /**
410 * Text area resizer
411 */
412 const description = document.getElementById('lf_description');
413
414 if (description != null) {
415 init(description);
416 // Submit editlink form with CTRL + Enter in the text area.
417 description.addEventListener('keydown', (event) => {
418 if (event.ctrlKey && event.keyCode === 13) {
419 document.getElementById('button-save-edit').click();
420 }
421 });
422 }
423
424 /**
425 * Bookmarklet alert
426 */
427 const bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
428 const bkmMessage = document.getElementById('bookmarklet-alert');
429 [].forEach.call(bookmarkletLinks, (link) => {
430 link.addEventListener('click', (event) => {
431 event.preventDefault();
432 alert(bkmMessage.value);
433 });
434 });
435
436 /**
437 * Firefox Social
438 */
439 const ffButton = document.getElementById('ff-social-button');
440 if (ffButton != null) {
441 ffButton.addEventListener('click', (event) => {
442 activateFirefoxSocial(event.target);
443 });
444 }
445
446 const continent = document.getElementById('continent');
447 const city = document.getElementById('city');
448 if (continent != null && city != null) {
449 continent.addEventListener('change', () => {
450 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
451 });
452 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
453 }
454
455 /**
456 * Bulk actions
457 */
458 const linkCheckboxes = document.querySelectorAll('.delete-checkbox');
459 const bar = document.getElementById('actions');
460 [...linkCheckboxes].forEach((checkbox) => {
461 checkbox.style.display = 'inline-block';
462 checkbox.addEventListener('click', () => {
463 const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
464 const count = [...linkCheckedCheckboxes].length;
465 if (count === 0 && bar.classList.contains('open')) {
466 bar.classList.toggle('open');
467 } else if (count > 0 && !bar.classList.contains('open')) {
468 bar.classList.toggle('open');
469 }
470 });
471 });
472
473 const deleteButton = document.getElementById('actions-delete');
474 const token = document.getElementById('token');
475 if (deleteButton != null && token != null) {
476 deleteButton.addEventListener('click', (event) => {
477 event.preventDefault();
478
479 const links = [];
480 const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
481 [...linkCheckedCheckboxes].forEach((checkbox) => {
482 links.push({
483 id: checkbox.value,
484 title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
485 });
486 });
487
488 let message = `Are you sure you want to delete ${links.length} links?\n`;
489 message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
490 const ids = [];
491 links.forEach((item) => {
492 message += ` - ${item.title}\n`;
493 ids.push(item.id);
494 });
495
496 if (window.confirm(message)) {
497 window.location = `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
498 }
499 });
500 }
501
502 /**
503 * Tag list operations
504 *
505 * TODO: support error code in the backend for AJAX requests
506 */
507 const tagList = document.querySelector('input[name="taglist"]');
508 let existingTags = tagList ? tagList.value.split(' ') : [];
509 let awesomepletes = [];
510
511 // Display/Hide rename form
512 const renameTagButtons = document.querySelectorAll('.rename-tag');
513 [...renameTagButtons].forEach((rename) => {
514 rename.addEventListener('click', (event) => {
515 event.preventDefault();
516 const block = findParent(event.target, 'div', { class: 'tag-list-item' });
517 const form = block.querySelector('.rename-tag-form');
518 if (form.style.display === 'none' || form.style.display === '') {
519 form.style.display = 'block';
520 } else {
521 form.style.display = 'none';
522 }
523 block.querySelector('input').focus();
524 });
525 });
526
527 // Rename a tag with an AJAX request
528 const renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
529 [...renameTagSubmits].forEach((rename) => {
530 rename.addEventListener('click', (event) => {
531 event.preventDefault();
532 const block = findParent(event.target, 'div', { class: 'tag-list-item' });
533 const input = block.querySelector('.rename-tag-input');
534 const totag = input.value.replace('/"/g', '\\"');
535 if (totag.trim() === '') {
536 return;
537 }
538 const refreshedToken = document.getElementById('token').value;
539 const fromtag = block.getAttribute('data-tag');
540 const xhr = new XMLHttpRequest();
541 xhr.open('POST', '?do=changetag');
542 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
543 xhr.onload = () => {
544 if (xhr.status !== 200) {
545 alert(`An error occurred. Return code: ${xhr.status}`);
546 location.reload();
547 } else {
548 block.setAttribute('data-tag', totag);
549 input.setAttribute('name', totag);
550 input.setAttribute('value', totag);
551 findParent(input, 'div', { class: 'rename-tag-form' }).style.display = 'none';
552 block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
553 block.querySelector('a.tag-link').setAttribute('href', `?searchtags=${encodeURIComponent(totag)}`);
554 block.querySelector('a.rename-tag').setAttribute('href', `?do=changetag&fromtag=${encodeURIComponent(totag)}`);
555
556 // Refresh awesomplete values
557 existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
558 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
559 }
560 };
561 xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
562 refreshToken();
563 });
564 });
565
566 // Validate input with enter key
567 const renameTagInputs = document.querySelectorAll('.rename-tag-input');
568 [...renameTagInputs].forEach((rename) => {
569 rename.addEventListener('keypress', (event) => {
570 if (event.keyCode === 13) { // enter
571 findParent(event.target, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
572 }
573 });
574 });
575
576 // Delete a tag with an AJAX query (alert popup confirmation)
577 const deleteTagButtons = document.querySelectorAll('.delete-tag');
578 [...deleteTagButtons].forEach((rename) => {
579 rename.style.display = 'inline';
580 rename.addEventListener('click', (event) => {
581 event.preventDefault();
582 const block = findParent(event.target, 'div', { class: 'tag-list-item' });
583 const tag = block.getAttribute('data-tag');
584 const refreshedToken = document.getElementById('token');
585
586 if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
587 const xhr = new XMLHttpRequest();
588 xhr.open('POST', '?do=changetag');
589 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
590 xhr.onload = () => {
591 block.remove();
592 };
593 xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
594 refreshToken();
595
596 existingTags = existingTags.filter(tagItem => tagItem !== tag);
597 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
598 }
599 });
600 });
601
602 const autocompleteFields = document.querySelectorAll('input[data-multiple]');
603 [...autocompleteFields].forEach((autocompleteField) => {
604 awesomepletes.push(createAwesompleteInstance(autocompleteField));
605 });
606})();