useAccessibility.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
  2. import { getFocusNodeList } from "rc-util/es/Dom/focus";
  3. import KeyCode from "rc-util/es/KeyCode";
  4. import raf from "rc-util/es/raf";
  5. import * as React from 'react';
  6. import { getMenuId } from "../context/IdContext";
  7. // destruct to reduce minify size
  8. var LEFT = KeyCode.LEFT,
  9. RIGHT = KeyCode.RIGHT,
  10. UP = KeyCode.UP,
  11. DOWN = KeyCode.DOWN,
  12. ENTER = KeyCode.ENTER,
  13. ESC = KeyCode.ESC,
  14. HOME = KeyCode.HOME,
  15. END = KeyCode.END;
  16. var ArrowKeys = [UP, DOWN, LEFT, RIGHT];
  17. function getOffset(mode, isRootLevel, isRtl, which) {
  18. var _offsets;
  19. var prev = 'prev';
  20. var next = 'next';
  21. var children = 'children';
  22. var parent = 'parent';
  23. // Inline enter is special that we use unique operation
  24. if (mode === 'inline' && which === ENTER) {
  25. return {
  26. inlineTrigger: true
  27. };
  28. }
  29. var inline = _defineProperty(_defineProperty({}, UP, prev), DOWN, next);
  30. var horizontal = _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEFT, isRtl ? next : prev), RIGHT, isRtl ? prev : next), DOWN, children), ENTER, children);
  31. var vertical = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, UP, prev), DOWN, next), ENTER, children), ESC, parent), LEFT, isRtl ? children : parent), RIGHT, isRtl ? parent : children);
  32. var offsets = {
  33. inline: inline,
  34. horizontal: horizontal,
  35. vertical: vertical,
  36. inlineSub: inline,
  37. horizontalSub: vertical,
  38. verticalSub: vertical
  39. };
  40. var type = (_offsets = offsets["".concat(mode).concat(isRootLevel ? '' : 'Sub')]) === null || _offsets === void 0 ? void 0 : _offsets[which];
  41. switch (type) {
  42. case prev:
  43. return {
  44. offset: -1,
  45. sibling: true
  46. };
  47. case next:
  48. return {
  49. offset: 1,
  50. sibling: true
  51. };
  52. case parent:
  53. return {
  54. offset: -1,
  55. sibling: false
  56. };
  57. case children:
  58. return {
  59. offset: 1,
  60. sibling: false
  61. };
  62. default:
  63. return null;
  64. }
  65. }
  66. function findContainerUL(element) {
  67. var current = element;
  68. while (current) {
  69. if (current.getAttribute('data-menu-list')) {
  70. return current;
  71. }
  72. current = current.parentElement;
  73. }
  74. // Normally should not reach this line
  75. /* istanbul ignore next */
  76. return null;
  77. }
  78. /**
  79. * Find focused element within element set provided
  80. */
  81. function getFocusElement(activeElement, elements) {
  82. var current = activeElement || document.activeElement;
  83. while (current) {
  84. if (elements.has(current)) {
  85. return current;
  86. }
  87. current = current.parentElement;
  88. }
  89. return null;
  90. }
  91. /**
  92. * Get focusable elements from the element set under provided container
  93. */
  94. export function getFocusableElements(container, elements) {
  95. var list = getFocusNodeList(container, true);
  96. return list.filter(function (ele) {
  97. return elements.has(ele);
  98. });
  99. }
  100. function getNextFocusElement(parentQueryContainer, elements, focusMenuElement) {
  101. var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
  102. // Key on the menu item will not get validate parent container
  103. if (!parentQueryContainer) {
  104. return null;
  105. }
  106. // List current level menu item elements
  107. var sameLevelFocusableMenuElementList = getFocusableElements(parentQueryContainer, elements);
  108. // Find next focus index
  109. var count = sameLevelFocusableMenuElementList.length;
  110. var focusIndex = sameLevelFocusableMenuElementList.findIndex(function (ele) {
  111. return focusMenuElement === ele;
  112. });
  113. if (offset < 0) {
  114. if (focusIndex === -1) {
  115. focusIndex = count - 1;
  116. } else {
  117. focusIndex -= 1;
  118. }
  119. } else if (offset > 0) {
  120. focusIndex += 1;
  121. }
  122. focusIndex = (focusIndex + count) % count;
  123. // Focus menu item
  124. return sameLevelFocusableMenuElementList[focusIndex];
  125. }
  126. export var refreshElements = function refreshElements(keys, id) {
  127. var elements = new Set();
  128. var key2element = new Map();
  129. var element2key = new Map();
  130. keys.forEach(function (key) {
  131. var element = document.querySelector("[data-menu-id='".concat(getMenuId(id, key), "']"));
  132. if (element) {
  133. elements.add(element);
  134. element2key.set(element, key);
  135. key2element.set(key, element);
  136. }
  137. });
  138. return {
  139. elements: elements,
  140. key2element: key2element,
  141. element2key: element2key
  142. };
  143. };
  144. export function useAccessibility(mode, activeKey, isRtl, id, containerRef, getKeys, getKeyPath, triggerActiveKey, triggerAccessibilityOpen, originOnKeyDown) {
  145. var rafRef = React.useRef();
  146. var activeRef = React.useRef();
  147. activeRef.current = activeKey;
  148. var cleanRaf = function cleanRaf() {
  149. raf.cancel(rafRef.current);
  150. };
  151. React.useEffect(function () {
  152. return function () {
  153. cleanRaf();
  154. };
  155. }, []);
  156. return function (e) {
  157. var which = e.which;
  158. if ([].concat(ArrowKeys, [ENTER, ESC, HOME, END]).includes(which)) {
  159. var keys = getKeys();
  160. var refreshedElements = refreshElements(keys, id);
  161. var _refreshedElements = refreshedElements,
  162. elements = _refreshedElements.elements,
  163. key2element = _refreshedElements.key2element,
  164. element2key = _refreshedElements.element2key;
  165. // First we should find current focused MenuItem/SubMenu element
  166. var activeElement = key2element.get(activeKey);
  167. var focusMenuElement = getFocusElement(activeElement, elements);
  168. var focusMenuKey = element2key.get(focusMenuElement);
  169. var offsetObj = getOffset(mode, getKeyPath(focusMenuKey, true).length === 1, isRtl, which);
  170. // Some mode do not have fully arrow operation like inline
  171. if (!offsetObj && which !== HOME && which !== END) {
  172. return;
  173. }
  174. // Arrow prevent default to avoid page scroll
  175. if (ArrowKeys.includes(which) || [HOME, END].includes(which)) {
  176. e.preventDefault();
  177. }
  178. var tryFocus = function tryFocus(menuElement) {
  179. if (menuElement) {
  180. var focusTargetElement = menuElement;
  181. // Focus to link instead of menu item if possible
  182. var link = menuElement.querySelector('a');
  183. if (link !== null && link !== void 0 && link.getAttribute('href')) {
  184. focusTargetElement = link;
  185. }
  186. var targetKey = element2key.get(menuElement);
  187. triggerActiveKey(targetKey);
  188. /**
  189. * Do not `useEffect` here since `tryFocus` may trigger async
  190. * which makes React sync update the `activeKey`
  191. * that force render before `useRef` set the next activeKey
  192. */
  193. cleanRaf();
  194. rafRef.current = raf(function () {
  195. if (activeRef.current === targetKey) {
  196. focusTargetElement.focus();
  197. }
  198. });
  199. }
  200. };
  201. if ([HOME, END].includes(which) || offsetObj.sibling || !focusMenuElement) {
  202. // ========================== Sibling ==========================
  203. // Find walkable focus menu element container
  204. var parentQueryContainer;
  205. if (!focusMenuElement || mode === 'inline') {
  206. parentQueryContainer = containerRef.current;
  207. } else {
  208. parentQueryContainer = findContainerUL(focusMenuElement);
  209. }
  210. // Get next focus element
  211. var targetElement;
  212. var focusableElements = getFocusableElements(parentQueryContainer, elements);
  213. if (which === HOME) {
  214. targetElement = focusableElements[0];
  215. } else if (which === END) {
  216. targetElement = focusableElements[focusableElements.length - 1];
  217. } else {
  218. targetElement = getNextFocusElement(parentQueryContainer, elements, focusMenuElement, offsetObj.offset);
  219. }
  220. // Focus menu item
  221. tryFocus(targetElement);
  222. // ======================= InlineTrigger =======================
  223. } else if (offsetObj.inlineTrigger) {
  224. // Inline trigger no need switch to sub menu item
  225. triggerAccessibilityOpen(focusMenuKey);
  226. // =========================== Level ===========================
  227. } else if (offsetObj.offset > 0) {
  228. triggerAccessibilityOpen(focusMenuKey, true);
  229. cleanRaf();
  230. rafRef.current = raf(function () {
  231. // Async should resync elements
  232. refreshedElements = refreshElements(keys, id);
  233. var controlId = focusMenuElement.getAttribute('aria-controls');
  234. var subQueryContainer = document.getElementById(controlId);
  235. // Get sub focusable menu item
  236. var targetElement = getNextFocusElement(subQueryContainer, refreshedElements.elements);
  237. // Focus menu item
  238. tryFocus(targetElement);
  239. }, 5);
  240. } else if (offsetObj.offset < 0) {
  241. var keyPath = getKeyPath(focusMenuKey, true);
  242. var parentKey = keyPath[keyPath.length - 2];
  243. var parentMenuElement = key2element.get(parentKey);
  244. // Focus menu item
  245. triggerAccessibilityOpen(parentKey, false);
  246. tryFocus(parentMenuElement);
  247. }
  248. }
  249. // Pass origin key down event
  250. originOnKeyDown === null || originOnKeyDown === void 0 || originOnKeyDown(e);
  251. };
  252. }