dom.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /**
  2. * Returns `unsafeWindow` if the `@grant unsafeWindow` is given, otherwise falls back to the regular `window`
  3. */
  4. export function getUnsafeWindow() {
  5. try {
  6. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  7. return unsafeWindow;
  8. }
  9. catch(e) {
  10. return window;
  11. }
  12. }
  13. /**
  14. * Inserts {@linkcode afterElement} as a sibling just after the provided {@linkcode beforeElement}
  15. * @returns Returns the {@linkcode afterElement}
  16. */
  17. export function insertAfter(beforeElement: Element, afterElement: Element) {
  18. beforeElement.parentNode?.insertBefore(afterElement, beforeElement.nextSibling);
  19. return afterElement;
  20. }
  21. /**
  22. * Adds a parent container around the provided element
  23. * @returns Returns the new parent element
  24. */
  25. export function addParent(element: Element, newParent: Element) {
  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) {
  40. const styleElem = document.createElement("style");
  41. styleElem.innerHTML = 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
  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) {
  51. const promises = srcUrls.map(src => new Promise((res, rej) => {
  52. const image = new Image();
  53. image.src = src;
  54. image.addEventListener("load", () => res(image));
  55. image.addEventListener("error", (evt) => rejects && rej(evt));
  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. */
  65. export function openInNewTab(href: string, background?: boolean) {
  66. try {
  67. GM.openInTab(href, background);
  68. }
  69. catch(e) {
  70. const openElem = document.createElement("a");
  71. Object.assign(openElem, {
  72. className: "userutils-open-in-new-tab",
  73. target: "_blank",
  74. rel: "noopener noreferrer",
  75. href,
  76. });
  77. openElem.style.display = "none";
  78. document.body.appendChild(openElem);
  79. openElem.click();
  80. // timeout just to be safe
  81. setTimeout(openElem.remove, 50);
  82. }
  83. }
  84. /**
  85. * Intercepts the specified event on the passed object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  86. * If no predicate is specified, all events will be discarded.
  87. * 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.
  88. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  89. */
  90. export function interceptEvent<TEvtObj extends EventTarget, TPredicateEvt extends Event>(
  91. eventObject: TEvtObj,
  92. eventName: Parameters<TEvtObj["addEventListener"]>[0],
  93. predicate: (event: TPredicateEvt) => boolean = () => true,
  94. ) {
  95. // default is 25 on FF so this should hopefully be more than enough
  96. // @ts-ignore
  97. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  98. if(isNaN(Error.stackTraceLimit))
  99. Error.stackTraceLimit = 100;
  100. (function(original: typeof eventObject.addEventListener) {
  101. // @ts-ignore
  102. eventObject.__proto__.addEventListener = function(...args: Parameters<typeof eventObject.addEventListener>) {
  103. const origListener = typeof args[1] === "function" ? args[1] : args[1]?.handleEvent ?? (() => void 0);
  104. args[1] = function(...a) {
  105. if(args[0] === eventName && predicate((Array.isArray(a) ? a[0] : a) as TPredicateEvt))
  106. return;
  107. else
  108. return origListener.apply(this, a);
  109. };
  110. original.apply(this, args);
  111. };
  112. // @ts-ignore
  113. })(eventObject.__proto__.addEventListener);
  114. }
  115. /**
  116. * Intercepts the specified event on the window object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  117. * If no predicate is specified, all events will be discarded.
  118. * 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.
  119. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  120. */
  121. export function interceptWindowEvent<TEvtKey extends keyof WindowEventMap>(
  122. eventName: TEvtKey,
  123. predicate: (event: WindowEventMap[TEvtKey]) => boolean = () => true,
  124. ) {
  125. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  126. }
  127. /** Checks if an element is scrollable in the horizontal and vertical directions */
  128. export function isScrollable(element: Element) {
  129. const { overflowX, overflowY } = getComputedStyle(element);
  130. return {
  131. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  132. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth,
  133. };
  134. }
  135. /**
  136. * Executes the callback when the passed element's property changes.
  137. * Contrary to an element's attributes, properties can usually not be observed with a MutationObserver.
  138. * This function shims the getter and setter of the property to invoke the callback.
  139. *
  140. * [Source](https://stackoverflow.com/a/61975440)
  141. * @param property The name of the property to observe
  142. * @param callback Callback to execute when the value is changed
  143. */
  144. export function observeElementProp<
  145. TElem extends Element = HTMLElement,
  146. TPropKey extends keyof TElem = keyof TElem,
  147. >(
  148. element: TElem,
  149. property: TPropKey,
  150. callback: (oldVal: TElem[TPropKey], newVal: TElem[TPropKey]) => void
  151. ) {
  152. const elementPrototype = Object.getPrototypeOf(element);
  153. // eslint-disable-next-line no-prototype-builtins
  154. if(elementPrototype.hasOwnProperty(property)) {
  155. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  156. Object.defineProperty(element, property, {
  157. get: function() {
  158. // @ts-ignore
  159. // eslint-disable-next-line prefer-rest-params
  160. return descriptor?.get?.apply(this, arguments);
  161. },
  162. set: function() {
  163. const oldValue = this[property];
  164. // @ts-ignore
  165. // eslint-disable-next-line prefer-rest-params
  166. descriptor?.set?.apply(this, arguments);
  167. const newValue = this[property];
  168. if(typeof callback === "function") {
  169. // @ts-ignore
  170. callback.bind(this, oldValue, newValue);
  171. }
  172. return newValue;
  173. }
  174. });
  175. }
  176. }
  177. /**
  178. * Returns a "frame" of the closest siblings of the {@linkcode refElement}, based on the passed amount of siblings and {@linkcode refElementAlignment}
  179. * @param refElement The reference element to return the relative closest siblings from
  180. * @param siblingAmount The amount of siblings to return
  181. * @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
  182. * @param includeRef If set to `true` (default), the provided {@linkcode refElement} will be included in the returned array at the corresponding position
  183. * @template TSibling The type of the sibling elements that are returned
  184. * @returns An array of sibling elements
  185. */
  186. export function getSiblingsFrame<
  187. TSibling extends Element = HTMLElement,
  188. >(
  189. refElement: Element,
  190. siblingAmount: number,
  191. refElementAlignment: "center-top" | "center-bottom" | "top" | "bottom" = "center-top",
  192. includeRef = true,
  193. ): TSibling[] {
  194. const siblings = [...refElement.parentNode?.childNodes ?? []] as TSibling[];
  195. const elemSiblIdx = siblings.indexOf(refElement as TSibling);
  196. if(elemSiblIdx === -1)
  197. throw new Error("Element doesn't have a parent node");
  198. if(refElementAlignment === "top")
  199. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  200. else if(refElementAlignment.startsWith("center-")) {
  201. // if the amount of siblings is even, one of the two center ones will be decided by the value of `refElementAlignment`
  202. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  203. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  204. // if the amount of siblings is even, the top offset of 1 will be applied whenever `includeRef` is set to true
  205. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  206. // if the amount of siblings is odd, the bottom offset of 1 will be applied whenever `includeRef` is set to true
  207. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  208. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  209. // filter out the reference element if `includeRef` is set to false,
  210. // then slice the array to the desired framing including the offsets
  211. return [
  212. ...siblings
  213. .filter((_, idx) => includeRef || idx !== elemSiblIdx)
  214. .slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  215. ];
  216. }
  217. else if(refElementAlignment === "bottom")
  218. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  219. return [] as TSibling[];
  220. }