@codecademy/gamut

74.0.174.0.2-alpha.b25375.0
dist/Form/SelectDropdown/elements/containers.js
~dist/Form/SelectDropdown/elements/containers.jsModified
+211−39
Index: package/dist/Form/SelectDropdown/elements/containers.js
===================================================================
--- package/dist/Form/SelectDropdown/elements/containers.js
+++ package/dist/Form/SelectDropdown/elements/containers.js
@@ -1,5 +1,5 @@
-import { createContext, useEffect, useLayoutEffect } from 'react';
+import { createContext, useContext, useEffect, useLayoutEffect } from 'react';
 import ReactSelect, { components as SelectDropdownElements } from 'react-select';
 import CreatableSelect from 'react-select/creatable';
 import { DEFAULT_SELECT_DROPDOWN_TRANSLATIONS } from '../core/translations';
 import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
@@ -37,21 +37,61 @@
  * Renders the selected values as a comma-separated string in the hidden input.
  */
 export const CustomContainer = ({
   children,
+  innerProps,
   ...rest
 }) => {
   const {
+    selectInputRef
+  } = useContext(SelectDropdownContext);
+  const {
     inputProps,
-    name
+    isSearchable,
+    menuIsOpen,
+    name,
+    onBlur,
+    onFocus,
+    openMenuOnFocus
   } = rest.selectProps;
   const hiddenProps = inputProps?.hidden || {};
   const hasHiddenProps = inputProps?.hidden && Object.keys(inputProps.hidden).length > 0;
   const value = rest.hasValue ? rest.getValue().map(({
     value
   }) => value).join(', ') : '';
+
+  /*
+   * Non-searchable: react-select only sees focus and blur on its hidden input, which
+   * can't take focus. Handle them on the whole select, so every internal control counts
+   * (value, clear button, chevron). Our handling runs first and the consumer's callbacks
+   * run after it, so a consumer's callback can't stop the menu from opening or closing.
+   */
+  const handleFocus = event => {
+    const nextFocus = event.relatedTarget;
+    if (nextFocus && event.currentTarget.contains(nextFocus)) return;
+    if (openMenuOnFocus) {
+      selectInputRef?.current?.openMenu('first');
+    }
+    onFocus?.(event);
+  };
+  const handleBlur = event => {
+    const nextFocus = event.relatedTarget;
+    if (nextFocus && event.currentTarget.contains(nextFocus)) return;
+    if (menuIsOpen) {
+      selectInputRef?.current?.onMenuClose();
+    }
+    onBlur?.(event);
+  };
+  const selectOnlyHandlers = isSearchable === false ? {
+    onBlur: handleBlur,
+    onFocus: handleFocus
+  } : {};
   return /*#__PURE__*/_jsxs(SelectDropdownElements.SelectContainer, {
     ...rest,
+    innerProps: {
+      ...innerProps,
+      ...selectOnlyHandlers
+    },
     children: [children, hasHiddenProps && /*#__PURE__*/_jsx("input", {
       name: name,
       type: "hidden",
       value: value,
@@ -59,58 +99,190 @@
     })]
   });
 };
 
