dom.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. 'use strict';
  2. if (!/^Win\d+/.test(navigator.platform)) {
  3. document.documentElement.classList.add('non-windows');
  4. }
  5. // polyfill for old browsers to enable [...results] and for-of
  6. for (const type of [NodeList, NamedNodeMap, HTMLCollection, HTMLAllCollection]) {
  7. if (!type.prototype[Symbol.iterator]) {
  8. type.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  9. }
  10. }
  11. $.remove = (selector, base = document) => {
  12. const el = selector && typeof selector === 'string' ? $(selector, base) : selector;
  13. if (el) {
  14. el.remove();
  15. }
  16. };
  17. $$.remove = (selector, base = document) => {
  18. for (const el of base.querySelectorAll(selector)) {
  19. el.remove();
  20. }
  21. };
  22. {
  23. // display a full text tooltip on buttons with ellipsis overflow and no inherent title
  24. const addTooltipsToEllipsized = () => {
  25. for (const btn of document.getElementsByTagName('button')) {
  26. if (btn.title && !btn.titleIsForEllipsis ||
  27. btn.clientWidth === btn.preresizeClientWidth) {
  28. continue;
  29. }
  30. btn.preresizeClientWidth = btn.clientWidth;
  31. const padding = btn.offsetWidth - btn.clientWidth;
  32. const displayedWidth = btn.getBoundingClientRect().width - padding;
  33. if (btn.scrollWidth > displayedWidth) {
  34. btn.title = btn.textContent;
  35. btn.titleIsForEllipsis = true;
  36. } else if (btn.title) {
  37. btn.title = '';
  38. }
  39. }
  40. };
  41. // enqueue after DOMContentLoaded/load events
  42. setTimeout(addTooltipsToEllipsized);
  43. // throttle on continuous resizing
  44. let timer;
  45. window.addEventListener('resize', () => {
  46. clearTimeout(timer);
  47. timer = setTimeout(addTooltipsToEllipsized, 100);
  48. });
  49. }
  50. onDOMready().then(() => {
  51. $.remove('#firefox-transitions-bug-suppressor');
  52. initCollapsibles();
  53. });
  54. if (!chrome.app && chrome.windows) {
  55. // die if unable to access BG directly
  56. chrome.windows.getCurrent(wnd => {
  57. if (!BG && wnd.incognito) {
  58. // private windows can't get bg page
  59. location.href = '/msgbox/dysfunctional.html';
  60. throw 0;
  61. }
  62. });
  63. // add favicon in Firefox
  64. setTimeout(() => {
  65. if (!window.prefs) {
  66. return;
  67. }
  68. const iconset = ['', 'light/'][prefs.get('iconset')] || '';
  69. for (const size of [38, 32, 19, 16]) {
  70. document.head.appendChild($create('link', {
  71. rel: 'icon',
  72. href: `/images/icon/${iconset}${size}.png`,
  73. sizes: size + 'x' + size,
  74. }));
  75. }
  76. });
  77. // set hyphenation language
  78. document.documentElement.setAttribute('lang', chrome.i18n.getUILanguage());
  79. }
  80. function onDOMready() {
  81. if (document.readyState !== 'loading') {
  82. return Promise.resolve();
  83. }
  84. return new Promise(resolve => {
  85. document.addEventListener('DOMContentLoaded', function _() {
  86. document.removeEventListener('DOMContentLoaded', _);
  87. resolve();
  88. });
  89. });
  90. }
  91. function scrollElementIntoView(element, {invalidMarginRatio = 0} = {}) {
  92. // align to the top/bottom of the visible area if wasn't visible
  93. const {top, height} = element.getBoundingClientRect();
  94. const {top: parentTop, bottom: parentBottom} = element.parentNode.getBoundingClientRect();
  95. const windowHeight = window.innerHeight;
  96. if (top < Math.max(parentTop, windowHeight * invalidMarginRatio) ||
  97. top > Math.min(parentBottom, windowHeight) - height - windowHeight * invalidMarginRatio) {
  98. window.scrollBy(0, top - windowHeight / 2 + height);
  99. }
  100. }
  101. function animateElement(
  102. element, {
  103. className = 'highlight',
  104. removeExtraClasses = [],
  105. onComplete,
  106. } = {}) {
  107. return element && new Promise(resolve => {
  108. element.addEventListener('animationend', function _() {
  109. element.removeEventListener('animationend', _);
  110. element.classList.remove(
  111. className,
  112. // In Firefox, `resolve()` might be called one frame later.
  113. // This is helpful to clean-up on the same frame
  114. ...removeExtraClasses
  115. );
  116. // TODO: investigate why animation restarts for 'display' modification in .then()
  117. if (typeof onComplete === 'function') {
  118. onComplete.call(element);
  119. }
  120. resolve();
  121. });
  122. element.classList.add(className);
  123. });
  124. }
  125. function enforceInputRange(element) {
  126. const min = Number(element.min);
  127. const max = Number(element.max);
  128. const doNotify = () => element.dispatchEvent(new Event('change', {bubbles: true}));
  129. const onChange = ({type}) => {
  130. if (type === 'input' && element.checkValidity()) {
  131. doNotify();
  132. } else if (type === 'change' && !element.checkValidity()) {
  133. element.value = Math.max(min, Math.min(max, Number(element.value)));
  134. doNotify();
  135. }
  136. };
  137. element.addEventListener('change', onChange);
  138. element.addEventListener('input', onChange);
  139. }
  140. function $(selector, base = document) {
  141. // we have ids with . like #manage.onlyEnabled which looks like #id.class
  142. // so since getElementById is superfast we'll try it anyway
  143. const byId = selector.startsWith('#') && document.getElementById(selector.slice(1));
  144. return byId || base.querySelector(selector);
  145. }
  146. function $$(selector, base = document) {
  147. return [...base.querySelectorAll(selector)];
  148. }
  149. function $create(selector = 'div', properties, children) {
  150. /*
  151. $create('tag#id.class.class', ?[children])
  152. $create('tag#id.class.class', ?textContentOrChildNode)
  153. $create('tag#id.class.class', {properties}, ?[children])
  154. $create('tag#id.class.class', {properties}, ?textContentOrChildNode)
  155. tag is 'div' by default, #id and .class are optional
  156. $create([children])
  157. $create({propertiesAndOptions})
  158. $create({propertiesAndOptions}, ?[children])
  159. tag: string, default 'div'
  160. appendChild: element/string or an array of elements/strings
  161. dataset: object
  162. any DOM property: assigned as is
  163. tag may include namespace like 'ns:tag'
  164. */
  165. let ns, tag, opt;
  166. if (typeof selector === 'string') {
  167. if (Array.isArray(properties) ||
  168. properties instanceof Node ||
  169. typeof properties !== 'object') {
  170. opt = {};
  171. children = properties;
  172. } else {
  173. opt = properties || {};
  174. }
  175. const idStart = (selector.indexOf('#') + 1 || selector.length + 1) - 1;
  176. const classStart = (selector.indexOf('.') + 1 || selector.length + 1) - 1;
  177. const id = selector.slice(idStart + 1, classStart);
  178. if (id) {
  179. opt.id = id;
  180. }
  181. const cls = selector.slice(classStart + 1);
  182. if (cls) {
  183. opt[selector.includes(':') ? 'class' : 'className'] =
  184. cls.includes('.') ? cls.replace(/\./g, ' ') : cls;
  185. }
  186. tag = selector.slice(0, Math.min(idStart, classStart));
  187. } else if (Array.isArray(selector)) {
  188. tag = 'div';
  189. opt = {};
  190. children = selector;
  191. } else {
  192. opt = selector;
  193. tag = opt.tag;
  194. delete opt.tag;
  195. children = opt.appendChild || properties;
  196. delete opt.appendChild;
  197. }
  198. if (tag && tag.includes(':')) {
  199. ([ns, tag] = tag.split(':'));
  200. }
  201. const element = ns
  202. ? document.createElementNS(ns === 'SVG' || ns === 'svg' ? 'http://www.w3.org/2000/svg' : ns, tag)
  203. : document.createElement(tag || 'div');
  204. for (const child of Array.isArray(children) ? children : [children]) {
  205. if (child) {
  206. element.appendChild(child instanceof Node ? child : document.createTextNode(child));
  207. }
  208. }
  209. if (opt.dataset) {
  210. Object.assign(element.dataset, opt.dataset);
  211. delete opt.dataset;
  212. }
  213. if (opt.attributes) {
  214. for (const attr in opt.attributes) {
  215. element.setAttribute(attr, opt.attributes[attr]);
  216. }
  217. delete opt.attributes;
  218. }
  219. if (ns) {
  220. for (const attr in opt) {
  221. const i = attr.indexOf(':') + 1;
  222. const attrNS = i && `http://www.w3.org/1999/${attr.slice(0, i - 1)}`;
  223. element.setAttributeNS(attrNS || null, attr, opt[attr]);
  224. }
  225. } else {
  226. Object.assign(element, opt);
  227. }
  228. return element;
  229. }
  230. function $createLink(href = '', content) {
  231. const opt = {
  232. tag: 'a',
  233. target: '_blank',
  234. rel: 'noopener'
  235. };
  236. if (typeof href === 'object') {
  237. Object.assign(opt, href);
  238. } else {
  239. opt.href = href;
  240. }
  241. opt.appendChild = opt.appendChild || content;
  242. return $create(opt);
  243. }
  244. // makes <details> with [data-pref] save/restore their state
  245. function initCollapsibles({bindClickOn = 'h2'} = {}) {
  246. const prefMap = {};
  247. const elements = $$('details[data-pref]');
  248. if (!elements.length) {
  249. return;
  250. }
  251. for (const el of elements) {
  252. const key = el.dataset.pref;
  253. prefMap[key] = el;
  254. el.open = prefs.get(key);
  255. (bindClickOn && $(bindClickOn, el) || el).addEventListener('click', onClick);
  256. }
  257. prefs.subscribe(Object.keys(prefMap), (key, value) => {
  258. const el = prefMap[key];
  259. if (el.open !== value) {
  260. el.open = value;
  261. }
  262. });
  263. function onClick(event) {
  264. if (event.target.closest('.intercepts-click')) {
  265. event.preventDefault();
  266. } else {
  267. setTimeout(saveState, 0, event.target.closest('details'));
  268. }
  269. }
  270. function saveState(el) {
  271. prefs.set(el.dataset.pref, el.open);
  272. }
  273. }