code.gitea.io/gitea@v1.21.7/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      const $dropdown = $(el);
    25      if (!el[ariaPatchKey]) {
    26        attachInit($dropdown);
    27      }
    28      if (needDelegate) {
    29        delegateOne($dropdown);
    30      }
    31    }
    32    return ret;
    33  }
    34  
    35  // make the item has role=option/menuitem, add an id if there wasn't one yet, make items as non-focusable
    36  // the elements inside the dropdown menu item should not be focusable, the focus should always be on the dropdown primary element.
    37  function updateMenuItem(dropdown, item) {
    38    if (!item.id) item.id = generateAriaId();
    39    item.setAttribute('role', dropdown[ariaPatchKey].listItemRole);
    40    item.setAttribute('tabindex', '-1');
    41    for (const a of item.querySelectorAll('a')) a.setAttribute('tabindex', '-1');
    42  }
    43  
    44  // make the label item and its "delete icon" has correct aria attributes
    45  function updateSelectionLabel($label) {
    46    // the "label" is like this: "<a|div class="ui label" data-value="1">the-label-name <i|svg class="delete icon"/></a>"
    47    if (!$label.attr('id')) $label.attr('id', generateAriaId());
    48    $label.attr('tabindex', '-1');
    49    $label.find('.delete.icon').attr({
    50      'aria-hidden': 'false',
    51      'aria-label': window.config.i18n.remove_label_str.replace('%s', $label.attr('data-value')),
    52      'role': 'button',
    53    });
    54  }
    55  
    56  // delegate the dropdown's template functions and callback functions to add aria attributes.
    57  function delegateOne($dropdown) {
    58    const dropdownCall = fomanticDropdownFn.bind($dropdown);
    59  
    60    // 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.
    61    // Actually, Fomantic UI doesn't support such layout/usage. It needs to patch the "focusSearch" / "blurSearch" functions to make sure it toggles the menu.
    62    const oldFocusSearch = dropdownCall('internal', 'focusSearch');
    63    const oldBlurSearch = dropdownCall('internal', 'blurSearch');
    64    // * If the "dropdown icon" is clicked, Fomantic calls "focusSearch", so show the menu
    65    dropdownCall('internal', 'focusSearch', function () { dropdownCall('show'); oldFocusSearch.call(this) });
    66    // * If the "dropdown icon" is clicked again when the menu is visible, Fomantic calls "blurSearch", so hide the menu
    67    dropdownCall('internal', 'blurSearch', function () { oldBlurSearch.call(this); dropdownCall('hide') });
    68  
    69    // the "template" functions are used for dynamic creation (eg: AJAX)
    70    const dropdownTemplates = {...dropdownCall('setting', 'templates'), t: performance.now()};
    71    const dropdownTemplatesMenuOld = dropdownTemplates.menu;
    72    dropdownTemplates.menu = function(response, fields, preserveHTML, className) {
    73      // when the dropdown menu items are loaded from AJAX requests, the items are created dynamically
    74      const menuItems = dropdownTemplatesMenuOld(response, fields, preserveHTML, className);
    75      const $wrapper = $('<div>').append(menuItems);
    76      const $items = $wrapper.find('> .item');
    77      $items.each((_, item) => updateMenuItem($dropdown[0], item));
    78      $dropdown[0][ariaPatchKey].deferredRefreshAriaActiveItem();
    79      return $wrapper.html();
    80    };
    81    dropdownCall('setting', 'templates', dropdownTemplates);
    82  
    83    // the `onLabelCreate` is used to add necessary aria attributes for dynamically created selection labels
    84    const dropdownOnLabelCreateOld = dropdownCall('setting', 'onLabelCreate');
    85    dropdownCall('setting', 'onLabelCreate', function(value, text) {
    86      const $label = dropdownOnLabelCreateOld.call(this, value, text);
    87      updateSelectionLabel($label);
    88      return $label;
    89    });
    90  }
    91  
    92  // for static dropdown elements (generated by server-side template), prepare them with necessary aria attributes
    93  function attachStaticElements($dropdown, $focusable, $menu) {
    94    const dropdown = $dropdown[0];
    95  
    96    // prepare static dropdown menu list popup
    97    if (!$menu.attr('id')) $menu.attr('id', generateAriaId());
    98    $menu.find('> .item').each((_, item) => updateMenuItem(dropdown, item));
    99    // this role could only be changed after its content is ready, otherwise some browsers+readers (like Chrome+AppleVoice) crash
   100    $menu.attr('role', dropdown[ariaPatchKey].listPopupRole);
   101  
   102    // prepare selection label items
   103    $dropdown.find('.ui.label').each((_, label) => updateSelectionLabel($(label)));
   104  
   105    // make the primary element (focusable) aria-friendly
   106    $focusable.attr({
   107      'role': $focusable.attr('role') ?? dropdown[ariaPatchKey].focusableRole,
   108      'aria-haspopup': dropdown[ariaPatchKey].listPopupRole,
   109      'aria-controls': $menu.attr('id'),
   110      'aria-expanded': 'false',
   111    });
   112  
   113    // use tooltip's content as aria-label if there is no aria-label
   114    const tooltipContent = $dropdown.attr('data-tooltip-content');
   115    if (tooltipContent && !$dropdown.attr('aria-label')) {
   116      $dropdown.attr('aria-label', tooltipContent);
   117    }
   118  }
   119  
   120  function attachInit($dropdown) {
   121    const dropdown = $dropdown[0];
   122    dropdown[ariaPatchKey] = {};
   123    if ($dropdown.hasClass('custom')) return;
   124  
   125    // Dropdown has 2 different focusing behaviors
   126    // * with search input: the input is focused, and it works with aria-activedescendant pointing another sibling element.
   127    // * without search input (but the readonly text), the dropdown itself is focused. then the aria-activedescendant points to the element inside dropdown
   128    // 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.
   129  
   130    // Expected user interactions for dropdown with aria support:
   131    // * user can use Tab to focus in the dropdown, then the dropdown menu (list) will be shown
   132    // * user presses Tab on the focused dropdown to move focus to next sibling focusable element (but not the menu item)
   133    // * user can use arrow key Up/Down to navigate between menu items
   134    // * when user presses Enter:
   135    //    - if the menu item is clickable (eg: <a>), then trigger the click event
   136    //    - otherwise, the dropdown control (low-level code) handles the Enter event, hides the dropdown menu
   137  
   138    // TODO: multiple selection is only partially supported. Check and test them one by one in the future.
   139  
   140    const $textSearch = $dropdown.find('input.search').eq(0);
   141    const $focusable = $textSearch.length ? $textSearch : $dropdown; // the primary element for focus, see comment above
   142    if (!$focusable.length) return;
   143  
   144    // as a combobox, the input should not have autocomplete by default
   145    if ($textSearch.length && !$textSearch.attr('autocomplete')) {
   146      $textSearch.attr('autocomplete', 'off');
   147    }
   148  
   149    let $menu = $dropdown.find('> .menu');
   150    if (!$menu.length) {
   151      // 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
   152      $menu = $('<div class="menu"></div>').appendTo($dropdown);
   153    }
   154  
   155    // There are 2 possible solutions about the role: combobox or menu.
   156    // The idea is that if there is an input, then it's a combobox, otherwise it's a menu.
   157    // Since #19861 we have prepared the "combobox" solution, but didn't get enough time to put it into practice and test before.
   158    const isComboBox = $dropdown.find('input').length > 0;
   159  
   160    dropdown[ariaPatchKey].focusableRole = isComboBox ? 'combobox' : 'menu';
   161    dropdown[ariaPatchKey].listPopupRole = isComboBox ? 'listbox' : '';
   162    dropdown[ariaPatchKey].listItemRole = isComboBox ? 'option' : 'menuitem';
   163  
   164    attachDomEvents($dropdown, $focusable, $menu);
   165    attachStaticElements($dropdown, $focusable, $menu);
   166  }
   167  
   168  function attachDomEvents($dropdown, $focusable, $menu) {
   169    const dropdown = $dropdown[0];
   170    // when showing, it has class: ".animating.in"
   171    // when hiding, it has class: ".visible.animating.out"
   172    const isMenuVisible = () => ($menu.hasClass('visible') && !$menu.hasClass('out')) || $menu.hasClass('in');
   173  
   174    // update aria attributes according to current active/selected item
   175    const refreshAriaActiveItem = () => {
   176      const menuVisible = isMenuVisible();
   177      $focusable.attr('aria-expanded', menuVisible ? 'true' : 'false');
   178  
   179      // if there is an active item, use it (the user is navigating between items)
   180      // otherwise use the "selected" for combobox (for the last selected item)
   181      const $active = $menu.find('> .item.active, > .item.selected');
   182      // if the popup is visible and has an active/selected item, use its id as aria-activedescendant
   183      if (menuVisible) {
   184        $focusable.attr('aria-activedescendant', $active.attr('id'));
   185      } else if (dropdown[ariaPatchKey].listPopupRole === 'menu') {
   186        // for menu, when the popup is hidden, no need to keep the aria-activedescendant, and clear the active/selected item
   187        $focusable.removeAttr('aria-activedescendant');
   188        $active.removeClass('active').removeClass('selected');
   189      }
   190    };
   191  
   192    $dropdown.on('keydown', (e) => {
   193      // here it must use keydown event before dropdown's keyup handler, otherwise there is no Enter event in our keyup handler
   194      if (e.key === 'Enter') {
   195        const dropdownCall = fomanticDropdownFn.bind($dropdown);
   196        let $item = dropdownCall('get item', dropdownCall('get value'));
   197        if (!$item) $item = $menu.find('> .item.selected'); // when dropdown filters items by input, there is no "value", so query the "selected" item
   198        // if the selected item is clickable, then trigger the click event.
   199        // we can not click any item without check, because Fomantic code might also handle the Enter event. that would result in double click.
   200        if ($item && ($item.is('a') || $item.hasClass('js-aria-clickable'))) $item[0].click();
   201      }
   202    });
   203  
   204    // use setTimeout to run the refreshAria in next tick (to make sure the Fomantic UI code has finished its work)
   205    // do not return any value, jQuery has return-value related behaviors.
   206    // when the popup is hiding, it's better to have a small "delay", because there is a Fomantic UI animation
   207    // without the delay for hiding, the UI will be somewhat laggy and sometimes may get stuck in the animation.
   208    const deferredRefreshAriaActiveItem = (delay = 0) => { setTimeout(refreshAriaActiveItem, delay) };
   209    dropdown[ariaPatchKey].deferredRefreshAriaActiveItem = deferredRefreshAriaActiveItem;
   210    $dropdown.on('keyup', (e) => { if (e.key.startsWith('Arrow')) deferredRefreshAriaActiveItem(); });
   211  
   212    // if the dropdown has been opened by focus, do not trigger the next click event again.
   213    // otherwise the dropdown will be closed immediately, especially on Android with TalkBack
   214    // * desktop event sequence: mousedown -> focus -> mouseup -> click
   215    // * mobile event sequence: focus -> mousedown -> mouseup -> click
   216    // Fomantic may stop propagation of blur event, use capture to make sure we can still get the event
   217    let ignoreClickPreEvents = 0, ignoreClickPreVisible = 0;
   218    dropdown.addEventListener('mousedown', () => {
   219      ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
   220      ignoreClickPreEvents++;
   221    }, true);
   222    dropdown.addEventListener('focus', () => {
   223      ignoreClickPreVisible += isMenuVisible() ? 1 : 0;
   224      ignoreClickPreEvents++;
   225      deferredRefreshAriaActiveItem();
   226    }, true);
   227    dropdown.addEventListener('blur', () => {
   228      ignoreClickPreVisible = ignoreClickPreEvents = 0;
   229      deferredRefreshAriaActiveItem(100);
   230    }, true);
   231    dropdown.addEventListener('mouseup', () => {
   232      setTimeout(() => {
   233        ignoreClickPreVisible = ignoreClickPreEvents = 0;
   234        deferredRefreshAriaActiveItem(100);
   235      }, 0);
   236    }, true);
   237    dropdown.addEventListener('click', (e) => {
   238      if (isMenuVisible() &&
   239        ignoreClickPreVisible !== 2 && // dropdown is switch from invisible to visible
   240        ignoreClickPreEvents === 2 // the click event is related to mousedown+focus
   241      ) {
   242        e.stopPropagation(); // if the dropdown menu has been opened by focus, do not trigger the next click event again
   243      }
   244      ignoreClickPreEvents = ignoreClickPreVisible = 0;
   245    }, true);
   246  }