Webpack / Rewrite all JS to ES6 Syntax

This commit is contained in:
ArthurHoaro 2018-02-24 18:30:30 +01:00
parent d78c23e00d
commit d42da54350
5 changed files with 654 additions and 722 deletions

View file

@ -0,0 +1,10 @@
import Blazy from 'blazy';
(() => {
const picwall = document.getElementById('picwall_container');
if (picwall != null) {
// Suppress ESLint error because that's how bLazy works
/* eslint-disable no-new */
new Blazy();
}
})();

View file

@ -1,102 +1,268 @@
/** @licstart The following is the entire license notice for the import Awesomplete from 'awesomplete';
* JavaScript code in this page.
/**
* Find a parent element according to its tag and its attributes
* *
* Copyright: (c) 2011-2015 Sébastien SAUVAGE <sebsauvage@sebsauvage.net> * @param element Element where to start the search
* (c) 2011-2017 The Shaarli Community, see AUTHORS * @param tagName Expected parent tag name
* @param attributes Associative array of expected attributes (name=>value).
* *
* This software is provided 'as-is', without any express or implied warranty. * @returns Found element or null.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*/ */
function findParent(element, tagName, attributes) {
const parentMatch = key => attributes[key] !== '' && element.getAttribute(key).indexOf(attributes[key]) !== -1;
while (element) {
if (element.tagName.toLowerCase() === tagName) {
if (Object.keys(attributes).find(parentMatch)) {
return element;
}
}
element = element.parentElement;
}
return null;
}
window.onload = function () { /**
* Ajax request to refresh the CSRF token.
*/
function refreshToken() {
const xhr = new XMLHttpRequest();
xhr.open('GET', '?do=token');
xhr.onload = () => {
const token = document.getElementById('token');
token.setAttribute('value', xhr.responseText);
};
xhr.send();
}
/** function createAwesompleteInstance(element, tags = []) {
const awesome = new Awesomplete(Awesomplete.$(element));
// Tags are separated by a space
awesome.filter = (text, input) => Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
// Insert new selected tag in the input
awesome.replace = (text) => {
const before = awesome.input.value.match(/^.+ \s*|/)[0];
awesome.input.value = `${before}${text} `;
};
// Highlight found items
awesome.item = (text, input) => Awesomplete.ITEM(text, input.match(/[^ ]*$/)[0]);
// Don't display already selected items
const reg = /(\w+) /g;
let match;
awesome.data = (item, input) => {
while ((match = reg.exec(input))) {
if (item === match[1]) {
return '';
}
}
return item;
};
awesome.minChars = 1;
if (tags.length) {
awesome.list = tags;
}
return awesome;
}
/**
* Update awesomplete list of tag for all elements matching the given selector
*
* @param selector CSS selector
* @param tags Array of tags
* @param instances List of existing awesomplete instances
*/
function updateAwesompleteList(selector, tags, instances) {
if (instances.length === 0) {
// First load: create Awesomplete instances
const elements = document.querySelectorAll(selector);
[...elements].forEach((element) => {
instances.push(createAwesompleteInstance(element, tags));
});
} else {
// Update awesomplete tag list
instances.map((item) => {
item.list = tags;
return item;
});
}
return instances;
}
/**
* html_entities in JS
*
* @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
*/
function htmlEntities(str) {
return str.replace(/[\u00A0-\u9999<>&]/gim, i => `&#${i.charCodeAt(0)};`);
}
function activateFirefoxSocial(node) {
const loc = location.href;
const baseURL = loc.substring(0, loc.lastIndexOf('/') + 1);
const data = {
name: document.title,
description: document.getElementById('translation-delete-link').innerHTML,
author: 'Shaarli',
version: '1.0.0',
iconURL: `${baseURL}/images/favicon.ico`,
icon32URL: `${baseURL}/images/favicon.ico`,
icon64URL: `${baseURL}/images/favicon.ico`,
shareURL: `${baseURL}?post=%{url}&title=%{title}&description=%{text}&source=firefoxsocialapi`,
homepageURL: baseURL,
};
node.setAttribute('data-service', JSON.stringify(data));
const activate = new CustomEvent('ActivateSocialFeature');
node.dispatchEvent(activate);
}
/**
* Add the class 'hidden' to city options not attached to the current selected continent.
*
* @param cities List of <option> elements
* @param currentContinent Current selected continent
* @param reset Set to true to reset the selected value
*/
function hideTimezoneCities(cities, currentContinent, reset = null) {
let first = true;
if (reset == null) {
reset = false;
}
[...cities].forEach((option) => {
if (option.getAttribute('data-continent') !== currentContinent) {
option.className = 'hidden';
} else {
option.className = '';
if (reset === true && first === true) {
option.setAttribute('selected', 'selected');
first = false;
}
}
});
}
/**
* Retrieve an element up in the tree from its class name. * Retrieve an element up in the tree from its class name.
*/ */
function getParentByClass(el, className) { function getParentByClass(el, className) {
var p = el.parentNode; const p = el.parentNode;
if (p == null || p.classList.contains(className)) { if (p == null || p.classList.contains(className)) {
return p; return p;
} }
return getParentByClass(p, className); return getParentByClass(p, className);
} }
function toggleHorizontal() {
/** [...document.getElementById('shaarli-menu').querySelectorAll('.menu-transform')].forEach((el) => {
* Handle responsive menu.
* Source: http://purecss.io/layouts/tucked-menu-vertical/
*/
(function (window, document) {
var menu = document.getElementById('shaarli-menu'),
WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange':'resize';
function toggleHorizontal() {
[].forEach.call(
document.getElementById('shaarli-menu').querySelectorAll('.menu-transform'),
function(el){
el.classList.toggle('pure-menu-horizontal'); el.classList.toggle('pure-menu-horizontal');
} });
); }
};
function toggleMenu() { function toggleMenu(menu) {
// set timeout so that the panel has a chance to roll up // set timeout so that the panel has a chance to roll up
// before the menu switches states // before the menu switches states
if (menu.classList.contains('open')) { if (menu.classList.contains('open')) {
setTimeout(toggleHorizontal, 500); setTimeout(toggleHorizontal, 500);
} } else {
else {
toggleHorizontal(); toggleHorizontal();
} }
menu.classList.toggle('open'); menu.classList.toggle('open');
document.getElementById('menu-toggle').classList.toggle('x'); document.getElementById('menu-toggle').classList.toggle('x');
}; }
function closeMenu() { function closeMenu(menu) {
if (menu.classList.contains('open')) { if (menu.classList.contains('open')) {
toggleMenu(); toggleMenu(menu);
} }
}
function toggleFold(button, description, thumb) {
// Switch fold/expand - up = fold
if (button.classList.contains('fa-chevron-up')) {
button.title = document.getElementById('translation-expand').innerHTML;
if (description != null) {
description.style.display = 'none';
}
if (thumb != null) {
thumb.style.display = 'none';
}
} else {
button.title = document.getElementById('translation-fold').innerHTML;
if (description != null) {
description.style.display = 'block';
}
if (thumb != null) {
thumb.style.display = 'block';
}
}
button.classList.toggle('fa-chevron-down');
button.classList.toggle('fa-chevron-up');
}
function removeClass(element, classname) {
element.className = element.className.replace(new RegExp(`(?:^|\\s)${classname}(?:\\s|$)`), ' ');
}
function init(description) {
function resize() {
/* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
const scrollTop = window.pageYOffset ||
(document.documentElement || document.body.parentNode || document.body).scrollTop;
description.style.height = 'auto';
description.style.height = `${description.scrollHeight + 10}px`;
window.scrollTo(0, scrollTop);
} }
var menuToggle = document.getElementById('menu-toggle'); /* 0-timeout to get the already changed text */
function delayedResize() {
window.setTimeout(resize, 0);
}
const observe = (element, event, handler) => {
element.addEventListener(event, handler, false);
};
observe(description, 'change', resize);
observe(description, 'cut', delayedResize);
observe(description, 'paste', delayedResize);
observe(description, 'drop', delayedResize);
observe(description, 'keydown', delayedResize);
resize();
}
(() => {
/**
* Handle responsive menu.
* Source: http://purecss.io/layouts/tucked-menu-vertical/
*/
const menu = document.getElementById('shaarli-menu');
const WINDOW_CHANGE_EVENT = ('onorientationchange' in window) ? 'orientationchange' : 'resize';
const menuToggle = document.getElementById('menu-toggle');
if (menuToggle != null) { if (menuToggle != null) {
menuToggle.addEventListener('click', function (e) { menuToggle.addEventListener('click', () => toggleMenu(menu));
toggleMenu();
});
} }
window.addEventListener(WINDOW_CHANGE_EVENT, closeMenu); window.addEventListener(WINDOW_CHANGE_EVENT, () => closeMenu(menu));
})(this, this.document);
/** /**
* Fold/Expand shaares description and thumbnail. * Fold/Expand shaares description and thumbnail.
*/ */
var foldAllButtons = document.getElementsByClassName('fold-all'); const foldAllButtons = document.getElementsByClassName('fold-all');
var foldButtons = document.getElementsByClassName('fold-button'); const foldButtons = document.getElementsByClassName('fold-button');
[].forEach.call(foldButtons, function (foldButton) { [...foldButtons].forEach((foldButton) => {
// Retrieve description // Retrieve description
var description = null; let description = null;
var thumbnail = null; let thumbnail = null;
var linklistItem = getParentByClass(foldButton, 'linklist-item'); const linklistItem = getParentByClass(foldButton, 'linklist-item');
if (linklistItem != null) { if (linklistItem != null) {
description = linklistItem.querySelector('.linklist-item-description'); description = linklistItem.querySelector('.linklist-item-description');
thumbnail = linklistItem.querySelector('.linklist-item-thumbnail'); thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
@ -105,27 +271,27 @@ window.onload = function () {
} }
} }
foldButton.addEventListener('click', function (event) { foldButton.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
toggleFold(event.target, description, thumbnail); toggleFold(event.target, description, thumbnail);
}); });
}); });
if (foldAllButtons != null) { if (foldAllButtons != null) {
[].forEach.call(foldAllButtons, function (foldAllButton) { [].forEach.call(foldAllButtons, (foldAllButton) => {
foldAllButton.addEventListener('click', function (event) { foldAllButton.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') != -1 ? 'down' : 'up'; const state = foldAllButton.firstElementChild.getAttribute('class').indexOf('down') !== -1 ? 'down' : 'up';
[].forEach.call(foldButtons, function (foldButton) { [].forEach.call(foldButtons, (foldButton) => {
if (foldButton.firstElementChild.classList.contains('fa-chevron-up') && state == 'down' if ((foldButton.firstElementChild.classList.contains('fa-chevron-up') && state === 'down')
|| foldButton.firstElementChild.classList.contains('fa-chevron-down') && state == 'up' || (foldButton.firstElementChild.classList.contains('fa-chevron-down') && state === 'up')
) { ) {
return; return;
} }
// Retrieve description // Retrieve description
var description = null; let description = null;
var thumbnail = null; let thumbnail = null;
var linklistItem = getParentByClass(foldButton, 'linklist-item'); const linklistItem = getParentByClass(foldButton, 'linklist-item');
if (linklistItem != null) { if (linklistItem != null) {
description = linklistItem.querySelector('.linklist-item-description'); description = linklistItem.querySelector('.linklist-item-description');
thumbnail = linklistItem.querySelector('.linklist-item-thumbnail'); thumbnail = linklistItem.querySelector('.linklist-item-thumbnail');
@ -140,43 +306,18 @@ window.onload = function () {
foldAllButton.firstElementChild.classList.toggle('fa-chevron-up'); foldAllButton.firstElementChild.classList.toggle('fa-chevron-up');
foldAllButton.title = state === 'down' foldAllButton.title = state === 'down'
? document.getElementById('translation-fold-all').innerHTML ? document.getElementById('translation-fold-all').innerHTML
: document.getElementById('translation-expand-all').innerHTML : document.getElementById('translation-expand-all').innerHTML;
}); });
}); });
} }
function toggleFold(button, description, thumb)
{
// Switch fold/expand - up = fold
if (button.classList.contains('fa-chevron-up')) {
button.title = document.getElementById('translation-expand').innerHTML;
if (description != null) {
description.style.display = 'none';
}
if (thumb != null) {
thumb.style.display = 'none';
}
}
else {
button.title = document.getElementById('translation-fold').innerHTML;
if (description != null) {
description.style.display = 'block';
}
if (thumb != null) {
thumb.style.display = 'block';
}
}
button.classList.toggle('fa-chevron-down');
button.classList.toggle('fa-chevron-up');
}
/** /**
* Confirmation message before deletion. * Confirmation message before deletion.
*/ */
var deleteLinks = document.querySelectorAll('.confirm-delete'); const deleteLinks = document.querySelectorAll('.confirm-delete');
[].forEach.call(deleteLinks, function(deleteLink) { [...deleteLinks].forEach((deleteLink) => {
deleteLink.addEventListener('click', function(event) { deleteLink.addEventListener('click', (event) => {
if(! confirm(document.getElementById('translation-delete-link').innerHTML)) { if (!confirm(document.getElementById('translation-delete-link').innerHTML)) {
event.preventDefault(); event.preventDefault();
} }
}); });
@ -185,10 +326,10 @@ window.onload = function () {
/** /**
* Close alerts * Close alerts
*/ */
var closeLinks = document.querySelectorAll('.pure-alert-close'); const closeLinks = document.querySelectorAll('.pure-alert-close');
[].forEach.call(closeLinks, function(closeLink) { [...closeLinks].forEach((closeLink) => {
closeLink.addEventListener('click', function(event) { closeLink.addEventListener('click', (event) => {
var alert = getParentByClass(event.target, 'pure-alert-closable'); const alert = getParentByClass(event.target, 'pure-alert-closable');
alert.style.display = 'none'; alert.style.display = 'none';
}); });
}); });
@ -197,21 +338,21 @@ window.onload = function () {
* New version dismiss. * New version dismiss.
* Hide the message for one week using localStorage. * Hide the message for one week using localStorage.
*/ */
var newVersionDismiss = document.getElementById('new-version-dismiss'); const newVersionDismiss = document.getElementById('new-version-dismiss');
var newVersionMessage = document.querySelector('.new-version-message'); const newVersionMessage = document.querySelector('.new-version-message');
if (newVersionMessage != null if (newVersionMessage != null
&& localStorage.getItem('newVersionDismiss') != null && localStorage.getItem('newVersionDismiss') != null
&& parseInt(localStorage.getItem('newVersionDismiss')) + 7*24*60*60*1000 > (new Date()).getTime() && parseInt(localStorage.getItem('newVersionDismiss'), 10) + (7 * 24 * 60 * 60 * 1000) > (new Date()).getTime()
) { ) {
newVersionMessage.style.display = 'none'; newVersionMessage.style.display = 'none';
} }
if (newVersionDismiss != null) { if (newVersionDismiss != null) {
newVersionDismiss.addEventListener('click', function () { newVersionDismiss.addEventListener('click', () => {
localStorage.setItem('newVersionDismiss', (new Date()).getTime()); localStorage.setItem('newVersionDismiss', (new Date()).getTime().toString());
}); });
} }
var hiddenReturnurl = document.getElementsByName('returnurl'); const hiddenReturnurl = document.getElementsByName('returnurl');
if (hiddenReturnurl != null) { if (hiddenReturnurl != null) {
hiddenReturnurl.value = window.location.href; hiddenReturnurl.value = window.location.href;
} }
@ -219,10 +360,10 @@ window.onload = function () {
/** /**
* Autofocus text fields * Autofocus text fields
*/ */
var autofocusElements = document.querySelectorAll('.autofocus'); const autofocusElements = document.querySelectorAll('.autofocus');
var breakLoop = false; let breakLoop = false;
[].forEach.call(autofocusElements, function(autofocusElement) { [].forEach.call(autofocusElements, (autofocusElement) => {
if (autofocusElement.value == '' && ! breakLoop) { if (autofocusElement.value === '' && !breakLoop) {
autofocusElement.focus(); autofocusElement.focus();
breakLoop = true; breakLoop = true;
} }
@ -231,19 +372,19 @@ window.onload = function () {
/** /**
* Handle sub menus/forms * Handle sub menus/forms
*/ */
var openers = document.getElementsByClassName('subheader-opener'); const openers = document.getElementsByClassName('subheader-opener');
if (openers != null) { if (openers != null) {
[].forEach.call(openers, function(opener) { [...openers].forEach((opener) => {
opener.addEventListener('click', function(event) { opener.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var id = opener.getAttribute('data-open-id'); const id = opener.getAttribute('data-open-id');
var sub = document.getElementById(id); const sub = document.getElementById(id);
if (sub != null) { if (sub != null) {
[].forEach.call(document.getElementsByClassName('subheader-form'), function (element) { [...document.getElementsByClassName('subheader-form')].forEach((element) => {
if (element != sub) { if (element !== sub) {
removeClass(element, 'open') removeClass(element, 'open');
} }
}); });
@ -253,86 +394,40 @@ window.onload = function () {
}); });
} }
function removeClass(element, classname) {
element.className = element.className.replace(new RegExp('(?:^|\\s)'+ classname + '(?:\\s|$)'), ' ');
}
/** /**
* Remove CSS target padding (for fixed bar) * Remove CSS target padding (for fixed bar)
*/ */
if (location.hash != '') { if (location.hash !== '') {
var anchor = document.getElementById(location.hash.substr(1)); const anchor = document.getElementById(location.hash.substr(1));
if (anchor != null) { if (anchor != null) {
var padsize = anchor.clientHeight; const padsize = anchor.clientHeight;
this.window.scroll(0, this.window.scrollY - padsize); window.scroll(0, window.scrollY - padsize);
anchor.style.paddingTop = 0; anchor.style.paddingTop = '0';
} }
} }
/** /**
* Text area resizer * Text area resizer
*/ */
var description = document.getElementById('lf_description'); const description = document.getElementById('lf_description');
var observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
function init () {
function resize () {
/* Fix jumpy resizing: https://stackoverflow.com/a/18262927/1484919 */
var scrollTop = window.pageYOffset ||
(document.documentElement || document.body.parentNode || document.body).scrollTop;
description.style.height = 'auto';
description.style.height = description.scrollHeight+10+'px';
window.scrollTo(0, scrollTop);
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(description, 'change', resize);
observe(description, 'cut', delayedResize);
observe(description, 'paste', delayedResize);
observe(description, 'drop', delayedResize);
observe(description, 'keydown', delayedResize);
resize();
}
if (description != null) { if (description != null) {
init(); init(description);
// Submit editlink form with CTRL + Enter in the text area. // Submit editlink form with CTRL + Enter in the text area.
description.addEventListener('keydown', function (event) { description.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.keyCode === 13) { if (event.ctrlKey && event.keyCode === 13) {
document.getElementById('button-save-edit').click(); document.getElementById('button-save-edit').click();
} }
}); });
} }
/**
* Awesomplete trigger.
*/
var tags = document.getElementById('lf_tags');
if (tags != null) {
awesompleteUniqueTag('#lf_tags');
}
/**
* bLazy trigger
*/
var picwall = document.getElementById('picwall_container');
if (picwall != null) {
var bLazy = new Blazy();
}
/** /**
* Bookmarklet alert * Bookmarklet alert
*/ */
var bookmarkletLinks = document.querySelectorAll('.bookmarklet-link'); const bookmarkletLinks = document.querySelectorAll('.bookmarklet-link');
var bkmMessage = document.getElementById('bookmarklet-alert'); const bkmMessage = document.getElementById('bookmarklet-alert');
[].forEach.call(bookmarkletLinks, function(link) { [].forEach.call(bookmarkletLinks, (link) => {
link.addEventListener('click', function(event) { link.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
alert(bkmMessage.value); alert(bkmMessage.value);
}); });
@ -341,32 +436,17 @@ window.onload = function () {
/** /**
* Firefox Social * Firefox Social
*/ */
var ffButton = document.getElementById('ff-social-button'); const ffButton = document.getElementById('ff-social-button');
if (ffButton != null) { if (ffButton != null) {
ffButton.addEventListener('click', function(event) { ffButton.addEventListener('click', (event) => {
activateFirefoxSocial(event.target); activateFirefoxSocial(event.target);
}); });
} }
/** const continent = document.getElementById('continent');
* Plugin admin order const city = document.getElementById('city');
*/
var orderPA = document.querySelectorAll('.order');
[].forEach.call(orderPA, function(link) {
link.addEventListener('click', function(event) {
event.preventDefault();
if (event.target.classList.contains('order-up')) {
return orderUp(event.target.parentNode.parentNode.getAttribute('data-order'));
} else if (event.target.classList.contains('order-down')) {
return orderDown(event.target.parentNode.parentNode.getAttribute('data-order'));
}
});
});
var continent = document.getElementById('continent');
var city = document.getElementById('city');
if (continent != null && city != null) { if (continent != null && city != null) {
continent.addEventListener('change', function (event) { continent.addEventListener('change', () => {
hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true); hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
}); });
hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false); hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
@ -375,49 +455,46 @@ window.onload = function () {
/** /**
* Bulk actions * Bulk actions
*/ */
var linkCheckboxes = document.querySelectorAll('.delete-checkbox'); const linkCheckboxes = document.querySelectorAll('.delete-checkbox');
var bar = document.getElementById('actions'); const bar = document.getElementById('actions');
[].forEach.call(linkCheckboxes, function(checkbox) { [...linkCheckboxes].forEach((checkbox) => {
checkbox.style.display = 'inline-block'; checkbox.style.display = 'inline-block';
checkbox.addEventListener('click', function(event) { checkbox.addEventListener('click', () => {
var count = 0; const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked'); const count = [...linkCheckedCheckboxes].length;
[].forEach.call(linkCheckedCheckboxes, function(checkbox) { if (count === 0 && bar.classList.contains('open')) {
count++;
});
if (count == 0 && bar.classList.contains('open')) {
bar.classList.toggle('open'); bar.classList.toggle('open');
} else if (count > 0 && ! bar.classList.contains('open')) { } else if (count > 0 && !bar.classList.contains('open')) {
bar.classList.toggle('open'); bar.classList.toggle('open');
} }
}); });
}); });
var deleteButton = document.getElementById('actions-delete'); const deleteButton = document.getElementById('actions-delete');
var token = document.querySelector('input[type="hidden"][name="token"]'); const token = document.getElementById('token');
if (deleteButton != null && token != null) { if (deleteButton != null && token != null) {
deleteButton.addEventListener('click', function(event) { deleteButton.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var links = []; const links = [];
var linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked'); const linkCheckedCheckboxes = document.querySelectorAll('.delete-checkbox:checked');
[].forEach.call(linkCheckedCheckboxes, function(checkbox) { [...linkCheckedCheckboxes].forEach((checkbox) => {
links.push({ links.push({
'id': checkbox.value, id: checkbox.value,
'title': document.querySelector('.linklist-item[data-id="'+ checkbox.value +'"] .linklist-link').innerHTML title: document.querySelector(`.linklist-item[data-id="${checkbox.value}"] .linklist-link`).innerHTML,
}); });
}); });
var message = 'Are you sure you want to delete '+ links.length +' links?\n'; let message = `Are you sure you want to delete ${links.length} links?\n`;
message += 'This action is IRREVERSIBLE!\n\nTitles:\n'; message += 'This action is IRREVERSIBLE!\n\nTitles:\n';
var ids = []; const ids = [];
links.forEach(function(item) { links.forEach((item) => {
message += ' - '+ item['title'] +'\n'; message += ` - ${item.title}\n`;
ids.push(item['id']); ids.push(item.id);
}); });
if (window.confirm(message)) { if (window.confirm(message)) {
window.location = '?delete_link&lf_linkdate='+ ids.join('+') +'&token='+ token.value; window.location = `?delete_link&lf_linkdate=${ids.join('+')}&token=${token.value}`;
} }
}); });
} }
@ -427,18 +504,18 @@ window.onload = function () {
* *
* TODO: support error code in the backend for AJAX requests * TODO: support error code in the backend for AJAX requests
*/ */
var tagList = document.querySelector('input[name="taglist"]'); const tagList = document.querySelector('input[name="taglist"]');
var existingTags = tagList ? tagList.value.split(' ') : []; let existingTags = tagList ? tagList.value.split(' ') : [];
var awesomepletes = []; let awesomepletes = [];
// Display/Hide rename form // Display/Hide rename form
var renameTagButtons = document.querySelectorAll('.rename-tag'); const renameTagButtons = document.querySelectorAll('.rename-tag');
[].forEach.call(renameTagButtons, function(rename) { [...renameTagButtons].forEach((rename) => {
rename.addEventListener('click', function(event) { rename.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var block = findParent(event.target, 'div', {'class': 'tag-list-item'}); const block = findParent(event.target, 'div', { class: 'tag-list-item' });
var form = block.querySelector('.rename-tag-form'); const form = block.querySelector('.rename-tag-form');
if (form.style.display == 'none' || form.style.display == '') { if (form.style.display === 'none' || form.style.display === '') {
form.style.display = 'block'; form.style.display = 'block';
} else { } else {
form.style.display = 'none'; form.style.display = 'none';
@ -448,217 +525,82 @@ window.onload = function () {
}); });
// Rename a tag with an AJAX request // Rename a tag with an AJAX request
var renameTagSubmits = document.querySelectorAll('.validate-rename-tag'); const renameTagSubmits = document.querySelectorAll('.validate-rename-tag');
[].forEach.call(renameTagSubmits, function(rename) { [...renameTagSubmits].forEach((rename) => {
rename.addEventListener('click', function(event) { rename.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var block = findParent(event.target, 'div', {'class': 'tag-list-item'}); const block = findParent(event.target, 'div', { class: 'tag-list-item' });
var input = block.querySelector('.rename-tag-input'); const input = block.querySelector('.rename-tag-input');
var totag = input.value.replace('/"/g', '\\"'); const totag = input.value.replace('/"/g', '\\"');
if (totag.trim() == '') { if (totag.trim() === '') {
return; return;
} }
var fromtag = block.getAttribute('data-tag'); const refreshedToken = document.getElementById('token').value;
var token = document.getElementById('token').value; const fromtag = block.getAttribute('data-tag');
const xhr = new XMLHttpRequest();
xhr = new XMLHttpRequest();
xhr.open('POST', '?do=changetag'); xhr.open('POST', '?do=changetag');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() { xhr.onload = () => {
if (xhr.status !== 200) { if (xhr.status !== 200) {
alert('An error occurred. Return code: '+ xhr.status); alert(`An error occurred. Return code: ${xhr.status}`);
location.reload(); location.reload();
} else { } else {
block.setAttribute('data-tag', totag); block.setAttribute('data-tag', totag);
input.setAttribute('name', totag); input.setAttribute('name', totag);
input.setAttribute('value', totag); input.setAttribute('value', totag);
findParent(input, 'div', {'class': 'rename-tag-form'}).style.display = 'none'; findParent(input, 'div', { class: 'rename-tag-form' }).style.display = 'none';
block.querySelector('a.tag-link').innerHTML = htmlEntities(totag); block.querySelector('a.tag-link').innerHTML = htmlEntities(totag);
block.querySelector('a.tag-link').setAttribute('href', '?searchtags='+ encodeURIComponent(totag)); block.querySelector('a.tag-link').setAttribute('href', `?searchtags=${encodeURIComponent(totag)}`);
block.querySelector('a.rename-tag').setAttribute('href', '?do=changetag&fromtag='+ encodeURIComponent(totag)); block.querySelector('a.rename-tag').setAttribute('href', `?do=changetag&fromtag=${encodeURIComponent(totag)}`);
// Refresh awesomplete values // Refresh awesomplete values
for (var key in existingTags) { existingTags = existingTags.map(tag => (tag === fromtag ? totag : tag));
if (existingTags[key] == fromtag) {
existingTags[key] = totag;
}
}
awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes); awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
} }
}; };
xhr.send('renametag=1&fromtag='+ encodeURIComponent(fromtag) +'&totag='+ encodeURIComponent(totag) +'&token='+ token); xhr.send(`renametag=1&fromtag=${encodeURIComponent(fromtag)}&totag=${encodeURIComponent(totag)}&token=${refreshedToken}`);
refreshToken(); refreshToken();
}); });
}); });
// Validate input with enter key // Validate input with enter key
var renameTagInputs = document.querySelectorAll('.rename-tag-input'); const renameTagInputs = document.querySelectorAll('.rename-tag-input');
[].forEach.call(renameTagInputs, function(rename) { [...renameTagInputs].forEach((rename) => {
rename.addEventListener('keypress', (event) => {
rename.addEventListener('keypress', function(event) {
if (event.keyCode === 13) { // enter if (event.keyCode === 13) { // enter
findParent(event.target, 'div', {'class': 'tag-list-item'}).querySelector('.validate-rename-tag').click(); findParent(event.target, 'div', { class: 'tag-list-item' }).querySelector('.validate-rename-tag').click();
} }
}); });
}); });
// Delete a tag with an AJAX query (alert popup confirmation) // Delete a tag with an AJAX query (alert popup confirmation)
var deleteTagButtons = document.querySelectorAll('.delete-tag'); const deleteTagButtons = document.querySelectorAll('.delete-tag');
[].forEach.call(deleteTagButtons, function(rename) { [...deleteTagButtons].forEach((rename) => {
rename.style.display = 'inline'; rename.style.display = 'inline';
rename.addEventListener('click', function(event) { rename.addEventListener('click', (event) => {
event.preventDefault(); event.preventDefault();
var block = findParent(event.target, 'div', {'class': 'tag-list-item'}); const block = findParent(event.target, 'div', { class: 'tag-list-item' });
var tag = block.getAttribute('data-tag'); const tag = block.getAttribute('data-tag');
var token = document.getElementById('token').value; const refreshedToken = document.getElementById('token');
if (confirm('Are you sure you want to delete the tag "'+ tag +'"?')) { if (confirm(`Are you sure you want to delete the tag "${tag}"?`)) {
xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('POST', '?do=changetag'); xhr.open('POST', '?do=changetag');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() { xhr.onload = () => {
block.remove(); block.remove();
}; };
xhr.send(encodeURI('deletetag=1&fromtag='+ tag +'&token='+ token)); xhr.send(encodeURI(`deletetag=1&fromtag=${tag}&token=${refreshedToken}`));
refreshToken(); refreshToken();
existingTags = existingTags.filter(tagItem => tagItem !== tag);
awesomepletes = updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes);
} }
}); });
}); });
updateAwesompleteList('.rename-tag-input', existingTags, awesomepletes); const autocompleteFields = document.querySelectorAll('input[data-multiple]');
}; [...autocompleteFields].forEach((autocompleteField) => {
awesomepletes.push(createAwesompleteInstance(autocompleteField));
/**
* Find a parent element according to its tag and its attributes
*
* @param element Element where to start the search
* @param tagName Expected parent tag name
* @param attributes Associative array of expected attributes (name=>value).
*
* @returns Found element or null.
*/
function findParent(element, tagName, attributes)
{
while (element) {
if (element.tagName.toLowerCase() == tagName) {
var match = true;
for (var key in attributes) {
if (! element.hasAttribute(key)
|| (attributes[key] != '' && element.getAttribute(key).indexOf(attributes[key]) == -1)
) {
match = false;
break;
}
}
if (match) {
return element;
}
}
element = element.parentElement;
}
return null;
}
/**
* Ajax request to refresh the CSRF token.
*/
function refreshToken()
{
var xhr = new XMLHttpRequest();
xhr.open('GET', '?do=token');
xhr.onload = function() {
var token = document.getElementById('token');
token.setAttribute('value', xhr.responseText);
};
xhr.send();
}
/**
* Update awesomplete list of tag for all elements matching the given selector
*
* @param selector CSS selector
* @param tags Array of tags
* @param instances List of existing awesomplete instances
*/
function updateAwesompleteList(selector, tags, instances)
{
// First load: create Awesomplete instances
if (instances.length == 0) {
var elements = document.querySelectorAll(selector);
[].forEach.call(elements, function (element) {
instances.push(new Awesomplete(
element,
{'list': tags}
));
}); });
} else { })();
// Update awesomplete tag list
for (var key in instances) {
instances[key].list = tags;
}
}
return instances;
}
/**
* html_entities in JS
*
* @see http://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript
*/
function htmlEntities(str)
{
return str.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
}
function activateFirefoxSocial(node) {
var loc = location.href;
var baseURL = loc.substring(0, loc.lastIndexOf("/") + 1);
var title = document.title;
// Keeping the data separated (ie. not in the DOM) so that it's maintainable and diffable.
var data = {
name: title,
description: document.getElementById('translation-delete-link').innerHTML,
author: "Shaarli",
version: "1.0.0",
iconURL: baseURL + "/images/favicon.ico",
icon32URL: baseURL + "/images/favicon.ico",
icon64URL: baseURL + "/images/favicon.ico",
shareURL: baseURL + "?post=%{url}&title=%{title}&description=%{text}&source=firefoxsocialapi",
homepageURL: baseURL
};
node.setAttribute("data-service", JSON.stringify(data));
var activate = new CustomEvent("ActivateSocialFeature");
node.dispatchEvent(activate);
}
/**
* Add the class 'hidden' to city options not attached to the current selected continent.
*
* @param cities List of <option> elements
* @param currentContinent Current selected continent
* @param reset Set to true to reset the selected value
*/
function hideTimezoneCities(cities, currentContinent) {
var first = true;
if (reset == null) {
reset = false;
}
[].forEach.call(cities, function (option) {
if (option.getAttribute('data-continent') != currentContinent) {
option.className = 'hidden';
} else {
option.className = '';
if (reset === true && first === true) {
option.setAttribute('selected', 'selected');
first = false;
}
}
});
}

View file

@ -1,43 +1,13 @@
/** @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright: (c) 2011-2015 Sébastien SAUVAGE <sebsauvage@sebsauvage.net>
* (c) 2011-2017 The Shaarli Community, see AUTHORS
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*/
/** /**
* Change the position counter of a row. * Change the position counter of a row.
* *
* @param elem Element Node to change. * @param elem Element Node to change.
* @param toPos int New position. * @param toPos int New position.
*/ */
function changePos(elem, toPos) function changePos(elem, toPos) {
{ const elemName = elem.getAttribute('data-line');
var elemName = elem.getAttribute('data-line')
elem.setAttribute('data-order', toPos); elem.setAttribute('data-order', toPos);
var hiddenInput = document.querySelector('[name="order_'+ elemName +'"]'); const hiddenInput = document.querySelector(`[name="order_${elemName}"]`);
hiddenInput.setAttribute('value', toPos); hiddenInput.setAttribute('value', toPos);
} }
@ -47,25 +17,23 @@ function changePos(elem, toPos)
* @param pos Element Node to move. * @param pos Element Node to move.
* @param move int Move: +1 (down) or -1 (up) * @param move int Move: +1 (down) or -1 (up)
*/ */
function changeOrder(pos, move) function changeOrder(pos, move) {
{ const newpos = parseInt(pos, 10) + move;
var newpos = parseInt(pos) + move; let lines = document.querySelectorAll(`[data-order="${pos}"]`);
var lines = document.querySelectorAll('[data-order="'+ pos +'"]'); const changelines = document.querySelectorAll(`[data-order="${newpos}"]`);
var changelines = document.querySelectorAll('[data-order="'+ newpos +'"]');
// If we go down reverse lines to preserve the rows order // If we go down reverse lines to preserve the rows order
if (move > 0) { if (move > 0) {
lines = [].slice.call(lines).reverse(); lines = [].slice.call(lines).reverse();
} }
for (var i = 0 ; i < lines.length ; i++) { for (let i = 0; i < lines.length; i += 1) {
var parent = changelines[0].parentNode; const parent = changelines[0].parentNode;
changePos(lines[i], newpos); changePos(lines[i], newpos);
changePos(changelines[i], parseInt(pos)); changePos(changelines[i], parseInt(pos, 10));
var changeItem = move < 0 ? changelines[0] : changelines[changelines.length - 1].nextSibling; const changeItem = move < 0 ? changelines[0] : changelines[changelines.length - 1].nextSibling;
parent.insertBefore(lines[i], changeItem); parent.insertBefore(lines[i], changeItem);
} }
} }
/** /**
@ -73,15 +41,12 @@ function changeOrder(pos, move)
* *
* @param pos int row counter. * @param pos int row counter.
* *
* @returns false * @return false
*/ */
function orderUp(pos) function orderUp(pos) {
{ if (pos !== 0) {
if (pos == 0) {
return false;
}
changeOrder(pos, -1); changeOrder(pos, -1);
return false; }
} }
/** /**
@ -91,13 +56,26 @@ function orderUp(pos)
* *
* @returns false * @returns false
*/ */
function orderDown(pos) function orderDown(pos) {
{ const lastpos = parseInt(document.querySelector('[data-order]:last-child').getAttribute('data-order'), 10);
var lastpos = document.querySelector('[data-order]:last-child').getAttribute('data-order'); if (pos !== lastpos) {
if (pos == lastpos) { changeOrder(pos, 1);
return false;
} }
changeOrder(pos, +1);
return false;
} }
(() => {
/**
* Plugin admin order
*/
const orderPA = document.querySelectorAll('.order');
[...orderPA].forEach((link) => {
link.addEventListener('click', (event) => {
event.preventDefault();
if (event.target.classList.contains('order-up')) {
orderUp(parseInt(event.target.parentNode.parentNode.getAttribute('data-order'), 10));
} else if (event.target.classList.contains('order-down')) {
orderDown(parseInt(event.target.parentNode.parentNode.getAttribute('data-order'), 10));
}
});
});
})();

View file

@ -1,3 +1,11 @@
$fa-font-path: "~font-awesome/fonts";
@import "~font-awesome/scss/font-awesome.scss";
@import '~purecss/build/pure.css';
@import '~purecss/build/grids-responsive.css';
@import '~pure-extras/css/pure-extras.css';
@import '~awesomplete/awesomplete.css';
/** /**
* General * General
*/ */
@ -873,10 +881,6 @@ body, .pure-g [class*="pure-u"] {
/** /**
* PAGE FORM - COMPLETE * PAGE FORM - COMPLETE
*/ */
.page-form-complete {
#background: #f5f5f5;
}
.page-form-complete div, .page-form-complete p { .page-form-complete div, .page-form-complete p {
color: #252525; color: #252525;
} }

View file

@ -1,32 +1,30 @@
window.onload = function () { import Awesomplete from 'awesomplete';
var continent = document.getElementById('continent'); import 'awesomplete/awesomplete.css';
var city = document.getElementById('city');
if (continent != null && city != null) {
continent.addEventListener('change', function(event) {
hideTimezoneCities(city, continent.options[continent.selectedIndex].value, true);
});
hideTimezoneCities(city, continent.options[continent.selectedIndex].value, false);
}
};
/** (() => {
* Add the class 'hidden' to city options not attached to the current selected continent. const awp = Awesomplete.$;
* const autocompleteFields = document.querySelectorAll('input[data-multiple]');
* @param cities List of <option> elements [...autocompleteFields].forEach((autocompleteField) => {
* @param currentContinent Current selected continent const awesomplete = new Awesomplete(awp(autocompleteField));
* @param reset Set to true to reset the selected value awesomplete.filter = (text, input) => Awesomplete.FILTER_CONTAINS(text, input.match(/[^ ]*$/)[0]);
*/ awesomplete.replace = (text) => {
function hideTimezoneCities(cities, currentContinent, reset = false) { const before = awesomplete.input.value.match(/^.+ \s*|/)[0];
var first = true; awesomplete.input.value = `${before}${text} `;
[].forEach.call(cities, function(option) { };
if (option.getAttribute('data-continent') != currentContinent) { awesomplete.minChars = 1;
option.className = 'hidden';
} else { autocompleteField.addEventListener('input', () => {
option.className = ''; const proposedTags = autocompleteField.getAttribute('data-list').replace(/,/g, '').split(' ');
if (reset === true && first === true) { const reg = /(\w+) /g;
option.setAttribute('selected', 'selected'); let match;
first = false; while ((match = reg.exec(autocompleteField.value)) !== null) {
const id = proposedTags.indexOf(match[1]);
if (id !== -1) {
proposedTags.splice(id, 1);
} }
} }
awesomplete.list = proposedTags;
}); });
} });
})();