"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = LinkPickerResults;
var _reactNative = require("react-native");
var _compose = require("@wordpress/compose");
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _styles = _interopRequireDefault(require("./styles.scss"));
var _bottomSheet = _interopRequireDefault(require("../bottom-sheet"));
var _bottomSheetContext = require("../bottom-sheet/bottom-sheet-context");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const PER_PAGE = 20;
const REQUEST_DEBOUNCE_DELAY = 400;
const MINIMUM_QUERY_SIZE = 2;
const meetsThreshold = query => MINIMUM_QUERY_SIZE <= query.length;
function LinkPickerResults({
  query,
  onLinkPicked,
  directEntry
}) {
  const [links, setLinks] = (0, _element.useState)([directEntry]);
  const [hasAllSuggestions, setHasAllSuggestions] = (0, _element.useState)(false);
  const nextPage = (0, _element.useRef)(1);
  const pendingRequest = (0, _element.useRef)();
  const clearRequest = () => {
    pendingRequest.current = null;
  };

  // A stable debounced function to fetch suggestions and append.
  const {
    fetchMoreSuggestions
  } = (0, _data.useSelect)(select => {
    const {
      getSettings
    } = select('core/block-editor');
    const fetchLinkSuggestions = async ({
      search
    }) => {
      if (meetsThreshold(search)) {
        return await getSettings().__experimentalFetchLinkSuggestions(search, {
          page: nextPage.current,
          type: 'post',
          perPage: PER_PAGE
        });
      }
    };
    const fetchMore = async ({
      query: search,
      links: currentSuggestions
    }) => {
      // Return early if we've already detected the end of data or we are
      // already awaiting a response.
      if (hasAllSuggestions || pendingRequest.current) {
        return;
      }
      const request = fetchLinkSuggestions({
        search
      });
      pendingRequest.current = request;
      const suggestions = await request;

      // Only update links for the most recent request.
      if (suggestions && request === pendingRequest.current) {
        // Since we don't have the response header, we check if the results
        // are truncated to determine we've reached the end.
        if (suggestions.length < PER_PAGE) {
          setHasAllSuggestions(true);
        }
        setLinks([...currentSuggestions, ...suggestions]);
        nextPage.current++;
      }
      clearRequest();
    };
    return {
      fetchMoreSuggestions: (0, _compose.debounce)(fetchMore, REQUEST_DEBOUNCE_DELAY)
    };
    // Not adding dependencies for now, to avoid introducing a regression
    // (see https://github.com/WordPress/gutenberg/pull/23922#discussion_r1170634879).
  }, []);

  // Prevent setting state when unmounted.
  (0, _element.useEffect)(() => clearRequest, []);

  // Any time the query changes, we reset pagination.
  (0, _element.useEffect)(() => {
    clearRequest();
    nextPage.current = 1;
    setHasAllSuggestions(false);
    setLinks([directEntry]);
    fetchMoreSuggestions({
      query,
      links: [directEntry]
    });
    // See https://github.com/WordPress/gutenberg/pull/41166
  }, [query]);
  const onEndReached = () => fetchMoreSuggestions({
    query,
    links
  });
  const spinner = !hasAllSuggestions && meetsThreshold(query) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
    style: _styles.default.spinner,
    testID: "link-picker-loading",
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ActivityIndicator, {
      animating: true
    })
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_bottomSheetContext.BottomSheetConsumer, {
    children: ({
      listProps
    }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.FlatList, {
      data: links,
      keyboardShouldPersistTaps: "always",
      renderItem: ({
        item
      }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_bottomSheet.default.LinkSuggestionItemCell, {
        suggestion: item,
        onLinkPicked: onLinkPicked
      }),
      keyExtractor: ({
        url,
        type
      }) => `${url}-${type}`,
      onEndReached: onEndReached,
      onEndReachedThreshold: 0.1,
      initialNumToRender: PER_PAGE,
      ListFooterComponent: spinner,
      ...listProps,
      contentContainerStyle: [...listProps.contentContainerStyle, _styles.default.list]
    })
  });
}
//# sourceMappingURL=link-picker-results.native.js.map