stylus/js/dom.js

288 lines
8.0 KiB
JavaScript
Raw Normal View History

2017-03-25 05:54:58 +00:00
'use strict';
2017-04-21 17:35:22 +00:00
if (!navigator.userAgent.includes('Windows')) {
document.documentElement.classList.add('non-windows');
}
2017-04-08 10:19:44 +00:00
// polyfill for old browsers to enable [...results] and for-of
for (const type of [NodeList, NamedNodeMap, HTMLCollection, HTMLAllCollection]) {
if (!type.prototype[Symbol.iterator]) {
type.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
}
}
{
// display a full text tooltip on buttons with ellipsis overflow and no inherent title
const addTooltipsToEllipsized = () => {
for (const btn of document.getElementsByTagName('button')) {
if (btn.title && !btn.titleIsForEllipsis ||
btn.clientWidth === btn.preresizeClientWidth) {
continue;
}
btn.preresizeClientWidth = btn.clientWidth;
const padding = btn.offsetWidth - btn.clientWidth;
const displayedWidth = btn.getBoundingClientRect().width - padding;
if (btn.scrollWidth > displayedWidth) {
btn.title = btn.textContent;
btn.titleIsForEllipsis = true;
} else if (btn.title) {
btn.title = '';
}
}
};
// enqueue after DOMContentLoaded/load events
setTimeout(addTooltipsToEllipsized);
// throttle on continuous resizing
window.addEventListener('resize', () => debounce(addTooltipsToEllipsized, 100));
}
2017-05-16 22:09:31 +00:00
// add favicon in Firefox
2017-07-12 20:44:59 +00:00
// eslint-disable-next-line no-unused-expressions
2017-06-28 10:49:04 +00:00
navigator.userAgent.includes('Firefox') && setTimeout(() => {
dieOnDysfunction();
2017-06-28 10:49:04 +00:00
const iconset = ['', 'light/'][prefs.get('iconset')] || '';
for (const size of [38, 32, 19, 16]) {
2017-05-16 22:09:31 +00:00
document.head.appendChild($element({
tag: 'link',
rel: 'icon',
2017-06-28 10:49:04 +00:00
href: `/images/icon/${iconset}${size}.png`,
2017-05-16 22:09:31 +00:00
sizes: size + 'x' + size,
}));
}
2017-08-27 09:56:54 +00:00
// set hyphenation language
document.documentElement.setAttribute('lang', chrome.i18n.getUILanguage());
2017-06-28 10:49:04 +00:00
});
2017-05-16 22:09:31 +00:00
2017-03-25 05:54:58 +00:00
function onDOMready() {
2017-07-16 18:02:00 +00:00
if (document.readyState !== 'loading') {
2017-03-25 05:54:58 +00:00
return Promise.resolve();
}
return new Promise(resolve => {
document.addEventListener('DOMContentLoaded', function _() {
document.removeEventListener('DOMContentLoaded', _);
resolve();
});
});
}
2017-08-18 15:58:59 +00:00
function onDOMscripted(scripts) {
if (scripts) {
return new Promise(resolve => {
addResolver(resolve);
onDOMscripted.scriptQueue = scripts;
loadNextScript();
});
}
if (onDOMscripted.scriptQueue) {
return new Promise(resolve => addResolver(resolve));
}
2017-08-18 16:13:03 +00:00
if (document.readyState !== 'loading') {
2017-08-18 15:58:59 +00:00
if (onDOMscripted.resolveOnReady) {
onDOMscripted.resolveOnReady.forEach(r => r());
onDOMscripted.resolveOnReady = null;
}
return Promise.resolve();
}
return onDOMready().then(onDOMscripted);
function loadNextScript() {
const next = onDOMscripted.scriptQueue.shift();
if (!next) {
onDOMscripted.scriptQueue = null;
onDOMscripted();
2017-08-18 16:13:03 +00:00
} else if (typeof next === 'function') {
2017-08-18 15:58:59 +00:00
Promise.resolve(next())
.then(loadNextScript);
2017-08-18 16:13:03 +00:00
} else {
2017-08-18 15:58:59 +00:00
Promise.all(
(next instanceof Array ? next : [next]).map(next =>
2017-08-18 16:13:03 +00:00
typeof next === 'function'
2017-08-18 15:58:59 +00:00
? next()
: injectScript({src: next, async: true})
)
).then(loadNextScript);
}
}
function addResolver(r) {
if (!onDOMscripted.resolveOnReady) {
onDOMscripted.resolveOnReady = [];
}
onDOMscripted.resolveOnReady.push(r);
}
}
function injectScript(properties) {
2017-08-18 16:13:03 +00:00
if (typeof properties === 'string') {
2017-08-18 15:58:59 +00:00
properties = {src: properties};
}
if (!properties || !properties.src) {
return;
}
2017-08-29 11:28:13 +00:00
if (injectScript.cache) {
if (injectScript.cache.has(properties.src)) {
return Promise.resolve();
}
} else {
injectScript.cache = new Set();
}
injectScript.cache.add(properties.src);
2017-08-18 15:58:59 +00:00
const script = document.head.appendChild(document.createElement('script'));
Object.assign(script, properties);
if (!properties.onload) {
return new Promise(resolve => {
script.onload = () => {
script.onload = null;
resolve();
};
2017-08-18 15:58:59 +00:00
});
}
}
function injectCSS(url) {
if (!url) {
return;
}
document.head.appendChild($element({
tag: 'link',
rel: 'stylesheet',
href: url
}));
}
2017-03-25 05:54:58 +00:00
function scrollElementIntoView(element) {
// align to the top/bottom of the visible area if wasn't visible
const bounds = element.getBoundingClientRect();
if (bounds.top < 0 || bounds.top > innerHeight - bounds.height) {
element.scrollIntoView(bounds.top < 0);
}
}
function animateElement(
element, {
className = 'highlight',
removeExtraClasses = [],
remove = false,
} = {}) {
return element && new Promise(resolve => {
2017-03-25 05:54:58 +00:00
element.addEventListener('animationend', function _() {
element.removeEventListener('animationend', _);
element.classList.remove(
className,
// In Firefox, `resolve()` might be called one frame later.
// This is helpful to clean-up on the same frame
...removeExtraClasses
);
2017-03-25 05:54:58 +00:00
// TODO: investigate why animation restarts if the elements is removed in .then()
if (remove) {
element.remove();
}
resolve();
});
element.classList.add(className);
});
}
function enforceInputRange(element) {
const min = Number(element.min);
const max = Number(element.max);
const doNotify = () => element.dispatchEvent(new Event('change', {bubbles: true}));
const onChange = ({type}) => {
2017-07-16 18:02:00 +00:00
if (type === 'input' && element.checkValidity()) {
doNotify();
2017-07-16 18:02:00 +00:00
} else if (type === 'change' && !element.checkValidity()) {
element.value = Math.max(min, Math.min(max, Number(element.value)));
doNotify();
}
};
element.addEventListener('change', onChange);
element.addEventListener('input', onChange);
}
2017-03-25 05:54:58 +00:00
function $(selector, base = document) {
// we have ids with . like #manage.onlyEnabled which looks like #id.class
2017-03-25 05:54:58 +00:00
// so since getElementById is superfast we'll try it anyway
const byId = selector.startsWith('#') && document.getElementById(selector.slice(1));
return byId || base.querySelector(selector);
}
function $$(selector, base = document) {
return [...base.querySelectorAll(selector)];
}
function $element(opt) {
// tag: string, default 'div', may include namespace like 'ns#tag'
// appendChild: element/string or an array of elements/strings
// dataset: object
// any DOM property: assigned as is
const [ns, tag] = opt.tag && opt.tag.includes('#')
? opt.tag.split('#')
: [null, opt.tag];
const element = ns
2017-07-16 18:02:00 +00:00
? document.createElementNS(ns === 'SVG' || ns === 'svg' ? 'http://www.w3.org/2000/svg' : ns, tag)
: document.createElement(tag || 'div');
const children = opt.appendChild instanceof Array ? opt.appendChild : [opt.appendChild];
for (const child of children) {
if (child) {
element.appendChild(child instanceof Node ? child : document.createTextNode(child));
}
}
delete opt.appendChild;
delete opt.tag;
if (opt.dataset) {
Object.assign(element.dataset, opt.dataset);
delete opt.dataset;
}
if (ns) {
for (const attr in opt) {
element.setAttributeNS(null, attr, opt[attr]);
}
} else {
Object.assign(element, opt);
}
return element;
}
function dieOnDysfunction() {
function die() {
location.href = '/msgbox/dysfunctional.html';
throw 0;
}
(() => {
try {
return indexedDB;
} catch (e) {
die();
}
})();
Object.assign(indexedDB.open('test'), {
onerror: die,
onupgradeneeded: indexedDB.deleteDatabase('test'),
});
// TODO: fallback to sendMessage in FF since private windows can't get bg page
chrome.windows.getCurrent(wnd => wnd.incognito && die());
2017-08-28 10:10:38 +00:00
// check if privacy settings were fixed but the extension wasn't reloaded,
// use setTimeout to auto-cancel if already dead
setTimeout(() => {
const bg = chrome.extension.getBackgroundPage();
if (bg && !(bg.cachedStyles || {}).list) {
chrome.storage.local.get('reloaded', data => {
if (!data || Date.now() - (data.reloaded || 0) > 10e3) {
chrome.storage.local.set({reloaded: Date.now()}, () => chrome.runtime.reload());
}
});
}
});
}