# All files Select.tsx

100% Statements 442/442
77.77% Branches 14/18
100% Functions 3/3
100% Lines 442/442

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
    4431x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    8x
    8x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    14x
    3x
    3x
    11x
    14x
    14x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    24x
    24x
    24x
    24x
    24x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    9x
    9x
    1x
    1x
    8x
    8x
    8x
    8x
    9x
    9x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
    87x
     "use client";
    import { cnb } from "cnbuilder";
    import {
      useMemo,
      useRef,
      useState,
      type ChangeEvent,
      type HTMLAttributes,
      type InputHTMLAttributes,
      type ReactElement,
      type ReactNode,
      type Ref,
    } from "react";
    import { type BoxProps } from "../box/Box.js";
    import { IconRotator } from "../icon/IconRotator.js";
    import { getIcon } from "../icon/iconConfig.js";
    import { Menu, type MenuProps } from "../menu/Menu.js";
    import { KeyboardMovementProvider } from "../movement/useKeyboardMovementProvider.js";
    import {
      type LabelA11y,
      type PropsWithRef,
      type RequireAtLeastOne,
    } from "../types.js";
    import { useEnsuredId } from "../useEnsuredId.js";
    import { useEnsuredRef } from "../useEnsuredRef.js";
    import { label as labelStyles } from "./Label.js";
    import { SelectedOption } from "./SelectedOption.js";
    import {
      TextFieldContainer,
      type TextFieldContainerProps,
    } from "./TextFieldContainer.js";
    import { getFormConfig } from "./formConfig.js";
    import { select } from "./selectStyles.js";
    import { extractOptionsFromChildren } from "./selectUtils.js";
    import { textField } from "./textFieldStyles.js";
    import { type UserAgentAutoCompleteProps } from "./types.js";
    import { useFormReset } from "./useFormReset.js";
    import { ListboxProvider, type ListboxContext } from "./useListboxProvider.js";
    import { useSelectCombobox } from "./useSelectCombobox.js";

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

    /**
     * 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<TextFieldContainerProps, "label">,
        Pick<InputHTMLAttributes<HTMLInputElement>, "form" | "required">,
        UserAgentAutoCompleteProps {
      /**
       * @defaultValue `"select-" + useId()`
       */
      id?: string;

      /**
       * Optional placeholder text or element to render while no options have been
       * selected.
       */
      placeholder?: ReactNode;

      /**
       * 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;

      /**
       * An optional floating label to display like other form fields.
       */
      label?: ReactNode;

      /**
       * Optional props to pass to the `<span>` that surrounds the {@link label}
       */
      labelProps?: PropsWithRef<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>;

      /**
       * 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>;
      inputProps?: InputHTMLAttributes<HTMLInputElement>;

      /**
       * A ref for the container `<div>` element.
       */
      containerRef?: Ref<HTMLDivElement>;

      /**
       * 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={label ? labelId : id}` -- this will be undefined if
       *   `aria-label` is provided
       * - `anchor={BELOW_CENTER_ANCHOR}`
       * - `width="min"`
       */
      menuProps?: Omit<MenuProps, "visible" | "onRequestClose" | "fixedTo">;

      /**
       * Any additional props to pass to the div that contains the current visible
       * option.
       */
      selectedOptionProps?: BoxProps;

      /**
       * Set this to `true` if all the `Option` components should display the
       * selected icon after the children instead of before.
       *
       * @see {@link disableSelectedIcon} to remove the selected icon instead.
       *
       * @defaultValue `false`
       */
      selectedIconAfter?: boolean;

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

      /**
       * Set this to `true` to update all the `Option` components to no longer
       * render an icon while selected.
       *
       * @defaultValue `false`
       */
      disableSelectedIcon?: 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**
     *
     * @example
     * Simple Example
     * ```tsx
     * import { Select, Option } from "react-md";
     * import { useState, type ReactElement } from "react";
     *
     * function Example(): ReactElement {
     *   const [value, setValue] = useState("");
     *
     *   return (
     *     <Select
     *       label="Select"
     *       value={value}
     *       onChange={(event) => setValue(event.currentTarget.value)}
     *       placeholder="Select a value"
     *     >
     *       <Option value="a">Option 1</Option>
     *       <Option value="b">Option 2</Option>
     *       <Option value="c">Option 3</Option>
     *       <Option value="d">Option 4</Option>
     *     </Select>
     *   );
     * }
     * ```
     *
     * @example
     * Testing
     * ```tsx
     * rmdRender(
     *   <Select label="Select" selectedOptionProps={{ "data-testid": "selected" }}>
     *     <Option value="a">Option 1</Option>
     *     <Option value="b">Option 2</Option>
     *     <Option value="c">Option 3</Option>
     *     <Option value="d">Option 4</Option>
     *   </Select>
     * );
     *
     * const user = userEvent.setup();
     * const select = screen.getByRole("combobox", { name: "Select" });
     * const selected = screen.getByTestId("selected")
     * const selectInput = screen.getByRole("textbox", { hidden: true });
     * expect(selected).toHaveTextContent("");
     * expect(selectInput).toHaveValue("");
     *
     * await user.click(select);
     * await user.click(screen.getByRole("option"), { name: "Option 2" });
     *
     * expect(selected).toHaveTextContent("Option 2");
     * expect(selectInput).toHaveValue("b");
     * ```
     *
     * @remarks \@since 6.0.0 Rewritten with a new API.
     */
    export function Select<Value extends string>(
      props: RequireAtLeastOne<SelectProps<Value>, "label" | keyof LabelA11y>
    ): ReactElement {
      const {
        id,
        form,
        autoCompleteValue,
        autoComplete = autoCompleteValue,
        name = autoCompleteValue,
        className,
        onClick,
        onFocus,
        onKeyDown,
        inputRef: propInputRef,
        inputProps,
        containerRef,
        placeholder,
        menuProps = {},
        label,
        labelProps = {},
        selectedOptionProps,
        icon: propIcon,
        value,
        defaultValue,
        theme: propTheme,
        onChange = noop,
        rightAddon: propRightAddon,
        active = false,
        required,
        selectedIconAfter = false,
        disableOptionAddon = false,
        disableSelectedIcon = false,
        children,
        ...remaining
      } = props;
      const { dense, error, disabled } = props;

      const comboboxId = useEnsuredId(id, "select");
      const inputId = useEnsuredId(inputProps?.id, "select-value");
      const selectLabelId = useEnsuredId(labelProps.id, "select-label");
      const labelId = label ? selectLabelId : undefined;

      const [localValue, setLocalValue] = useState(() => {
        if (typeof defaultValue !== "undefined") {
          return defaultValue;
        }

        return typeof value !== "undefined" ? value : EMPTY_STRING;
      });
      const currentValue = typeof value === "undefined" ? localValue : value;
      const initialValue = useRef(currentValue);
      const { options, currentOption } = extractOptionsFromChildren(
        children,
        currentValue
      );

      const { visible, comboboxProps, movementContext, getMenuProps } =
        useSelectCombobox({
          form,
          value: currentValue,
          values: options,
          onClick,
          onFocus,
          onKeyDown,
          disabled,
          popupId: menuProps.id,
          popupRef: menuProps.nodeRef,
          comboboxId,
          comboboxRef: containerRef,
        });

      const [inputRef, inputRefCallback] = useEnsuredRef(propInputRef);
      useFormReset({
        form,
        elementRef: inputRef,
        defaultValue: initialValue.current,
      });
      const listboxContext = useMemo<ListboxContext>(
        () => ({
          inputRef,
          currentValue,
          selectedIconAfter,
          disableSelectedIcon,
        }),
        [currentValue, disableSelectedIcon, inputRef, selectedIconAfter]
      );

      const icon = getIcon("dropdown", propIcon);
      const theme = getFormConfig("theme", propTheme);
      let rightAddon = propRightAddon;
      if (typeof rightAddon === "undefined" && icon) {
        rightAddon = <IconRotator rotated={visible}>{icon}</IconRotator>;
      }

      let listboxLabelledBy = menuProps["aria-labelledby"];
      const listboxLabel = menuProps["aria-label"];
      if (!listboxLabel && !listboxLabelledBy) {
        listboxLabelledBy = labelId || comboboxId;
      }

      return (
        <ListboxProvider value={listboxContext}>
          <KeyboardMovementProvider value={movementContext}>
            <TextFieldContainer
              aria-labelledby={labelId}
              {...remaining}
              {...comboboxProps}
              label={!!label}
              theme={theme}
              active={active || visible}
              className={cnb("rmd-select-container", className)}
              rightAddon={rightAddon}
            >
              <SelectedOption
                option={currentOption}
                placeholder={placeholder}
                disableAddon={disableOptionAddon}
                {...selectedOptionProps}
              />
              <input
                aria-hidden
                id={inputId}
                ref={inputRefCallback}
                type="text"
                autoComplete={autoComplete}
                name={name}
                tabIndex={-1}
                disabled={disabled}
                required={required}
                placeholder=" "
                {...inputProps}
                value={value}
                defaultValue={defaultValue}
                className={cnb(select({ theme }), textField())}
                onChange={(event) => {
                  onChange(event as SelectChangeEvent<Value>);
                  if (typeof value !== "undefined") {
                    return;
                  }

                  const nextValue = event.currentTarget.value;
                  const nextOption = options.find((option) => option === nextValue);

                  setLocalValue(nextOption ?? initialValue.current);
                }}
              />
              {label && (
                <span
                  {...labelProps}
                  id={labelId}
                  className={labelStyles({
                    dense,
                    error,
                    disabled,
                    active: active || visible,
                    floating: true,
                    floatingActive: !!placeholder || !!currentOption,
                    className: labelProps.className,
                  })}
                >
                  {label}
                </span>
              )}
            </TextFieldContainer>
            <Menu
              {...getMenuProps(menuProps)}
              aria-label={listboxLabel}
              aria-labelledby={listboxLabelledBy as string}
            >
              {children}
            </Menu>
          </KeyboardMovementProvider>
        </ListboxProvider>
      );
    }