base.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import Awesomplete from 'awesomplete';
  2. /**
  3. * Find a parent element according to its tag and its attributes
  4. *
  5. * @param element Element where to start the search
  6. * @param tagName Expected parent tag name
  7. * @param attributes Associative array of expected attributes (name=>value).
  8. *
  9. * @returns Found element or null.
  10. */
  11. function findParent(element, tagName, attributes) {
  12. const parentMatch = key => attributes[key] !== '' && element.getAttribute(key).indexOf(attributes[key]) !== -1;
  13. while (element) {
  14. if (element.tagName.toLowerCase() === tagName) {
  15. if (Object.keys(attributes).find(parentMatch)) {
  16. return element;
  17. }
  18. }
  19. element = element.parentElement;
  20. }
  21. return null;
  22. }
  23. /**
  24. * Ajax request to refresh the CSRF token.
  25. */
  26. function refreshToken() {
  27. const xhr = new XMLHttpRequest();
  28. xhr.open('GET', '?do=token');
  29. xhr.onload = () => {
  30. const token = document.getElementById('token');
  31. token.setAttribute('value', xhr.responseText);
  32. };
  33. xhr.send();
  34. }
  35. function createAwesompleteInstance(element, tags = []) {
  36. const awesome = new Awesomplete(Awesomplete.$(element));
  37. // Tags are separated by a space
  38. awesome.filter = (text, input) => Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
  39. // Insert new selected tag in the input
  40. awesome.replace = (text) => {
  41. const before = awesome.input.value.match(/^.+ \s*|/)[0];
  42. awesome.input.value = `${before}${text} `;
  43. };
  44. // Highlight found items
  45. awesome.item = (text, input) => Awesomplete.ITEM(text, input.match(/[^ ]*$/)[0]);
  46. // Don't display already selected items
  47. const reg = /(\w+) /g;
  48. let match;
  49. awesome.data = (item, input) => {
  50. while ((match = reg.exec(input))) {
  51. if (item === match[1]) {
  52. return '';
  53. }
  54. }
  55. return item;
  56. };
  57. awesome.minChars = 1;
  58. if (tags.length) {
  59. awesome.list = tags;
  60. }
  61. return awesome;
  62. }
  63. /**
  64. * Update awesomplete list of tag for all elements matching the given selector
  65. *
  66. * @param selector CSS selector
  67. * @param tags Array of tags
  68. * @param instances List of existing awesomplete instances
  69. */
  70. function updateAwesompleteList(selector, tags, instances) {
  71. if (instances.length === 0) {
  72. // First load: create Awesomplete instances
  73. const elements = document.querySelectorAll(selector);
  74. [...elements].forEach((element) => {
  75. instances.push(createAwesompleteInstance(element, tags));
  76. });
  77. } else {
  78. // Update awesomplete tag list
  79. instances.map((item) => {
  80. item.list = tags;
  81. return item;
  82. });
  83. }
  84. return instances;
  85. }
  86. /**
  87. * html_entities in JS
  88. *
  89. * @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
  90. */
  91. function htmlEntities(str) {
  92. return str.replace(/[\u00A0-\u9999<>&]/gim, i => `&#${i.charCodeAt(0)};`);
  93. }
  94. /**
  95. * Add the class 'hidden' to city options not attached to the current selected continent.
  96. *
  97. * @param cities List of <option> elements
  98. * @param currentContinent Current selected continent
  99. * @param reset Set to true to reset the selected value
  100. */
  101. function hideTimezoneCities(cities, currentContinent, reset = null) {
  102. let first = true;
  103. if (reset == null) {
  104. reset = false;
  105. }
  106. [...cities].forEach((option) => {
  107. if (option.getAttribute('data-continent') !== currentContinent) {
  108. option.className = 'hidden';
  109. } else {
  110. option.className = '';
  111. if (reset === true && first === true) {
  112. option.setAttribute('selected', 'selected');
  113. first = false;
  114. }
  115. }
  116. });
  117. }
  118. /**
  119. * Retrieve an element up in the tree from its class name.
  120. */
  121. function getParentByClass(el, className) {
  122. const p = el.parentNode;
  123. if (p == null || p.classList.contains(className)) {
  124. return p;
  125. }
  126. return getParentByClass(p, className);
  127. }
  128. function toggleHorizontal() {
  129. [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
  130. el.classList.toggle('pure-menu-horizontal');
  131. });
  132. }
  133. function toggleMenu(menu) {
  134. // set timeout so that the panel has a chance to roll up
  135. // before the menu switches states
  136. if (menu.classList.contains('open')) {
  137. setTimeout(toggleHorizontal, 500);
  138. } else {
  139. toggleHorizontal();
  140. }
  141. menu.classList.toggle('open');
  142. document.getElementById('menu-toggle').classList.toggle('x');
  143. }
  144. function closeMenu(menu) {
  145. if (menu.classList.contains('open')) {
  146. toggleMenu(menu);
  147. }
  148. }
  149. function toggleFold(button, description, thumb) {
  150. // Switch fold/expand - up = fold
  151. if (button.classList.contains('fa-chevron-up')) {
  152. button.title = document.getElementById('translation-expand').innerHTML;
  153. if (description != null) {
  154. description.style.display = 'none';
  155. }
  156. if (thumb != null) {
  157. thumb.style.display = 'none';
  158. }
  159. } else {
  160. button.title = document.getElementById('translation-fold').innerHTML;
  161. if (description != null) {
  162. description.style.display = 'block';
  163. }
  164. if (thumb != null) {
  165. thumb.style.display = 'block';
  166. }
  167. }
  168. button.classList.toggle('fa-chevron-down');
  169. button.classList.toggle('fa-chevron-up');
  170. }
  171. function removeClass(element, classname) {
  172. element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
  173. }
  174. function init(description) {
  175. function resize() {
  176. /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
  177. const scrollTop = window.pageYOffset ||
  178. (document.documentElement || document.body.parentNode || document.body).scrollTop;
  179. description.style.height = 'auto';
  180. description.style.height = `${description.scrollHeight + 10}px`;
  181. window.scrollTo(0, scrollTop);
  182. }
  183. /* 0-timeout to get the already changed text */
  184. function delayedResize() {
  185. window.setTimeout(resize, 0);
  186. }
  187. const observe = (element, event, handler) => {
  188. element.addEventListener(event, handler, false);
  189. };
  190. observe(description, 'change', resize);
  191. observe(description, 'cut', delayedResize);
  192. observe(description, 'paste', delayedResize);
  193. observe(description, 'drop', delayedResize);
  194. observe(description, 'keydown', delayedResize);
  195. resize();
  196. }
  197. (() => {
  198. /**
  199. * Handle responsive menu.
  200. * Source: http://purecss.io/layouts/tucked-menu-vertical/
  201. */
  202. const menu = document.getElementById('shaarli-menu');
  203. const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
  204. const menuToggle = document.getElementById('menu-toggle');
  205. if (menuToggle != null) {
  206. menuToggle.addEventListener('click', () => toggleMenu(menu));
  207. }
  208. window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
  209. /**
  210. * Fold/Expand shaares description and thumbnail.
  211. */
  212. const foldAllButtons = document.getElementsByClassName('fold-all');
  213. const foldButtons = document.getElementsByClassName('fold-button');
  214. [...foldButtons].forEach((foldButton) => {
  215. // Retrieve description
  216. let description = null;
  217. let thumbnail = null;
  218. const linklistItem = getParentByClass(foldButton, 'linklist-item');
  219. if (linklistItem != null) {
  220. description = linklistItem.querySelector('.linklist-item-description');
  221. thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
  222. if (description != null || thumbnail != null) {
  223. foldButton.style.display = 'inline';
  224. }
  225. }
  226. foldButton.addEventListener('click', (event) => {
  227. event.preventDefault();
  228. toggleFold(event.target, description, thumbnail);
  229. });
  230. });
  231. if (foldAllButtons != null) {
  232. [].forEach.call(foldAllButtons, (foldAllButton) => {
  233. foldAllButton.addEventListener('click', (event) => {
  234. event.preventDefault();
  235. const state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
  236. [].forEach.call(foldButtons, (foldButton) => {
  237. if ((foldButton.firstElementChild.classList.contains('fa-chevron-up') && state === 'down')
  238. || (foldButton.firstElementChild.classList.contains('fa-chevron-down') && state === 'up')
  239. ) {
  240. return;
  241. }
  242. // Retrieve description
  243. let description = null;
  244. let thumbnail = null;
  245. const linklistItem = getParentByClass(foldButton, 'linklist-item');
  246. if (linklistItem != null) {
  247. description = linklistItem.querySelector('.linklist-item-description');
  248. thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
  249. if (description != null || thumbnail != null) {
  250. foldButton.style.display = 'inline';
  251. }
  252. }
  253. toggleFold(foldButton.firstElementChild, description, thumbnail);
  254. });
  255. foldAllButton.firstElementChild.classList.toggle('fa-chevron-down');
  256. foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
  257. foldAllButton.title = state === 'down'
  258. ? document.getElementById('translation-fold-all').innerHTML
  259. : document.getElementById('translation-expand-all').innerHTML;
  260. });
  261. });
  262. }
  263. /**
  264. * Confirmation message before deletion.
  265. */
  266. const deleteLinks = document.querySelectorAll('.confirm-delete');
  267. [...deleteLinks].forEach((deleteLink) => {
  268. deleteLink.addEventListener('click', (event) => {
  269. if (!confirm(document.getElementById('translation-delete-link').innerHTML)) {
  270. event.preventDefault();
  271. }
  272. });
  273. });
  274. /**
  275. * Close alerts
  276. */
  277. const closeLinks = document.querySelectorAll('.pure-alert-close');
  278. [...closeLinks].forEach((closeLink) => {
  279. closeLink.addEventListener('click', (event) => {
  280. const alert = getParentByClass(event.target, 'pure-alert-closable');
  281. alert.style.display = 'none';
  282. });
  283. });
  284. /**
  285. * New version dismiss.
  286. * Hide the message for one week using localStorage.
  287. */
  288. const newVersionDismiss = document.getElementById('new-version-dismiss');
  289. const newVersionMessage = document.querySelector('.new-version-message');
  290. if (newVersionMessage != null
  291. && localStorage.getItem('newVersionDismiss') != null
  292. && parseInt(localStorage.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
  293. ) {
  294. newVersionMessage.style.display = 'none';
  295. }
  296. if (newVersionDismiss != null) {
  297. newVersionDismiss.addEventListener('click', () => {
  298. localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
  299. });
  300. }
  301. const hiddenReturnurl = document.getElementsByName('returnurl');
  302. if (hiddenReturnurl != null) {
  303. hiddenReturnurl.value = window.location.href;
  304. }
  305. /**
  306. * Autofocus text fields
  307. */
  308. const autofocusElements = document.querySelectorAll('.autofocus');
  309. let breakLoop = false;
  310. [].forEach.call(autofocusElements, (autofocusElement) => {
  311. if (autofocusElement.value === '' && !breakLoop) {
  312. autofocusElement.focus();
  313. breakLoop = true;
  314. }
  315. });
  316. /**
  317. * Handle sub menus/forms
  318. */
  319. const openers = document.getElementsByClassName('subheader-opener');
  320. if (openers != null) {
  321. [...openers].forEach((opener) => {
  322. opener.addEventListener('click', (event) => {
  323. event.preventDefault();
  324. const id = opener.getAttribute('data-open-id');
  325. const sub = document.getElementById(id);
  326. if (sub != null) {
  327. [...document.getElementsByClassName('subheader-form')].forEach((element) => {
  328. if (element !== sub) {
  329. removeClass(element, 'open');
  330. }
  331. });
  332. sub.classList.toggle('open');
  333. }
  334. });
  335. });
  336. }
  337. /**
  338. * Remove CSS target padding (for fixed bar)
  339. */
  340. if (location.hash !== '') {
  341. const anchor = document.getElementById(location.hash.substr(1));
  342. if (anchor != null) {
  343. const padsize = anchor.clientHeight;
  344. window.scroll(0, window.scrollY - padsize);
  345. anchor.style.paddingTop = '0';
  346. }
  347. }
  348. /**
  349. * Text area resizer
  350. */
  351. const description = document.getElementById('lf_description');
  352. if (description != null) {
  353. init(description);
  354. // Submit editlink form with CTRL + Enter in the text area.
  355. description.addEventListener('keydown', (event) => {
  356. if (event.ctrlKey && event.keyCode === 13) {
  357. document.getElementById('button-save-edit').click();
  358. }
  359. });
  360. }
  361. /**
  362. * Bookmarklet alert
  363. */
  364. const bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
  365. const bkmMessage = document.getElementById('bookmarklet-alert');
  366. [].forEach.call(bookmarkletLinks, (link) => {
  367. link.addEventListener('click', (event) => {
  368. event.preventDefault();
  369. alert(bkmMessage.value);
  370. });
  371. });
  372. const continent = document.getElementById('continent');
  373. const city = document.getElementById('city');
  374. if (continent != null && city != null) {
  375. continent.addEventListener('change', () => {
  376. hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
  377. });
  378. hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
  379. }
  380. /**
  381. * Bulk actions
  382. */
  383. const linkCheckboxes = document.querySelectorAll('.link-checkbox');
  384. const bar = document.getElementById('actions');
  385. [...linkCheckboxes].forEach((checkbox) => {
  386. checkbox.style.display = 'inline-block';
  387. checkbox.addEventListener('change', () => {
  388. const linkCheckedCheckboxes = document.querySelectorAll('.link-checkbox:checked');
  389. const count = [...linkCheckedCheckboxes].length;
  390. if (count === 0 && bar.classList.contains('open')) {
  391. bar.classList.toggle('open');
  392. } else if (count > 0 && !bar.classList.contains('open')) {
  393. bar.classList.toggle('open');
  394. }
  395. });
  396. });
  397. const deleteButton = document.getElementById('actions-delete');
  398. const token = document.getElementById('token');
  399. if (deleteButton != null && token != null) {
  400. deleteButton.addEventListener('click', (event) => {
  401. event.preventDefault();
  402. const links = [];
  403. const linkCheckedCheckboxes = document.querySelectorAll('.link-checkbox:checked');
  404. [...linkCheckedCheckboxes].forEach((checkbox) => {
  405. links.push({
  406. id: checkbox.value,
  407. title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
  408. });
  409. });
  410. let message = `Are you sure you want to delete ${links.length} links?\n`;
  411. message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
  412. const ids = [];
  413. links.forEach((item) => {
  414. message += ` - ${item.title}\n`;
  415. ids.push(item.id);
  416. });
  417. if (window.confirm(message)) {
  418. window.location = `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
  419. }
  420. });
  421. }
  422. /**
  423. * Select all button
  424. */
  425. const selectAllButtons = document.querySelectorAll('.select-all-button');
  426. [...selectAllButtons].forEach((selectAllButton) => {
  427. selectAllButton.addEventListener('click', (e) => {
  428. e.preventDefault();
  429. const checked = selectAllButton.classList.contains('filter-off');
  430. [...selectAllButtons].forEach((selectAllButton2) => {
  431. selectAllButton2.classList.toggle('filter-off');
  432. selectAllButton2.classList.toggle('filter-on');
  433. });
  434. [...linkCheckboxes].forEach((linkCheckbox) => {
  435. linkCheckbox.checked = checked;
  436. linkCheckbox.dispatchEvent(new Event('change'));
  437. });
  438. });
  439. });
  440. /**
  441. * Tag list operations
  442. *
  443. * TODO: support error code in the backend for AJAX requests
  444. */
  445. const tagList = document.querySelector('input[name="taglist"]');
  446. let existingTags = tagList ? tagList.value.split(' ') : [];
  447. let awesomepletes = [];
  448. // Display/Hide rename form
  449. const renameTagButtons = document.querySelectorAll('.rename-tag');
  450. [...renameTagButtons].forEach((rename) => {
  451. rename.addEventListener('click', (event) => {
  452. event.preventDefault();
  453. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  454. const form = block.querySelector('.rename-tag-form');
  455. if (form.style.display === 'none' || form.style.display === '') {
  456. form.style.display = 'block';
  457. } else {
  458. form.style.display = 'none';
  459. }
  460. block.querySelector('input').focus();
  461. });
  462. });
  463. // Rename a tag with an AJAX request
  464. const renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
  465. [...renameTagSubmits].forEach((rename) => {
  466. rename.addEventListener('click', (event) => {
  467. event.preventDefault();
  468. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  469. const input = block.querySelector('.rename-tag-input');
  470. const totag = input.value.replace('/"/g', '\\"');
  471. if (totag.trim() === '') {
  472. return;
  473. }
  474. const refreshedToken = document.getElementById('token').value;
  475. const fromtag = block.getAttribute('data-tag');
  476. const xhr = new XMLHttpRequest();
  477. xhr.open('POST', '?do=changetag');
  478. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  479. xhr.onload = () => {
  480. if (xhr.status !== 200) {
  481. alert(`An error occurred. Return code: ${xhr.status}`);
  482. location.reload();
  483. } else {
  484. block.setAttribute('data-tag', totag);
  485. input.setAttribute('name', totag);
  486. input.setAttribute('value', totag);
  487. findParent(input, 'div', { class: 'rename-tag-form' }).style.display = 'none';
  488. block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
  489. block.querySelector('a.tag-link').setAttribute('href', `?searchtags=${encodeURIComponent(totag)}`);
  490. block.querySelector('a.rename-tag').setAttribute('href', `?do=changetag&fromtag=${encodeURIComponent(totag)}`);
  491. // Refresh awesomplete values
  492. existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
  493. awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
  494. }
  495. };
  496. xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
  497. refreshToken();
  498. });
  499. });
  500. // Validate input with enter key
  501. const renameTagInputs = document.querySelectorAll('.rename-tag-input');
  502. [...renameTagInputs].forEach((rename) => {
  503. rename.addEventListener('keypress', (event) => {
  504. if (event.keyCode === 13) { // enter
  505. findParent(event.target, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
  506. }
  507. });
  508. });
  509. // Delete a tag with an AJAX query (alert popup confirmation)
  510. const deleteTagButtons = document.querySelectorAll('.delete-tag');
  511. [...deleteTagButtons].forEach((rename) => {
  512. rename.style.display = 'inline';
  513. rename.addEventListener('click', (event) => {
  514. event.preventDefault();
  515. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  516. const tag = block.getAttribute('data-tag');
  517. const refreshedToken = document.getElementById('token').value;
  518. if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
  519. const xhr = new XMLHttpRequest();
  520. xhr.open('POST', '?do=changetag');
  521. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  522. xhr.onload = () => {
  523. block.remove();
  524. };
  525. xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
  526. refreshToken();
  527. existingTags = existingTags.filter(tagItem => tagItem !== tag);
  528. awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
  529. }
  530. });
  531. });
  532. const autocompleteFields = document.querySelectorAll('input[data-multiple]');
  533. [...autocompleteFields].forEach((autocompleteField) => {
  534. awesomepletes.push(createAwesompleteInstance(autocompleteField));
  535. });
  536. })();