1 import Awesomplete
from 'awesomplete';
5 * Find a parent element according to its tag and its attributes
7 * @param element Element where to start the search
8 * @param tagName Expected parent tag name
9 * @param attributes Associative array of expected attributes (name=>value).
11 * @returns Found element or null.
13 function findParent(element
, tagName
, attributes
) {
14 const parentMatch
= (key
) => attributes
[key
] !== '' && element
.getAttribute(key
).indexOf(attributes
[key
]) !== -1;
16 if (element
.tagName
.toLowerCase() === tagName
) {
17 if (Object
.keys(attributes
).find(parentMatch
)) {
21 element
= element
.parentElement
;
27 * Ajax request to refresh the CSRF token.
29 function refreshToken(basePath
, callback
) {
30 const xhr
= new XMLHttpRequest();
31 xhr
.open('GET', `${basePath}/admin/token`);
33 const elements
= document
.querySelectorAll('input[name="token"]');
34 [...elements
].forEach((element
) => {
35 element
.setAttribute('value', xhr
.responseText
);
39 callback(xhr
.response
);
45 function createAwesompleteInstance(element
, tags
= []) {
46 const awesome
= new Awesomplete(Awesomplete
.$(element
));
47 // Tags are separated by a space
48 awesome
.filter
= (text
, input
) => Awesomplete
.FILTER_CONTAINS(text
, input
.match(/[^ ]*$/)[0]);
49 // Insert new selected tag in the input
50 awesome
.replace
= (text
) => {
51 const before
= awesome
.input
.value
.match(/^.+ \s
*|/)[0];
52 awesome
.input
.value
= `${before}${text} `;
54 // Highlight found items
55 awesome
.item
= (text
, input
) => Awesomplete
.ITEM(text
, input
.match(/[^ ]*$/)[0]);
56 // Don't display already selected items
57 const reg
= /(\w+) /g;
59 awesome
.data
= (item
, input
) => {
60 while ((match
= reg
.exec(input
))) {
61 if (item
=== match
[1]) {
76 * Update awesomplete list of tag for all elements matching the given selector
78 * @param selector CSS selector
79 * @param tags Array of tags
80 * @param instances List of existing awesomplete instances
82 function updateAwesompleteList(selector
, tags
, instances
) {
83 if (instances
.length
=== 0) {
84 // First load: create Awesomplete instances
85 const elements
= document
.querySelectorAll(selector
);
86 [...elements
].forEach((element
) => {
87 instances
.push(createAwesompleteInstance(element
, tags
));
90 // Update awesomplete tag list
91 instances
.map((item
) => {
100 * Add the class 'hidden' to city options not attached to the current selected continent.
102 * @param cities List of <option> elements
103 * @param currentContinent Current selected continent
104 * @param reset Set to true to reset the selected value
106 function hideTimezoneCities(cities
, currentContinent
, reset
= null) {
111 [...cities
].forEach((option
) => {
112 if (option
.getAttribute('data-continent') !== currentContinent
) {
113 option
.className
= 'hidden';
115 option
.className
= '';
116 if (reset
=== true && first
=== true) {
117 option
.setAttribute('selected', 'selected');
125 * Retrieve an element up in the tree from its class name.
127 function getParentByClass(el
, className
) {
128 const p
= el
.parentNode
;
129 if (p
== null || p
.classList
.contains(className
)) {
132 return getParentByClass(p
, className
);
135 function toggleHorizontal() {
136 [...document
.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el
) => {
137 el
.classList
.toggle('pure-menu-horizontal');
141 function toggleMenu(menu
) {
142 // set timeout so that the panel has a chance to roll up
143 // before the menu switches states
144 if (menu
.classList
.contains('open')) {
145 setTimeout(toggleHorizontal
, 500);
149 menu
.classList
.toggle('open');
150 document
.getElementById('menu-toggle').classList
.toggle('x');
153 function closeMenu(menu
) {
154 if (menu
.classList
.contains('open')) {
159 function toggleFold(button
, description
, thumb
) {
160 // Switch fold/expand - up = fold
161 if (button
.classList
.contains('fa-chevron-up')) {
162 button
.title
= document
.getElementById('translation-expand').innerHTML
;
163 if (description
!= null) {
164 description
.style
.display
= 'none';
167 thumb
.style
.display
= 'none';
170 button
.title
= document
.getElementById('translation-fold').innerHTML
;
171 if (description
!= null) {
172 description
.style
.display
= 'block';
175 thumb
.style
.display
= 'block';
178 button
.classList
.toggle('fa-chevron-down');
179 button
.classList
.toggle('fa-chevron-up');
182 function removeClass(element
, classname
) {
183 element
.className
= element
.className
.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
186 function init(description
) {
188 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
189 const scrollTop
= window
.pageYOffset
190 || (document
.documentElement
|| document
.body
.parentNode
|| document
.body
).scrollTop
;
192 description
.style
.height
= 'auto';
193 description
.style
.height
= `${description.scrollHeight + 10}px`;
195 window
.scrollTo(0, scrollTop
);
198 /* 0-timeout to get the already changed text */
199 function delayedResize() {
200 window
.setTimeout(resize
, 0);
203 const observe
= (element
, event
, handler
) => {
204 element
.addEventListener(event
, handler
, false);
206 observe(description
, 'change', resize
);
207 observe(description
, 'cut', delayedResize
);
208 observe(description
, 'paste', delayedResize
);
209 observe(description
, 'drop', delayedResize
);
210 observe(description
, 'keydown', delayedResize
);
216 const basePath
= document
.querySelector('input[name="js_base_path"]').value
;
219 * Handle responsive menu.
220 * Source: http://purecss.io/layouts/tucked-menu-vertical/
222 const menu
= document
.getElementById('shaarli-menu');
223 const WINDOW_CHANGE_EVENT
= ('onorientationchange' in window
) ? 'orientationchange' : 'resize';
225 const menuToggle
= document
.getElementById('menu-toggle');
226 if (menuToggle
!= null) {
227 menuToggle
.addEventListener('click', () => toggleMenu(menu
));
230 window
.addEventListener(WINDOW_CHANGE_EVENT
, () => closeMenu(menu
));
233 * Fold/Expand shaares description and thumbnail.
235 const foldAllButtons
= document
.getElementsByClassName('fold-all');
236 const foldButtons
= document
.getElementsByClassName('fold-button');
238 [...foldButtons
].forEach((foldButton
) => {
239 // Retrieve description
240 let description
= null;
241 let thumbnail
= null;
242 const linklistItem
= getParentByClass(foldButton
, 'linklist-item');
243 if (linklistItem
!= null) {
244 description
= linklistItem
.querySelector('.linklist-item-description');
245 thumbnail
= linklistItem
.querySelector('.linklist-item-thumbnail');
246 if (description
!= null || thumbnail
!= null) {
247 foldButton
.style
.display
= 'inline';
251 foldButton
.addEventListener('click', (event
) => {
252 event
.preventDefault();
253 toggleFold(event
.target
, description
, thumbnail
);
257 if (foldAllButtons
!= null) {
258 [].forEach
.call(foldAllButtons
, (foldAllButton
) => {
259 foldAllButton
.addEventListener('click', (event
) => {
260 event
.preventDefault();
261 const state
= foldAllButton
.firstElementChild
.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
262 [].forEach
.call(foldButtons
, (foldButton
) => {
263 if ((foldButton
.firstElementChild
.classList
.contains('fa-chevron-up') && state
=== 'down')
264 || (foldButton
.firstElementChild
.classList
.contains('fa-chevron-down') && state
=== 'up')
268 // Retrieve description
269 let description
= null;
270 let thumbnail
= null;
271 const linklistItem
= getParentByClass(foldButton
, 'linklist-item');
272 if (linklistItem
!= null) {
273 description
= linklistItem
.querySelector('.linklist-item-description');
274 thumbnail
= linklistItem
.querySelector('.linklist-item-thumbnail');
275 if (description
!= null || thumbnail
!= null) {
276 foldButton
.style
.display
= 'inline';
280 toggleFold(foldButton
.firstElementChild
, description
, thumbnail
);
282 foldAllButton
.firstElementChild
.classList
.toggle('fa-chevron-down');
283 foldAllButton
.firstElementChild
.classList
.toggle('fa-chevron-up');
284 foldAllButton
.title
= state
=== 'down'
285 ? document
.getElementById('translation-fold-all').innerHTML
286 : document
.getElementById('translation-expand-all').innerHTML
;
292 * Confirmation message before deletion.
294 const deleteLinks
= document
.querySelectorAll('.confirm-delete');
295 [...deleteLinks
].forEach((deleteLink
) => {
296 deleteLink
.addEventListener('click', (event
) => {
297 const type
= event
.currentTarget
.getAttribute('data-type') || 'link';
298 if (!confirm(document
.getElementById(`translation-delete-${type}`).innerHTML
)) {
299 event
.preventDefault();
307 const closeLinks
= document
.querySelectorAll('.pure-alert-close');
308 [...closeLinks
].forEach((closeLink
) => {
309 closeLink
.addEventListener('click', (event
) => {
310 const alert
= getParentByClass(event
.target
, 'pure-alert-closable');
311 alert
.style
.display
= 'none';
316 * New version dismiss.
317 * Hide the message for one week using localStorage.
319 const newVersionDismiss
= document
.getElementById('new-version-dismiss');
320 const newVersionMessage
= document
.querySelector('.new-version-message');
321 if (newVersionMessage
!= null
322 && localStorage
.getItem('newVersionDismiss') != null
323 && parseInt(localStorage
.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
325 newVersionMessage
.style
.display
= 'none';
327 if (newVersionDismiss
!= null) {
328 newVersionDismiss
.addEventListener('click', () => {
329 localStorage
.setItem('newVersionDismiss', (new Date()).getTime().toString());
333 const hiddenReturnurl
= document
.getElementsByName('returnurl');
334 if (hiddenReturnurl
!= null) {
335 hiddenReturnurl
.value
= window
.location
.href
;
339 * Autofocus text fields
341 const autofocusElements
= document
.querySelectorAll('.autofocus');
342 let breakLoop
= false;
343 [].forEach
.call(autofocusElements
, (autofocusElement
) => {
344 if (autofocusElement
.value
=== '' && !breakLoop
) {
345 autofocusElement
.focus();
351 * Handle sub menus/forms
353 const openers
= document
.getElementsByClassName('subheader-opener');
354 if (openers
!= null) {
355 [...openers
].forEach((opener
) => {
356 opener
.addEventListener('click', (event
) => {
357 event
.preventDefault();
359 const id
= opener
.getAttribute('data-open-id');
360 const sub
= document
.getElementById(id
);
363 [...document
.getElementsByClassName('subheader-form')].forEach((element
) => {
364 if (element
!== sub
) {
365 removeClass(element
, 'open');
369 sub
.classList
.toggle('open');
376 * Remove CSS target padding (for fixed bar)
378 if (location
.hash
!== '') {
379 const anchor
= document
.getElementById(location
.hash
.substr(1));
380 if (anchor
!= null) {
381 const padsize
= anchor
.clientHeight
;
382 window
.scroll(0, window
.scrollY
- padsize
);
383 anchor
.style
.paddingTop
= '0';
390 const description
= document
.getElementById('lf_description');
392 if (description
!= null) {
394 // Submit editlink form with CTRL + Enter in the text area.
395 description
.addEventListener('keydown', (event
) => {
396 if (event
.ctrlKey
&& event
.keyCode
=== 13) {
397 document
.getElementById('button-save-edit').click();
405 const bookmarkletLinks
= document
.querySelectorAll('.bookmarklet-link');
406 const bkmMessage
= document
.getElementById('bookmarklet-alert');
407 [].forEach
.call(bookmarkletLinks
, (link
) => {
408 link
.addEventListener('click', (event
) => {
409 event
.preventDefault();
410 alert(bkmMessage
.value
);
414 const continent
= document
.getElementById('continent');
415 const city
= document
.getElementById('city');
416 if (continent
!= null && city
!= null) {
417 continent
.addEventListener('change', () => {
418 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, true);
420 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, false);
426 const linkCheckboxes
= document
.querySelectorAll('.link-checkbox');
427 const bar
= document
.getElementById('actions');
428 [...linkCheckboxes
].forEach((checkbox
) => {
429 checkbox
.style
.display
= 'inline-block';
430 checkbox
.addEventListener('change', () => {
431 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
432 const count
= [...linkCheckedCheckboxes
].length
;
433 if (count
=== 0 && bar
.classList
.contains('open')) {
434 bar
.classList
.toggle('open');
435 } else if (count
> 0 && !bar
.classList
.contains('open')) {
436 bar
.classList
.toggle('open');
441 const deleteButton
= document
.getElementById('actions-delete');
442 const token
= document
.getElementById('token');
443 if (deleteButton
!= null && token
!= null) {
444 deleteButton
.addEventListener('click', (event
) => {
445 event
.preventDefault();
448 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
449 [...linkCheckedCheckboxes
].forEach((checkbox
) => {
452 title: document
.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML
,
456 let message
= `Are you sure you want to delete ${links.length} links?\n`;
457 message
+= 'This action is IRREVERSIBLE!\n\nTitles:\n';
459 links
.forEach((item
) => {
460 message
+= ` - ${item.title}\n`;
464 if (window
.confirm(message
)) {
465 window
.location
= `${basePath}/admin/shaare/delete?id=${ids.join('+')}&token=${token.value}`;
470 const changeVisibilityButtons
= document
.querySelectorAll('.actions-change-visibility');
471 if (changeVisibilityButtons
!= null && token
!= null) {
472 [...changeVisibilityButtons
].forEach((button
) => {
473 button
.addEventListener('click', (event
) => {
474 event
.preventDefault();
475 const visibility
= event
.target
.getAttribute('data-visibility');
478 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
479 [...linkCheckedCheckboxes
].forEach((checkbox
) => {
482 title: document
.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML
,
486 const ids
= links
.map((item
) => item
.id
);
488 `${basePath}/admin/shaare/visibility?token=${token.value}&newVisibility=${visibility}&id=${ids.join('+')}`
497 const selectAllButtons
= document
.querySelectorAll('.select-all-button');
498 [...selectAllButtons
].forEach((selectAllButton
) => {
499 selectAllButton
.addEventListener('click', (e
) => {
501 const checked
= selectAllButton
.classList
.contains('filter-off');
502 [...selectAllButtons
].forEach((selectAllButton2
) => {
503 selectAllButton2
.classList
.toggle('filter-off');
504 selectAllButton2
.classList
.toggle('filter-on');
506 [...linkCheckboxes
].forEach((linkCheckbox
) => {
507 linkCheckbox
.checked
= checked
;
508 linkCheckbox
.dispatchEvent(new Event('change'));
514 * Tag list operations
516 * TODO: support error code in the backend for AJAX requests
518 const tagList
= document
.querySelector('input[name="taglist"]');
519 let existingTags
= tagList
? tagList
.value
.split(' ') : [];
520 let awesomepletes
= [];
522 // Display/Hide rename form
523 const renameTagButtons
= document
.querySelectorAll('.rename-tag');
524 [...renameTagButtons
].forEach((rename
) => {
525 rename
.addEventListener('click', (event
) => {
526 event
.preventDefault();
527 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
528 const form
= block
.querySelector('.rename-tag-form');
529 if (form
.style
.display
=== 'none' || form
.style
.display
=== '') {
530 form
.style
.display
= 'block';
532 form
.style
.display
= 'none';
534 block
.querySelector('input').focus();
538 // Rename a tag with an AJAX request
539 const renameTagSubmits
= document
.querySelectorAll('.validate-rename-tag');
540 [...renameTagSubmits
].forEach((rename
) => {
541 rename
.addEventListener('click', (event
) => {
542 event
.preventDefault();
543 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
544 const input
= block
.querySelector('.rename-tag-input');
545 const totag
= input
.value
.replace('/"/g', '\\"');
546 if (totag
.trim() === '') {
549 const refreshedToken
= document
.getElementById('token').value
;
550 const fromtag
= block
.getAttribute('data-tag');
551 const fromtagUrl
= block
.getAttribute('data-tag-url');
552 const xhr
= new XMLHttpRequest();
553 xhr
.open('POST', `${basePath}/admin/tags`);
554 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
556 if (xhr
.status
!== 200) {
557 alert(`An error occurred. Return code: ${xhr.status}`);
560 block
.setAttribute('data-tag', totag
);
561 block
.setAttribute('data-tag-url', encodeURIComponent(totag
));
562 input
.setAttribute('name', totag
);
563 input
.setAttribute('value', totag
);
564 findParent(input
, 'div', { class: 'rename-tag-form' }).style
.display
= 'none';
565 block
.querySelector('a.tag-link').innerHTML
= he
.encode(totag
);
567 .querySelector('a.tag-link')
568 .setAttribute('href', `${basePath}/?searchtags=${encodeURIComponent(totag)}`);
570 .querySelector('a.count')
571 .setAttribute('href', `${basePath}/add-tag/${encodeURIComponent(totag)}`);
573 .querySelector('a.rename-tag')
574 .setAttribute('href', `${basePath}/admin/tags?fromtag=${encodeURIComponent(totag)}`);
576 // Refresh awesomplete values
577 existingTags
= existingTags
.map((tag
) => (tag
=== fromtag
? totag : tag
));
578 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
581 xhr
.send(`renametag=1&fromtag=${fromtagUrl}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
582 refreshToken(basePath
);
586 // Validate input with enter key
587 const renameTagInputs
= document
.querySelectorAll('.rename-tag-input');
588 [...renameTagInputs
].forEach((rename
) => {
589 rename
.addEventListener('keypress', (event
) => {
590 if (event
.keyCode
=== 13) { // enter
591 findParent(event
.target
, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
596 // Delete a tag with an AJAX query (alert popup confirmation)
597 const deleteTagButtons
= document
.querySelectorAll('.delete-tag');
598 [...deleteTagButtons
].forEach((rename
) => {
599 rename
.style
.display
= 'inline';
600 rename
.addEventListener('click', (event
) => {
601 event
.preventDefault();
602 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
603 const tag
= block
.getAttribute('data-tag');
604 const tagUrl
= block
.getAttribute('data-tag-url');
605 const refreshedToken
= document
.getElementById('token').value
;
607 if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
608 const xhr
= new XMLHttpRequest();
609 xhr
.open('POST', `${basePath}/admin/tags`);
610 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
614 xhr
.send(`deletetag=1&fromtag=${tagUrl}&token=${refreshedToken}`);
615 refreshToken(basePath
);
617 existingTags
= existingTags
.filter((tagItem
) => tagItem
!== tag
);
618 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
623 const autocompleteFields
= document
.querySelectorAll('input[data-multiple]');
624 [...autocompleteFields
].forEach((autocompleteField
) => {
625 awesomepletes
.push(createAwesompleteInstance(autocompleteField
));
628 const exportForm
= document
.querySelector('#exportform');
629 if (exportForm
!= null) {
630 exportForm
.addEventListener('submit', (event
) => {
631 event
.preventDefault();
633 refreshToken(basePath
, () => {
634 event
.target
.submit();
639 const bulkCreationButton
= document
.querySelector('.addlink-batch-show-more-block');
640 if (bulkCreationButton
!= null) {
641 const toggleBulkCreationVisibility
= (showMoreBlockElement
, formElement
) => {
642 if (bulkCreationButton
.classList
.contains('pure-u-0')) {
643 showMoreBlockElement
.classList
.remove('pure-u-0');
644 formElement
.classList
.add('pure-u-0');
646 showMoreBlockElement
.classList
.add('pure-u-0');
647 formElement
.classList
.remove('pure-u-0');
651 const bulkCreationForm
= document
.querySelector('.addlink-batch-form-block');
653 toggleBulkCreationVisibility(bulkCreationButton
, bulkCreationForm
);
654 bulkCreationButton
.querySelector('a').addEventListener('click', (e
) => {
656 toggleBulkCreationVisibility(bulkCreationButton
, bulkCreationForm
);
659 // Force to send falsy value if the checkbox is not checked.
660 const privateButton
= bulkCreationForm
.querySelector('input[type="checkbox"][name="private"]');
661 const privateHiddenButton
= bulkCreationForm
.querySelector('input[type="hidden"][name="private"]');
662 privateButton
.addEventListener('click', () => {
663 privateHiddenButton
.disabled
= !privateHiddenButton
.disabled
;
665 privateHiddenButton
.disabled
= privateButton
.checked
;