]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - assets/default/js/base.js
1 import Awesomplete
from 'awesomplete';
4 * Find a parent element according to its tag and its attributes
6 * @param element Element where to start the search
7 * @param tagName Expected parent tag name
8 * @param attributes Associative array of expected attributes (name=>value).
10 * @returns Found element or null.
12 function findParent(element
, tagName
, attributes
) {
13 const parentMatch
= (key
) => attributes
[key
] !== '' && element
.getAttribute(key
).indexOf(attributes
[key
]) !== -1;
15 if (element
.tagName
.toLowerCase() === tagName
) {
16 if (Object
.keys(attributes
).find(parentMatch
)) {
20 element
= element
.parentElement
;
26 * Ajax request to refresh the CSRF token.
28 function refreshToken(basePath
, callback
) {
29 const xhr
= new XMLHttpRequest();
30 xhr
.open('GET', `${basePath}/admin/token`);
32 const elements
= document
.querySelectorAll('input[name="token"]');
33 [...elements
].forEach((element
) => {
34 element
.setAttribute('value', xhr
.responseText
);
38 callback(xhr
.response
);
44 function createAwesompleteInstance(element
, tags
= []) {
45 const awesome
= new Awesomplete(Awesomplete
.$(element
));
46 // Tags are separated by a space
47 awesome
.filter
= (text
, input
) => Awesomplete
.FILTER_CONTAINS(text
, input
.match(/[^ ]*$/)[0]);
48 // Insert new selected tag in the input
49 awesome
.replace
= (text
) => {
50 const before
= awesome
.input
.value
.match(/^.+ \s
*|/)[0];
51 awesome
.input
.value
= `${before}${text} `;
53 // Highlight found items
54 awesome
.item
= (text
, input
) => Awesomplete
.ITEM(text
, input
.match(/[^ ]*$/)[0]);
55 // Don't display already selected items
56 const reg
= /(\w+) /g;
58 awesome
.data
= (item
, input
) => {
59 while ((match
= reg
.exec(input
))) {
60 if (item
=== match
[1]) {
75 * Update awesomplete list of tag for all elements matching the given selector
77 * @param selector CSS selector
78 * @param tags Array of tags
79 * @param instances List of existing awesomplete instances
81 function updateAwesompleteList(selector
, tags
, instances
) {
82 if (instances
.length
=== 0) {
83 // First load: create Awesomplete instances
84 const elements
= document
.querySelectorAll(selector
);
85 [...elements
].forEach((element
) => {
86 instances
.push(createAwesompleteInstance(element
, tags
));
89 // Update awesomplete tag list
90 instances
.map((item
) => {
101 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
103 function htmlEntities(str
) {
104 return str
.replace(/[\u00A0-\u9999<>&]/gim, (i
) => `&#${i.charCodeAt(0)};`);
108 * Add the class 'hidden' to city options not attached to the current selected continent.
110 * @param cities List of <option> elements
111 * @param currentContinent Current selected continent
112 * @param reset Set to true to reset the selected value
114 function hideTimezoneCities(cities
, currentContinent
, reset
= null) {
119 [...cities
].forEach((option
) => {
120 if (option
.getAttribute('data-continent') !== currentContinent
) {
121 option
.className
= 'hidden';
123 option
.className
= '';
124 if (reset
=== true && first
=== true) {
125 option
.setAttribute('selected', 'selected');
133 * Retrieve an element up in the tree from its class name.
135 function getParentByClass(el
, className
) {
136 const p
= el
.parentNode
;
137 if (p
== null || p
.classList
.contains(className
)) {
140 return getParentByClass(p
, className
);
143 function toggleHorizontal() {
144 [...document
.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el
) => {
145 el
.classList
.toggle('pure-menu-horizontal');
149 function toggleMenu(menu
) {
150 // set timeout so that the panel has a chance to roll up
151 // before the menu switches states
152 if (menu
.classList
.contains('open')) {
153 setTimeout(toggleHorizontal
, 500);
157 menu
.classList
.toggle('open');
158 document
.getElementById('menu-toggle').classList
.toggle('x');
161 function closeMenu(menu
) {
162 if (menu
.classList
.contains('open')) {
167 function toggleFold(button
, description
, thumb
) {
168 // Switch fold/expand - up = fold
169 if (button
.classList
.contains('fa-chevron-up')) {
170 button
.title
= document
.getElementById('translation-expand').innerHTML
;
171 if (description
!= null) {
172 description
.style
.display
= 'none';
175 thumb
.style
.display
= 'none';
178 button
.title
= document
.getElementById('translation-fold').innerHTML
;
179 if (description
!= null) {
180 description
.style
.display
= 'block';
183 thumb
.style
.display
= 'block';
186 button
.classList
.toggle('fa-chevron-down');
187 button
.classList
.toggle('fa-chevron-up');
190 function removeClass(element
, classname
) {
191 element
.className
= element
.className
.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
194 function init(description
) {
196 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
197 const scrollTop
= window
.pageYOffset
198 || (document
.documentElement
|| document
.body
.parentNode
|| document
.body
).scrollTop
;
200 description
.style
.height
= 'auto';
201 description
.style
.height
= `${description.scrollHeight + 10}px`;
203 window
.scrollTo(0, scrollTop
);
206 /* 0-timeout to get the already changed text */
207 function delayedResize() {
208 window
.setTimeout(resize
, 0);
211 const observe
= (element
, event
, handler
) => {
212 element
.addEventListener(event
, handler
, false);
214 observe(description
, 'change', resize
);
215 observe(description
, 'cut', delayedResize
);
216 observe(description
, 'paste', delayedResize
);
217 observe(description
, 'drop', delayedResize
);
218 observe(description
, 'keydown', delayedResize
);
224 const basePath
= document
.querySelector('input[name="js_base_path"]').value
;
227 * Handle responsive menu.
228 * Source: http://purecss.io/layouts/tucked-menu-vertical/
230 const menu
= document
.getElementById('shaarli-menu');
231 const WINDOW_CHANGE_EVENT
= ('onorientationchange' in window
) ? 'orientationchange' : 'resize';
233 const menuToggle
= document
.getElementById('menu-toggle');
234 if (menuToggle
!= null) {
235 menuToggle
.addEventListener('click', () => toggleMenu(menu
));
238 window
.addEventListener(WINDOW_CHANGE_EVENT
, () => closeMenu(menu
));
241 * Fold/Expand shaares description and thumbnail.
243 const foldAllButtons
= document
.getElementsByClassName('fold-all');
244 const foldButtons
= document
.getElementsByClassName('fold-button');
246 [...foldButtons
].forEach((foldButton
) => {
247 // Retrieve description
248 let description
= null;
249 let thumbnail
= null;
250 const linklistItem
= getParentByClass(foldButton
, 'linklist-item');
251 if (linklistItem
!= null) {
252 description
= linklistItem
.querySelector('.linklist-item-description');
253 thumbnail
= linklistItem
.querySelector('.linklist-item-thumbnail');
254 if (description
!= null || thumbnail
!= null) {
255 foldButton
.style
.display
= 'inline';
259 foldButton
.addEventListener('click', (event
) => {
260 event
.preventDefault();
261 toggleFold(event
.target
, description
, thumbnail
);
265 if (foldAllButtons
!= null) {
266 [].forEach
.call(foldAllButtons
, (foldAllButton
) => {
267 foldAllButton
.addEventListener('click', (event
) => {
268 event
.preventDefault();
269 const state
= foldAllButton
.firstElementChild
.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
270 [].forEach
.call(foldButtons
, (foldButton
) => {
271 if ((foldButton
.firstElementChild
.classList
.contains('fa-chevron-up') && state
=== 'down')
272 || (foldButton
.firstElementChild
.classList
.contains('fa-chevron-down') && state
=== 'up')
276 // Retrieve description
277 let description
= null;
278 let thumbnail
= null;
279 const linklistItem
= getParentByClass(foldButton
, 'linklist-item');
280 if (linklistItem
!= null) {
281 description
= linklistItem
.querySelector('.linklist-item-description');
282 thumbnail
= linklistItem
.querySelector('.linklist-item-thumbnail');
283 if (description
!= null || thumbnail
!= null) {
284 foldButton
.style
.display
= 'inline';
288 toggleFold(foldButton
.firstElementChild
, description
, thumbnail
);
290 foldAllButton
.firstElementChild
.classList
.toggle('fa-chevron-down');
291 foldAllButton
.firstElementChild
.classList
.toggle('fa-chevron-up');
292 foldAllButton
.title
= state
=== 'down'
293 ? document
.getElementById('translation-fold-all').innerHTML
294 : document
.getElementById('translation-expand-all').innerHTML
;
300 * Confirmation message before deletion.
302 const deleteLinks
= document
.querySelectorAll('.confirm-delete');
303 [...deleteLinks
].forEach((deleteLink
) => {
304 deleteLink
.addEventListener('click', (event
) => {
305 if (!confirm(document
.getElementById('translation-delete-link').innerHTML
)) {
306 event
.preventDefault();
314 const closeLinks
= document
.querySelectorAll('.pure-alert-close');
315 [...closeLinks
].forEach((closeLink
) => {
316 closeLink
.addEventListener('click', (event
) => {
317 const alert
= getParentByClass(event
.target
, 'pure-alert-closable');
318 alert
.style
.display
= 'none';
323 * New version dismiss.
324 * Hide the message for one week using localStorage.
326 const newVersionDismiss
= document
.getElementById('new-version-dismiss');
327 const newVersionMessage
= document
.querySelector('.new-version-message');
328 if (newVersionMessage
!= null
329 && localStorage
.getItem('newVersionDismiss') != null
330 && parseInt(localStorage
.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
332 newVersionMessage
.style
.display
= 'none';
334 if (newVersionDismiss
!= null) {
335 newVersionDismiss
.addEventListener('click', () => {
336 localStorage
.setItem('newVersionDismiss', (new Date()).getTime().toString());
340 const hiddenReturnurl
= document
.getElementsByName('returnurl');
341 if (hiddenReturnurl
!= null) {
342 hiddenReturnurl
.value
= window
.location
.href
;
346 * Autofocus text fields
348 const autofocusElements
= document
.querySelectorAll('.autofocus');
349 let breakLoop
= false;
350 [].forEach
.call(autofocusElements
, (autofocusElement
) => {
351 if (autofocusElement
.value
=== '' && !breakLoop
) {
352 autofocusElement
.focus();
358 * Handle sub menus/forms
360 const openers
= document
.getElementsByClassName('subheader-opener');
361 if (openers
!= null) {
362 [...openers
].forEach((opener
) => {
363 opener
.addEventListener('click', (event
) => {
364 event
.preventDefault();
366 const id
= opener
.getAttribute('data-open-id');
367 const sub
= document
.getElementById(id
);
370 [...document
.getElementsByClassName('subheader-form')].forEach((element
) => {
371 if (element
!== sub
) {
372 removeClass(element
, 'open');
376 sub
.classList
.toggle('open');
383 * Remove CSS target padding (for fixed bar)
385 if (location
.hash
!== '') {
386 const anchor
= document
.getElementById(location
.hash
.substr(1));
387 if (anchor
!= null) {
388 const padsize
= anchor
.clientHeight
;
389 window
.scroll(0, window
.scrollY
- padsize
);
390 anchor
.style
.paddingTop
= '0';
397 const description
= document
.getElementById('lf_description');
399 if (description
!= null) {
401 // Submit editlink form with CTRL + Enter in the text area.
402 description
.addEventListener('keydown', (event
) => {
403 if (event
.ctrlKey
&& event
.keyCode
=== 13) {
404 document
.getElementById('button-save-edit').click();
412 const bookmarkletLinks
= document
.querySelectorAll('.bookmarklet-link');
413 const bkmMessage
= document
.getElementById('bookmarklet-alert');
414 [].forEach
.call(bookmarkletLinks
, (link
) => {
415 link
.addEventListener('click', (event
) => {
416 event
.preventDefault();
417 alert(bkmMessage
.value
);
421 const continent
= document
.getElementById('continent');
422 const city
= document
.getElementById('city');
423 if (continent
!= null && city
!= null) {
424 continent
.addEventListener('change', () => {
425 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, true);
427 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, false);
433 const linkCheckboxes
= document
.querySelectorAll('.link-checkbox');
434 const bar
= document
.getElementById('actions');
435 [...linkCheckboxes
].forEach((checkbox
) => {
436 checkbox
.style
.display
= 'inline-block';
437 checkbox
.addEventListener('change', () => {
438 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
439 const count
= [...linkCheckedCheckboxes
].length
;
440 if (count
=== 0 && bar
.classList
.contains('open')) {
441 bar
.classList
.toggle('open');
442 } else if (count
> 0 && !bar
.classList
.contains('open')) {
443 bar
.classList
.toggle('open');
448 const deleteButton
= document
.getElementById('actions-delete');
449 const token
= document
.getElementById('token');
450 if (deleteButton
!= null && token
!= null) {
451 deleteButton
.addEventListener('click', (event
) => {
452 event
.preventDefault();
455 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
456 [...linkCheckedCheckboxes
].forEach((checkbox
) => {
459 title: document
.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML
,
463 let message
= `Are you sure you want to delete ${links.length} links?\n`;
464 message
+= 'This action is IRREVERSIBLE!\n\nTitles:\n';
466 links
.forEach((item
) => {
467 message
+= ` - ${item.title}\n`;
471 if (window
.confirm(message
)) {
472 window
.location
= `${basePath}/admin/shaare/delete?id=${ids.join('+')}&token=${token.value}`;
477 const changeVisibilityButtons
= document
.querySelectorAll('.actions-change-visibility');
478 if (changeVisibilityButtons
!= null && token
!= null) {
479 [...changeVisibilityButtons
].forEach((button
) => {
480 button
.addEventListener('click', (event
) => {
481 event
.preventDefault();
482 const visibility
= event
.target
.getAttribute('data-visibility');
485 const linkCheckedCheckboxes
= document
.querySelectorAll('.link-checkbox:checked');
486 [...linkCheckedCheckboxes
].forEach((checkbox
) => {
489 title: document
.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML
,
493 const ids
= links
.map((item
) => item
.id
);
495 `${basePath}/admin/shaare/visibility?token=${token.value}&newVisibility=${visibility}&id=${ids.join('+')}`
504 const selectAllButtons
= document
.querySelectorAll('.select-all-button');
505 [...selectAllButtons
].forEach((selectAllButton
) => {
506 selectAllButton
.addEventListener('click', (e
) => {
508 const checked
= selectAllButton
.classList
.contains('filter-off');
509 [...selectAllButtons
].forEach((selectAllButton2
) => {
510 selectAllButton2
.classList
.toggle('filter-off');
511 selectAllButton2
.classList
.toggle('filter-on');
513 [...linkCheckboxes
].forEach((linkCheckbox
) => {
514 linkCheckbox
.checked
= checked
;
515 linkCheckbox
.dispatchEvent(new Event('change'));
521 * Tag list operations
523 * TODO: support error code in the backend for AJAX requests
525 const tagList
= document
.querySelector('input[name="taglist"]');
526 let existingTags
= tagList
? tagList
.value
.split(' ') : [];
527 let awesomepletes
= [];
529 // Display/Hide rename form
530 const renameTagButtons
= document
.querySelectorAll('.rename-tag');
531 [...renameTagButtons
].forEach((rename
) => {
532 rename
.addEventListener('click', (event
) => {
533 event
.preventDefault();
534 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
535 const form
= block
.querySelector('.rename-tag-form');
536 if (form
.style
.display
=== 'none' || form
.style
.display
=== '') {
537 form
.style
.display
= 'block';
539 form
.style
.display
= 'none';
541 block
.querySelector('input').focus();
545 // Rename a tag with an AJAX request
546 const renameTagSubmits
= document
.querySelectorAll('.validate-rename-tag');
547 [...renameTagSubmits
].forEach((rename
) => {
548 rename
.addEventListener('click', (event
) => {
549 event
.preventDefault();
550 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
551 const input
= block
.querySelector('.rename-tag-input');
552 const totag
= input
.value
.replace('/"/g', '\\"');
553 if (totag
.trim() === '') {
556 const refreshedToken
= document
.getElementById('token').value
;
557 const fromtag
= block
.getAttribute('data-tag');
558 const xhr
= new XMLHttpRequest();
559 xhr
.open('POST', `${basePath}/admin/tags`);
560 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
562 if (xhr
.status
!== 200) {
563 alert(`An error occurred. Return code: ${xhr.status}`);
566 block
.setAttribute('data-tag', totag
);
567 input
.setAttribute('name', totag
);
568 input
.setAttribute('value', totag
);
569 findParent(input
, 'div', { class: 'rename-tag-form' }).style
.display
= 'none';
570 block
.querySelector('a.tag-link').innerHTML
= htmlEntities(totag
);
572 .querySelector('a.tag-link')
573 .setAttribute('href', `${basePath}/?searchtags=${encodeURIComponent(totag)}`);
575 .querySelector('a.rename-tag')
576 .setAttribute('href', `${basePath}/admin/tags?fromtag=${encodeURIComponent(totag)}`);
578 // Refresh awesomplete values
579 existingTags
= existingTags
.map((tag
) => (tag
=== fromtag
? totag : tag
));
580 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
583 xhr
.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
584 refreshToken(basePath
);
588 // Validate input with enter key
589 const renameTagInputs
= document
.querySelectorAll('.rename-tag-input');
590 [...renameTagInputs
].forEach((rename
) => {
591 rename
.addEventListener('keypress', (event
) => {
592 if (event
.keyCode
=== 13) { // enter
593 findParent(event
.target
, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
598 // Delete a tag with an AJAX query (alert popup confirmation)
599 const deleteTagButtons
= document
.querySelectorAll('.delete-tag');
600 [...deleteTagButtons
].forEach((rename
) => {
601 rename
.style
.display
= 'inline';
602 rename
.addEventListener('click', (event
) => {
603 event
.preventDefault();
604 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
605 const tag
= block
.getAttribute('data-tag');
606 const refreshedToken
= document
.getElementById('token').value
;
608 if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
609 const xhr
= new XMLHttpRequest();
610 xhr
.open('POST', `${basePath}/admin/tags`);
611 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
615 xhr
.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
616 refreshToken(basePath
);
618 existingTags
= existingTags
.filter((tagItem
) => tagItem
!== tag
);
619 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
624 const autocompleteFields
= document
.querySelectorAll('input[data-multiple]');
625 [...autocompleteFields
].forEach((autocompleteField
) => {
626 awesomepletes
.push(createAwesompleteInstance(autocompleteField
));
629 const exportForm
= document
.querySelector('#exportform');
630 if (exportForm
!= null) {
631 exportForm
.addEventListener('submit', (event
) => {
632 event
.preventDefault();
634 refreshToken(basePath
, () => {
635 event
.target
.submit();