# All files / form SelectV2.tsx

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

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

     "use client";
    import { cnb } from "cnbuilder";
    import {
      useMemo,
      useRef,
      useState,
      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 { KeyboardMovementProvider } from "../movement/useKeyboardMovementProvider.js";
    import { BELOW_CENTER_ANCHOR } from "../positioning/constants.js";
    import {
      type TransitionEnterHandler,
      type TransitionExitHandler,
    } from "../transition/types.js";
    import { useEnsuredRef } from "../useEnsuredRef.js";
    import { type SelectChangeEvent } from "./SelectOriginal.js";
    import { SelectedOption } from "./SelectedOption.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 { getNonDisabledOptions, useCombobox } from "./useCombobox.js";
    import { useFormReset } from "./useFormReset.js";
    import { ListboxProvider, type ListboxContext } from "./useListboxProvider.js";

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

    export interface SelectV2Props<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">;
      selectedIconAfter?: boolean;

      /**
       * 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`
       */
      disableOptionAddon?: 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;
    }

    export function SelectV2<Value extends string>(
      props: SelectV2Props<Value>
    ): ReactElement {
      const {
        value,
        className,
        defaultValue,
        children,
        active,
        onChange = noop,
        icon: propIcon,
        theme: propTheme,
        inputRef: propInputRef,
        inputClassName,
        menuProps = {},
        containerProps = {},
        leftAddon,
        rightAddon: propRightAddon,
        selectedIconAfter = false,
        disableOptionAddon = false,
        disableSelectedIcon = false,
        ...remaining
      } = props;
      const { form, disabled } = props;
      const {
        // movementProps,
        movementContext,
        popupRef,
        popupProps,
        comboboxRef,
        comboboxProps,
        currentFocusIndex,
        hide,
        setActiveDescendantId,
        visible,
      } = useCombobox({
        form,
        disabled,
        popupId: menuProps.id,
        popupRef: menuProps.nodeRef,
        comboboxId: containerProps.id,
        comboboxRef: containerProps.ref,
        autocomplete: "select",
        onClick: containerProps.onClick,
        onFocus: containerProps.onFocus,
        onKeyDown: containerProps.onKeyDown,
      });

      const [inputRef, inputRefCallback] = useEnsuredRef(propInputRef);
      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);
      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>;
      }
      const { options, currentOption } = extractOptionsFromChildren(
        children,
        currentValue
      );

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

          const menu = popupRef.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 focusables = getNonDisabledOptions(menu);
          const index = Math.max(
            0,
            options.findIndex((option) => option.value === currentValue)
          );
          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
              ref={inputRefCallback}
              containerProps={{
                ...containerProps,
                ...comboboxProps,
              }}
              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
                );

                setLocalValue(nextOption ? nextOption.value : initialValue.current);
              }}
            >
              <SelectedOption
                option={currentOption}
                disableAddon={disableOptionAddon}
              />
            </TextField>
            <Menu
              anchor={BELOW_CENTER_ANCHOR}
              width="min"
              {...menuProps}
              {...popupProps}
              visible={visible}
              fixedTo={comboboxRef}
              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>
      );
    }