]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - assets/default/js/base.js
Use multi-level routes for existing controllers instead of 1 level everywhere
[github/shaarli/Shaarli.git] / assets / default / js / base.js
CommitLineData
a33c5653 1import Awesomplete from 'awesomplete';
b9b41d25 2
82e3bb5f
A
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 */
a33c5653
A
12function 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 }
aa4797ba 19 }
a33c5653
A
20 element = element.parentElement;
21 }
22 return null;
aa4797ba
A
23}
24
82e3bb5f
A
25/**
26 * Ajax request to refresh the CSRF token.
27 */
818b3193 28function refreshToken(basePath) {
a33c5653 29 const xhr = new XMLHttpRequest();
818b3193 30 xhr.open('GET', `${basePath}/?do=token`);
a33c5653
A
31 xhr.onload = () => {
32 const token = document.getElementById('token');
33 token.setAttribute('value', xhr.responseText);
34 };
35 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;
aa4797ba
A
66}
67
82e3bb5f
A
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 */
a33c5653
A
75function updateAwesompleteList(selector, tags, instances) {
76 if (instances.length === 0) {
82e3bb5f 77 // First load: create Awesomplete instances
a33c5653
A
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;
82e3bb5f
A
90}
91
aa4797ba
A
92/**
93 * html_entities in JS
94 *
95 * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
96 */
a33c5653
A
97function htmlEntities(str) {
98 return str.replace(/[\u00A0-\u9999<>&]/gim, i => `&#${i.charCodeAt(0)};`);
aa4797ba
A
99}
100
a0737313
A
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 */
a33c5653
A
108function 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 }
aa4797ba 122 }
a33c5653
A
123 });
124}
125
126/**
127 * Retrieve an element up in the tree from its class name.
128 */
129function 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
137function toggleHorizontal() {
138 [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
139 el.classList.toggle('pure-menu-horizontal');
140 });
141}
142
143function 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
155function closeMenu(menu) {
156 if (menu.classList.contains('open')) {
157 toggleMenu(menu);
158 }
159}
160
161function 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
184function removeClass(element, classname) {
185 element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
186}
187
188function 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(() => {
818b3193
A
218 const basePath = document.querySelector('input[name="js_base_path"]').value;
219
a33c5653
A
220 /**
221 * Handle responsive menu.
222 * Source: http://purecss.io/layouts/tucked-menu-vertical/
223 */
224 const menu = document.getElementById('shaarli-menu');
225 const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
226
227 const menuToggle = document.getElementById('menu-toggle');
228 if (menuToggle != null) {
229 menuToggle.addEventListener('click', () => toggleMenu(menu));
230 }
231
232 window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
233
234 /**
235 * Fold/Expand shaares description and thumbnail.
236 */
237 const foldAllButtons = document.getElementsByClassName('fold-all');
238 const foldButtons = document.getElementsByClassName('fold-button');
239
240 [...foldButtons].forEach((foldButton) => {
241 // Retrieve description
242 let description = null;
243 let thumbnail = null;
244 const linklistItem = getParentByClass(foldButton, 'linklist-item');
245 if (linklistItem != null) {
246 description = linklistItem.querySelector('.linklist-item-description');
247 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
248 if (description != null || thumbnail != null) {
249 foldButton.style.display = 'inline';
250 }
251 }
252
253 foldButton.addEventListener('click', (event) => {
254 event.preventDefault();
255 toggleFold(event.target, description, thumbnail);
256 });
257 });
258
259 if (foldAllButtons != null) {
260 [].forEach.call(foldAllButtons, (foldAllButton) => {
261 foldAllButton.addEventListener('click', (event) => {
262 event.preventDefault();
263 const state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
264 [].forEach.call(foldButtons, (foldButton) => {
265 if ((foldButton.firstElementChild.classList.contains('fa-chevron-up') && state === 'down')
266 || (foldButton.firstElementChild.classList.contains('fa-chevron-down') && state === 'up')
267 ) {
268 return;
269 }
270 // Retrieve description
271 let description = null;
272 let thumbnail = null;
273 const linklistItem = getParentByClass(foldButton, 'linklist-item');
274 if (linklistItem != null) {
275 description = linklistItem.querySelector('.linklist-item-description');
276 thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
277 if (description != null || thumbnail != null) {
278 foldButton.style.display = 'inline';
279 }
280 }
281
282 toggleFold(foldButton.firstElementChild, description, thumbnail);
283 });
284 foldAllButton.firstElementChild.classList.toggle('fa-chevron-down');
285 foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
286 foldAllButton.title = state === 'down'
287 ? document.getElementById('translation-fold-all').innerHTML
288 : document.getElementById('translation-expand-all').innerHTML;
289 });
290 });
291 }
292
293 /**
294 * Confirmation message before deletion.
295 */
296 const deleteLinks = document.querySelectorAll('.confirm-delete');
297 [...deleteLinks].forEach((deleteLink) => {
298 deleteLink.addEventListener('click', (event) => {
299 if (!confirm(document.getElementById('translation-delete-link').innerHTML)) {
300 event.preventDefault();
301 }
302 });
303 });
304
305 /**
306 * Close alerts
307 */
308 const closeLinks = document.querySelectorAll('.pure-alert-close');
309 [...closeLinks].forEach((closeLink) => {
310 closeLink.addEventListener('click', (event) => {
311 const alert = getParentByClass(event.target, 'pure-alert-closable');
312 alert.style.display = 'none';
313 });
314 });
315
316 /**
317 * New version dismiss.
318 * Hide the message for one week using localStorage.
319 */
320 const newVersionDismiss = document.getElementById('new-version-dismiss');
321 const newVersionMessage = document.querySelector('.new-version-message');
322 if (newVersionMessage != null
323 && localStorage.getItem('newVersionDismiss') != null
324 && parseInt(localStorage.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
325 ) {
326 newVersionMessage.style.display = 'none';
327 }
328 if (newVersionDismiss != null) {
329 newVersionDismiss.addEventListener('click', () => {
330 localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
331 });
332 }
333
334 const hiddenReturnurl = document.getElementsByName('returnurl');
335 if (hiddenReturnurl != null) {
336 hiddenReturnurl.value = window.location.href;
337 }
338
339 /**
340 * Autofocus text fields
341 */
342 const autofocusElements = document.querySelectorAll('.autofocus');
343 let breakLoop = false;
344 [].forEach.call(autofocusElements, (autofocusElement) => {
345 if (autofocusElement.value === '' && !breakLoop) {
346 autofocusElement.focus();
347 breakLoop = true;
348 }
349 });
350
351 /**
352 * Handle sub menus/forms
353 */
354 const openers = document.getElementsByClassName('subheader-opener');
355 if (openers != null) {
356 [...openers].forEach((opener) => {
357 opener.addEventListener('click', (event) => {
358 event.preventDefault();
359
360 const id = opener.getAttribute('data-open-id');
361 const sub = document.getElementById(id);
362
363 if (sub != null) {
364 [...document.getElementsByClassName('subheader-form')].forEach((element) => {
365 if (element !== sub) {
366 removeClass(element, 'open');
a0737313 367 }
a33c5653
A
368 });
369
370 sub.classList.toggle('open');
a0737313 371 }
a33c5653 372 });
a0737313 373 });
a33c5653
A
374 }
375
376 /**
377 * Remove CSS target padding (for fixed bar)
378 */
379 if (location.hash !== '') {
380 const anchor = document.getElementById(location.hash.substr(1));
381 if (anchor != null) {
382 const padsize = anchor.clientHeight;
383 window.scroll(0, window.scrollY - padsize);
384 anchor.style.paddingTop = '0';
385 }
386 }
387
388 /**
389 * Text area resizer
390 */
391 const description = document.getElementById('lf_description');
392
393 if (description != null) {
394 init(description);
395 // Submit editlink form with CTRL + Enter in the text area.
396 description.addEventListener('keydown', (event) => {
397 if (event.ctrlKey && event.keyCode === 13) {
398 document.getElementById('button-save-edit').click();
399 }
400 });
401 }
402
403 /**
404 * Bookmarklet alert
405 */
406 const bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
407 const bkmMessage = document.getElementById('bookmarklet-alert');
408 [].forEach.call(bookmarkletLinks, (link) => {
409 link.addEventListener('click', (event) => {
410 event.preventDefault();
411 alert(bkmMessage.value);
412 });
413 });
414
a33c5653
A
415 const continent = document.getElementById('continent');
416 const city = document.getElementById('city');
417 if (continent != null && city != null) {
418 continent.addEventListener('change', () => {
419 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
420 });
421 hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
422 }
423
424 /**
425 * Bulk actions
426 */
fc574e64 427 const linkCheckboxes = document.querySelectorAll('.link-checkbox');
a33c5653
A
428 const bar = document.getElementById('actions');
429 [...linkCheckboxes].forEach((checkbox) => {
430 checkbox.style.display = 'inline-block';
fc574e64
A
431 checkbox.addEventListener('change', () => {
432 const linkCheckedCheckboxes = document.querySelectorAll('.link-checkbox:checked');
a33c5653
A
433 const count = [...linkCheckedCheckboxes].length;
434 if (count === 0 && bar.classList.contains('open')) {
435 bar.classList.toggle('open');
436 } else if (count > 0 && !bar.classList.contains('open')) {
437 bar.classList.toggle('open');
438 }
439 });
440 });
441
442 const deleteButton = document.getElementById('actions-delete');
443 const token = document.getElementById('token');
444 if (deleteButton != null && token != null) {
445 deleteButton.addEventListener('click', (event) => {
446 event.preventDefault();
447
448 const links = [];
fc574e64 449 const linkCheckedCheckboxes = document.querySelectorAll('.link-checkbox:checked');
a33c5653
A
450 [...linkCheckedCheckboxes].forEach((checkbox) => {
451 links.push({
452 id: checkbox.value,
453 title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
454 });
455 });
456
457 let message = `Are you sure you want to delete ${links.length} links?\n`;
458 message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
459 const ids = [];
460 links.forEach((item) => {
461 message += ` - ${item.title}\n`;
462 ids.push(item.id);
463 });
464
465 if (window.confirm(message)) {
9c75f877 466 window.location = `${basePath}/admin/shaare/delete?id=${ids.join('+')}&token=${token.value}`;
a33c5653
A
467 }
468 });
469 }
470
8d03f705
A
471 const changeVisibilityButtons = document.querySelectorAll('.actions-change-visibility');
472 if (changeVisibilityButtons != null && token != null) {
473 [...changeVisibilityButtons].forEach((button) => {
474 button.addEventListener('click', (event) => {
475 event.preventDefault();
476 const visibility = event.target.getAttribute('data-visibility');
477
478 const links = [];
479 const linkCheckedCheckboxes = document.querySelectorAll('.link-checkbox:checked');
480 [...linkCheckedCheckboxes].forEach((checkbox) => {
481 links.push({
482 id: checkbox.value,
483 title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
484 });
485 });
486
487 const ids = links.map(item => item.id);
818b3193
A
488 window.location =
489 `${basePath}/?change_visibility&token=${token.value}&newVisibility=${visibility}&ids=${ids.join('+')}`;
8d03f705
A
490 });
491 });
492 }
493
fc574e64
A
494 /**
495 * Select all button
496 */
497 const selectAllButtons = document.querySelectorAll('.select-all-button');
498 [...selectAllButtons].forEach((selectAllButton) => {
499 selectAllButton.addEventListener('click', (e) => {
500 e.preventDefault();
501 const checked = selectAllButton.classList.contains('filter-off');
502 [...selectAllButtons].forEach((selectAllButton2) => {
503 selectAllButton2.classList.toggle('filter-off');
504 selectAllButton2.classList.toggle('filter-on');
505 });
506 [...linkCheckboxes].forEach((linkCheckbox) => {
507 linkCheckbox.checked = checked;
508 linkCheckbox.dispatchEvent(new Event('change'));
509 });
510 });
511 });
512
a33c5653
A
513 /**
514 * Tag list operations
515 *
516 * TODO: support error code in the backend for AJAX requests
517 */
518 const tagList = document.querySelector('input[name="taglist"]');
519 let existingTags = tagList ? tagList.value.split(' ') : [];
520 let awesomepletes = [];
521
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';
531 } else {
532 form.style.display = 'none';
533 }
534 block.querySelector('input').focus();
535 });
536 });
537
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() === '') {
547 return;
548 }
549 const refreshedToken = document.getElementById('token').value;
550 const fromtag = block.getAttribute('data-tag');
551 const xhr = new XMLHttpRequest();
9c75f877 552 xhr.open('POST', `${basePath}/admin/tags`);
a33c5653
A
553 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
554 xhr.onload = () => {
555 if (xhr.status !== 200) {
556 alert(`An error occurred. Return code: ${xhr.status}`);
557 location.reload();
558 } else {
559 block.setAttribute('data-tag', totag);
560 input.setAttribute('name', totag);
561 input.setAttribute('value', totag);
562 findParent(input, 'div', { class: 'rename-tag-form' }).style.display = 'none';
563 block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
818b3193
A
564 block
565 .querySelector('a.tag-link')
566 .setAttribute('href', `${basePath}/?searchtags=${encodeURIComponent(totag)}`);
567 block
568 .querySelector('a.rename-tag')
9c75f877 569 .setAttribute('href', `${basePath}/admin/tags?fromtag=${encodeURIComponent(totag)}`);
a33c5653
A
570
571 // Refresh awesomplete values
572 existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
573 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
574 }
575 };
576 xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
818b3193 577 refreshToken(basePath);
a33c5653
A
578 });
579 });
580
581 // Validate input with enter key
582 const renameTagInputs = document.querySelectorAll('.rename-tag-input');
583 [...renameTagInputs].forEach((rename) => {
584 rename.addEventListener('keypress', (event) => {
585 if (event.keyCode === 13) { // enter
586 findParent(event.target, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
587 }
588 });
589 });
590
591 // Delete a tag with an AJAX query (alert popup confirmation)
592 const deleteTagButtons = document.querySelectorAll('.delete-tag');
593 [...deleteTagButtons].forEach((rename) => {
594 rename.style.display = 'inline';
595 rename.addEventListener('click', (event) => {
596 event.preventDefault();
597 const block = findParent(event.target, 'div', { class: 'tag-list-item' });
598 const tag = block.getAttribute('data-tag');
4fa9a3c5 599 const refreshedToken = document.getElementById('token').value;
a33c5653
A
600
601 if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
602 const xhr = new XMLHttpRequest();
9c75f877 603 xhr.open('POST', `${basePath}/admin/tags`);
a33c5653
A
604 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
605 xhr.onload = () => {
606 block.remove();
607 };
608 xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
818b3193 609 refreshToken(basePath);
a33c5653
A
610
611 existingTags = existingTags.filter(tagItem => tagItem !== tag);
612 awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
613 }
614 });
615 });
616
617 const autocompleteFields = document.querySelectorAll('input[data-multiple]');
618 [...autocompleteFields].forEach((autocompleteField) => {
619 awesomepletes.push(createAwesompleteInstance(autocompleteField));
620 });
621})();