code.gitea.io/gitea@v1.22.3/web_src/js/modules/fomantic/dropdown.js (about)

     1  import $ from 'jquery';
     2  import {generateAriaId} from './base.js';
     3  
     4  const ariaPatchKey = '_giteaAriaPatchDropdown';
     5  const fomanticDropdownFn = $.fn.dropdown;
     6  
     7  // use our own `$().dropdown` function to patch Fomantic's dropdown module
     8  export function initAriaDropdownPatch() {
     9    if ($.fn.dropdown === ariaDropdownFn) throw new Error('initAriaDropdownPatch could only be called once');
    10    $.fn.dropdown = ariaDropdownFn;
    11    ariaDropdownFn.settings = fomanticDropdownFn.settings;
    12  }
    13  
    14  // the patched `$.fn.dropdown` function, it passes the arguments to Fomantic's `$.fn.dropdown` function, and:
    15  // * it does the one-time attaching on the first call
    16  // * it delegates the `onLabelCreate` to the patched `onLabelCreate` to add necessary aria attributes
    17  function ariaDropdownFn(...args) {
    18    const ret = fomanticDropdownFn.apply(this, args);
    19  
    20    // if the `$().dropdown()` call is without arguments, or it has non-string (object) argument,
    21    // it means that this call will reset the dropdown internal settings, then we need to re-delegate the callbacks.
    22    const needDelegate = (!args.length || typeof args[0] !== 'string');
    23    for (const el of this) {
    24      if (!el[ariaPatchKey]) {
    25        attachInit(el);
    26      }
    27      if (needDelegate) {
    28        delegateOne($(el));
    29      }
    30    }
    31    return ret;
    32  }
    33  
    34  // make the item has role=option/menuitem, add an id if there wasn't one yet, make items as non-focusable
    35  // the elements inside the dropdown menu item should not be focusable, the focus should always be on the dropdown primary element.
    36  function updateMenuItem(dropdown, item) {
    37    if (!item.id) item.id = generateAriaId();
    38    item.setAttribute('role', dropdown[ariaPatchKey].listItemRole);
    39    item.setAttribute('tabindex', '-1');
    40    for (const el of item.querySelectorAll('a, input, button')) el.setAttribute('tabindex', '-1');
    41  }
    42  /**
    43   * make the label item and its "delete icon" have correct aria attributes
    44   * @param {HTMLElement} label
    45   */
    46  function updateSelectionLabel(label) {
    47    // the "label" is like this: "<a|div class="ui label" data-value="1">the-label-name <i|svg class="delete icon"/></a>"
    48    if (!label.id) {
    49      label.id = generateAriaId();
    50    }
    51    label.tabIndex = -1;
    52  
    53    const deleteIcon = label.querySelector('.delete.icon');
    54    if (deleteIcon) {
    55      deleteIcon.setAttribute('aria-hidden', 'false');
    56      deleteIcon.setAttribute('aria-label', window.config.i18n.remove_label_str.replace('%s', label.getAttribute('data-value')));
    57      deleteIcon.setAttribute('role', 'button');
    58    }
    59  }
    60  
    61  // delegate the dropdown's template functions and callback functions to add aria attributes.
    62  function delegateOne($dropdown) {
    63    const dropdownCall = fomanticDropdownFn.bind($dropdown);
    64  
    65    // If there is a "search input" in the "menu", Fomantic will only "focus the input" but not "toggle the menu" when the "dropdown icon" is clicked.
    66    // Actually, Fomantic UI doesn't support such layout/usage. It needs to patch the "focusSearch" / "blurSearch" functions to make sure it toggles the menu.
    67    const oldFocusSearch = dropdownCall('internal', 'focusSearch');
    68    const oldBlurSearch = dropdownCall('internal', 'blurSearch');
    69    // * If the "dropdown icon" is clicked, Fomantic calls "focusSearch", so show the menu
    70    dropdownCall('internal', 'focusSearch', function () { dropdownCall('show'); oldFocusSearch.call(this) });
    71    // * If the "dropdown icon" is clicked again when the menu is visible, Fomantic calls "blurSearch", so hide the menu
    72    dropdownCall('internal', 'blurSearch', function () { oldBlurSearch.call(this); dropdownCall('hide') });
    73  
    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, fields, preserveHTML, className) {
    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  
    90    // the `onLabelCreate` is used to add necessary aria attributes for dynamically created selection labels
    91    const dropdownOnLabelCreateOld = dropdownCall('setting', 'onLabelCreate');
    92    dropdownCall('setting', 'onLabelCreate', function(value, text) {
    93      const $label = dropdownOnLabelCreateOld.call(this, value, text);
    94      updateSelectionLabel($label[0]);
    95      return $label;
    96    });
    97  
    98    const oldSet = dropdownCall('internal', 'set');
    99    const oldSetDirection = oldSet.direction;
   100    oldSet.direction = function($menu) {
   101      oldSetDirection.call(this, $menu);
   102      const classNames = dropdownCall('setting', 'className');
   103      $menu = $menu || $dropdown.find('> .menu');
   104      const elMenu = $menu[0];
   105      // detect whether the menu is outside the viewport, and adjust the position
   106      // 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.
   107      elMenu.classList.add(classNames.loading);
   108      if (elMenu.getBoundingClientRect().right > document.documentElement.clientWidth) {
   109        elMenu.classList.add(classNames.leftward);
   110      }
   111      elMenu.classList.remove(classNames.loading);
   112    };
   113  }
   114  
   115  // for static dropdown elements (generated by server-side template), prepare them with necessary aria attributes
   116  function attachStaticElements(dropdown, focusable, menu) {
   117    // prepare static dropdown menu list popup
   118    if (!menu.id) {
   119      menu.id = generateAriaId();
   120    }
   121  
   122    $(menu).find('> .item').each((_, item) => updateMenuItem(dropdown, item));
   123  
   124    // this role could only be changed after its content is ready, otherwise some browsers+readers (like Chrome+AppleVoice) crash
   125    menu.setAttribute('role', dropdown[ariaPatchKey].listPopupRole);
   126  
   127    // prepare selection label items
   128    for (const label of dropdown.querySelectorAll('.ui.label')) {
   129      updateSelectionLabel(label);
   130    }
   131  
   132    // make the primary element (focusable) aria-friendly
   133    focusable.setAttribute('role', focusable.getAttribute('role') ?? dropdown[ariaPatchKey].focusableRole);
   134    focusable.setAttribute('aria-haspopup', dropdown[ariaPatchKey].listPopupRole);
   135    focusable.setAttribute('aria-controls', menu.id);
   136    focusable.setAttribute('aria-expanded', 'false');
   137  
   138    // use tooltip's content as aria-label if there is no aria-label
   139    const tooltipContent = dropdown.getAttribute('data-tooltip-content');
   140    if (tooltipContent && !dropdown.getAttribute('aria-label')) {
   141      dropdown.setAttribute('aria-label', tooltipContent);
   142    }
   143  }
   144  
   145  function attachInit(dropdown) {
   146    dropdown[ariaPatchKey] = {};
   147    if (dropdown.classList.contains('custom')) return;
   148  
   149    // Dropdown has 2 different focusing behaviors
   150    // * with search input: the input is focused, and it works with aria-activedescendant pointing another sibling element.
   151    // * without search input (but the readonly text), the dropdown itself is focused. then the aria-activedescendant points to the element inside dropdown
   152    // 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.
   153  
   154    // Expected user interactions for dropdown with aria support:
   155    // * user can use Tab to focus in the dropdown, then the dropdown menu (list) will be shown
   156    // * user presses Tab on the focused dropdown to move focus to next sibling focusable element (but not the menu item)
   157    // * user can use arrow key Up/Down to navigate between menu items
   158    // * when user presses Enter:
   159    //    - if the menu item is clickable (eg: <a>), then trigger the click event
   160    //    - otherwise, the dropdown control (low-level code) handles the Enter event, hides the dropdown menu
   161  
   162    // TODO: multiple selection is only partially supported. Check and test them one by one in the future.
   163  
   164    const textSearch = dropdown.querySelector('input.search');
   165    const focusable = textSearch || dropdown; // the primary element for focus, see comment above
   166    if (!focusable) return;
   167  
   168    // as a combobox, the input should not have autocomplete by default
   169    if (textSearch && !textSearch.getAttribute('autocomplete')) {
   170      textSearch.setAttribute('autocomplete', 'off');
   171    }
   172  
   173    let menu = $(dropdown).find('> .menu')[0];
   174    if (!menu) {
   175      // 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
   176      menu = document.createElement('div');
   177      menu.classList.add('menu');
   178      dropdown.append(menu);
   179    }
   180  
   181    // There are 2 possible solutions about the role: combobox or menu.
   182    // The idea is that if there is an input, then it's a combobox, otherwise it's a menu.
   183    // Since #19861 we have prepared the "combobox" solution, but didn't get enough time to put it into practice and test before.
   184    const isComboBox = dropdown.querySelectorAll('input').length > 0;
   185  
   186    dropdown[ariaPatchKey].focusableRole = isComboBox ? 'combobox' : 'menu';
   187    dropdown[ariaPatchKey].listPopupRole = isComboBox ? 'listbox' : '';
   188    dropdown[ariaPatchKey].listItemRole = isComboBox ? 'option' : 'menuitem';
   189  
   190    attachDomEvents(dropdown, focusable, menu);
   191    attachStaticElements(dropdown, focusable, menu);
   192  }
   193  
   194  function attachDomEvents(dropdown, focusable, menu) {
   195    // when showing, it has class: ".animating.in"
   196    // when hiding, it has class: ".visible.animating.out"
   197    const isMenuVisible = () => (menu.classList.contains('visible') && !menu.classList.contains('out')) || menu.classList.contains('in');
   198  
   199    // update aria attributes according to current active/selected item
   200    const refreshAriaActiveItem = () => {
   201      const menuVisible = isMenuVisible();
   202      focusable.setAttribute('aria-expanded', menuVisible ? 'true' : 'false');
   203  
   204      // if there is an active item, use it (the user is navigating between items)
   205      // otherwise use the "selected" for combobox (for the last selected item)
   206      const active = $(menu).find('> .item.active, > .item.selected')[0];
   207      if (!active) return;
   208      // if the popup is visible and has an active/selected item, use its id as aria-activedescendant
   209      if (menuVisible) {
   210        focusable.setAttribute('aria-activedescendant', active.id);
   211      } else if (dropdown[ariaPatchKey].listPopupRole === 'menu') {
   212        // for menu, when the popup is hidden, no need to keep the aria-activedescendant, and clear the active/selected item
   213        focusable.removeAttribute('aria-activedescendant');
   214        active.classList.remove('active', 'selected');
   215      }
   216    };
   217  
   218    dropdown.addEventListener('keydown', (e) => {
   219      // here it must use keydown event before dropdown's keyup handler, otherwise there is no Enter event in our keyup handler
   220      if (e.key === 'Enter') {
   221        const dropdownCall = fomanticDropdownFn.bind($(dropdown));
   222        let $item = dropdownCall('get item', dropdownCall('get value'));
   223        if (!$item) $item = $(menu).find('> .item.selected'); // when dropdown filters items by input, there is no "value", so query the "selected" item
   224        // if the selected item is clickable, then trigger the click event.
   225        // we can not click any item without check, because Fomantic code might also handle the Enter event. that would result in double click.
   226        if ($item?.[0]?.matches('a, .js-aria-clickable')) $item[0].click();
   227      }
   228    });
   229  
   230    // use setTimeout to run the refreshAria in next tick (to make sure the Fomantic UI code has finished its work)
   231    // do not return any value, jQuery has return-value related behaviors.
   232    // when the popup is hiding, it's better to have a small "delay", because there is a Fomantic UI animation
   233    // without the delay for hiding, the UI will be somewhat laggy and sometimes may get stuck in the animation.
   234    const deferredRefreshAriaActiveItem = (delay = 0) => { setTimeout(refreshAriaActiveItem, delay) };
   235    dropdown[ariaPatchKey].deferredRefreshAriaActiveItem = deferredRefreshAriaActiveItem;
   236    dropdown.addEventListener('keyup', (e) => { if (e.key.startsWith('Arrow')) deferredRefreshAriaActiveItem(); });
   237  
   238    // if the dropdown has been opened by focus, do not trigger the next click event again.
   239    // otherwise the dropdown will be closed immediately, especially on Android with TalkBack
   240    // * desktop event sequence: mousedown -> focus -> mouseup -> click
   241    // * mobile event sequence: focus -> mousedown -> mouseup -> click
   242    // Fomantic may stop propagation of blur event, use capture to make sure we can still get the event
   243    let ignoreClickPreEvents = 0, ignoreClickPreVisible = 0;
   244    dropdown.addEventListener('mousedown', () => {
   245      ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
   246      ignoreClickPreEvents++;
   247    }, true);
   248    dropdown.addEventListener('focus', () => {
   249      ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
   250      ignoreClickPreEvents++;
   251      deferredRefreshAriaActiveItem();
   252    }, true);
   253    dropdown.addEventListener('blur', () => {
   254      ignoreClickPreVisible = ignoreClickPreEvents = 0;
   255      deferredRefreshAriaActiveItem(100);
   256    }, true);
   257    dropdown.addEventListener('mouseup', () => {
   258      setTimeout(() => {
   259        ignoreClickPreVisible = ignoreClickPreEvents = 0;
   260        deferredRefreshAriaActiveItem(100);
   261      }, 0);
   262    }, true);
   263    dropdown.addEventListener('click', (e) => {
   264      if (isMenuVisible() &&
   265        ignoreClickPreVisible !== 2 && // dropdown is switch from invisible to visible
   266        ignoreClickPreEvents === 2 // the click event is related to mousedown+focus
   267      ) {
   268        e.stopPropagation(); // if the dropdown menu has been opened by focus, do not trigger the next click event again
   269      }
   270      ignoreClickPreEvents = ignoreClickPreVisible = 0;
   271    }, true);
   272  }