1
0

dom.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /**
  2. * @module lib/dom
  3. * This module contains various functions for working with the DOM - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#dom)
  4. */
  5. import { PlatformError } from "./errors.js";
  6. /** Whether the DOM has finished loading */
  7. let domReady = false;
  8. document.addEventListener("DOMContentLoaded", () => domReady = true);
  9. /**
  10. * Returns `unsafeWindow` if the `@grant unsafeWindow` is given, otherwise falls back to the regular `window`
  11. */
  12. export function getUnsafeWindow(): Window {
  13. try {
  14. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  15. return unsafeWindow;
  16. }
  17. catch {
  18. return window;
  19. }
  20. }
  21. /**
  22. * Adds a parent container around the provided element
  23. * @returns Returns the new parent element
  24. */
  25. export function addParent<TElem extends Element, TParentElem extends Element>(element: TElem, newParent: TParentElem): TParentElem {
  26. const oldParent = element.parentNode;
  27. if(!oldParent)
  28. throw new Error("Element doesn't have a parent node");
  29. oldParent.replaceChild(newParent, element);
  30. newParent.appendChild(element);
  31. return newParent;
  32. }
  33. /**
  34. * Adds global CSS style in the form of a `<style>` element in the document's `<head>`
  35. * This needs to be run after the `DOMContentLoaded` event has fired on the document object (or instantly if `@run-at document-end` is used).
  36. * @param style CSS string
  37. * @returns Returns the created style element
  38. */
  39. export function addGlobalStyle(style: string): HTMLStyleElement {
  40. const styleElem = document.createElement("style");
  41. setInnerHtmlUnsafe(styleElem, style);
  42. document.head.appendChild(styleElem);
  43. return styleElem;
  44. }
  45. /**
  46. * Preloads an array of image URLs so they can be loaded instantly from the browser cache later on
  47. * @param rejects If set to `true`, the returned PromiseSettledResults will contain rejections for any of the images that failed to load. Is set to `false` by default.
  48. * @returns Returns an array of `PromiseSettledResult` - each resolved result will contain the loaded image element, while each rejected result will contain an `ErrorEvent`
  49. */
  50. export function preloadImages(srcUrls: string[], rejects = false): Promise<PromiseSettledResult<HTMLImageElement>[]> {
  51. const promises = srcUrls.map(src => new Promise<HTMLImageElement>((res, rej) => {
  52. const image = new Image();
  53. image.addEventListener("load", () => res(image));
  54. image.addEventListener("error", (evt) => rejects && rej(evt));
  55. image.src = src;
  56. }));
  57. return Promise.allSettled(promises);
  58. }
  59. /**
  60. * Tries to use `GM.openInTab` to open the given URL in a new tab, otherwise if the grant is not given, creates an invisible anchor element and clicks it.
  61. * For the fallback to work, this function needs to be run in response to a user interaction event, else the browser might reject it.
  62. * @param href The URL to open in a new tab
  63. * @param background If set to `true`, the tab will be opened in the background - set to `undefined` (default) to use the browser's default behavior
  64. * @param additionalProps Additional properties to set on the anchor element (only applies when `GM.openInTab` is not available)
  65. */
  66. export function openInNewTab(href: string, background?: boolean, additionalProps?: Partial<HTMLAnchorElement>): void {
  67. try {
  68. if(typeof window.GM === "object")
  69. GM.openInTab(href, background);
  70. }
  71. catch {
  72. const openElem = document.createElement("a");
  73. Object.assign(openElem, {
  74. className: "userutils-open-in-new-tab",
  75. target: "_blank",
  76. rel: "noopener noreferrer",
  77. tabIndex: -1,
  78. ariaHidden: "true",
  79. href,
  80. ...additionalProps,
  81. });
  82. Object.assign(openElem.style, {
  83. display: "none",
  84. pointerEvents: "none",
  85. });
  86. document.body.appendChild(openElem);
  87. openElem.click();
  88. // schedule removal after the click event has been processed
  89. setTimeout(() => {
  90. try {
  91. openElem.remove();
  92. }
  93. catch {
  94. void 0;
  95. }
  96. }, 0);
  97. }
  98. }
  99. /**
  100. * Intercepts the specified event on the passed object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  101. * If no predicate is specified, all events will be discarded.
  102. * This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are added after this function is called.
  103. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  104. */
  105. export function interceptEvent<
  106. TEvtObj extends EventTarget,
  107. TPredicateEvt extends Event
  108. > (
  109. eventObject: TEvtObj,
  110. eventName: Parameters<TEvtObj["addEventListener"]>[0],
  111. predicate: (event: TPredicateEvt) => boolean = () => true,
  112. ): void {
  113. // @ts-ignore
  114. if(typeof window.GM === "object" && GM?.info?.scriptHandler && GM.info.scriptHandler === "FireMonkey" && (eventObject === window || eventObject === getUnsafeWindow()))
  115. throw new PlatformError("Intercepting window events is not supported on FireMonkey due to the isolated context the userscript runs in.");
  116. // default is 25 on FF so this should hopefully be more than enough
  117. // @ts-ignore
  118. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  119. if(isNaN(Error.stackTraceLimit))
  120. Error.stackTraceLimit = 100;
  121. (function(original: typeof eventObject.addEventListener) {
  122. // @ts-ignore
  123. eventObject.__proto__.addEventListener = function(...args: Parameters<typeof eventObject.addEventListener>) {
  124. const origListener = typeof args[1] === "function" ? args[1] : args[1]?.handleEvent ?? (() => void 0);
  125. args[1] = function(...a) {
  126. if(args[0] === eventName && predicate((Array.isArray(a) ? a[0] : a) as TPredicateEvt))
  127. return;
  128. else
  129. return origListener.apply(this, a);
  130. };
  131. original.apply(this, args);
  132. };
  133. // @ts-ignore
  134. })(eventObject.__proto__.addEventListener);
  135. }
  136. /**
  137. * Intercepts the specified event on the window object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  138. * If no predicate is specified, all events will be discarded.
  139. * This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are added after this function is called.
  140. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  141. */
  142. export function interceptWindowEvent<TEvtKey extends keyof WindowEventMap>(
  143. eventName: TEvtKey,
  144. predicate: (event: WindowEventMap[TEvtKey]) => boolean = () => true,
  145. ): void {
  146. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  147. }
  148. /** Checks if an element is scrollable in the horizontal and vertical directions */
  149. export function isScrollable(element: Element): Record<"vertical" | "horizontal", boolean> {
  150. const { overflowX, overflowY } = getComputedStyle(element);
  151. return {
  152. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  153. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth,
  154. };
  155. }
  156. /**
  157. * Executes the callback when the passed element's property changes.
  158. * Contrary to an element's attributes, properties can usually not be observed with a MutationObserver.
  159. * This function shims the getter and setter of the property to invoke the callback.
  160. *
  161. * [Source](https://stackoverflow.com/a/61975440)
  162. * @param property The name of the property to observe
  163. * @param callback Callback to execute when the value is changed
  164. */
  165. export function observeElementProp<
  166. TElem extends Element = HTMLElement,
  167. TPropKey extends keyof TElem = keyof TElem,
  168. > (
  169. element: TElem,
  170. property: TPropKey,
  171. callback: (oldVal: TElem[TPropKey], newVal: TElem[TPropKey]) => void
  172. ): void {
  173. const elementPrototype = Object.getPrototypeOf(element);
  174. // eslint-disable-next-line no-prototype-builtins
  175. if(elementPrototype.hasOwnProperty(property)) {
  176. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  177. Object.defineProperty(element, property, {
  178. get: function() {
  179. // @ts-ignore
  180. // eslint-disable-next-line prefer-rest-params
  181. return descriptor?.get?.apply(this, arguments);
  182. },
  183. set: function() {
  184. const oldValue = this[property];
  185. // @ts-ignore
  186. // eslint-disable-next-line prefer-rest-params
  187. descriptor?.set?.apply(this, arguments);
  188. const newValue = this[property];
  189. if(typeof callback === "function") {
  190. // @ts-ignore
  191. callback.bind(this, oldValue, newValue);
  192. }
  193. return newValue;
  194. }
  195. });
  196. }
  197. }
  198. /**
  199. * Returns a "frame" of the closest siblings of the {@linkcode refElement}, based on the passed amount of siblings and {@linkcode refElementAlignment}
  200. * @param refElement The reference element to return the relative closest siblings from
  201. * @param siblingAmount The amount of siblings to return
  202. * @param refElementAlignment Can be set to `center-top` (default), `center-bottom`, `top`, or `bottom`, which will determine where the relative location of the provided {@linkcode refElement} is in the returned array
  203. * @param includeRef If set to `true` (default), the provided {@linkcode refElement} will be included in the returned array at the corresponding position
  204. * @template TSibling The type of the sibling elements that are returned
  205. * @returns An array of sibling elements
  206. */
  207. export function getSiblingsFrame<
  208. TSibling extends Element = HTMLElement,
  209. > (
  210. refElement: Element,
  211. siblingAmount: number,
  212. refElementAlignment: "center-top" | "center-bottom" | "top" | "bottom" = "center-top",
  213. includeRef = true,
  214. ): TSibling[] {
  215. const siblings = [...refElement.parentNode?.childNodes ?? []] as TSibling[];
  216. const elemSiblIdx = siblings.indexOf(refElement as TSibling);
  217. if(elemSiblIdx === -1)
  218. throw new Error("Element doesn't have a parent node");
  219. if(refElementAlignment === "top")
  220. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  221. else if(refElementAlignment.startsWith("center-")) {
  222. // if the amount of siblings is even, one of the two center ones will be decided by the value of `refElementAlignment`
  223. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  224. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  225. // if the amount of siblings is even, the top offset of 1 will be applied whenever `includeRef` is set to true
  226. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  227. // if the amount of siblings is odd, the bottom offset of 1 will be applied whenever `includeRef` is set to true
  228. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  229. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  230. // filter out the reference element if `includeRef` is set to false,
  231. // then slice the array to the desired framing including the offsets
  232. return [
  233. ...siblings
  234. .filter((_, idx) => includeRef || idx !== elemSiblIdx)
  235. .slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  236. ];
  237. }
  238. else if(refElementAlignment === "bottom")
  239. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  240. return [] as TSibling[];
  241. }
  242. let ttPolicy: { createHTML: (html: string) => string } | undefined;
  243. /**
  244. * Sets the innerHTML property of the provided element without any sanitation or validation.
  245. * Uses a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) on Chromium-based browsers to trick the browser into thinking the HTML is safe.
  246. * Use this if the page makes use of the CSP directive `require-trusted-types-for 'script'` and throws a "This document requires 'TrustedHTML' assignment" error on Chromium-based browsers.
  247. *
  248. * - ⚠️ This function does not perform any sanitization and should thus be used with utmost caution, as it can easily lead to XSS vulnerabilities!
  249. */
  250. export function setInnerHtmlUnsafe<TElement extends Element = HTMLElement>(element: TElement, html: string): TElement {
  251. // @ts-ignore
  252. if(!ttPolicy && typeof window?.trustedTypes?.createPolicy === "function") {
  253. // @ts-ignore
  254. ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
  255. createHTML: (unsafeHtml: string) => unsafeHtml,
  256. });
  257. }
  258. element.innerHTML = ttPolicy?.createHTML?.(html) ?? html;
  259. return element;
  260. }
  261. /**
  262. * Creates an invisible temporary element to probe its rendered style.
  263. * Has to be run after the `DOMContentLoaded` event has fired on the document object.
  264. * @param probeStyle Function to probe the element's style. First argument is the element's style object from [`window.getComputedStyle()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle), second argument is the element itself
  265. * @param element The element to probe, or a function that creates and returns the element - should not be added to the DOM prior to calling this function! - all probe elements will have the class `_uu_probe_element` added to them
  266. * @param hideOffscreen Whether to hide the element offscreen, enabled by default - disable if you want to probe the position style properties of the element
  267. * @param parentElement The parent element to append the probe element to, defaults to `document.body`
  268. * @returns The value returned by the `probeElement` function
  269. */
  270. export function probeElementStyle<
  271. TValue,
  272. TElem extends HTMLElement = HTMLSpanElement,
  273. > (
  274. probeStyle: (style: CSSStyleDeclaration, element: TElem) => TValue,
  275. element?: TElem | (() => TElem),
  276. hideOffscreen = true,
  277. parentElement = document.body,
  278. ): TValue {
  279. const el = element
  280. ? typeof element === "function" ? element() : element
  281. : document.createElement("span") as TElem;
  282. if(hideOffscreen) {
  283. el.style.position = "absolute";
  284. el.style.left = "-9999px";
  285. el.style.top = "-9999px";
  286. el.style.zIndex = "-9999";
  287. }
  288. el.classList.add("_uu_probe_element");
  289. parentElement.appendChild(el);
  290. const style = window.getComputedStyle(el);
  291. const result = probeStyle(style, el);
  292. setTimeout(() => el.remove(), 1);
  293. return result;
  294. }
  295. /** Returns whether or not the DOM has finished loading */
  296. export function isDomLoaded(): boolean {
  297. return domReady;
  298. }
  299. /**
  300. * Executes a callback and/or resolves the returned Promise when the DOM has finished loading.
  301. * Immediately executes/resolves if the DOM is already loaded.
  302. * @param cb Callback to execute when the DOM has finished loading
  303. * @returns Returns a Promise that resolves when the DOM has finished loading
  304. */
  305. export function onDomLoad(cb?: () => void): Promise<void> {
  306. return new Promise((res) => {
  307. if(domReady) {
  308. cb?.();
  309. res();
  310. }
  311. else
  312. document.addEventListener("DOMContentLoaded", () => {
  313. cb?.();
  314. res();
  315. });
  316. });
  317. }