aria.mjs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const FOCUSABLE_ELEMENT_SELECTORS = `a[href],button:not([disabled]),button:not([hidden]),:not([tabindex="-1"]),input:not([disabled]),input:not([type="hidden"]),select:not([disabled]),textarea:not([disabled])`;
  2. const isVisible = (element) => {
  3. if (process.env.NODE_ENV === "test")
  4. return true;
  5. const computed = getComputedStyle(element);
  6. return computed.position === "fixed" ? false : element.offsetParent !== null;
  7. };
  8. const obtainAllFocusableElements = (element) => {
  9. return Array.from(element.querySelectorAll(FOCUSABLE_ELEMENT_SELECTORS)).filter((item) => isFocusable(item) && isVisible(item));
  10. };
  11. const isFocusable = (element) => {
  12. if (element.tabIndex > 0 || element.tabIndex === 0 && element.getAttribute("tabIndex") !== null) {
  13. return true;
  14. }
  15. if (element.tabIndex < 0 || element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true") {
  16. return false;
  17. }
  18. switch (element.nodeName) {
  19. case "A": {
  20. return !!element.href && element.rel !== "ignore";
  21. }
  22. case "INPUT": {
  23. return !(element.type === "hidden" || element.type === "file");
  24. }
  25. case "BUTTON":
  26. case "SELECT":
  27. case "TEXTAREA": {
  28. return true;
  29. }
  30. default: {
  31. return false;
  32. }
  33. }
  34. };
  35. const attemptFocus = (element) => {
  36. var _a;
  37. if (!isFocusable(element)) {
  38. return false;
  39. }
  40. (_a = element.focus) == null ? void 0 : _a.call(element);
  41. return document.activeElement === element;
  42. };
  43. const triggerEvent = function(elm, name, ...opts) {
  44. let eventName;
  45. if (name.includes("mouse") || name.includes("click")) {
  46. eventName = "MouseEvents";
  47. } else if (name.includes("key")) {
  48. eventName = "KeyboardEvent";
  49. } else {
  50. eventName = "HTMLEvents";
  51. }
  52. const evt = document.createEvent(eventName);
  53. evt.initEvent(name, ...opts);
  54. elm.dispatchEvent(evt);
  55. return elm;
  56. };
  57. const isLeaf = (el) => !el.getAttribute("aria-owns");
  58. const getSibling = (el, distance, elClass) => {
  59. const { parentNode } = el;
  60. if (!parentNode)
  61. return null;
  62. const siblings = parentNode.querySelectorAll(elClass);
  63. const index = Array.prototype.indexOf.call(siblings, el);
  64. return siblings[index + distance] || null;
  65. };
  66. const focusNode = (el) => {
  67. if (!el)
  68. return;
  69. el.focus();
  70. !isLeaf(el) && el.click();
  71. };
  72. export { attemptFocus, focusNode, getSibling, isFocusable, isLeaf, isVisible, obtainAllFocusableElements, triggerEvent };
  73. //# sourceMappingURL=aria.mjs.map