]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - assets/default/js/base.js
Use version condition in the root .htaccess
[github/shaarli/Shaarli.git] / assets / default / js / base.js
1 import Awesomplete from 'awesomplete';
2
3 /**
4 * Find a parent element according to its tag and its attributes
5 *
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).
9 *
10 * @returns Found element or null.
11 */
12 function findParent(element, tagName, attributes) {
13 const parentMatch = key => attributes[key] !== '' && element.getAttribute(key).indexOf(attributes[key]) !== -1;
14 while (element) {
15 if (element.tagName.toLowerCase() === tagName) {
16 if (Object.keys(attributes).find(parentMatch)) {
17 return element;
18 }
19 }
20 element = element.parentElement;
21 }
22 return null;
23 }
24
25 /**
26 * Ajax request to refresh the CSRF token.
27 */
28 function refreshToken() {
29 const xhr = new XMLHttpRequest();
30 xhr.open('GET', '?do=token');
31 xhr.onload = () => {
32 const token = document.getElementById('token');
33 token.setAttribute('value', xhr.responseText);
34 };
35 xhr.send();
36 }
37
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} `;
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;
66 }
67
68 /**
69 * Update awesomplete list of tag for all elements matching the given selector
70 *
71 * @param selector CSS selector
72 * @param tags Array of tags
73 * @param instances List of existing awesomplete instances
74 */
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));
81 });
82 } else {
83 // Update awesomplete tag list
84 instances.map((item) => {
85 item.list = tags;
86 return item;
87 });
88 }
89 return instances;
90 }
91
92 /**
93 * html_entities in JS
94 *
95 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
96 */
97 function htmlEntities(str) {
98 return str.replace(/[\u00A0-\u9999<>&]/gim, i => `&#${i.charCodeAt(0)};`);
99 }
100
101 /**
102 * Add the class 'hidden' to city options not attached to the current selected continent.
103 *
104 * @param cities List of <option> elements
105 * @param currentContinent Current selected continent
106 * @param reset Set to true to reset the selected value
107 */
108 function hideTimezoneCities(cities, currentContinent, reset = null) {
109 let first = true;
110 if (reset == null) {
111 reset = false;
112 }
113 [...cities].forEach((option) => {
114 if (option.getAttribute('data-continent') !== currentContinent) {
115 option.className = 'hidden';
116 } else {
117 option.className = '';
118 if (reset === true && first === true) {
119 option.setAttribute('selected', 'selected');
120 first = false;
121 }
122 }
123 });
124 }
125
126 /**
127 * Retrieve an element up in the tree from its class name.
128 */
129 function getParentByClass(el, className) {
130 const p = el.parentNode;
131 if (p == null || p.classList.contains(className)) {
132 return p;
133 }
134 return getParentByClass(p, className);
135 }
136
137 function toggleHorizontal() {
138 [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
139 el.classList.toggle('pure-menu-horizontal');
140 });
141 }
142
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);
148 } else {
149 toggleHorizontal();
150 }
151 menu.classList.toggle('open');
152 document.getElementById('menu-toggle').classList.toggle('x');
153 }
154
155 function closeMenu(menu) {
156 if (menu.classList.contains('open')) {
157 toggleMenu(menu);
158 }
159 }
160
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';
167 }
168 if (thumb != null) {
169 thumb.style.display = 'none';
170 }
171 } else {
172 button.title = document.getElementById('translation-fold').innerHTML;
173 if (description != null) {
174 description.style.display = 'block';
175 }
176 if (thumb != null) {
177 thumb.style.display = 'block';
178 }
179 }
180 button.classList.toggle('fa-chevron-down');
181 button.classList.toggle('fa-chevron-up');
182 }
183
184 function removeClass(element, classname) {
185 element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
186 }
187
188 function init(description) {
189 function resize() {
190 /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
191 const scrollTop = window.pageYOffset ||
192 (document.documentElement || document.body.parentNode || document.body).scrollTop;
193
194 description.style.height = 'auto';
195 description.style.height = `${description.scrollHeight + 10}px`;
196
197 window.scrollTo(0, scrollTop);
198 }
199
200 /* 0-timeout to get the already changed text */
201 function delayedResize() {
202 window.setTimeout(resize, 0);
203 }
204
205 const observe = (element, event, handler) => {
206 element.addEventListener(event, handler, false);
207 };
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);
213
214 resize();
215 }
216
217 (() => {
218 /**
219 * Handle responsive menu.
220 * Source: http://purecss.io/layouts/tucked-menu-vertical/
221 */
222 const menu = document.getElementById('shaarli-menu');
223 const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
224
225 const menuToggle = document.getElementById('menu-toggle');
226 if (menuToggle != null) {
227 menuToggle.addEventListener('click', () => toggleMenu(menu));
228 }
229
230 window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
231
232 /**
233 * Fold/Expand shaares description and thumbnail.
234 */
235 const foldAllButtons = document.getElementsByClassName('fold-all');
236 const foldButtons = document.getElementsByClassName('fold-button');
237
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';
248 }
249 }
250
251 foldButton.addEventListener('click', (event) => {
252 event.preventDefault();
253 toggleFold(event.target, description, thumbnail);
254 });
255 });
256
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')
265 ) {
266 return;
267 }
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';
277 }
278 }
279
280 toggleFold(foldButton.firstElementChild, description, thumbnail);
281 });
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;
287 });
288 });
289 }
290
291 /**
292 * Confirmation message before deletion.
293 */
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();
299 }
300 });
301 });
302
303 /**
304 * Close alerts
305 */
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';
311 });
312 });
313
314 /**
315 * New version dismiss.
316 * Hide the message for one week using localStorage.
317 */
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()
323 ) {
324 newVersionMessage.style.display = 'none';
325 }
326 if (newVersionDismiss != null) {
327 newVersionDismiss.addEventListener('click', () => {
328 localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
329 });
330 }
331
332 const hiddenReturnurl = document.getElementsByName('returnurl');
333 if (hiddenReturnurl != null) {
334 hiddenReturnurl.value = window.location.href;
335 }
336
337 /**
338 * Autofocus text fields
339 */
340 const autofocusElements = document.querySelectorAll('.autofocus');
341 let breakLoop = false;
342 [].forEach.call(autofocusElements, (autofocusElement) => {
343 if (autofocusElement.value === '' && !breakLoop) {
344 autofocusElement.focus();
345 breakLoop = true;
346 }
347 });
348
349 /**
350 * Handle sub menus/forms
351 */
352 const openers = document.getElementsByClassName('subheader-opener');
353 if (openers != null) {
354 [...openers].forEach((opener) => {
355 opener.addEventListener('click', (event) => {
356 event.preventDefault();
357
358 const id = opener.getAttribute('data-open-id');
359 const sub = document.getElementById(id);
360
361 if (sub != null) {
362 [...document.getElementsByClassName('subheader-form')].forEach((element) => {
363 if (element !== sub) {
364 removeClass(element, 'open');
365 }
366 });
367
368 sub.classList.toggle('open');
369 }
370 });
371 });
372 }
373
374 /**
375 * Remove CSS target padding (for fixed bar)
376 */
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';
383 }
384 }
385
386 /**
387 * Text area resizer
388 */
389 const description = document.getElementById('lf_description');
390
391 if (description != null) {
392 init(description);
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();
397 }
398 });
399 }
400
401 /**
402 * Bookmarklet alert
403 */
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);
410 });
411 });
412
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);
418 });
419 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
420 }
421
422 /**
423 * Bulk actions
424 */
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');
436 }
437 });
438 });
439
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();
445
446 const links = [];
447 const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
448 [...linkCheckedCheckboxes].forEach((checkbox) => {
449 links.push({
450 id: checkbox.value,
451 title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
452 });
453 });
454
455 let message = `Are you sure you want to delete ${links.length} links?\n`;
456 message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
457 const ids = [];
458 links.forEach((item) => {
459 message += ` - ${item.title}\n`;
460 ids.push(item.id);
461 });
462
463 if (window.confirm(message)) {
464 window.location = `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
465 }
466 });
467 }
468
469 /**
470 * Tag list operations
471 *
472 * TODO: support error code in the backend for AJAX requests
473 */
474 const tagList = document.querySelector('input[name="taglist"]');
475 let existingTags = tagList ? tagList.value.split(' ') : [];
476 let awesomepletes = [];
477
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';
487 } else {
488 form.style.display = 'none';
489 }
490 block.querySelector('input').focus();
491 });
492 });
493
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() === '') {
503 return;
504 }
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');
510 xhr.onload = () => {
511 if (xhr.status !== 200) {
512 alert(`An error occurred. Return code: ${xhr.status}`);
513 location.reload();
514 } else {
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)}`);
522
523 // Refresh awesomplete values
524 existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
525 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
526 }
527 };
528 xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
529 refreshToken();
530 });
531 });
532
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();
539 }
540 });
541 });
542
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');
552
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');
557 xhr.onload = () => {
558 block.remove();
559 };
560 xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
561 refreshToken();
562
563 existingTags = existingTags.filter(tagItem => tagItem !== tag);
564 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
565 }
566 });
567 });
568
569 const autocompleteFields = document.querySelectorAll('input[data-multiple]');
570 [...autocompleteFields].forEach((autocompleteField) => {
571 awesomepletes.push(createAwesompleteInstance(autocompleteField));
572 });
573 })();