]>
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() {
29 const xhr
= new XMLHttpRequest();
30 xhr
.open('GET', '?do=token');
32 const token
= document
.getElementById('token');
33 token
.setAttribute('value', xhr
.responseText
);
38 function 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} `;
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;
52 awesome
.data
= (item
, input
) => {
53 while ((match
= reg
.exec(input
))) {
54 if (item
=== match
[1]) {
69 * Update awesomplete list of tag for all elements matching the given selector
71 * @param selector CSS selector
72 * @param tags Array of tags
73 * @param instances List of existing awesomplete instances
75 function updateAwesompleteList(selector
, tags
, instances
) {
76 if (instances
.length
=== 0) {
77 // First load: create Awesomplete instances
78 const elements
= document
.querySelectorAll(selector
);
79 [...elements
].forEach((element
) => {
80 instances
.push(createAwesompleteInstance(element
, tags
));
83 // Update awesomplete tag list
84 instances
.map((item
) => {
95 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
97 function htmlEntities(str
) {
98 return str
.replace(/[\u00A0-\u9999<>&]/gim, i
=> `&#${i.charCodeAt(0)};`);
102 * Add the class 'hidden' to city options not attached to the current selected continent.
104 * @param cities List of <option> elements
105 * @param currentContinent Current selected continent
106 * @param reset Set to true to reset the selected value
108 function hideTimezoneCities(cities
, currentContinent
, reset
= null) {
113 [...cities
].forEach((option
) => {
114 if (option
.getAttribute('data-continent') !== currentContinent
) {
115 option
.className
= 'hidden';
117 option
.className
= '';
118 if (reset
=== true && first
=== true) {
119 option
.setAttribute('selected', 'selected');
127 * Retrieve an element up in the tree from its class name.
129 function getParentByClass(el
, className
) {
130 const p
= el
.parentNode
;
131 if (p
== null || p
.classList
.contains(className
)) {
134 return getParentByClass(p
, className
);
137 function toggleHorizontal() {
138 [...document
.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el
) => {
139 el
.classList
.toggle('pure-menu-horizontal');
143 function toggleMenu(menu
) {
144 // set timeout so that the panel has a chance to roll up
145 // before the menu switches states
146 if (menu
.classList
.contains('open')) {
147 setTimeout(toggleHorizontal
, 500);
151 menu
.classList
.toggle('open');
152 document
.getElementById('menu-toggle').classList
.toggle('x');
155 function closeMenu(menu
) {
156 if (menu
.classList
.contains('open')) {
161 function toggleFold(button
, description
, thumb
) {
162 // Switch fold/expand - up = fold
163 if (button
.classList
.contains('fa-chevron-up')) {
164 button
.title
= document
.getElementById('translation-expand').innerHTML
;
165 if (description
!= null) {
166 description
.style
.display
= 'none';
169 thumb
.style
.display
= 'none';
172 button
.title
= document
.getElementById('translation-fold').innerHTML
;
173 if (description
!= null) {
174 description
.style
.display
= 'block';
177 thumb
.style
.display
= 'block';
180 button
.classList
.toggle('fa-chevron-down');
181 button
.classList
.toggle('fa-chevron-up');
184 function removeClass(element
, classname
) {
185 element
.className
= element
.className
.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
188 function init(description
) {
190 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
191 const scrollTop
= window
.pageYOffset
||
192 (document
.documentElement
|| document
.body
.parentNode
|| document
.body
).scrollTop
;
194 description
.style
.height
= 'auto';
195 description
.style
.height
= `${description.scrollHeight + 10}px`;
197 window
.scrollTo(0, scrollTop
);
200 /* 0-timeout to get the already changed text */
201 function delayedResize() {
202 window
.setTimeout(resize
, 0);
205 const observe
= (element
, event
, handler
) => {
206 element
.addEventListener(event
, handler
, false);
208 observe(description
, 'change', resize
);
209 observe(description
, 'cut', delayedResize
);
210 observe(description
, 'paste', delayedResize
);
211 observe(description
, 'drop', delayedResize
);
212 observe(description
, 'keydown', delayedResize
);
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 if (!confirm(document
.getElementById('translation-delete-link').innerHTML
)) {
298 event
.preventDefault();
306 const closeLinks
= document
.querySelectorAll('.pure-alert-close');
307 [...closeLinks
].forEach((closeLink
) => {
308 closeLink
.addEventListener('click', (event
) => {
309 const alert
= getParentByClass(event
.target
, 'pure-alert-closable');
310 alert
.style
.display
= 'none';
315 * New version dismiss.
316 * Hide the message for one week using localStorage.
318 const newVersionDismiss
= document
.getElementById('new-version-dismiss');
319 const newVersionMessage
= document
.querySelector('.new-version-message');
320 if (newVersionMessage
!= null
321 && localStorage
.getItem('newVersionDismiss') != null
322 && parseInt(localStorage
.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
324 newVersionMessage
.style
.display
= 'none';
326 if (newVersionDismiss
!= null) {
327 newVersionDismiss
.addEventListener('click', () => {
328 localStorage
.setItem('newVersionDismiss', (new Date()).getTime().toString());
332 const hiddenReturnurl
= document
.getElementsByName('returnurl');
333 if (hiddenReturnurl
!= null) {
334 hiddenReturnurl
.value
= window
.location
.href
;
338 * Autofocus text fields
340 const autofocusElements
= document
.querySelectorAll('.autofocus');
341 let breakLoop
= false;
342 [].forEach
.call(autofocusElements
, (autofocusElement
) => {
343 if (autofocusElement
.value
=== '' && !breakLoop
) {
344 autofocusElement
.focus();
350 * Handle sub menus/forms
352 const openers
= document
.getElementsByClassName('subheader-opener');
353 if (openers
!= null) {
354 [...openers
].forEach((opener
) => {
355 opener
.addEventListener('click', (event
) => {
356 event
.preventDefault();
358 const id
= opener
.getAttribute('data-open-id');
359 const sub
= document
.getElementById(id
);
362 [...document
.getElementsByClassName('subheader-form')].forEach((element
) => {
363 if (element
!== sub
) {
364 removeClass(element
, 'open');
368 sub
.classList
.toggle('open');
375 * Remove CSS target padding (for fixed bar)
377 if (location
.hash
!== '') {
378 const anchor
= document
.getElementById(location
.hash
.substr(1));
379 if (anchor
!= null) {
380 const padsize
= anchor
.clientHeight
;
381 window
.scroll(0, window
.scrollY
- padsize
);
382 anchor
.style
.paddingTop
= '0';
389 const description
= document
.getElementById('lf_description');
391 if (description
!= null) {
393 // Submit editlink form with CTRL + Enter in the text area.
394 description
.addEventListener('keydown', (event
) => {
395 if (event
.ctrlKey
&& event
.keyCode
=== 13) {
396 document
.getElementById('button-save-edit').click();
404 const bookmarkletLinks
= document
.querySelectorAll('.bookmarklet-link');
405 const bkmMessage
= document
.getElementById('bookmarklet-alert');
406 [].forEach
.call(bookmarkletLinks
, (link
) => {
407 link
.addEventListener('click', (event
) => {
408 event
.preventDefault();
409 alert(bkmMessage
.value
);
413 const continent
= document
.getElementById('continent');
414 const city
= document
.getElementById('city');
415 if (continent
!= null && city
!= null) {
416 continent
.addEventListener('change', () => {
417 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, true);
419 hideTimezoneCities(city
, continent
.options
[continent
.selectedIndex
].value
, false);
425 const linkCheckboxes
= document
.querySelectorAll('.delete-checkbox');
426 const bar
= document
.getElementById('actions');
427 [...linkCheckboxes
].forEach((checkbox
) => {
428 checkbox
.style
.display
= 'inline-block';
429 checkbox
.addEventListener('click', () => {
430 const linkCheckedCheckboxes
= document
.querySelectorAll('.delete-checkbox:checked');
431 const count
= [...linkCheckedCheckboxes
].length
;
432 if (count
=== 0 && bar
.classList
.contains('open')) {
433 bar
.classList
.toggle('open');
434 } else if (count
> 0 && !bar
.classList
.contains('open')) {
435 bar
.classList
.toggle('open');
440 const deleteButton
= document
.getElementById('actions-delete');
441 const token
= document
.getElementById('token');
442 if (deleteButton
!= null && token
!= null) {
443 deleteButton
.addEventListener('click', (event
) => {
444 event
.preventDefault();
447 const linkCheckedCheckboxes
= document
.querySelectorAll('.delete-checkbox:checked');
448 [...linkCheckedCheckboxes
].forEach((checkbox
) => {
451 title: document
.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML
,
455 let message
= `Are you sure you want to delete ${links.length} links?\n`;
456 message
+= 'This action is IRREVERSIBLE!\n\nTitles:\n';
458 links
.forEach((item
) => {
459 message
+= ` - ${item.title}\n`;
463 if (window
.confirm(message
)) {
464 window
.location
= `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
470 * Tag list operations
472 * TODO: support error code in the backend for AJAX requests
474 const tagList
= document
.querySelector('input[name="taglist"]');
475 let existingTags
= tagList
? tagList
.value
.split(' ') : [];
476 let awesomepletes
= [];
478 // Display/Hide rename form
479 const renameTagButtons
= document
.querySelectorAll('.rename-tag');
480 [...renameTagButtons
].forEach((rename
) => {
481 rename
.addEventListener('click', (event
) => {
482 event
.preventDefault();
483 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
484 const form
= block
.querySelector('.rename-tag-form');
485 if (form
.style
.display
=== 'none' || form
.style
.display
=== '') {
486 form
.style
.display
= 'block';
488 form
.style
.display
= 'none';
490 block
.querySelector('input').focus();
494 // Rename a tag with an AJAX request
495 const renameTagSubmits
= document
.querySelectorAll('.validate-rename-tag');
496 [...renameTagSubmits
].forEach((rename
) => {
497 rename
.addEventListener('click', (event
) => {
498 event
.preventDefault();
499 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
500 const input
= block
.querySelector('.rename-tag-input');
501 const totag
= input
.value
.replace('/"/g', '\\"');
502 if (totag
.trim() === '') {
505 const refreshedToken
= document
.getElementById('token').value
;
506 const fromtag
= block
.getAttribute('data-tag');
507 const xhr
= new XMLHttpRequest();
508 xhr
.open('POST', '?do=changetag');
509 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
511 if (xhr
.status
!== 200) {
512 alert(`An error occurred. Return code: ${xhr.status}`);
515 block
.setAttribute('data-tag', totag
);
516 input
.setAttribute('name', totag
);
517 input
.setAttribute('value', totag
);
518 findParent(input
, 'div', { class: 'rename-tag-form' }).style
.display
= 'none';
519 block
.querySelector('a.tag-link').innerHTML
= htmlEntities(totag
);
520 block
.querySelector('a.tag-link').setAttribute('href', `?searchtags=${encodeURIComponent(totag)}`);
521 block
.querySelector('a.rename-tag').setAttribute('href', `?do=changetag&fromtag=${encodeURIComponent(totag)}`);
523 // Refresh awesomplete values
524 existingTags
= existingTags
.map(tag
=> (tag
=== fromtag
? totag : tag
));
525 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
528 xhr
.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
533 // Validate input with enter key
534 const renameTagInputs
= document
.querySelectorAll('.rename-tag-input');
535 [...renameTagInputs
].forEach((rename
) => {
536 rename
.addEventListener('keypress', (event
) => {
537 if (event
.keyCode
=== 13) { // enter
538 findParent(event
.target
, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
543 // Delete a tag with an AJAX query (alert popup confirmation)
544 const deleteTagButtons
= document
.querySelectorAll('.delete-tag');
545 [...deleteTagButtons
].forEach((rename
) => {
546 rename
.style
.display
= 'inline';
547 rename
.addEventListener('click', (event
) => {
548 event
.preventDefault();
549 const block
= findParent(event
.target
, 'div', { class: 'tag-list-item' });
550 const tag
= block
.getAttribute('data-tag');
551 const refreshedToken
= document
.getElementById('token');
553 if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
554 const xhr
= new XMLHttpRequest();
555 xhr
.open('POST', '?do=changetag');
556 xhr
.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
560 xhr
.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
563 existingTags
= existingTags
.filter(tagItem
=> tagItem
!== tag
);
564 awesomepletes
= updateAwesompleteList('.rename-tag-input', existingTags
, awesomepletes
);
569 const autocompleteFields
= document
.querySelectorAll('input[data-multiple]');
570 [...autocompleteFields
].forEach((autocompleteField
) => {
571 awesomepletes
.push(createAwesompleteInstance(autocompleteField
));