You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dom.js 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import {debounce} from 'throttle-debounce';
  2. function elementsCall(el, func, ...args) {
  3. if (typeof el === 'string' || el instanceof String) {
  4. el = document.querySelectorAll(el);
  5. }
  6. if (el instanceof Node) {
  7. func(el, ...args);
  8. } else if (el.length !== undefined) {
  9. // this works for: NodeList, HTMLCollection, Array, jQuery
  10. for (const e of el) {
  11. func(e, ...args);
  12. }
  13. } else {
  14. throw new Error('invalid argument to be shown/hidden');
  15. }
  16. }
  17. /**
  18. * @param el string (selector), Node, NodeList, HTMLCollection, Array or jQuery
  19. * @param force force=true to show or force=false to hide, undefined to toggle
  20. */
  21. function toggleShown(el, force) {
  22. if (force === true) {
  23. el.classList.remove('gt-hidden');
  24. } else if (force === false) {
  25. el.classList.add('gt-hidden');
  26. } else if (force === undefined) {
  27. el.classList.toggle('gt-hidden');
  28. } else {
  29. throw new Error('invalid force argument');
  30. }
  31. }
  32. export function showElem(el) {
  33. elementsCall(el, toggleShown, true);
  34. }
  35. export function hideElem(el) {
  36. elementsCall(el, toggleShown, false);
  37. }
  38. export function toggleElem(el, force) {
  39. elementsCall(el, toggleShown, force);
  40. }
  41. export function isElemHidden(el) {
  42. const res = [];
  43. elementsCall(el, (e) => res.push(e.classList.contains('gt-hidden')));
  44. if (res.length > 1) throw new Error(`isElemHidden doesn't work for multiple elements`);
  45. return res[0];
  46. }
  47. export function queryElemSiblings(el, selector) {
  48. return Array.from(el.parentNode.children).filter((child) => child !== el && child.matches(selector));
  49. }
  50. export function onDomReady(cb) {
  51. if (document.readyState === 'loading') {
  52. document.addEventListener('DOMContentLoaded', cb);
  53. } else {
  54. cb();
  55. }
  56. }
  57. // checks whether an element is owned by the current document, and whether it is a document fragment or element node
  58. // if it is, it means it is a "normal" element managed by us, which can be modified safely.
  59. export function isDocumentFragmentOrElementNode(el) {
  60. try {
  61. return el.ownerDocument === document && el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
  62. } catch {
  63. // in case the el is not in the same origin, then the access to nodeType would fail
  64. return false;
  65. }
  66. }
  67. // autosize a textarea to fit content. Based on
  68. // https://github.com/github/textarea-autosize
  69. // ---------------------------------------------------------------------
  70. // Copyright (c) 2018 GitHub, Inc.
  71. //
  72. // Permission is hereby granted, free of charge, to any person obtaining
  73. // a copy of this software and associated documentation files (the
  74. // "Software"), to deal in the Software without restriction, including
  75. // without limitation the rights to use, copy, modify, merge, publish,
  76. // distribute, sublicense, and/or sell copies of the Software, and to
  77. // permit persons to whom the Software is furnished to do so, subject to
  78. // the following conditions:
  79. //
  80. // The above copyright notice and this permission notice shall be
  81. // included in all copies or substantial portions of the Software.
  82. // ---------------------------------------------------------------------
  83. export function autosize(textarea, {viewportMarginBottom = 0} = {}) {
  84. let isUserResized = false;
  85. // lastStyleHeight and initialStyleHeight are CSS values like '100px'
  86. let lastMouseX, lastMouseY, lastStyleHeight, initialStyleHeight;
  87. function onUserResize(event) {
  88. if (isUserResized) return;
  89. if (lastMouseX !== event.clientX || lastMouseY !== event.clientY) {
  90. const newStyleHeight = textarea.style.height;
  91. if (lastStyleHeight && lastStyleHeight !== newStyleHeight) {
  92. isUserResized = true;
  93. }
  94. lastStyleHeight = newStyleHeight;
  95. }
  96. lastMouseX = event.clientX;
  97. lastMouseY = event.clientY;
  98. }
  99. function overflowOffset() {
  100. let offsetTop = 0;
  101. let el = textarea;
  102. while (el !== document.body && el !== null) {
  103. offsetTop += el.offsetTop || 0;
  104. el = el.offsetParent;
  105. }
  106. const top = offsetTop - document.defaultView.scrollY;
  107. const bottom = document.documentElement.clientHeight - (top + textarea.offsetHeight);
  108. return {top, bottom};
  109. }
  110. function resizeToFit() {
  111. if (isUserResized) return;
  112. if (textarea.offsetWidth <= 0 && textarea.offsetHeight <= 0) return;
  113. try {
  114. const {top, bottom} = overflowOffset();
  115. const isOutOfViewport = top < 0 || bottom < 0;
  116. const computedStyle = getComputedStyle(textarea);
  117. const topBorderWidth = parseFloat(computedStyle.borderTopWidth);
  118. const bottomBorderWidth = parseFloat(computedStyle.borderBottomWidth);
  119. const isBorderBox = computedStyle.boxSizing === 'border-box';
  120. const borderAddOn = isBorderBox ? topBorderWidth + bottomBorderWidth : 0;
  121. const adjustedViewportMarginBottom = bottom < viewportMarginBottom ? bottom : viewportMarginBottom;
  122. const curHeight = parseFloat(computedStyle.height);
  123. const maxHeight = curHeight + bottom - adjustedViewportMarginBottom;
  124. textarea.style.height = 'auto';
  125. let newHeight = textarea.scrollHeight + borderAddOn;
  126. if (isOutOfViewport) {
  127. // it is already out of the viewport:
  128. // * if the textarea is expanding: do not resize it
  129. if (newHeight > curHeight) {
  130. newHeight = curHeight;
  131. }
  132. // * if the textarea is shrinking, shrink line by line (just use the
  133. // scrollHeight). do not apply max-height limit, otherwise the page
  134. // flickers and the textarea jumps
  135. } else {
  136. // * if it is in the viewport, apply the max-height limit
  137. newHeight = Math.min(maxHeight, newHeight);
  138. }
  139. textarea.style.height = `${newHeight}px`;
  140. lastStyleHeight = textarea.style.height;
  141. } finally {
  142. // ensure that the textarea is fully scrolled to the end, when the cursor
  143. // is at the end during an input event
  144. if (textarea.selectionStart === textarea.selectionEnd &&
  145. textarea.selectionStart === textarea.value.length) {
  146. textarea.scrollTop = textarea.scrollHeight;
  147. }
  148. }
  149. }
  150. function onFormReset() {
  151. isUserResized = false;
  152. if (initialStyleHeight !== undefined) {
  153. textarea.style.height = initialStyleHeight;
  154. } else {
  155. textarea.style.removeProperty('height');
  156. }
  157. }
  158. textarea.addEventListener('mousemove', onUserResize);
  159. textarea.addEventListener('input', resizeToFit);
  160. textarea.form?.addEventListener('reset', onFormReset);
  161. initialStyleHeight = textarea.style.height ?? undefined;
  162. if (textarea.value) resizeToFit();
  163. return {
  164. resizeToFit,
  165. destroy() {
  166. textarea.removeEventListener('mousemove', onUserResize);
  167. textarea.removeEventListener('input', resizeToFit);
  168. textarea.form?.removeEventListener('reset', onFormReset);
  169. },
  170. };
  171. }
  172. export function onInputDebounce(fn) {
  173. return debounce(300, fn);
  174. }
  175. // Set the `src` attribute on an element and returns a promise that resolves once the element
  176. // has loaded or errored. Suitable for all elements mention in:
  177. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/load_event
  178. export function loadElem(el, src) {
  179. return new Promise((resolve) => {
  180. el.addEventListener('load', () => resolve(true), {once: true});
  181. el.addEventListener('error', () => resolve(false), {once: true});
  182. el.src = src;
  183. });
  184. }
  185. // some browsers like PaleMoon don't have "SubmitEvent" support, so polyfill it by a tricky method: use the last clicked button as submitter
  186. // it can't use other transparent polyfill patches because PaleMoon also doesn't support "addEventListener(capture)"
  187. const needSubmitEventPolyfill = typeof SubmitEvent === 'undefined';
  188. export function submitEventSubmitter(e) {
  189. e = e.originalEvent ?? e; // if the event is wrapped by jQuery, use "originalEvent", otherwise, use the event itself
  190. return needSubmitEventPolyfill ? (e.target._submitter || null) : e.submitter;
  191. }
  192. function submitEventPolyfillListener(e) {
  193. const form = e.target.closest('form');
  194. if (!form) return;
  195. form._submitter = e.target.closest('button:not([type]), button[type="submit"], input[type="submit"]');
  196. }
  197. export function initSubmitEventPolyfill() {
  198. if (!needSubmitEventPolyfill) return;
  199. console.warn(`This browser doesn't have "SubmitEvent" support, use a tricky method to polyfill`);
  200. document.body.addEventListener('click', submitEventPolyfillListener);
  201. document.body.addEventListener('focus', submitEventPolyfillListener);
  202. }
  203. /**
  204. * Check if an element is visible, equivalent to jQuery's `:visible` pseudo.
  205. * Note: This function doesn't account for all possible visibility scenarios.
  206. * @param {HTMLElement} element The element to check.
  207. * @returns {boolean} True if the element is visible.
  208. */
  209. export function isElemVisible(element) {
  210. if (!element) return false;
  211. return Boolean(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
  212. }
  213. // extract text and images from "paste" event
  214. export function getPastedContent(e) {
  215. const images = [];
  216. for (const item of e.clipboardData?.items ?? []) {
  217. if (item.type?.startsWith('image/')) {
  218. images.push(item.getAsFile());
  219. }
  220. }
  221. const text = e.clipboardData?.getData?.('text') ?? '';
  222. return {text, images};
  223. }
  224. // replace selected text in a textarea while preserving editor history, e.g. CTRL-Z works after this
  225. export function replaceTextareaSelection(textarea, text) {
  226. const before = textarea.value.slice(0, textarea.selectionStart ?? undefined);
  227. const after = textarea.value.slice(textarea.selectionEnd ?? undefined);
  228. let success = true;
  229. textarea.contentEditable = 'true';
  230. try {
  231. success = document.execCommand('insertText', false, text);
  232. } catch {
  233. success = false;
  234. }
  235. textarea.contentEditable = 'false';
  236. if (success && !textarea.value.slice(0, textarea.selectionStart ?? undefined).endsWith(text)) {
  237. success = false;
  238. }
  239. if (!success) {
  240. textarea.value = `${before}${text}${after}`;
  241. textarea.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true}));
  242. }
  243. }