Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dom.js 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 onDomReady(cb) {
  48. if (document.readyState === 'loading') {
  49. document.addEventListener('DOMContentLoaded', cb);
  50. } else {
  51. cb();
  52. }
  53. }
  54. // autosize a textarea to fit content. Based on
  55. // https://github.com/github/textarea-autosize
  56. // ---------------------------------------------------------------------
  57. // Copyright (c) 2018 GitHub, Inc.
  58. //
  59. // Permission is hereby granted, free of charge, to any person obtaining
  60. // a copy of this software and associated documentation files (the
  61. // "Software"), to deal in the Software without restriction, including
  62. // without limitation the rights to use, copy, modify, merge, publish,
  63. // distribute, sublicense, and/or sell copies of the Software, and to
  64. // permit persons to whom the Software is furnished to do so, subject to
  65. // the following conditions:
  66. //
  67. // The above copyright notice and this permission notice shall be
  68. // included in all copies or substantial portions of the Software.
  69. // ---------------------------------------------------------------------
  70. export function autosize(textarea, {viewportMarginBottom = 0} = {}) {
  71. let isUserResized = false;
  72. // lastStyleHeight and initialStyleHeight are CSS values like '100px'
  73. let lastMouseX, lastMouseY, lastStyleHeight, initialStyleHeight;
  74. function onUserResize(event) {
  75. if (isUserResized) return;
  76. if (lastMouseX !== event.clientX || lastMouseY !== event.clientY) {
  77. const newStyleHeight = textarea.style.height;
  78. if (lastStyleHeight && lastStyleHeight !== newStyleHeight) {
  79. isUserResized = true;
  80. }
  81. lastStyleHeight = newStyleHeight;
  82. }
  83. lastMouseX = event.clientX;
  84. lastMouseY = event.clientY;
  85. }
  86. function overflowOffset() {
  87. let offsetTop = 0;
  88. let el = textarea;
  89. while (el !== document.body && el !== null) {
  90. offsetTop += el.offsetTop || 0;
  91. el = el.offsetParent;
  92. }
  93. const top = offsetTop - document.defaultView.scrollY;
  94. const bottom = document.documentElement.clientHeight - (top + textarea.offsetHeight);
  95. return {top, bottom};
  96. }
  97. function resizeToFit() {
  98. if (isUserResized) return;
  99. if (textarea.offsetWidth <= 0 && textarea.offsetHeight <= 0) return;
  100. try {
  101. const {top, bottom} = overflowOffset();
  102. const isOutOfViewport = top < 0 || bottom < 0;
  103. const computedStyle = getComputedStyle(textarea);
  104. const topBorderWidth = parseFloat(computedStyle.borderTopWidth);
  105. const bottomBorderWidth = parseFloat(computedStyle.borderBottomWidth);
  106. const isBorderBox = computedStyle.boxSizing === 'border-box';
  107. const borderAddOn = isBorderBox ? topBorderWidth + bottomBorderWidth : 0;
  108. const adjustedViewportMarginBottom = bottom < viewportMarginBottom ? bottom : viewportMarginBottom;
  109. const curHeight = parseFloat(computedStyle.height);
  110. const maxHeight = curHeight + bottom - adjustedViewportMarginBottom;
  111. textarea.style.height = 'auto';
  112. let newHeight = textarea.scrollHeight + borderAddOn;
  113. if (isOutOfViewport) {
  114. // it is already out of the viewport:
  115. // * if the textarea is expanding: do not resize it
  116. if (newHeight > curHeight) {
  117. newHeight = curHeight;
  118. }
  119. // * if the textarea is shrinking, shrink line by line (just use the
  120. // scrollHeight). do not apply max-height limit, otherwise the page
  121. // flickers and the textarea jumps
  122. } else {
  123. // * if it is in the viewport, apply the max-height limit
  124. newHeight = Math.min(maxHeight, newHeight);
  125. }
  126. textarea.style.height = `${newHeight}px`;
  127. lastStyleHeight = textarea.style.height;
  128. } finally {
  129. // ensure that the textarea is fully scrolled to the end, when the cursor
  130. // is at the end during an input event
  131. if (textarea.selectionStart === textarea.selectionEnd &&
  132. textarea.selectionStart === textarea.value.length) {
  133. textarea.scrollTop = textarea.scrollHeight;
  134. }
  135. }
  136. }
  137. function onFormReset() {
  138. isUserResized = false;
  139. if (initialStyleHeight !== undefined) {
  140. textarea.style.height = initialStyleHeight;
  141. } else {
  142. textarea.style.removeProperty('height');
  143. }
  144. }
  145. textarea.addEventListener('mousemove', onUserResize);
  146. textarea.addEventListener('input', resizeToFit);
  147. textarea.form?.addEventListener('reset', onFormReset);
  148. initialStyleHeight = textarea.style.height ?? undefined;
  149. if (textarea.value) resizeToFit();
  150. return {
  151. resizeToFit,
  152. destroy() {
  153. textarea.removeEventListener('mousemove', onUserResize);
  154. textarea.removeEventListener('input', resizeToFit);
  155. textarea.form?.removeEventListener('reset', onFormReset);
  156. }
  157. };
  158. }
  159. export function onInputDebounce(fn) {
  160. return debounce(300, fn);
  161. }
  162. // Set the `src` attribute on an element and returns a promise that resolves once the element
  163. // has loaded or errored. Suitable for all elements mention in:
  164. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/load_event
  165. export function loadElem(el, src) {
  166. return new Promise((resolve) => {
  167. el.addEventListener('load', () => resolve(true), {once: true});
  168. el.addEventListener('error', () => resolve(false), {once: true});
  169. el.src = src;
  170. });
  171. }
  172. // some browsers like PaleMoon don't have "SubmitEvent" support, so polyfill it by a tricky method: use the last clicked button as submitter
  173. // it can't use other transparent polyfill patches because PaleMoon also doesn't support "addEventListener(capture)"
  174. const needSubmitEventPolyfill = typeof SubmitEvent === 'undefined';
  175. export function submitEventSubmitter(e) {
  176. return needSubmitEventPolyfill ? (e.target._submitter || null) : e.submitter;
  177. }
  178. function submitEventPolyfillListener(e) {
  179. const form = e.target.closest('form');
  180. if (!form) return;
  181. form._submitter = e.target.closest('button:not([type]), button[type="submit"], input[type="submit"]');
  182. }
  183. export function initSubmitEventPolyfill() {
  184. if (!needSubmitEventPolyfill) return;
  185. console.warn(`This browser doesn't have "SubmitEvent" support, use a tricky method to polyfill`);
  186. document.body.addEventListener('click', submitEventPolyfillListener);
  187. document.body.addEventListener('focus', submitEventPolyfillListener);
  188. }