# All files / form Select.tsx

0% Statements 0/526
0% Branches 0/1
0% Functions 0/1
0% Lines 0/526

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527

     "use client";
    import { cnb } from "cnbuilder";
    import {
      useEffect,
      useMemo,
      useRef,
      useState,
      type ChangeEvent,
      type ReactElement,
      type ReactNode,
      type Ref,
    } from "react";
    import { IconRotator } from "../icon/IconRotator.js";
    import { getIcon } from "../icon/iconConfig.js";
    import { Menu, type MenuProps } from "../menu/Menu.js";
    import { findMatchIndex } from "../movement/findMatchIndex.js";
    import {
      KeyboardMovementProvider,
      useKeyboardMovementProvider,
    } from "../movement/useKeyboardMovementProvider.js";
    import { isSearchableEvent } from "../movement/utils.js";
    import { BELOW_CENTER_ANCHOR } from "../positioning/constants.js";
    import {
      type TransitionEnterHandler,
      type TransitionExitHandler,
    } from "../transition/types.js";
    import { useEnsuredId } from "../useEnsuredId.js";
    import { useEnsuredRef } from "../useEnsuredRef.js";
    import { useToggle } from "../useToggle.js";
    import { loop } from "../utils/loop.js";
    import { SelectValue } from "./SelectValue.js";
    import { TextField, type TextFieldProps } from "./TextField.js";
    import { getFormConfig } from "./formConfig.js";
    import { select } from "./selectStyles.js";
    import { extractOptionsFromChildren } from "./selectUtils.js";
    import {
      type FormFieldOptions,
      type UserAgentAutoCompleteProps,
    } from "./types.js";
    import { ListboxProvider } from "./useListboxProvider.js";
    import { triggerManualChangeEvent, tryToSubmitRelatedForm } from "./utils.js";

    const EMPTY_STRING = "" as const;
    const noop = (): void => {
      // do nothing
    };

    const getNonDisabledOptions = (
      container: HTMLElement
    ): readonly HTMLElement[] => [
      ...container.querySelectorAll<HTMLLIElement>(
        '[role="option"]:not([aria-disabled])'
      ),
    ];

    /**
     * This is a convenience type for casting the `event.currentTarget.value` of a
     * `Select`'s change event to be union of available values.
     *
     * Note: The change event does not provide any sort of validation on the value
     * so automation tools like Cypress, Playwright, or Selenium might set an
     * invalid value. This also does not work for numbers, so you will need to
     * implement that yourself.
     *
     * @example
     * Simple Usage
     * ```tsx
     * import type { SelectedChangeEvent } from "@react-md/core";
     * import { Select, Option } from "@react-md/core";
     * import type { ReactElement } from "react";
     *
     * type Value = "" | "a" | "b" | "c" | "d";
     *
     * function Example(): ReactElement {
     *   const [value, setValue] = useState<Value>("");
     *
     *   const handleChange = (event: SelectChangeEvent<Value>): void => {
     *     // No type error!
     *     // `event.currentTarget.value`'s type is `Value` instead of a generic `string`
     *     setValue(event.currentTarget.value);
     *   };
     *
     *   return (
     *     <Select
     *       label="Label"
     *       value={value}
     *       onChange={handleChange}
     *     >
     *       <Option value="a">First</Option>
     *       <Option value="b">Second</Option>
     *       <Option value="c">Third</Option>
     *       <Option value="d">Fourth</Option>
     *     </Select>
     *   );
     * }
     * ```
     * @remarks \@since 6.0.0
     */
    export type SelectChangeEvent<Value extends string> =
      ChangeEvent<HTMLInputElement> & { currentTarget: { value: Value } };

    /**
     * @remarks \@since 6.0.0 Rewritten with a new API.
     */
    export interface SelectProps<Value extends string>
      extends Omit<TextFieldProps, "placeholder" | "type" | "onChange">,
        UserAgentAutoCompleteProps,
        FormFieldOptions {
      /**
       * An optional ref to pass to the hidden `<input type="text" />` element that
       * stores the current value. This is really only useful if you'd like to keep
       * this component uncontrolled and access the value through
       * `inputRef.current.value`.
       */
      inputRef?: Ref<HTMLInputElement>;

      /**
       * Set this to a custom dropdown icon or `null` to not render a dropdown icon.
       *
       * @defaultValue `getIcon("dropdown")`
       */
      icon?: ReactNode;

      /**
       * Set this value to fully control the value of the select component. The
       * {@link onChange} handler **must** also be provided if this prop exists.
       */
      value?: Value;

      /**
       * An optional default value when the value of the select component is
       * uncontrolled.
       *
       * @defaultValue `""`
       */
      defaultValue?: Value;

      /** @see {@link SelectChangeEvent} */
      onChange?(event: SelectChangeEvent<Value>): void;

      /**
       * Any additional props to provide to the `Menu` component that renders all
       * the `Option`s.
       *
       * The menu will always have these default values unless explicity
       * overwritten by this prop:
       *
       * - `aria-labelledby={containerId}`
       * - `anchor={BELOW_CENTER_ANCHOR}`
       * - `width="min"`
       */
      menuProps?: Omit<MenuProps, "visible" | "onRequestClose" | "fixedTo">;

      /**
       * Set this to `true` to update all the `Option` components to no longer
       * render an icon while selected.
       *
       * @defaultValue `false`
       */
      disableSelectedIcon?: boolean;

      /**
       * Set this to `true` to prevent the current option from rendering the
       * `leftAddon` in the `TextFieldContainer`.
       *
       * @defaultValue `false`
       */
      disableValueAddon?: boolean;

      /**
       * This should be the available `Option`s for the select to choose from. It
       * can also contain `OptGroup` or any other elements but only clicking on an
       * `Option` component will update the value.
       */
      children: ReactNode;
    }

    /**
     * **Client Component**
     *
     * @remarks \@since 6.0.0 Rewritten with a new API.
     */
    export function Select<Value extends string>(
      props: SelectProps<Value>
    ): ReactElement {
      const {
        id: propId,
        className,
        active = false,
        inputRef: propInputRef,
        inputClassName,
        menuProps = {},
        containerProps: propContainerProps = {},
        icon: propIcon,
        value,
        defaultValue,
        theme: propTheme,
        onChange = noop,
        leftAddon,
        rightAddon: propRightAddon,
        disableValueAddon = false,
        disableSelectedIcon = false,
        children,
        ...remaining
      } = props;
      const { disabled = false, form } = props;

      const id = useEnsuredId(propId, "select");
      const containerId = useEnsuredId(propContainerProps.id, "select-container");
      const icon = getIcon("dropdown", propIcon);
      const theme = getFormConfig("theme", propTheme);

      const { toggled: visible, enable: show, disable: hide } = useToggle();
      const [inputRef, inputRefCallback] = useEnsuredRef(propInputRef);
      const [containerRef, containerRefCallback] = useEnsuredRef(
        propContainerProps.ref
      );
      const [menuRef, menuRefCallback] = useEnsuredRef(menuProps.nodeRef);
      const [currentValue, setCurrentValue] = useState(() => {
        if (typeof defaultValue !== "undefined") {
          return defaultValue;
        }

        return typeof value !== "undefined" ? value : EMPTY_STRING;
      });
      const initialValue = useRef(currentValue);

      useEffect(() => {
        const select = inputRef.current;
        if (!select) {
          return;
        }

        const formElement =
          select.closest<HTMLFormElement>("form") ||
          (form && document.getElementById(form)) ||
          null;

        if (!formElement) {
          return;
        }

        const handleReset = (): void => {
          triggerManualChangeEvent(select, initialValue.current);
        };

        formElement.addEventListener("reset", handleReset);
        return () => {
          formElement.removeEventListener("reset", handleReset);
        };
      }, [form, inputRef]);

      const { options, searchValues, currentOption, currentIndex } =
        extractOptionsFromChildren(
          children,
          typeof value === "undefined" ? currentValue : value
        );
      const totalOptions = options.length - 1;

      let rightAddon = propRightAddon;
      if (typeof rightAddon === "undefined" && icon) {
        rightAddon = <IconRotator rotated={visible}>{icon}</IconRotator>;
      }

      const listboxContext = useMemo(
        () => ({
          inputRef,
          currentValue: typeof value === "undefined" ? currentValue : value,
          disableSelectedIcon,
        }),
        [currentValue, disableSelectedIcon, inputRef, value]
      );

      // TODO: Need to update this to support editable listboxes where these props
      // would go to the input element instead of the container
      const a11yProps = {
        "aria-haspopup": "listbox",
        "aria-expanded": visible,
        role: "combobox",
        tabIndex: disabled ? -1 : 0,
      } as const;
      const {
        movementProps,
        movementContext,
        currentFocusIndex,
        setActiveDescendantId,
      } = useKeyboardMovementProvider<HTMLDivElement>({
        onFocus: propContainerProps.onFocus,
        onClick(event) {
          propContainerProps.onClick?.(event);
          if (disabled) {
            return;
          }

          show();
        },
        onKeyDown(event) {
          propContainerProps.onKeyDown?.(event);
          if (disabled) {
            return;
          }

          if (visible) {
            if (event.key === "Escape" || event.key === "Tab") {
              event.stopPropagation();
              hide();
            }

            return;
          }

          if (isSearchableEvent(event)) {
            event.stopPropagation();

            const nextIndex = findMatchIndex({
              value: event.key,
              values: searchValues,
              startIndex: event.shiftKey ? -1 : currentIndex,
            });

            if (nextIndex !== -1) {
              triggerManualChangeEvent(inputRef.current, options[nextIndex].value);
            }
            return;
          }

          switch (event.key) {
            case " ":
              event.preventDefault();
              event.stopPropagation();
              show();
              break;
            case "Enter":
              tryToSubmitRelatedForm(event, form);
              break;
            case "Home":
              event.preventDefault();
              event.stopPropagation();
              if (currentIndex !== 0) {
                triggerManualChangeEvent(inputRef.current, options[0].value);
              }
              break;
            case "End":
              event.preventDefault();
              event.stopPropagation();
              if (currentIndex !== totalOptions) {
                triggerManualChangeEvent(
                  inputRef.current,
                  options[totalOptions].value
                );
              }
              break;
            case "ArrowDown":
            case "ArrowUp": {
              event.preventDefault();
              event.stopPropagation();

              const increment = event.key === "ArrowDown";
              if (currentIndex === -1 && !increment) {
                // this matches the native select behavior where it will do
                // nothing if there is no current value
                return;
              }

              const nextIndex = loop({
                max: totalOptions,
                value: currentIndex,
                minmax: true,
                increment,
              });

              triggerManualChangeEvent(inputRef.current, options[nextIndex].value);
              break;
            }
          }
        },
        loopable: false,
        searchable: true,
        programmatic: true,
        includeDisabled: false,
        tabIndexBehavior: "virtual",
        getDefaultFocusedIndex(focusOptions) {
          if (typeof menuProps.getDefaultFocusedIndex === "function") {
            return menuProps.getDefaultFocusedIndex(focusOptions);
          }

          const val = typeof value === "undefined" ? currentValue : value;
          return options.findIndex((option) => option.value === val);
        },
        getFocusableElements() {
          const menu = menuRef.current;
          if (!menu) {
            return [];
          }

          return [
            ...menu.querySelectorAll<HTMLLIElement>(
              '[role="option"]:not([aria-disabled])'
            ),
          ];
        },
      });

      const containerProps: Required<SelectProps<Value>>["containerProps"] = {
        ...propContainerProps,
        ...movementProps,
        ...a11yProps,
        ref: containerRefCallback,
      };

      const { onEntering, onEntered, onExiting, onExited, disableTransition } =
        menuProps;
      const handleMounting =
        (callback: TransitionEnterHandler | undefined = noop, skipped: boolean) =>
        (appearing: boolean) => {
          callback(appearing);

          const menu = menuRef.current;
          if (!menu || skipped) {
            return;
          }

          // Since the keyboard movement behavior is tied to the
          // `TextFieldContainer` or `input` element instead of the menu for this
          // widget, the focus index and active descendant must manually be updated
          // whenever the menu becomes visible. Without this, no items will be
          // focused until the first keyboard event that would move focus
          const val = typeof value === "undefined" ? currentValue : value;
          const focusables = getNonDisabledOptions(menu);
          const index = Math.max(
            0,
            options.findIndex((option) => option.value === val)
          );
          focusables[index].scrollIntoView({ block: "nearest" });
          currentFocusIndex.current = index;
          setActiveDescendantId(focusables[index]?.id || "");
        };

      const handleUnmounting =
        (callback: TransitionExitHandler | undefined = noop, skipped = false) =>
        (): void => {
          callback();

          if (!skipped) {
            // since the menu is unmounted or set to hidden while not visible, need
            // to clear the aria-activedescendant and current focus index when
            // hiding
            currentFocusIndex.current = -1;
            setActiveDescendantId("");
          }
        };

      return (
        <ListboxProvider value={listboxContext}>
          <KeyboardMovementProvider value={movementContext}>
            <TextField
              {...remaining}
              aria-hidden
              id={id}
              ref={inputRefCallback}
              containerProps={containerProps}
              type="text"
              tabIndex={-1}
              theme={theme}
              value={value}
              defaultValue={defaultValue}
              active={active || visible}
              leftAddon={leftAddon}
              rightAddon={rightAddon}
              className={cnb("rmd-select-container", className)}
              inputClassName={select({
                theme,
                className: inputClassName,
              })}
              onChange={(event) => {
                onChange(event as SelectChangeEvent<Value>);
                if (typeof value !== "undefined") {
                  return;
                }

                const nextValue = event.currentTarget.value;
                const valueAsNumber = parseFloat(nextValue);
                const nextOption = options.find(
                  (option) =>
                    // need to compare both here since
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-expect-error
                    option.value === nextValue || option.value === valueAsNumber
                );

                setCurrentValue(
                  nextOption ? nextOption.value : initialValue.current
                );
              }}
            >
              <SelectValue disableAddon={disableValueAddon} {...currentOption} />
            </TextField>
            <Menu
              aria-labelledby={containerId}
              anchor={BELOW_CENTER_ANCHOR}
              role="listbox"
              width="min"
              {...menuProps}
              ref={menuRefCallback}
              visible={visible}
              fixedTo={containerRef}
              onRequestClose={hide}
              onEntering={handleMounting(onEntering, false)}
              onEntered={handleMounting(onEntered, !disableTransition)}
              onExiting={handleUnmounting(onExiting, false)}
              onExited={handleUnmounting(onExited, !disableTransition)}
              sheetProps={{
                ...menuProps.sheetProps,
                onEntering: handleMounting(menuProps.sheetProps?.onEntering, false),
                onEntered: handleMounting(
                  menuProps.sheetProps?.onEntered,
                  !disableTransition
                ),
              }}
            >
              {children}
            </Menu>
          </KeyboardMovementProvider>
        </ListboxProvider>
      );
    }