+/*
+ * With isSearchable={false}, react-select renders a hidden <input role="combobox">.
+ * Screen readers announce it as editable ("type text", "auto complete"), which is
+ * wrong for a control that takes no typing. Instead, the ValueContainer is the
+ * combobox (ARIA APG select-only pattern) and takes focus. react-select's keydown
+ * handling still applies because keydown bubbles up to its container.
+ */
+const SELECT_ONLY_ARIA_PROPS = ['aria-describedby', 'aria-errormessage', 'aria-invalid', 'aria-label', 'aria-labelledby', 'aria-required'];
+
+/* Methods on react-select's Select instance, reached through the selectRef. */
+
+const useSelectOnlyInput = (inputId, isSearchable) => {
+  useLayoutEffect(() => {
+    if (isSearchable !== false || !inputId) return;
+
+    /*
+     * Match the <input> by tag, not just by id: when a consumer's id equals name, react-select's
+     * container carries the same id and getElementById would return the container instead.
+     */
+    const input = Array.from(document.getElementsByTagName('input')).find(element => element.id === inputId);
+    const trigger = input?.parentElement?.closest('[role="combobox"]');
+    if (!input || !trigger) return;
+
+    /*
+     * A disabled input can't take focus, so react-select's focusInput() calls
+     * become no-ops and focus stays on the trigger.
+     */
+    input.setAttribute('disabled', '');
+    input.setAttribute('aria-hidden', 'true');
+    input.removeAttribute('role');
+
+    /*
+     * The label targets the (disabled) input, which can't receive focus or a label click.
+     * Name the trigger from that label instead, and focus the trigger when the label is clicked.
+     */
+    const label = Array.from(document.querySelectorAll('label')).find(element => element.htmlFor === inputId);
+    const focusTrigger = () => trigger.focus();
+    if (label) {
+      if (!label.id) label.id = `${inputId}-label`;
+      if (!trigger.hasAttribute('aria-labelledby')) {
+        trigger.setAttribute('aria-labelledby', label.id);
+      }
+      label.addEventListener('click', focusTrigger);
+    }
+
+    /*
+     * react-select only sets aria-activedescendant on the hidden input off Apple devices
+     * (its isAppleDevice check), so VoiceOver on macOS gets nothing from it. Derive the
+     * active option from the rendered menu instead: Gamut sets aria-selected on the
+     * focused option. The container is SelectContainer > Control > ValueContainer.
+     */
+    const container = trigger.parentElement?.parentElement ?? trigger;
+    const syncActiveOption = () => {
+      const isExpanded = trigger.getAttribute('aria-expanded') === 'true';
+      const listbox = container.querySelector('[role="listbox"]');
+      const activeOption = container.querySelector('[role="option"][aria-selected="true"]');
+      if (listbox?.id && isExpanded) {
+        trigger.setAttribute('aria-controls', listbox.id);
+      } else {
+        trigger.removeAttribute('aria-controls');
+      }
+      if (activeOption?.id && isExpanded) {
+        trigger.setAttribute('aria-activedescendant', activeOption.id);
+      } else {
+        trigger.removeAttribute('aria-activedescendant');
+      }
+    };
+
+    /*
+     * aria-expanded is set on the trigger in a later React commit than the listbox
+     * mounts, so it has to be observed too, or the sync can run while it's still "false".
+     */
+    const observer = new MutationObserver(syncActiveOption);
+    observer.observe(container, {
+      attributeFilter: ['aria-expanded', 'aria-selected'],
+      attributes: true,
+      childList: true,
+      subtree: true
+    });
+    syncActiveOption();
+    return () => {
+      observer.disconnect();
+      label?.removeEventListener('click', focusTrigger);
+    };
+  }, [inputId, isSearchable]);
+};
+
 /**
- * Custom ValueContainer component that applies combobox props when isSearchable is false.
- * When isSearchable is false, react-select renders a dummy input (div) that doesn't accept
- * custom props, so we apply the combobox data attributes to the ValueContainer's innerProps.
+ * Non-searchable: react-select opens the menu on mousedown only once its input has
+ * focus, and the hidden input can't take focus. Open from the control instead, so a
+ * click on the padding works. Child handlers (the chevron, the clear button) call
+ * preventDefault first, so they keep their behaviour.
  */
