base.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. function activateFirefoxSocial(node) {
  95. const loc = location.href;
  96. const baseURL = loc.substring(0, loc.lastIndexOf('/') + 1);
  97. const data = {
  98. name: document.title,
  99. description: document.getElementById('translation-delete-link').innerHTML,
  100. author: 'Shaarli',
  101. version: '1.0.0',
  102. iconURL: `${baseURL}/images/favicon.ico`,
  103. icon32URL: `${baseURL}/images/favicon.ico`,
  104. icon64URL: `${baseURL}/images/favicon.ico`,
  105. shareURL: `${baseURL}?post=%{url}&title=%{title}&description=%{text}&source=firefoxsocialapi`,
  106. homepageURL: baseURL,
  107. };
  108. node.setAttribute('data-service', JSON.stringify(data));
  109. const activate = new CustomEvent('ActivateSocialFeature');
  110. node.dispatchEvent(activate);
  111. }
  112. /**
  113. * Add the class 'hidden' to city options not attached to the current selected continent.
  114. *
  115. * @param cities List of <option> elements
  116. * @param currentContinent Current selected continent
  117. * @param reset Set to true to reset the selected value
  118. */
  119. function hideTimezoneCities(cities, currentContinent, reset = null) {
  120. let first = true;
  121. if (reset == null) {
  122. reset = false;
  123. }
  124. [...cities].forEach((option) => {
  125. if (option.getAttribute('data-continent') !== currentContinent) {
  126. option.className = 'hidden';
  127. } else {
  128. option.className = '';
  129. if (reset === true && first === true) {
  130. option.setAttribute('selected', 'selected');
  131. first = false;
  132. }
  133. }
  134. });
  135. }
  136. /**
  137. * Retrieve an element up in the tree from its class name.
  138. */
  139. function getParentByClass(el, className) {
  140. const p = el.parentNode;
  141. if (p == null || p.classList.contains(className)) {
  142. return p;
  143. }
  144. return getParentByClass(p, className);
  145. }
  146. function toggleHorizontal() {
  147. [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
  148. el.classList.toggle('pure-menu-horizontal');
  149. });
  150. }
  151. function toggleMenu(menu) {
  152. // set timeout so that the panel has a chance to roll up
  153. // before the menu switches states
  154. if (menu.classList.contains('open')) {
  155. setTimeout(toggleHorizontal, 500);
  156. } else {
  157. toggleHorizontal();
  158. }
  159. menu.classList.toggle('open');
  160. document.getElementById('menu-toggle').classList.toggle('x');
  161. }
  162. function closeMenu(menu) {
  163. if (menu.classList.contains('open')) {
  164. toggleMenu(menu);
  165. }
  166. }
  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';
  173. }
  174. if (thumb != null) {
  175. thumb.style.display = 'none';
  176. }
  177. } else {
  178. button.title = document.getElementById('translation-fold').innerHTML;
  179. if (description != null) {
  180. description.style.display = 'block';
  181. }
  182. if (thumb != null) {
  183. thumb.style.display = 'block';
  184. }
  185. }
  186. button.classList.toggle('fa-chevron-down');
  187. button.classList.toggle('fa-chevron-up');
  188. }
  189. function removeClass(element, classname) {
  190. element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
  191. }
  192. function init(description) {
  193. function resize() {
  194. /* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
  195. const scrollTop = window.pageYOffset ||
  196. (document.documentElement || document.body.parentNode || document.body).scrollTop;
  197. description.style.height = 'auto';
  198. description.style.height = `${description.scrollHeight + 10}px`;
  199. window.scrollTo(0, scrollTop);
  200. }
  201. /* 0-timeout to get the already changed text */
  202. function delayedResize() {
  203. window.setTimeout(resize, 0);
  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. resize();
  214. }
  215. (() => {
  216. /**
  217. * Handle responsive menu.
  218. * Source: http://purecss.io/layouts/tucked-menu-vertical/
  219. */
  220. const menu = document.getElementById('shaarli-menu');
  221. const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
  222. const menuToggle = document.getElementById('menu-toggle');
  223. if (menuToggle != null) {
  224. menuToggle.addEventListener('click', () => toggleMenu(menu));
  225. }
  226. window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
  227. /**
  228. * Fold/Expand shaares description and thumbnail.
  229. */
  230. const foldAllButtons = document.getElementsByClassName('fold-all');
  231. const foldButtons = document.getElementsByClassName('fold-button');
  232. [...foldButtons].forEach((foldButton) => {
  233. // Retrieve description
  234. let description = null;
  235. let thumbnail = null;
  236. const linklistItem = getParentByClass(foldButton, 'linklist-item');
  237. if (linklistItem != null) {
  238. description = linklistItem.querySelector('.linklist-item-description');
  239. thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
  240. if (description != null || thumbnail != null) {
  241. foldButton.style.display = 'inline';
  242. }
  243. }
  244. foldButton.addEventListener('click', (event) => {
  245. event.preventDefault();
  246. toggleFold(event.target, description, thumbnail);
  247. });
  248. });
  249. if (foldAllButtons != null) {
  250. [].forEach.call(foldAllButtons, (foldAllButton) => {
  251. foldAllButton.addEventListener('click', (event) => {
  252. event.preventDefault();
  253. const state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
  254. [].forEach.call(foldButtons, (foldButton) => {
  255. if ((foldButton.firstElementChild.classList.contains('fa-chevron-up') && state === 'down')
  256. || (foldButton.firstElementChild.classList.contains('fa-chevron-down') && state === 'up')
  257. ) {
  258. return;
  259. }
  260. // Retrieve description
  261. let description = null;
  262. let thumbnail = null;
  263. const linklistItem = getParentByClass(foldButton, 'linklist-item');
  264. if (linklistItem != null) {
  265. description = linklistItem.querySelector('.linklist-item-description');
  266. thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
  267. if (description != null || thumbnail != null) {
  268. foldButton.style.display = 'inline';
  269. }
  270. }
  271. toggleFold(foldButton.firstElementChild, description, thumbnail);
  272. });
  273. foldAllButton.firstElementChild.classList.toggle('fa-chevron-down');
  274. foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
  275. foldAllButton.title = state === 'down'
  276. ? document.getElementById('translation-fold-all').innerHTML
  277. : document.getElementById('translation-expand-all').innerHTML;
  278. });
  279. });
  280. }
  281. /**
  282. * Confirmation message before deletion.
  283. */
  284. const deleteLinks = document.querySelectorAll('.confirm-delete');
  285. [...deleteLinks].forEach((deleteLink) => {
  286. deleteLink.addEventListener('click', (event) => {
  287. if (!confirm(document.getElementById('translation-delete-link').innerHTML)) {
  288. event.preventDefault();
  289. }
  290. });
  291. });
  292. /**
  293. * Close alerts
  294. */
  295. const closeLinks = document.querySelectorAll('.pure-alert-close');
  296. [...closeLinks].forEach((closeLink) => {
  297. closeLink.addEventListener('click', (event) => {
  298. const alert = getParentByClass(event.target, 'pure-alert-closable');
  299. alert.style.display = 'none';
  300. });
  301. });
  302. /**
  303. * New version dismiss.
  304. * Hide the message for one week using localStorage.
  305. */
  306. const newVersionDismiss = document.getElementById('new-version-dismiss');
  307. const newVersionMessage = document.querySelector('.new-version-message');
  308. if (newVersionMessage != null
  309. && localStorage.getItem('newVersionDismiss') != null
  310. && parseInt(localStorage.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
  311. ) {
  312. newVersionMessage.style.display = 'none';
  313. }
  314. if (newVersionDismiss != null) {
  315. newVersionDismiss.addEventListener('click', () => {
  316. localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
  317. });
  318. }
  319. const hiddenReturnurl = document.getElementsByName('returnurl');
  320. if (hiddenReturnurl != null) {
  321. hiddenReturnurl.value = window.location.href;
  322. }
  323. /**
  324. * Autofocus text fields
  325. */
  326. const autofocusElements = document.querySelectorAll('.autofocus');
  327. let breakLoop = false;
  328. [].forEach.call(autofocusElements, (autofocusElement) => {
  329. if (autofocusElement.value === '' && !breakLoop) {
  330. autofocusElement.focus();
  331. breakLoop = true;
  332. }
  333. });
  334. /**
  335. * Handle sub menus/forms
  336. */
  337. const openers = document.getElementsByClassName('subheader-opener');
  338. if (openers != null) {
  339. [...openers].forEach((opener) => {
  340. opener.addEventListener('click', (event) => {
  341. event.preventDefault();
  342. const id = opener.getAttribute('data-open-id');
  343. const sub = document.getElementById(id);
  344. if (sub != null) {
  345. [...document.getElementsByClassName('subheader-form')].forEach((element) => {
  346. if (element !== sub) {
  347. removeClass(element, 'open');
  348. }
  349. });
  350. sub.classList.toggle('open');
  351. }
  352. });
  353. });
  354. }
  355. /**
  356. * Remove CSS target padding (for fixed bar)
  357. */
  358. if (location.hash !== '') {
  359. const anchor = document.getElementById(location.hash.substr(1));
  360. if (anchor != null) {
  361. const padsize = anchor.clientHeight;
  362. window.scroll(0, window.scrollY - padsize);
  363. anchor.style.paddingTop = '0';
  364. }
  365. }
  366. /**
  367. * Text area resizer
  368. */
  369. const description = document.getElementById('lf_description');
  370. if (description != null) {
  371. init(description);
  372. // Submit editlink form with CTRL + Enter in the text area.
  373. description.addEventListener('keydown', (event) => {
  374. if (event.ctrlKey && event.keyCode === 13) {
  375. document.getElementById('button-save-edit').click();
  376. }
  377. });
  378. }
  379. /**
  380. * Bookmarklet alert
  381. */
  382. const bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
  383. const bkmMessage = document.getElementById('bookmarklet-alert');
  384. [].forEach.call(bookmarkletLinks, (link) => {
  385. link.addEventListener('click', (event) => {
  386. event.preventDefault();
  387. alert(bkmMessage.value);
  388. });
  389. });
  390. /**
  391. * Firefox Social
  392. */
  393. const ffButton = document.getElementById('ff-social-button');
  394. if (ffButton != null) {
  395. ffButton.addEventListener('click', (event) => {
  396. activateFirefoxSocial(event.target);
  397. });
  398. }
  399. const continent = document.getElementById('continent');
  400. const city = document.getElementById('city');
  401. if (continent != null && city != null) {
  402. continent.addEventListener('change', () => {
  403. hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
  404. });
  405. hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
  406. }
  407. /**
  408. * Bulk actions
  409. */
  410. const linkCheckboxes = document.querySelectorAll('.delete-checkbox');
  411. const bar = document.getElementById('actions');
  412. [...linkCheckboxes].forEach((checkbox) => {
  413. checkbox.style.display = 'inline-block';
  414. checkbox.addEventListener('click', () => {
  415. const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
  416. const count = [...linkCheckedCheckboxes].length;
  417. if (count === 0 && bar.classList.contains('open')) {
  418. bar.classList.toggle('open');
  419. } else if (count > 0 && !bar.classList.contains('open')) {
  420. bar.classList.toggle('open');
  421. }
  422. });
  423. });
  424. const deleteButton = document.getElementById('actions-delete');
  425. const token = document.getElementById('token');
  426. if (deleteButton != null && token != null) {
  427. deleteButton.addEventListener('click', (event) => {
  428. event.preventDefault();
  429. const links = [];
  430. const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
  431. [...linkCheckedCheckboxes].forEach((checkbox) => {
  432. links.push({
  433. id: checkbox.value,
  434. title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
  435. });
  436. });
  437. let message = `Are you sure you want to delete ${links.length} links?\n`;
  438. message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
  439. const ids = [];
  440. links.forEach((item) => {
  441. message += ` - ${item.title}\n`;
  442. ids.push(item.id);
  443. });
  444. if (window.confirm(message)) {
  445. window.location = `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
  446. }
  447. });
  448. }
  449. /**
  450. * Tag list operations
  451. *
  452. * TODO: support error code in the backend for AJAX requests
  453. */
  454. const tagList = document.querySelector('input[name="taglist"]');
  455. let existingTags = tagList ? tagList.value.split(' ') : [];
  456. let awesomepletes = [];
  457. // Display/Hide rename form
  458. const renameTagButtons = document.querySelectorAll('.rename-tag');
  459. [...renameTagButtons].forEach((rename) => {
  460. rename.addEventListener('click', (event) => {
  461. event.preventDefault();
  462. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  463. const form = block.querySelector('.rename-tag-form');
  464. if (form.style.display === 'none' || form.style.display === '') {
  465. form.style.display = 'block';
  466. } else {
  467. form.style.display = 'none';
  468. }
  469. block.querySelector('input').focus();
  470. });
  471. });
  472. // Rename a tag with an AJAX request
  473. const renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
  474. [...renameTagSubmits].forEach((rename) => {
  475. rename.addEventListener('click', (event) => {
  476. event.preventDefault();
  477. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  478. const input = block.querySelector('.rename-tag-input');
  479. const totag = input.value.replace('/"/g', '\\"');
  480. if (totag.trim() === '') {
  481. return;
  482. }
  483. const refreshedToken = document.getElementById('token').value;
  484. const fromtag = block.getAttribute('data-tag');
  485. const xhr = new XMLHttpRequest();
  486. xhr.open('POST', '?do=changetag');
  487. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  488. xhr.onload = () => {
  489. if (xhr.status !== 200) {
  490. alert(`An error occurred. Return code: ${xhr.status}`);
  491. location.reload();
  492. } else {
  493. block.setAttribute('data-tag', totag);
  494. input.setAttribute('name', totag);
  495. input.setAttribute('value', totag);
  496. findParent(input, 'div', { class: 'rename-tag-form' }).style.display = 'none';
  497. block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
  498. block.querySelector('a.tag-link').setAttribute('href', `?searchtags=${encodeURIComponent(totag)}`);
  499. block.querySelector('a.rename-tag').setAttribute('href', `?do=changetag&fromtag=${encodeURIComponent(totag)}`);
  500. // Refresh awesomplete values
  501. existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
  502. awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
  503. }
  504. };
  505. xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
  506. refreshToken();
  507. });
  508. });
  509. // Validate input with enter key
  510. const renameTagInputs = document.querySelectorAll('.rename-tag-input');
  511. [...renameTagInputs].forEach((rename) => {
  512. rename.addEventListener('keypress', (event) => {
  513. if (event.keyCode === 13) { // enter
  514. findParent(event.target, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
  515. }
  516. });
  517. });
  518. // Delete a tag with an AJAX query (alert popup confirmation)
  519. const deleteTagButtons = document.querySelectorAll('.delete-tag');
  520. [...deleteTagButtons].forEach((rename) => {
  521. rename.style.display = 'inline';
  522. rename.addEventListener('click', (event) => {
  523. event.preventDefault();
  524. const block = findParent(event.target, 'div', { class: 'tag-list-item' });
  525. const tag = block.getAttribute('data-tag');
  526. const refreshedToken = document.getElementById('token');
  527. if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
  528. const xhr = new XMLHttpRequest();
  529. xhr.open('POST', '?do=changetag');
  530. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  531. xhr.onload = () => {
  532. block.remove();
  533. };
  534. xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
  535. refreshToken();
  536. existingTags = existingTags.filter(tagItem => tagItem !== tag);
  537. awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
  538. }
  539. });
  540. });
  541. const autocompleteFields = document.querySelectorAll('input[data-multiple]');
  542. [...autocompleteFields].forEach((autocompleteField) => {
  543. awesomepletes.push(createAwesompleteInstance(autocompleteField));
  544. });
  545. })();