"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SearchInput = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeReanimated = _interopRequireWildcard(require("react-native-reanimated"));
var _context = require("../../context");
var _core = require("../../core");
var _fonts = require("../../utils/fonts");
var _icons = require("../icons");
var _typography = require("../typography");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/* eslint-disable functional/immutable-data */

/* Component visual attributes */const inputPaddingHorizontal = 12;
const inputPaddingVertical = 8;
const inputPaddingClearButton = 8;
const inputRadius = 8;
const iconMargin = 8;
const iconSize = 16;
const iconCloseSize = 24;
const inputFontSizePlaceholder = 14;
const cancelButtonMargin = 16;
const inputTransitionDuration = 250;
const AnimatedTextInput = _reactNativeReanimated.default.createAnimatedComponent(_reactNative.TextInput);
const AnimatedPressable = _reactNativeReanimated.default.createAnimatedComponent(_reactNative.Pressable);
const inputWithTimingConfig = {
  duration: inputTransitionDuration,
  easing: _reactNativeReanimated.Easing.inOut(_reactNativeReanimated.Easing.cubic)
};
const SearchInput = exports.SearchInput = /*#__PURE__*/(0, _react.forwardRef)(({
  accessibilityLabel,
  cancelButtonLabel,
  clearAccessibilityLabel,
  placeholder,
  autoFocus,
  keepCancelVisible = false,
  onCancel,
  onChangeText,
  pressable,
  testID,
  value = ""
}, ref) => {
  const searchInputRef = (0, _react.useRef)(null);
  const {
    newTypefaceEnabled
  } = (0, _context.useIONewTypeface)();

  /* Component visual attributes */
  const theme = (0, _context.useIOTheme)();
  const inputCaretColor = _core.IOColors[theme["interactiveElem-default"]];
  const inputBgColorDefault = _core.IOColors[theme["appBackground-secondary"]];
  const inputBgColorFocused = _core.IOColors[theme["appBackground-tertiary"]];
  const inputColorPlaceholder = _core.IOColors[theme["textBody-tertiary"]];
  const iconColor = theme["textBody-tertiary"];

  /* Widths used for the transition:
     - `SearchInput` entire width
     - `Cancel` button */
  const inputWidth = _reactNative.Dimensions.get("window").width - _core.IOVisualCostants.appMarginDefault * 2;
  const [cancelButtonWidth, setCancelButtonWidth] = (0, _react.useState)(0);
  const getCancelButtonWidth = ({
    nativeEvent
  }) => {
    setCancelButtonWidth(nativeEvent.layout.width);
  };
  const inputWidthWithCancel = inputWidth - cancelButtonWidth;
  (0, _react.useImperativeHandle)(ref, () => ({
    focus() {
      searchInputRef.current?.focus();
    }
  }), []);

  /* Reanimated styles */
  const inputAnimatedWidth = (0, _reactNativeReanimated.useSharedValue)(inputWidth);
  const isFocused = (0, _reactNativeReanimated.useSharedValue)(0);

  /* Applied to the `SearchInput` */
  const animatedStyle = (0, _reactNativeReanimated.useAnimatedStyle)(() => ({
    width: (0, _reactNativeReanimated.withTiming)(inputAnimatedWidth.value, inputWithTimingConfig),
    backgroundColor: (0, _reactNativeReanimated.interpolateColor)(isFocused.value, [0, 1], [inputBgColorDefault, inputBgColorFocused])
  }));

  /* Applied to the `Cancel` button */
  const cancelButtonAnimatedStyle = (0, _reactNativeReanimated.useAnimatedStyle)(() => {
    const showCancelButton = !pressable && keepCancelVisible ? 1 : isFocused.value;
    return {
      transform: [{
        translateX: (0, _reactNativeReanimated.interpolate)(showCancelButton, [0, 1], [cancelButtonWidth + _core.IOVisualCostants.appMarginDefault, 0], _reactNativeReanimated.Extrapolation.CLAMP)
      }],
      opacity: (0, _reactNativeReanimated.interpolate)(showCancelButton, [0, 1], [0.5, 1])
    };
  });

  /* Applied to the `Clear` button inside the `SearchInput` */
  const clearButtonAnimatedStyle = (0, _reactNativeReanimated.useAnimatedStyle)(() => {
    const showClearButton = value.length > 0;
    return {
      transform: [{
        scale: showClearButton ? (0, _reactNativeReanimated.withTiming)(1, inputWithTimingConfig) : (0, _reactNativeReanimated.withTiming)(0.5, inputWithTimingConfig)
      }],
      opacity: (0, _reactNativeReanimated.withTiming)(showClearButton ? 1 : 0, inputWithTimingConfig)
    };
  }, [value]);

  /* Related event handlers */
  const handleFocus = () => {
    isFocused.value = (0, _reactNativeReanimated.withTiming)(1, inputWithTimingConfig);
    inputAnimatedWidth.value = inputWidthWithCancel;
  };
  const handleBlur = () => {
    isFocused.value = (0, _reactNativeReanimated.withTiming)(0, inputWithTimingConfig);
    inputAnimatedWidth.value = keepCancelVisible ? inputWidthWithCancel : inputWidth;
  };
  const handleCancel = (0, _react.useCallback)(event => {
    onChangeText?.("");
    onCancel?.(event);
  }, [onCancel, onChangeText]);
  const handleClear = (0, _react.useCallback)(() => {
    onChangeText?.("");
    searchInputRef.current?.clear();
  }, [onChangeText]);
  const handleChangeText = (0, _react.useCallback)(text => onChangeText?.(text), [onChangeText]);
  const renderSearchBar = () => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNativeReanimated.default.View, {
    importantForAccessibility: pressable ? "no-hide-descendants" : "auto",
    style: styles.searchBar,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNativeReanimated.default.View, {
      style: [styles.searchInput, animatedStyle],
      pointerEvents: pressable ? "none" : "auto",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.iconContainer,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.Icon, {
          allowFontScaling: true,
          name: "search",
          size: iconSize,
          color: iconColor
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(AnimatedTextInput, {
        testID: testID,
        ref: searchInputRef,
        inputMode: "search",
        returnKeyType: "search",
        accessibilityRole: "search",
        accessibilityLabel: accessibilityLabel,
        numberOfLines: 1,
        style: [{
          color: _core.IOColors[theme["textBody-default"]],
          ...(0, _fonts.makeFontStyleObject)(inputFontSizePlaceholder, newTypefaceEnabled ? "Titillio" : "TitilliumSansPro", undefined, "Regular")
        }, styles.textInput, _reactNative.Platform.OS === "ios" ? styles.textInputIOS : styles.textInputAndroid],
        selectionColor: inputCaretColor,
        cursorColor: inputCaretColor,
        placeholder: placeholder,
        placeholderTextColor: inputColorPlaceholder,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onChangeText: handleChangeText,
        value: value,
        autoFocus: autoFocus,
        maxFontSizeMultiplier: _fonts.IOMaxFontSizeMultiplier
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(AnimatedPressable, {
        style: [styles.clearButton, clearButtonAnimatedStyle],
        onPress: handleClear,
        accessibilityLabel: clearAccessibilityLabel,
        accessibilityRole: "button",
        hitSlop: 16,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.Icon, {
          name: "closeSmall",
          size: iconCloseSize,
          color: iconColor
        })
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeReanimated.default.View, {
      onLayout: getCancelButtonWidth,
      style: [styles.cancelButton, cancelButtonAnimatedStyle],
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable, {
        accessibilityRole: "button",
        accessibilityLabel: cancelButtonLabel,
        onPress: handleCancel,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_typography.IOText, {
          color: theme["interactiveElem-default"],
          weight: "Semibold",
          size: _typography.buttonTextFontSize,
          lineHeight: _typography.buttonTextLineHeight,
          numberOfLines: 1,
          accessible: false,
          accessibilityElementsHidden: true,
          importantForAccessibility: "no-hide-descendants",
          children: cancelButtonLabel
        })
      })
    })]
  });
  return pressable ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable, {
    accessible: true,
    accessibilityRole: "button",
    accessibilityLabel: placeholder,
    onPress: pressable.onPress,
    children: renderSearchBar()
  }) : renderSearchBar();
});
const styles = _reactNative.StyleSheet.create({
  searchBar: {
    width: "100%",
    flexDirection: "row",
    justifyContent: "flex-start",
    alignItems: "center"
  },
  searchInput: {
    flexShrink: 0,
    borderRadius: inputRadius,
    borderCurve: "continuous",
    flexDirection: "row",
    alignItems: "center",
    paddingLeft: inputPaddingHorizontal,
    paddingRight: inputPaddingClearButton
  },
  textInput: {
    flexShrink: 1,
    flexGrow: 1
  },
  textInputIOS: {
    paddingVertical: inputPaddingVertical
  },
  textInputAndroid: {
    textAlignVertical: "center",
    overflow: "hidden"
  },
  iconContainer: {
    marginRight: iconMargin
  },
  cancelButton: {
    position: "absolute",
    right: 0,
    paddingLeft: cancelButtonMargin
  },
  clearButton: {
    transformOrigin: "center",
    marginLeft: iconMargin
  }
});
//# sourceMappingURL=SearchInput.js.map