+export const CustomControl = ({
+  innerProps,
+  ...rest
+}) => {
+  const {
+    selectInputRef
+  } = useContext(SelectDropdownContext);
+  const {
+    isDisabled,
+    isSearchable,
+    menuIsOpen
+  } = rest.selectProps;
+  if (isSearchable !== false) {
+    return /*#__PURE__*/_jsx(SelectDropdownElements.Control, {
+      ...rest,
+      innerProps: innerProps
+    });
+  }
+  const handleMouseDown = event => {
+    if (event.defaultPrevented || event.button !== 0 || isDisabled) return;
+    event.preventDefault();
+    event.currentTarget.querySelector('[role="combobox"]')?.focus();
+    const instance = selectInputRef?.current;
+    if (menuIsOpen) instance?.onMenuClose();else instance?.openMenu('first');
+  };
+  return /*#__PURE__*/_jsx(SelectDropdownElements.Control, {
+    ...rest,
+    innerProps: {
+      ...innerProps,
+      onMouseDown: handleMouseDown
+    }
+  });
+};
+
+/**
+ * Custom ValueContainer component. When isSearchable is false, it becomes the
+ * select-only combobox trigger (see `useSelectOnlyInput`). Otherwise it renders
+ * react-select's default ValueContainer.
+ */
 export const CustomValueContainer = ({
+  innerProps,
   ...rest
 }) => {
   const {
+    selectInputRef
+  } = useContext(SelectDropdownContext);
+  const {
+    inputId,
     inputProps,
-    isSearchable
+    isDisabled,
+    isSearchable,
+    menuIsOpen,
+    required
   } = rest.selectProps;
   const comboboxProps = inputProps?.combobox || {};
-  useLayoutEffect(() => {
-    if (isSearchable === false && Object.keys(comboboxProps).length > 0) {
-      // Find the input element by inputId since we can't use a ref on ValueContainer
-      const {
-        inputId
-      } = rest.selectProps;
-      if (inputId) {
-        const inputElement = document.getElementById(inputId);
-        if (inputElement?.getAttribute('role') === 'combobox') {
-          Object.entries(comboboxProps).forEach(([key, value]) => {
-            inputElement.setAttribute(key, value);
-          });
-        }
-      }
-    }
-    // We only want to run this effect when isSearchable or comboboxProps change
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, [isSearchable, comboboxProps, rest.selectProps.inputId]);
-
-  // When isSearchable is false, apply combobox props to ValueContainer's innerProps
-  // since the dummy input doesn't accept custom props
-  if (isSearchable === false && Object.keys(comboboxProps).length > 0) {
-    const {
-      innerProps,
-      ...otherProps
-    } = rest;
-    const mergedInnerProps = {
-      ...innerProps,
-      ...comboboxProps
-    };
+  useSelectOnlyInput(inputId, isSearchable);
+  if (isSearchable !== false || !inputId) {
     return /*#__PURE__*/_jsx(SelectDropdownElements.ValueContainer, {
-      ...otherProps,
-      innerProps: mergedInnerProps
+      ...rest
     });
   }
+  const ariaProps = Object.fromEntries(Object.entries(rest.selectProps).filter(([key, value]) => SELECT_ONLY_ARIA_PROPS.includes(key) && value !== undefined));
+
+  /* Read the ref inside handlers: it is still null during render on the first pass. */
+  const getInstance = () => selectInputRef?.current;
+  const handleMouseDown = event => {
+    if (event.button !== 0 || isDisabled) return;
+
+    // Stops react-select from focusing its hidden input on mousedown.
+    event.preventDefault();
+    event.currentTarget.focus();
+    if (menuIsOpen) getInstance()?.onMenuClose();else getInstance()?.openMenu('first');
+  };
   return /*#__PURE__*/_jsx(SelectDropdownElements.ValueContainer, {
-    ...rest
+    ...rest,
+    innerProps: {
+      ...innerProps,
+      ...ariaProps,
+      'aria-disabled': isDisabled || undefined,
+      /* react-select puts aria-required on its input; the trigger replaces that input, so set it here. */
+      'aria-required': required || undefined,
+      'aria-expanded': Boolean(menuIsOpen),
+      'aria-haspopup': 'listbox',
+      onMouseDown: handleMouseDown,
+      role: 'combobox',
+      tabIndex: isDisabled ? -1 : 0,
+      /* Last, so consumer data- and aria- props can override the defaults above, as before this change. */
+      ...comboboxProps
+    }
   });
 };
 
 /**