All files / atoms/Select/mobile Select.native.tsx

63.24% Statements 74/117
57.21% Branches 107/187
58.97% Functions 23/39
63.15% Lines 72/114

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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561                                                  7x   7x                                                   74x 74x 74x 74x         74x     74x 74x 13x                         74x   74x           74x                           74x 27x 3x     74x 29x 2x   8x       74x 32x 83x 25x   7x 28x       74x           74x             74x 74x 16x 16x 16x 16x   74x 13x 13x 13x     74x                 109x 109x 109x               109x               74x   74x   122x   109x   5x 3x   2x     3x 3x   2x 2x 2x   5x                                                                         74x   74x 27x     27x     27x 27x 27x       74x                                                                           74x                                                                                                                                                 12x 12x                                                   20x                 1x 1x                                                                                                                                                               1x                                                                                                     7x                                                              
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { SelectNativeProps } from '../Select.types';
import { clamp } from '@sb/libs/utils.native';
import {
  Dimensions,
  FlatList,
  InteractionManager,
  Keyboard,
  Modal,
  Platform,
  Pressable,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
  ViewStyle,
} from 'react-native';
import { useTheme } from '@sb/ui/components/Themes/ThemeProvider';
import { colors } from '@sb/styles/colors';
import { ChrevonDown, ChrevonUp, X } from '@sb/ui/components/atoms/Icons/index.native';
 
const ICON_SIZE = clamp(Dimensions.get('window').width * 0.07, 10, 26);
 
