moviewyrm/bookwyrm/static/js/shared.js

458 lines
13 KiB
JavaScript
Raw Normal View History

// set up javascript listeners
2021-01-14 21:02:28 +00:00
window.onload = function() {
// buttons that display or hide content
document.querySelectorAll('[data-controls]')
2021-01-14 23:16:18 +00:00
.forEach(t => t.onclick = toggleAction);
2021-01-14 23:16:18 +00:00
// javascript interactions (boost/fav)
Array.from(document.getElementsByClassName('interaction'))
.forEach(t => t.onsubmit = interact);
2021-01-14 23:16:18 +00:00
// Toggle all checkboxes.
document
.querySelectorAll('[data-action="toggle-all"]')
.forEach(input => {
input.addEventListener('change', toggleAllCheckboxes);
});
2021-01-14 23:29:37 +00:00
// tab groups
Array.from(document.getElementsByClassName('tab-group'))
.forEach(t => new TabGroup(t));
// handle aria settings on menus
Array.from(document.getElementsByClassName('pulldown-menu'))
.forEach(t => t.onclick = toggleMenu);
// display based on localstorage vars
document.querySelectorAll('[data-hide]')
.forEach(t => setDisplay(t));
// update localstorage
Array.from(document.getElementsByClassName('set-display'))
.forEach(t => t.onclick = updateDisplay);
2021-01-18 17:57:44 +00:00
// hidden submit button in a form
document.querySelectorAll('.hidden-form input')
.forEach(t => t.onchange = revealForm);
2021-01-19 00:32:02 +00:00
// polling
document.querySelectorAll('[data-poll]')
2021-01-19 22:59:46 +00:00
.forEach(el => polling(el));
2021-01-29 18:25:31 +00:00
// browser back behavior
document.querySelectorAll('[data-back]')
.forEach(t => t.onclick = back);
2021-01-14 21:02:28 +00:00
};
2021-01-29 18:25:31 +00:00
function back(e) {
e.preventDefault();
history.back();
}
2021-02-09 18:38:43 +00:00
function polling(el, delay) {
delay = delay || 10000;
delay += (Math.random() * 1000);
2021-01-19 22:59:46 +00:00
setTimeout(function() {
fetch('/api/updates/' + el.getAttribute('data-poll'))
.then(response => response.json())
.then(data => updateCountElement(el, data));
2021-02-09 18:38:43 +00:00
polling(el, delay * 1.25);
2021-01-19 22:59:46 +00:00
}, delay, el);
2021-01-19 00:32:02 +00:00
}
2021-01-19 22:59:46 +00:00
2021-01-19 00:32:02 +00:00
function updateCountElement(el, data) {
2021-01-19 22:59:46 +00:00
const currentCount = el.innerText;
2021-01-19 00:32:02 +00:00
const count = data[el.getAttribute('data-poll')];
if (count != currentCount) {
addRemoveClass(el, 'hidden', count < 1);
2021-01-19 22:59:46 +00:00
el.innerText = count;
2021-01-19 00:32:02 +00:00
}
}
2021-01-18 17:57:44 +00:00
function revealForm(e) {
var hidden = e.currentTarget.closest('.hidden-form').getElementsByClassName('hidden')[0];
if (hidden) {
removeClass(hidden, 'hidden');
}
}
function updateDisplay(e) {
// used in set reading goal
var key = e.target.getAttribute('data-id');
var value = e.target.getAttribute('data-value');
window.localStorage.setItem(key, value);
document.querySelectorAll('[data-hide="' + key + '"]')
.forEach(t => setDisplay(t));
}
function setDisplay(el) {
// used in set reading goal
var key = el.getAttribute('data-hide');
var value = window.localStorage.getItem(key);
addRemoveClass(el, 'hidden', value);
}
2021-01-18 04:19:09 +00:00
2021-01-14 23:16:18 +00:00
function toggleAction(e) {
var el = e.currentTarget;
var pressed = el.getAttribute('aria-pressed') == 'false';
var targetId = el.getAttribute('data-controls');
document.querySelectorAll('[data-controls="' + targetId + '"]')
.forEach(t => t.setAttribute('aria-pressed', (t.getAttribute('aria-pressed') == 'false')));
2021-01-17 03:57:20 +00:00
if (targetId) {
var target = document.getElementById(targetId);
2021-01-17 18:10:59 +00:00
addRemoveClass(target, 'hidden', !pressed);
addRemoveClass(target, 'is-active', pressed);
}
// show/hide container
var container = document.getElementById('hide-' + targetId);
if (!!container) {
addRemoveClass(container, 'hidden', pressed);
2021-01-17 03:57:20 +00:00
}
// set checkbox, if appropriate
var checkbox = el.getAttribute('data-controls-checkbox');
2021-01-17 03:57:20 +00:00
if (checkbox) {
document.getElementById(checkbox).checked = !!pressed;
}
// set focus, if appropriate
var focus = el.getAttribute('data-focus-target');
if (focus) {
var focusEl = document.getElementById(focus);
focusEl.focus();
setTimeout(function(){ focusEl.selectionStart = focusEl.selectionEnd = 10000; }, 0);
}
2021-01-14 21:02:28 +00:00
}
2020-03-16 01:12:45 +00:00
function interact(e) {
e.preventDefault();
ajaxPost(e.target);
var identifier = e.target.getAttribute('data-id');
Array.from(document.getElementsByClassName(identifier))
.forEach(t => addRemoveClass(t, 'hidden', t.className.indexOf('hidden') == -1));
2020-03-16 01:12:45 +00:00
}
/**
* Toggle all descendant checkboxes of a target.
*
* Use `data-target="ID_OF_TARGET"` on the node being listened to.
*
* @param {Event} event - change Event
* @return {undefined}
*/
function toggleAllCheckboxes(event) {
const mainCheckbox = event.target;
document
.querySelectorAll(`#${mainCheckbox.dataset.target} [type="checkbox"]`)
.forEach(checkbox => {checkbox.checked = mainCheckbox.checked;});
2020-11-13 18:14:24 +00:00
}
function toggleMenu(e) {
var el = e.currentTarget;
var expanded = el.getAttribute('aria-expanded') == 'false';
el.setAttribute('aria-expanded', expanded);
2021-01-18 04:19:09 +00:00
var targetId = el.getAttribute('data-controls');
if (targetId) {
var target = document.getElementById(targetId);
addRemoveClass(target, 'is-active', expanded);
}
2020-11-09 19:58:19 +00:00
}
function ajaxPost(form) {
fetch(form.action, {
method : "POST",
body: new FormData(form)
});
2020-03-15 21:15:36 +00:00
}
function addRemoveClass(el, classname, bool) {
if (bool) {
addClass(el, classname);
} else {
removeClass(el, classname);
}
}
function addClass(el, classname) {
var classes = el.className.split(' ');
if (classes.indexOf(classname) > -1) {
return;
}
el.className = classes.concat(classname).join(' ');
}
function removeClass(el, className) {
var classes = [];
if (el.className) {
classes = el.className.split(' ');
}
const idx = classes.indexOf(className);
if (idx > -1) {
classes.splice(idx, 1);
}
el.className = classes.join(' ');
}
/*
* The content below is licensed according to the W3C Software License at
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
* Heavily modified to web component by Zach Leatherman
* Modified back to vanilla JavaScript with support for Bulma markup and nested tabs by Ned Zimmerman
*/
class TabGroup {
constructor(container) {
2021-03-13 20:13:44 +00:00
this.container = container;
this.tablist = this.container.querySelector('[role="tablist"]');
this.buttons = this.tablist.querySelectorAll('[role="tab"]');
this.panels = this.container.querySelectorAll(':scope > [role="tabpanel"]');
this.delay = this.determineDelay();
if(!this.tablist || !this.buttons.length || !this.panels.length) {
return;
}
this.keys = this.keys();
this.direction = this.direction();
this.initButtons();
this.initPanels();
}
2021-03-13 20:13:44 +00:00
keys() {
2021-03-13 20:13:44 +00:00
return {
end: 35,
home: 36,
left: 37,
up: 38,
right: 39,
down: 40
};
}
2021-03-13 20:13:44 +00:00
// Add or substract depending on key pressed
direction() {
2021-03-13 20:13:44 +00:00
return {
37: -1,
38: -1,
39: 1,
40: 1
};
}
2021-03-13 20:13:44 +00:00
initButtons() {
2021-03-13 20:13:44 +00:00
let count = 0;
for(let button of this.buttons) {
let isSelected = button.getAttribute("aria-selected") === "true";
button.setAttribute("tabindex", isSelected ? "0" : "-1");
button.addEventListener('click', this.clickEventListener.bind(this));
button.addEventListener('keydown', this.keydownEventListener.bind(this));
button.addEventListener('keyup', this.keyupEventListener.bind(this));
button.index = count++;
}
}
2021-03-13 20:13:44 +00:00
initPanels() {
2021-03-13 20:13:44 +00:00
let selectedPanelId = this.tablist.querySelector('[role="tab"][aria-selected="true"]').getAttribute("aria-controls");
for(let panel of this.panels) {
if(panel.getAttribute("id") !== selectedPanelId) {
panel.setAttribute("hidden", "");
}
panel.setAttribute("tabindex", "0");
}
}
2021-03-13 20:13:44 +00:00
clickEventListener(event) {
2021-03-13 20:13:44 +00:00
let button = event.target.closest('a');
event.preventDefault();
2021-03-13 20:13:44 +00:00
this.activateTab(button, false);
}
2021-03-13 20:13:44 +00:00
// Handle keydown on tabs
keydownEventListener(event) {
2021-03-13 20:13:44 +00:00
var key = event.keyCode;
switch (key) {
case this.keys.end:
event.preventDefault();
// Activate last tab
this.activateTab(this.buttons[this.buttons.length - 1]);
break;
case this.keys.home:
event.preventDefault();
// Activate first tab
this.activateTab(this.buttons[0]);
break;
// Up and down are in keydown
// because we need to prevent page scroll >:)
case this.keys.up:
case this.keys.down:
this.determineOrientation(event);
break;
}
}
2021-03-13 20:13:44 +00:00
// Handle keyup on tabs
keyupEventListener(event) {
2021-03-13 20:13:44 +00:00
var key = event.keyCode;
switch (key) {
case this.keys.left:
case this.keys.right:
this.determineOrientation(event);
break;
}
}
2021-03-13 20:13:44 +00:00
// When a tablists aria-orientation is set to vertical,
// only up and down arrow should function.
// In all other cases only left and right arrow function.
determineOrientation(event) {
2021-03-13 20:13:44 +00:00
var key = event.keyCode;
var vertical = this.tablist.getAttribute('aria-orientation') == 'vertical';
var proceed = false;
if (vertical) {
if (key === this.keys.up || key === this.keys.down) {
event.preventDefault();
proceed = true;
}
}
else {
if (key === this.keys.left || key === this.keys.right) {
proceed = true;
}
}
if (proceed) {
this.switchTabOnArrowPress(event);
}
}
2021-03-13 20:13:44 +00:00
// Either focus the next, previous, first, or last tab
// depending on key pressed
switchTabOnArrowPress(event) {
2021-03-13 20:13:44 +00:00
var pressed = event.keyCode;
for (let button of this.buttons) {
button.addEventListener('focus', this.focusEventHandler.bind(this));
}
if (this.direction[pressed]) {
var target = event.target;
if (target.index !== undefined) {
if (this.buttons[target.index + this.direction[pressed]]) {
this.buttons[target.index + this.direction[pressed]].focus();
}
else if (pressed === this.keys.left || pressed === this.keys.up) {
this.focusLastTab();
}
else if (pressed === this.keys.right || pressed == this.keys.down) {
this.focusFirstTab();
}
}
}
}
2021-03-13 20:13:44 +00:00
// Activates any given tab panel
activateTab (tab, setFocus) {
2021-03-13 20:13:44 +00:00
if(tab.getAttribute("role") !== "tab") {
tab = tab.closest('[role="tab"]');
}
setFocus = setFocus || true;
// Deactivate all other tabs
this.deactivateTabs();
// Remove tabindex attribute
tab.removeAttribute('tabindex');
// Set the tab as selected
tab.setAttribute('aria-selected', 'true');
// Give the tab parent an is-active class
tab.parentNode.classList.add('is-active');
// Get the value of aria-controls (which is an ID)
var controls = tab.getAttribute('aria-controls');
// Remove hidden attribute from tab panel to make it visible
document.getElementById(controls).removeAttribute('hidden');
// Set focus when required
if (setFocus) {
tab.focus();
}
}
2021-03-13 20:13:44 +00:00
// Deactivate all tabs and tab panels
deactivateTabs() {
2021-03-13 20:13:44 +00:00
for (let button of this.buttons) {
button.parentNode.classList.remove('is-active');
button.setAttribute('tabindex', '-1');
button.setAttribute('aria-selected', 'false');
button.removeEventListener('focus', this.focusEventHandler.bind(this));
}
for (let panel of this.panels) {
panel.setAttribute('hidden', 'hidden');
}
}
2021-03-13 20:13:44 +00:00
focusFirstTab() {
2021-03-13 20:13:44 +00:00
this.buttons[0].focus();
}
2021-03-13 20:13:44 +00:00
focusLastTab() {
2021-03-13 20:13:44 +00:00
this.buttons[this.buttons.length - 1].focus();
}
2021-03-13 20:13:44 +00:00
// Determine whether there should be a delay
// when user navigates with the arrow keys
determineDelay() {
2021-03-13 20:13:44 +00:00
var hasDelay = this.tablist.hasAttribute('data-delay');
var delay = 0;
if (hasDelay) {
var delayValue = this.tablist.getAttribute('data-delay');
if (delayValue) {
delay = delayValue;
}
else {
// If no value is specified, default to 300ms
delay = 300;
}
}
2021-03-13 20:13:44 +00:00
return delay;
}
2021-03-13 20:13:44 +00:00
focusEventHandler(event) {
2021-03-13 20:13:44 +00:00
var target = event.target;
setTimeout(this.checkTabFocus.bind(this), this.delay, target);
}
// Only activate tab on focus if it still has focus after the delay
checkTabFocus(target) {
2021-03-13 20:13:44 +00:00
let focused = document.activeElement;
if (target === focused) {
this.activateTab(target, false);
}
}
2021-03-13 20:13:44 +00:00
}