All files / packages/ui/src/components/Select index.tsx

100% Statements 32/32
100% Branches 28/28
100% Functions 15/15
100% Lines 27/27

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                                                                                                                      25x 25x 25x     25x   1x         25x 14x 14x       43x   25x   2x 2x         25x 8x 7x   8x     25x   12x 2x   12x 3x 2x     12x                                 25x                                                                                                           18x                                         2x       14x                                                                                                                                                                  
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import { useCallback } from "react";
import {
  FlatList,
  Keyboard,
  Modal,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
 
import { ChevronDownIcon } from "@repo/ui/icons/ChevronDown";
import { makeStyles } from "@repo/ui/themes/makeStyles";
import { useTheme } from "@repo/ui/themes/ThemeContext";
 
import { Button } from "../Button";
 
interface SelectOption<T> {
  label: string;
  value: T;
}
 
export interface SelectProps<T> {
  label: string;
  options: SelectOption<T>[];
  optionsDisabled?: SelectOption<T>[];
  value?: T;
  onChange: (value: T) => void;
  leftIcon?: React.ReactNode;
  disabled?: boolean;
  placeholder?: string;
  errorMessage?: string;
  testID?: string;
}
 
export interface SelectRef {
  close: () => void;
}
 
function SelectInner<T>(
  {
    label,
    options,
    value,
    onChange,
    leftIcon,
    disabled = false,
    errorMessage,
    placeholder,
    optionsDisabled,
    testID,
  }: SelectProps<T>,
  ref: React.Ref<SelectRef>,
) {
  const [open, setOpen] = useState(false);
  const { theme } = useTheme();
  const styles = useStyles();
 
  // Expose close method via ref
  useImperativeHandle(ref, () => ({
    close: () => {
      setOpen(false);
    },
  }));
 
  // Close modal when component unmounts
  useEffect(() => {
    return () => {
      setOpen(false);
    };
  }, []);
 
  const selectedLabel = options.find((opt) => opt.value === value)?.label;
 
  const handlePressMenuItem = useCallback(
    (val: T) => {
      onChange(val);
      setOpen(false);
    },
    [onChange],
  );
 
  const handleToggleModal = () => {
    if (!open) {
      Keyboard.dismiss();
    }
    setOpen((prev) => !prev);
  };
 
  const renderItem = useCallback(
    ({ item }: { item: SelectOption<T> }) => {
      const isDisabled = optionsDisabled?.some(
        (opt) => opt.value === item.value,
      );
      const handlePress = () => {
        if (isDisabled) return;
        handlePressMenuItem(item.value);
      };
 
      return (
        <Button
          style={styles.option}
          textStyle={[
            styles.optionText,
            item.value === value && styles.optionTextSelected,
            isDisabled && styles.optionDisabled,
          ]}
          onPress={handlePress}
        >
          {item.label}
        </Button>
      );
    },
    [optionsDisabled, value, styles, handlePressMenuItem],
  );
 
  return (
    <View style={styles.container}>
      <Text style={styles.label}>{label}</Text>
 
      <TouchableOpacity
        style={[styles.selectButton, disabled && styles.selectButtonDisabled]}
        onPress={handleToggleModal}
        disabled={disabled}
        testID={testID}
        accessibilityLabel={
          disabled ? `${label} is disabled` : `Open ${label} select`
        }
      >
        {leftIcon && (
          <View style={[styles.leftIcon, disabled && styles.iconDisabled]}>
            {leftIcon}
          </View>
        )}
 
        <Text style={[styles.valueText, disabled && styles.valueTextDisabled]}>
          {selectedLabel || placeholder || "Select..."}
        </Text>
 
        <View style={disabled && styles.iconDisabled}>
          <ChevronDownIcon
            width={14}
            height={8}
            color={theme.colors.icon.active}
          />
        </View>
      </TouchableOpacity>
 
      {!disabled && (
        <Modal
          transparent
          visible={open}
          animationType="fade"
          onRequestClose={handleToggleModal}
        >
          <TouchableOpacity
            style={styles.modalOverlay}
            onPress={handleToggleModal}
            activeOpacity={1}
            accessible={false}
          >
            <TouchableOpacity
              style={styles.modalContent}
              activeOpacity={1}
              onPress={() => {}} // Stop propagation to backdrop
              accessible={false}
              testID="select-modal-content"
            >
              <FlatList
                data={options}
                keyExtractor={(item) => String(item.value)}
                ListEmptyComponent={
                  <View style={styles.emptyContainer}>
                    <Text style={styles.optionText}>No options available</Text>
                  </View>
                }
                renderItem={renderItem}
              />
            </TouchableOpacity>
          </TouchableOpacity>
        </Modal>
      )}
      {errorMessage && (
        <Text style={styles.errorMessage} accessibilityLiveRegion="polite">
          {errorMessage}
        </Text>
      )}
    </View>
  );
}
 
export const Select = forwardRef(SelectInner) as <T>(
  props: SelectProps<T> & { ref?: React.ForwardedRef<SelectRef> },
) => React.ReactElement | null;
 
const useStyles = makeStyles((theme) => ({
  container: {
    marginVertical: theme.metrics.spacing[2],
  },
  label: {
    marginBottom: theme.metrics.spacing[1],
    fontSize: theme.metrics.textSize[14],
    fontWeight: theme.metrics.fontWeight.medium,
    color: theme.colors.text.info,
  },
  selectButton: {
    flexDirection: "row",
    alignItems: "center",
    borderWidth: theme.metrics.borderWidth.default,
    borderColor: theme.colors.border.tertiary,
    height: theme.metrics.spacing[12.5],
    paddingHorizontal: theme.metrics.spacing[4],
    borderRadius: theme.metrics.borderRadius[1.5],
    backgroundColor: theme.colors.background.default,
  },
  selectButtonDisabled: {
    backgroundColor: theme.colors.background.disabled,
    borderColor: theme.colors.border.disabled,
  },
  leftIcon: {
    marginRight: theme.metrics.spacing[2],
  },
  iconDisabled: {
    opacity: theme.metrics.opacity[40],
  },
  valueText: {
    flex: 1,
    fontSize: theme.metrics.textSize[16],
    color: theme.colors.text.default,
  },
  valueTextDisabled: {
    color: theme.colors.text.tertiary,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.2)",
    justifyContent: "center",
    paddingHorizontal: theme.metrics.spacing[6],
  },
  modalContent: {
    backgroundColor: theme.colors.background.default,
    borderRadius: theme.metrics.borderRadius[1],
    maxHeight: "50%",
  },
  option: {
    backgroundColor: "transparent",
    paddingVertical: theme.metrics.spacing[4],
    paddingHorizontal: theme.metrics.spacing[6],
    width: "100%",
    justifyContent: "flex-start",
    alignItems: "flex-start",
    borderRadius: 0,
    height: "auto",
  },
  optionText: {
    fontSize: theme.metrics.textSize[16],
    color: theme.colors.text.default,
    textAlign: "left",
  },
  errorMessage: {
    position: "absolute",
    bottom: -theme.metrics.spacing[4.5],
    fontSize: theme.metrics.textSize[12],
    color: theme.colors.text.error,
  },
  optionTextSelected: {
    color: theme.colors.text.info,
  },
  optionDisabled: {
    color: theme.colors.text.tertiary,
  },
  emptyContainer: {
    padding: theme.metrics.spacing[6],
    alignItems: "center",
  },
}));