gitea源码

dropdown.ts 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import $ from 'jquery';
  2. import type {FomanticInitFunction} from '../../types.ts';
  3. import {generateElemId, queryElems} from '../../utils/dom.ts';
  4. const ariaPatchKey = '_giteaAriaPatchDropdown';
  5. const fomanticDropdownFn = $.fn.dropdown;
  6. // use our own `$().dropdown` function to patch Fomantic's dropdown module
  7. export function initAriaDropdownPatch() {
  8. if ($.fn.dropdown === ariaDropdownFn) throw new Error('initAriaDropdownPatch could only be called once');
  9. $.fn.dropdown = ariaDropdownFn;
  10. $.fn.fomanticExt.onResponseKeepSelectedItem = onResponseKeepSelectedItem;
  11. $.fn.fomanticExt.onDropdownAfterFiltered = onDropdownAfterFiltered;
  12. (ariaDropdownFn as FomanticInitFunction).settings = fomanticDropdownFn.settings;
  13. }
  14. // the patched `$.fn.dropdown` function, it passes the arguments to Fomantic's `$.fn.dropdown` function, and:
  15. // * it does the one-time element event attaching on the first call
  16. // * it delegates the module internal functions like `onLabelCreate` to the patched functions to add more features.
  17. function ariaDropdownFn(this: any, ...args: Parameters<FomanticInitFunction>) {
  18. const ret = fomanticDropdownFn.apply(this, args);
  19. for (let el of this) {
  20. // dropdown will replace '<select class="ui dropdown"/>' to '<div class="ui dropdown"><select (hidden)></select><div class="menu">...</div></div>'
  21. // so we need to correctly find the closest '.ui.dropdown' element, it is the real fomantic dropdown module.
  22. el = el.closest('.ui.dropdown');
  23. if (!el[ariaPatchKey]) {
  24. // the elements don't belong to the dropdown "module" and won't be reset
  25. // so we only need to initialize them once.
  26. attachInitElements(el);
  27. }
  28. // if the `$().dropdown()` is called without arguments, or it has non-string (object) argument,
  29. // it means that such call will reset the dropdown "module" including internal settings,
  30. // then we need to re-delegate the callbacks.
  31. const $dropdown = $(el);
  32. const dropdownModule = $dropdown.data('module-dropdown');
  33. if (!dropdownModule.giteaDelegated) {
  34. dropdownModule.giteaDelegated = true;
  35. delegateDropdownModule($dropdown);
  36. }
  37. }
  38. return ret;
  39. }
  40. // make the item has role=option/menuitem, add an id if there wasn't one yet, make items as non-focusable
  41. // the elements inside the dropdown menu item should not be focusable, the focus should always be on the dropdown primary element.
  42. function updateMenuItem(dropdown: HTMLElement, item: HTMLElement) {
  43. if (!item.id) item.id = generateElemId('_aria_dropdown_item_');
  44. item.setAttribute('role', (dropdown as any)[ariaPatchKey].listItemRole);
  45. item.setAttribute('tabindex', '-1');
  46. for (const el of item.querySelectorAll('a, input, button')) el.setAttribute('tabindex', '-1');
  47. }
  48. /**
  49. * make the label item and its "delete icon" have correct aria attributes
  50. * @param {HTMLElement} label
  51. */
  52. function updateSelectionLabel(label: HTMLElement) {
  53. // the "label" is like this: "<a|div class="ui label" data-value="1">the-label-name <i|svg class="delete icon"/></a>"
  54. if (!label.id) {
  55. label.id = generateElemId('_aria_dropdown_label_');
  56. }
  57. label.tabIndex = -1;
  58. const deleteIcon = label.querySelector('.delete.icon');
  59. if (deleteIcon) {
  60. deleteIcon.setAttribute('aria-hidden', 'false');
  61. deleteIcon.setAttribute('aria-label', window.config.i18n.remove_label_str.replace('%s', label.getAttribute('data-value')));
  62. deleteIcon.setAttribute('role', 'button');
  63. }
  64. }
  65. function onDropdownAfterFiltered(this: any) {
  66. const $dropdown = $(this).closest('.ui.dropdown'); // "this" can be the "ui dropdown" or "<select>"
  67. const hideEmptyDividers = $dropdown.dropdown('setting', 'hideDividers') === 'empty';
  68. const itemsMenu = $dropdown[0].querySelector('.scrolling.menu') || $dropdown[0].querySelector('.menu');
  69. if (hideEmptyDividers && itemsMenu) hideScopedEmptyDividers(itemsMenu);
  70. }
  71. // delegate the dropdown's template functions and callback functions to add aria attributes.
  72. function delegateDropdownModule($dropdown: any) {
  73. const dropdownCall = fomanticDropdownFn.bind($dropdown);
  74. // the "template" functions are used for dynamic creation (eg: AJAX)
  75. const dropdownTemplates = {...dropdownCall('setting', 'templates'), t: performance.now()};
  76. const dropdownTemplatesMenuOld = dropdownTemplates.menu;
  77. dropdownTemplates.menu = function(response: any, fields: any, preserveHTML: any, className: Record<string, string>) {
  78. // when the dropdown menu items are loaded from AJAX requests, the items are created dynamically
  79. const menuItems = dropdownTemplatesMenuOld(response, fields, preserveHTML, className);
  80. const div = document.createElement('div');
  81. div.innerHTML = menuItems;
  82. const $wrapper = $(div);
  83. const $items = $wrapper.find('> .item');
  84. $items.each((_, item) => updateMenuItem($dropdown[0], item));
  85. $dropdown[0][ariaPatchKey].deferredRefreshAriaActiveItem();
  86. return $wrapper.html();
  87. };
  88. dropdownCall('setting', 'templates', dropdownTemplates);
  89. // the `onLabelCreate` is used to add necessary aria attributes for dynamically created selection labels
  90. const dropdownOnLabelCreateOld = dropdownCall('setting', 'onLabelCreate');
  91. dropdownCall('setting', 'onLabelCreate', function(this: any, value: any, text: string) {
  92. const $label = dropdownOnLabelCreateOld.call(this, value, text);
  93. updateSelectionLabel($label[0]);
  94. return $label;
  95. });
  96. const oldSet = dropdownCall('internal', 'set');
  97. const oldSetDirection = oldSet.direction;
  98. oldSet.direction = function($menu: any) {
  99. oldSetDirection.call(this, $menu);
  100. const classNames = dropdownCall('setting', 'className');
  101. $menu = $menu || $dropdown.find('> .menu');
  102. const elMenu = $menu[0];
  103. // detect whether the menu is outside the viewport, and adjust the position
  104. // there is a bug in fomantic's builtin `direction` function, in some cases (when the menu width is only a little larger) it wrongly opens the menu at right and triggers the scrollbar.
  105. elMenu.classList.add(classNames.loading);
  106. if (elMenu.getBoundingClientRect().right > document.documentElement.clientWidth) {
  107. elMenu.classList.add(classNames.leftward);
  108. }
  109. elMenu.classList.remove(classNames.loading);
  110. };
  111. }
  112. // for static dropdown elements (generated by server-side template), prepare them with necessary aria attributes
  113. function attachStaticElements(dropdown: HTMLElement, focusable: HTMLElement, menu: HTMLElement) {
  114. // prepare static dropdown menu list popup
  115. if (!menu.id) {
  116. menu.id = generateElemId('_aria_dropdown_menu_');
  117. }
  118. $(menu).find('> .item').each((_, item) => updateMenuItem(dropdown, item));
  119. // this role could only be changed after its content is ready, otherwise some browsers+readers (like Chrome+AppleVoice) crash
  120. menu.setAttribute('role', (dropdown as any)[ariaPatchKey].listPopupRole);
  121. // prepare selection label items
  122. for (const label of dropdown.querySelectorAll<HTMLElement>('.ui.label')) {
  123. updateSelectionLabel(label);
  124. }
  125. // make the primary element (focusable) aria-friendly
  126. focusable.setAttribute('role', focusable.getAttribute('role') ?? (dropdown as any)[ariaPatchKey].focusableRole);
  127. focusable.setAttribute('aria-haspopup', (dropdown as any)[ariaPatchKey].listPopupRole);
  128. focusable.setAttribute('aria-controls', menu.id);
  129. focusable.setAttribute('aria-expanded', 'false');
  130. // use tooltip's content as aria-label if there is no aria-label
  131. const tooltipContent = dropdown.getAttribute('data-tooltip-content');
  132. if (tooltipContent && !dropdown.getAttribute('aria-label')) {
  133. dropdown.setAttribute('aria-label', tooltipContent);
  134. }
  135. }
  136. function attachInitElements(dropdown: HTMLElement) {
  137. (dropdown as any)[ariaPatchKey] = {};
  138. // Dropdown has 2 different focusing behaviors
  139. // * with search input: the input is focused, and it works with aria-activedescendant pointing another sibling element.
  140. // * without search input (but the readonly text), the dropdown itself is focused. then the aria-activedescendant points to the element inside dropdown
  141. // Some desktop screen readers may change the focus, but dropdown requires that the focus must be on its primary element, then they don't work well.
  142. // Expected user interactions for dropdown with aria support:
  143. // * user can use Tab to focus in the dropdown, then the dropdown menu (list) will be shown
  144. // * user presses Tab on the focused dropdown to move focus to next sibling focusable element (but not the menu item)
  145. // * user can use arrow key Up/Down to navigate between menu items
  146. // * when user presses Enter:
  147. // - if the menu item is clickable (eg: <a>), then trigger the click event
  148. // - otherwise, the dropdown control (low-level code) handles the Enter event, hides the dropdown menu
  149. // TODO: multiple selection is only partially supported. Check and test them one by one in the future.
  150. const textSearch = dropdown.querySelector<HTMLElement>('input.search');
  151. const focusable = textSearch || dropdown; // the primary element for focus, see comment above
  152. if (!focusable) return;
  153. // as a combobox, the input should not have autocomplete by default
  154. if (textSearch && !textSearch.getAttribute('autocomplete')) {
  155. textSearch.setAttribute('autocomplete', 'off');
  156. }
  157. let menu = $(dropdown).find('> .menu')[0];
  158. if (!menu) {
  159. // some "multiple selection" dropdowns don't have a static menu element in HTML, we need to pre-create it to make it have correct aria attributes
  160. menu = document.createElement('div');
  161. menu.classList.add('menu');
  162. dropdown.append(menu);
  163. }
  164. // There are 2 possible solutions about the role: combobox or menu.
  165. // The idea is that if there is an input, then it's a combobox, otherwise it's a menu.
  166. // Since #19861 we have prepared the "combobox" solution, but didn't get enough time to put it into practice and test before.
  167. const isComboBox = dropdown.querySelectorAll('input').length > 0;
  168. (dropdown as any)[ariaPatchKey].focusableRole = isComboBox ? 'combobox' : 'menu';
  169. (dropdown as any)[ariaPatchKey].listPopupRole = isComboBox ? 'listbox' : '';
  170. (dropdown as any)[ariaPatchKey].listItemRole = isComboBox ? 'option' : 'menuitem';
  171. attachDomEvents(dropdown, focusable, menu);
  172. attachStaticElements(dropdown, focusable, menu);
  173. }
  174. function attachDomEvents(dropdown: HTMLElement, focusable: HTMLElement, menu: HTMLElement) {
  175. // when showing, it has class: ".animating.in"
  176. // when hiding, it has class: ".visible.animating.out"
  177. const isMenuVisible = () => (menu.classList.contains('visible') && !menu.classList.contains('out')) || menu.classList.contains('in');
  178. // update aria attributes according to current active/selected item
  179. const refreshAriaActiveItem = () => {
  180. const menuVisible = isMenuVisible();
  181. focusable.setAttribute('aria-expanded', menuVisible ? 'true' : 'false');
  182. // if there is an active item, use it (the user is navigating between items)
  183. // otherwise use the "selected" for combobox (for the last selected item)
  184. const active = $(menu).find('> .item.active, > .item.selected')[0];
  185. if (!active) return;
  186. // if the popup is visible and has an active/selected item, use its id as aria-activedescendant
  187. if (menuVisible) {
  188. focusable.setAttribute('aria-activedescendant', active.id);
  189. } else if ((dropdown as any)[ariaPatchKey].listPopupRole === 'menu') {
  190. // for menu, when the popup is hidden, no need to keep the aria-activedescendant, and clear the active/selected item
  191. focusable.removeAttribute('aria-activedescendant');
  192. active.classList.remove('active', 'selected');
  193. }
  194. };
  195. dropdown.addEventListener('keydown', (e: KeyboardEvent) => {
  196. // here it must use keydown event before dropdown's keyup handler, otherwise there is no Enter event in our keyup handler
  197. if (e.key === 'Enter') {
  198. const elItem = menu.querySelector<HTMLElement>(':scope > .item.selected, .menu > .item.selected');
  199. // if the selected item is clickable, then trigger the click event.
  200. // we can not click any item without check, because Fomantic code might also handle the Enter event. that would result in double click.
  201. if (elItem?.matches('a, .js-aria-clickable') && !elItem.matches('.tw-hidden, .filtered')) {
  202. e.preventDefault();
  203. elItem.click();
  204. }
  205. }
  206. });
  207. // use setTimeout to run the refreshAria in next tick (to make sure the Fomantic UI code has finished its work)
  208. // do not return any value, jQuery has return-value related behaviors.
  209. // when the popup is hiding, it's better to have a small "delay", because there is a Fomantic UI animation
  210. // without the delay for hiding, the UI will be somewhat laggy and sometimes may get stuck in the animation.
  211. const deferredRefreshAriaActiveItem = (delay = 0) => { setTimeout(refreshAriaActiveItem, delay) };
  212. (dropdown as any)[ariaPatchKey].deferredRefreshAriaActiveItem = deferredRefreshAriaActiveItem;
  213. dropdown.addEventListener('keyup', (e) => { if (e.key.startsWith('Arrow')) deferredRefreshAriaActiveItem(); });
  214. // if the dropdown has been opened by focus, do not trigger the next click event again.
  215. // otherwise the dropdown will be closed immediately, especially on Android with TalkBack
  216. // * desktop event sequence: mousedown -> focus -> mouseup -> click
  217. // * mobile event sequence: focus -> mousedown -> mouseup -> click
  218. // Fomantic may stop propagation of blur event, use capture to make sure we can still get the event
  219. let ignoreClickPreEvents = 0, ignoreClickPreVisible = 0;
  220. dropdown.addEventListener('mousedown', () => {
  221. ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
  222. ignoreClickPreEvents++;
  223. }, true);
  224. dropdown.addEventListener('focus', () => {
  225. ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
  226. ignoreClickPreEvents++;
  227. deferredRefreshAriaActiveItem();
  228. }, true);
  229. dropdown.addEventListener('blur', () => {
  230. ignoreClickPreVisible = ignoreClickPreEvents = 0;
  231. deferredRefreshAriaActiveItem(100);
  232. }, true);
  233. dropdown.addEventListener('mouseup', () => {
  234. setTimeout(() => {
  235. ignoreClickPreVisible = ignoreClickPreEvents = 0;
  236. deferredRefreshAriaActiveItem(100);
  237. }, 0);
  238. }, true);
  239. dropdown.addEventListener('click', (e: MouseEvent) => {
  240. if (isMenuVisible() &&
  241. ignoreClickPreVisible !== 2 && // dropdown is switch from invisible to visible
  242. ignoreClickPreEvents === 2 // the click event is related to mousedown+focus
  243. ) {
  244. e.stopPropagation(); // if the dropdown menu has been opened by focus, do not trigger the next click event again
  245. }
  246. ignoreClickPreEvents = ignoreClickPreVisible = 0;
  247. }, true);
  248. }
  249. // Although Fomantic Dropdown supports "hideDividers", it doesn't really work with our "scoped dividers"
  250. // At the moment, "label dropdown items" use scopes, a sample case is:
  251. // * a-label
  252. // * divider
  253. // * scope/1
  254. // * scope/2
  255. // * divider
  256. // * z-label
  257. // when the "scope/*" are filtered out, we'd like to see "a-label" and "z-label" without the divider.
  258. export function hideScopedEmptyDividers(container: Element) {
  259. const visibleItems: Element[] = [];
  260. const curScopeVisibleItems: Element[] = [];
  261. let curScope: string = '', lastVisibleScope: string = '';
  262. const isDivider = (item: Element) => item.classList.contains('divider');
  263. const isScopedDivider = (item: Element) => isDivider(item) && item.hasAttribute('data-scope');
  264. const hideDivider = (item: Element) => item.classList.add('hidden', 'transition'); // dropdown has its own classes to hide items
  265. const showDivider = (item: Element) => item.classList.remove('hidden', 'transition');
  266. const isHidden = (item: Element) => item.classList.contains('hidden') || item.classList.contains('filtered') || item.classList.contains('tw-hidden');
  267. const handleScopeSwitch = (itemScope: string) => {
  268. if (curScopeVisibleItems.length === 1 && isScopedDivider(curScopeVisibleItems[0])) {
  269. hideDivider(curScopeVisibleItems[0]);
  270. } else if (curScopeVisibleItems.length) {
  271. if (isScopedDivider(curScopeVisibleItems[0]) && lastVisibleScope === curScope) {
  272. hideDivider(curScopeVisibleItems[0]);
  273. curScopeVisibleItems.shift();
  274. }
  275. visibleItems.push(...curScopeVisibleItems);
  276. lastVisibleScope = curScope;
  277. }
  278. curScope = itemScope;
  279. curScopeVisibleItems.length = 0;
  280. };
  281. // reset hidden dividers
  282. queryElems(container, '.divider', showDivider);
  283. // hide the scope dividers if the scope items are empty
  284. for (const item of container.children) {
  285. const itemScope = item.getAttribute('data-scope') || '';
  286. if (itemScope !== curScope) {
  287. handleScopeSwitch(itemScope);
  288. }
  289. if (!isHidden(item)) {
  290. curScopeVisibleItems.push(item as HTMLElement);
  291. }
  292. }
  293. handleScopeSwitch('');
  294. // hide all leading and trailing dividers
  295. while (visibleItems.length) {
  296. if (!isDivider(visibleItems[0])) break;
  297. hideDivider(visibleItems[0]);
  298. visibleItems.shift();
  299. }
  300. while (visibleItems.length) {
  301. if (!isDivider(visibleItems[visibleItems.length - 1])) break;
  302. hideDivider(visibleItems[visibleItems.length - 1]);
  303. visibleItems.pop();
  304. }
  305. // hide all duplicate dividers, hide current divider if next sibling is still divider
  306. // no need to update "visibleItems" array since this is the last loop
  307. for (let i = 0; i < visibleItems.length - 1; i++) {
  308. if (!visibleItems[i].matches('.divider')) continue;
  309. if (visibleItems[i + 1].matches('.divider')) hideDivider(visibleItems[i]);
  310. }
  311. }
  312. function onResponseKeepSelectedItem(dropdown: typeof $ | HTMLElement, selectedValue: string) {
  313. // There is a bug in fomantic dropdown when using "apiSettings" to fetch data
  314. // * when there is a selected item, the dropdown insists on hiding the selected one from the list:
  315. // * in the "filter" function: ('[data-value="'+value+'"]').addClass(className.filtered)
  316. //
  317. // When user selects one item, and click the dropdown again,
  318. // then the dropdown only shows other items and will select another (wrong) one.
  319. // It can't be easily fix by using setTimeout(patch, 0) in `onResponse` because the `onResponse` is called before another `setTimeout(..., timeLeft)`
  320. // Fortunately, the "timeLeft" is controlled by "loadingDuration" which is always zero at the moment, so we can use `setTimeout(..., 10)`
  321. const elDropdown = (dropdown instanceof HTMLElement) ? dropdown : (dropdown as any)[0];
  322. setTimeout(() => {
  323. queryElems(elDropdown, `.menu .item[data-value="${CSS.escape(selectedValue)}"].filtered`, (el) => el.classList.remove('filtered'));
  324. $(elDropdown).dropdown('set selected', selectedValue ?? '');
  325. }, 10);
  326. }