export const Select: React.FC<SelectNativeProps> = ({
  id,
  style,
  placeholder = 'Select an option',
  value,
  size = 'medium',
  disabled = false,
  onChange,
  options = [],
  multiple = false,
  mode = 'single',
  allowClear = false,
  searchable = false,
  emptyText = 'No options available',
  prefix,
  suffix,
  addonBefore,
  addonAfter,
  status = 'default',
  dropdownRender,
  textStyle,
  textCentered = false,
  dropdownStyle,
  onDropdownVisibleChange,
  defaultValue,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [isFocused, setIsFocused] = useState(false);
  const [dropdownPosition, setDropdownPosition] = useState({
    top: 0,
    left: 0,
    width: 200,
  });
  const [selectedValue, setSelectedValue] = useState<string | number | (string | number)[]>(
    value ?? defaultValue ?? (multiple ? [] : '')
  );
  const { theme } = useTheme();
  const measureSelectPosition = () => {
    selectRef.current?.measureInWindow((x, y, width, height) => {
      const extraOffset = Platform.OS === 'android' ? StatusBar.currentHeight || 0 : 0;
      const screenWidth = Dimensions.get('window').width;
      const dropdownWidth = Math.min(width, screenWidth - 32);
 
      setDropdownPosition({
        top: y + height + extraOffset,
        left: x + (width - dropdownWidth) / 2, // Center the dropdown horizontally
        width: dropdownWidth,
      });
    });
  };
 
  const isMultiple = mode === 'multiple' || multiple;
 
  const SelectSize: Record<NonNullable<SelectNativeProps['size']>, ViewStyle> = {
    small: { width: 150 },
    medium: { width: 200 },
    large: { width: 300 },
  };
 
  const Status: Record<NonNullable<SelectNativeProps['status']>, ViewStyle> = {
    default: {
      borderColor: 'transparent',
      borderWidth: 0,
    },
    warning: {
      borderColor: colors[theme].colorStatus_Warning,
      borderWidth: 1,
    },
    error: {
      borderColor: colors[theme].colorStatus_Error,
      borderWidth: 1,
    },
  };
  useEffect(() => {
    if (value !== undefined && value !== null) {
      setSelectedValue(value);
    }
  }, [value]);
  const filterOptions = useMemo(() => {
    if (!searchable || !search) return options;
    return options.filter(
      (option) =>
        typeof option.label === 'string' &&
        option.label.toLowerCase().includes(search.toLowerCase())
    );
  }, [search, options, searchable]);
  const selectedOptions = useMemo(() => {
    if (!isMultiple) {
      const option = options.find((opt) => opt.value === selectedValue);
      return option ? [option] : [];
    } else {
      return Array.isArray(selectedValue)
        ? options.filter((opt) => selectedValue.includes(opt.value))
        : [];
    }
  }, [options, selectedValue, isMultiple]);
  const handleClear = () => {
    setSelectedValue(isMultiple ? [] : '');
    onChange?.(isMultiple ? [] : '');
    setSearch('');
    setIsOpen(false);
  };
  const handleRemoveOption = (optionValue: string | number) => {
    const newValue = (selectedValue as (string | number)[]).filter(
      (value) => value !== optionValue
    );
    setSelectedValue(newValue);
    onChange?.(newValue);
  };
  const selectRef = useRef<View>(null);
  const toggleDropdown = (open: boolean) => {
    setIsOpen(open);
    onDropdownVisibleChange?.(open);
    setIsFocused(open);
    setSearch('');
  };
  const openDropdown = () => {
    InteractionManager.runAfterInteractions(() => {
      measureSelectPosition();
      toggleDropdown(true);
    });
  };
  const closeDropdown = () => {
    toggleDropdown(false);
  };
  function getItemBorderRadius(
    index: number,
    total: number,
    borderRadius: number,
    horizontal: boolean
  ): ViewStyle {
    const isFirst = index === 0;
    const isLast = index === total - 1;
    Iif (horizontal) {
      return {
        borderTopLeftRadius: isFirst ? borderRadius : 0,
        borderBottomLeftRadius: isFirst ? borderRadius : 0,
        borderTopRightRadius: isLast ? borderRadius : 0,
        borderBottomRightRadius: isLast ? borderRadius : 0,
      };
    } else {
      return {
        borderTopLeftRadius: 0,
        borderTopRightRadius: 0,
        borderBottomLeftRadius: isLast ? borderRadius : 0,
        borderBottomRightRadius: isLast ? borderRadius : 0,
      };
    }
  }
  const RenderDropdownContent = () => {
    const defaultMenu = (
      <FlatList
        data={filterOptions}
        keyExtractor={(item) => item.value.toString()}
        renderItem={({ item }) => (
          <TouchableOpacity
            onPress={() => {
              if (isMultiple) {
                const updated = Array.isArray(selectedValue)
                  ? selectedValue.includes(item.value)
                    ? selectedValue.filter((v) => v !== item.value)
                    : [...selectedValue, item.value]
                  : [item.value];
                setSelectedValue(updated);
                onChange?.(updated);
              } else {
                setSelectedValue(item.value);
                onChange?.(item.value);
                toggleDropdown(false);
              }
              setSearch('');
            }}
            style={[
              {
                paddingLeft: 10,
                paddingVertical: 7,
                backgroundColor: Array.isArray(selectedValue)
                  ? selectedValue.includes(item.value)
                    ? colors[theme].colorAccent
                    : 'transparent'
                  : selectedValue === item.value
                    ? colors[theme].colorAccent
                    : 'transparent',
                flexDirection: textCentered ? 'row' : 'column',
                justifyContent: textCentered ? 'center' : 'flex-start',
              },
              getItemBorderRadius(
                filterOptions.indexOf(item),
                filterOptions.length,
                containerRadius as number,
                false
              ),
            ]}
          >
            <Text
              className="font-normal"
              style={{
                color: colors[theme].colorPrimary,
              }}
            >
              {item.label}
            </Text>
          </TouchableOpacity>
        )}
        ListEmptyComponent={<Text style={{ padding: 8 }}>{emptyText}</Text>}
      />
    );
    return dropdownRender ? dropdownRender(defaultMenu) : defaultMenu;
  };
  useEffect(() => {
    const showSub = Keyboard.addListener('keyboardDidShow', () => {
      InteractionManager.runAfterInteractions(measureSelectPosition);
    });
    const hideSub = Keyboard.addListener('keyboardDidHide', () => {
      InteractionManager.runAfterInteractions(measureSelectPosition);
    });
    return () => {
      showSub.remove();
      hideSub.remove();
    };
  }, []);
  const containerRadius =
    (Array.isArray(style)
      ? style
          .filter(
            (sl): sl is ViewStyle =>
              !!sl &&
              typeof sl === 'object' &&
              ('borderBottomLeftRadius' in sl ||
                'borderBottomRightRadius' in sl ||
                'borderTopLeftRadius' in sl ||
                'borderTopRightRadius' in sl ||
                'borderRadius' in sl)
          )
          .find((sl) => {
            if ('borderBottomLeftRadius' in sl && sl.borderBottomLeftRadius !== undefined)
              return sl.borderBottomLeftRadius;
            if ('borderBottomRightRadius' in sl && sl.borderBottomRightRadius !== undefined)
              return sl.borderBottomRightRadius;
            if ('borderTopLeftRadius' in sl && sl.borderTopLeftRadius !== undefined)
              return sl.borderTopLeftRadius;
            if ('borderTopRightRadius' in sl && sl.borderTopRightRadius !== undefined)
              return sl.borderTopRightRadius;
            if ('borderRadius' in sl && sl.borderRadius !== undefined) return sl.borderRadius;
            return false;
          })?.borderRadius || 0
      : typeof style === 'object' && style !== null
        ? 'borderBottomLeftRadius' in style && style.borderBottomLeftRadius !== undefined
          ? style.borderBottomLeftRadius
          : 'borderBottomRightRadius' in style && style.borderBottomRightRadius !== undefined
            ? style.borderBottomRightRadius
            : 'borderTopLeftRadius' in style && style.borderTopLeftRadius !== undefined
              ? style.borderTopLeftRadius
              : 'borderTopRightRadius' in style && style.borderTopRightRadius !== undefined
                ? style.borderTopRightRadius
                : 'borderRadius' in style && style.borderRadius !== undefined
                  ? style.borderRadius
                  : 0
        : 0) ?? 0;
 
  return (
    <>
      {addonBefore && <View>{addonBefore}</View>}
      <Pressable
        testID={id}
        id={id}
        onPress={() => {
          if (!isOpen) {
            openDropdown();
          } else {
            closeDropdown();
          }
        }}
        ref={selectRef}
        style={[
          {
            flex: 1,
            height: 48,
            borderRadius: (containerRadius as number) + 4,
            opacity: disabled ? 0.5 : 1,
            shadowColor: isFocused ? colors[theme].buttonCyanHoverBg : 'transparent',
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.8,
            shadowRadius: 4,
            elevation: isFocused ? 5 : 0,
            backgroundColor: colors[theme].selectBackground,
            borderColor: isFocused ? colors[theme].colorCyan : 'transparent',
            borderWidth: isFocused ? 1.5 : 0,
          },
          SelectSize[size],
          style,
        ]}
      >
        <Pressable
          onPress={() => {
            if (!isOpen) {
              openDropdown();
            } else {
              closeDropdown();
            }
          }}
          style={[
            StyleSheet.absoluteFillObject,
            {
              padding: isMultiple && selectedOptions.length > 0 ? 10 : 0,
            },
            {
              alignItems: 'center',
              justifyContent: 'center',
            },
            Status[status],
          ]}
        >
          <View
            style={[
              {
                flex: 1,
                width: '100%',
                paddingLeft: 8,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
              },
            ]}
          >
            <TouchableOpacity
              style={[
                {
                  flexDirection: textCentered ? 'row' : 'column',
                  justifyContent: textCentered ? 'center' : 'flex-start',
                },
              ]}
              onPress={() => {
                if (!isOpen) {
                  openDropdown();
                } else E{
                  closeDropdown();
                }
              }}
              disabled={disabled}
              activeOpacity={disabled ? 1 : 0.7}
            >
              <View
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  alignItems: 'center',
                }}
              >
                {prefix && <Text>{prefix}</Text>}
                {selectedOptions?.length > 0 ? (
                  <ScrollView
                    horizontal
                    keyboardShouldPersistTaps="handled"
                    showsHorizontalScrollIndicator={false}
                    contentContainerStyle={[styles.container]}
                    scrollEventThrottle={16}
                    nestedScrollEnabled
                  >
                    {selectedOptions.map((option) => (
                      <Pressable
                        key={option.value}
                        style={
                          isMultiple
                            ? [styles.multiple, { backgroundColor: colors[theme].colorCyan }]
                            : {}
                        }
                        onStartShouldSetResponder={() => false}
                        onPress={() => {
                          if (!isOpen) {
                            openDropdown();
                          } else E{
                            closeDropdown();
                          }
                        }}
                      >
                        {typeof option.label === 'string' ? (
                          <Text
                            style={[
                              textStyle,
                              { color: colors[theme].colorPrimary },
                              isMultiple ? { color: 'white' } : {},
                            ]}
                            className="font-normal"
                          >
                            {option.label}
                          </Text>
                        ) : (
                          <View>{option.label}</View>
                        )}
                        {isMultiple && (
                          <Pressable
                            accessibilityLabel={`Remove ${option.label}`}
                            onPress={() => {
                              handleRemoveOption(option.value);
                            }}
                            style={{ marginLeft: 4 }}
                          >
                            <X height={10} width={10} color={colors[theme].colorSecondary} />
                          </Pressable>
                        )}
                      </Pressable>
                    ))}
                  </ScrollView>
                ) : (
                  <Text className="font-normal" style={{
              color: colors[theme].colorPrimary
            }}>{placeholder}</Text>
                )}
              </View>
            </TouchableOpacity>
            <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 10 }}>
              {allowClear && selectedOptions.length > 0 && (
                <TouchableOpacity onPress={() => handleClear()} style={{ marginLeft: 8 }}>
                  <X height={10} width={10} color={colors[theme].colorSecondary} />
                </TouchableOpacity>
              )}
              {(suffix && <Text>{suffix}</Text>) || (
                <TouchableOpacity
                  className="flex items-end self-center justify-center"
                  disabled={disabled}
                  onPress={() => {
                    if (!isOpen) {
                      openDropdown();
                    } else {
                      closeDropdown();
                    }
                  }}
                >
                  {isOpen ? (
                    <ChrevonUp
                      height={ICON_SIZE}
                      width={ICON_SIZE}
                      color={colors[theme].colorPrimary}
                    />
                  ) : (
                    <ChrevonDown
                      height={ICON_SIZE}
                      width={ICON_SIZE}
                      color={colors[theme].colorPrimary}
                    />
                  )}
                </TouchableOpacity>
              )}
            </View>
          </View>
          <Modal
            transparent
            visible={isOpen}
            animationType="fade"
            onRequestClose={() => toggleDropdown(false)}
            statusBarTranslucent
            testID="select-modal"
          >
            <View style={styles.modalOverlay} pointerEvents="box-none">
              <TouchableWithoutFeedback onPress={() => toggleDropdown(false)}>
                <View style={StyleSheet.absoluteFill} />
              </TouchableWithoutFeedback>
              <View
                style={[
                  {
                    position: 'absolute',
                    top: dropdownPosition.top,
                    left: Math.max(
                      16,
                      Math.min(
                        dropdownPosition.left,
                        Dimensions.get('window').width - dropdownPosition.width - 16
                      )
                    ),
                    width: dropdownPosition.width,
                    borderBottomLeftRadius: (containerRadius as number) + 4,
                    borderBottomRightRadius: (containerRadius as number) + 4,
                    backgroundColor: colors[theme].selectBackground,
                    height: 'auto',
                  },
                  styles.dropdown,
                  dropdownStyle,
                ]}
              >
                {searchable && (
                  <TextInput
                    placeholder="Search..."
                    value={search}
                    onChangeText={setSearch}
                    style={[
                      styles.searchInput,
                      { borderColor: colors[theme].colorSelect_TextColor },
                    ]}
                  />
                )}
                {RenderDropdownContent()}
              </View>
            </View>
          </Modal>
        </Pressable>
      </Pressable>
      {addonAfter && <View>{addonAfter}</View>}
    </>
  );
};
const styles = StyleSheet.create({
  dropdown: {
    overflow: 'hidden',
    maxHeight: 150,
    borderWidth: 0,
  },
  searchInput: {
    padding: 8,
    borderBottomWidth: 1,
    marginBottom: 8,
  },
  modalOverlay: {
    flex: 1,
  },
  multiple: {
    padding: 2.5,
    overflow: 'hidden',
    borderRadius: 4,
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 5,
  },
  container: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 2,
  },
});