"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _style = _interopRequireDefault(require("./style.scss"));
var _platformStyle = _interopRequireDefault(require("./platform-style.scss"));
var _button = _interopRequireDefault(require("../button"));
var _gridicons = _interopRequireDefault(require("../mobile/gridicons"));
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

// Merge platform specific styles with the default styles.
const baseStyles = {
  ..._style.default
};
for (const selector in _platformStyle.default) {
  baseStyles[selector] = {
    ...baseStyles[selector],
    ..._platformStyle.default[selector]
  };
}
function selectModifiedStyles(styles, modifier) {
  const modifierMatcher = new RegExp(`--${modifier}$`);
  const modifierSelectors = Object.keys(styles).filter(selector => selector.match(modifierMatcher));
  return modifierSelectors.reduce((modifiedStyles, modifierSelector) => {
    const blockElementSelector = modifierSelector.split('--')[0];
    modifiedStyles[blockElementSelector] = styles[modifierSelector];
    return modifiedStyles;
  }, {});
}
function mergeStyles(styles, updateStyles, selectors) {
  selectors.forEach(selector => {
    styles[selector] = {
      ...styles[selector],
      ...updateStyles[selector]
    };
  });
  return styles;
}
function SearchControl({
  value,
  onChange,
  placeholder = (0, _i18n.__)('Search blocks')
}) {
  const [isActive, setIsActive] = (0, _element.useState)(false);
  const [currentStyles, setCurrentStyles] = (0, _element.useState)(baseStyles);
  const isDark = (0, _reactNative.useColorScheme)() === 'dark';
  const inputRef = (0, _element.useRef)();
  const onCancelTimer = (0, _element.useRef)();
  const isIOS = _reactNative.Platform.OS === 'ios';
  const darkStyles = (0, _element.useMemo)(() => {
    return selectModifiedStyles(baseStyles, 'dark');
  }, []);
  const activeStyles = (0, _element.useMemo)(() => {
    return selectModifiedStyles(baseStyles, 'active');
  }, []);
  const activeDarkStyles = (0, _element.useMemo)(() => {
    return selectModifiedStyles(baseStyles, 'active-dark');
  }, []);
  (0, _element.useEffect)(() => {
    let futureStyles = {
      ...baseStyles
    };
    function mergeFutureStyles(modifiedStyles, shouldUseConditions) {
      const shouldUseModified = shouldUseConditions.every(should => should);
      const updatedStyles = shouldUseModified ? modifiedStyles : futureStyles;
      const selectors = Object.keys(modifiedStyles);
      futureStyles = mergeStyles(futureStyles, updatedStyles, selectors);
    }
    mergeFutureStyles(activeStyles, [isActive]);
    mergeFutureStyles(darkStyles, [isDark]);
    mergeFutureStyles(activeDarkStyles, [isActive, isDark]);
    setCurrentStyles(futureStyles);
    // See https://github.com/WordPress/gutenberg/pull/41166
  }, [isActive, isDark]);
  const clearInput = (0, _element.useCallback)(() => {
    onChange('');
  }, [onChange]);
  const onPress = (0, _element.useCallback)(() => {
    setIsActive(true);
    inputRef.current?.focus();
  }, []);
  const onFocus = (0, _element.useCallback)(() => {
    setIsActive(true);
  }, []);
  const onCancel = (0, _element.useCallback)(() => {
    clearTimeout(onCancelTimer.current);
    onCancelTimer.current = setTimeout(() => {
      inputRef.current?.blur();
      clearInput();
      setIsActive(false);
    }, 0);
  }, [clearInput]);
  const onKeyboardDidHide = (0, _element.useCallback)(() => {
    if (!isIOS) {
      onCancel();
    }
  }, [isIOS, onCancel]);
  (0, _element.useEffect)(() => {
    const keyboardHideSubscription = _reactNative.Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);
    return () => {
      clearTimeout(onCancelTimer.current);
      keyboardHideSubscription.remove();
    };
  }, [onKeyboardDidHide]);
  const {
    'search-control__container': containerStyle,
    'search-control__inner-container': innerContainerStyle,
    'search-control__input-container': inputContainerStyle,
    'search-control__form-input': formInputStyle,
    'search-control__form-input-placeholder': placeholderStyle,
    'search-control__input-button': inputButtonStyle,
    'search-control__input-button-left': inputButtonLeftStyle,
    'search-control__input-button-right': inputButtonRightStyle,
    'search-control__cancel-button': cancelButtonStyle,
    'search-control__cancel-button-text': cancelButtonTextStyle,
    'search-control__icon': iconStyle,
    'search-control__right-icon': rightIconStyle
  } = currentStyles;
  function renderLeftButton() {
    const button = !isIOS && isActive ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
      label: (0, _i18n.__)('Cancel search'),
      icon: _icons.arrowLeft,
      onClick: onCancel,
      style: iconStyle
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.Icon, {
      icon: _gridicons.default.search,
      fill: iconStyle?.color
    });
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: [inputButtonStyle, inputButtonLeftStyle],
      children: button
    });
  }
  function renderRightButton() {
    let button;

    // Add a View element to properly center the input placeholder via flexbox.
    if (isIOS && !isActive) {
      button = /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {});
    }
    if (!!value) {
      button = /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
        label: (0, _i18n.__)('Clear search'),
        icon: isIOS ? _icons.cancelCircleFilled : _icons.close,
        onClick: clearInput,
        style: [iconStyle, rightIconStyle]
      });
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: [inputButtonStyle, inputButtonRightStyle],
      children: button
    });
  }
  function renderCancel() {
    if (!isIOS) {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: cancelButtonStyle,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        onPress: onCancel,
        style: cancelButtonTextStyle,
        accessible: true,
        accessibilityRole: "button",
        accessibilityLabel: (0, _i18n.__)('Cancel search'),
        accessibilityHint: (0, _i18n.__)('Cancel search'),
        children: (0, _i18n.__)('Cancel')
      })
    });
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.TouchableOpacity, {
    style: containerStyle,
    onPress: onPress,
    activeOpacity: 1,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
      style: innerContainerStyle,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
        style: inputContainerStyle,
        children: [renderLeftButton(), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.TextInput, {
          ref: inputRef,
          style: formInputStyle,
          placeholderTextColor: placeholderStyle?.color,
          onChangeText: onChange,
          onFocus: onFocus,
          value: value,
          placeholder: placeholder
        }), renderRightButton()]
      }), isActive && renderCancel()]
    })
  });
}
var _default = exports.default = SearchControl;
//# sourceMappingURL=index.native.js.map