"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _clsx = _interopRequireDefault(require("clsx"));

var _loading = _interopRequireDefault(require("../loading"));

var _useRect = require("../hooks/use-rect");

var _useScrollParent = _interopRequireDefault(require("../hooks/use-scroll-parent"));

var _useEventListener = _interopRequireDefault(require("../hooks/use-event-listener"));

var _utils = require("../utils");

var _hooks = require("../hooks");

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _empty() {}

var List = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace,
      locale = _useContext.locale;

  var _createNamespace = createNamespace('list', prefixCls),
      bem = _createNamespace[0];

  var _useSetState = (0, _hooks.useSetState)({
    loading: props.loading,
    error: props.error
  }),
      state = _useSetState[0],
      updateState = _useSetState[1];

  var root = (0, _react.useRef)();
  var scrollParent = (0, _react.useRef)(null);
  var placeholder = (0, _react.useRef)();
  scrollParent.current = (0, _useScrollParent.default)(root); // 判断是否需要加载

  var check = _async(function () {
    if (!props.onLoad) return;

    if (state.loading || props.finished || state.error) {
      return;
    }

    var offset = props.offset,
        direction = props.direction;
    var scrollParentRect = (0, _useRect.getRect)(scrollParent.current);

    if (!scrollParentRect.height || (0, _utils.isHidden)(root.current)) {
      return;
    }

    var isReachEdge = false;
    var placeholderRect = (0, _useRect.getRect)(placeholder.current);

    if (direction === 'up') {
      isReachEdge = scrollParentRect.top - placeholderRect.top <= offset;
    } else {
      isReachEdge = placeholderRect.bottom - scrollParentRect.bottom <= offset;
    }

    return _invokeIgnored(function () {
      if (isReachEdge) {
        return _continueIgnored(_catch(function () {
          updateState({
            loading: true
          });
          return _invoke(function () {
            if (props.onLoad) return _awaitIgnored(props.onLoad());
          }, function () {
            updateState({
              loading: false
            });
          });
        }, function (error) {
          // eslint-disable-next-line no-console
          console.warn('onLoad error:', error);
          updateState({
            loading: false,
            error: true
          });
        }));
      }
    });
  });

  var renderFinishedText = function renderFinishedText() {
    if (props.finished && props.finishedText) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('finished-text'))
      }, props.finishedText);
    }

    return null;
  };

  var clickErrorText = function clickErrorText() {
    updateState({
      error: false
    });
    check();
  };

  var renderErrorText = function renderErrorText() {
    if (state.error && props.errorText) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('error-text')),
        onClick: clickErrorText
      }, props.errorText);
    }

    return null;
  };

  var renderLoading = function renderLoading() {
    if (state.loading && !props.finished) {
      return /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('loading'))
      }, /*#__PURE__*/(0, _react.isValidElement)(props.loadingText) ? props.loadingText : /*#__PURE__*/_react.default.createElement(_loading.default, {
        className: (0, _clsx.default)(bem('loading-icon')),
        size: 16
      }, props.loadingText || locale.loading));
    }

    return null;
  };

  (0, _hooks.useUpdateEffect)(function () {
    if (props.autoCheck) {
      check();
    }
  }, [state.loading, props.finished, props.error]);
  (0, _hooks.useUpdateEffect)(function () {
    updateState({
      loading: props.loading,
      error: props.error
    });
  }, [props.loading, props.error]);
  (0, _hooks.useUpdateEffect)(function () {
    if (scrollParent.current && props.immediateCheck) {
      check();
    }
  }, [scrollParent.current]);
  (0, _useEventListener.default)('scroll', check, {
    target: scrollParent.current,
    depends: [state.loading, props.finished, state.error]
  });
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      check: check,
      state: state
    };
  });

  var Placeholder = /*#__PURE__*/_react.default.createElement("div", {
    ref: placeholder,
    className: (0, _clsx.default)(bem('placeholder'))
  });

  return /*#__PURE__*/_react.default.createElement("div", {
    ref: root,
    role: "feed",
    className: (0, _clsx.default)(bem(), props.className),
    style: props.style,
    "aria-busy": state.loading
  }, props.direction === 'down' ? props.children : Placeholder, renderLoading(), renderFinishedText(), renderErrorText(), props.direction === 'up' ? props.children : Placeholder);
});

function _awaitIgnored(value, direct) {
  if (!direct) {
    return value && value.then ? value.then(_empty) : Promise.resolve();
  }
}

function _invoke(body, then) {
  var result = body();

  if (result && result.then) {
    return result.then(then);
  }

  return then(result);
}

function _catch(body, recover) {
  try {
    var result = body();
  } catch (e) {
    return recover(e);
  }

  if (result && result.then) {
    return result.then(void 0, recover);
  }

  return result;
}

function _continueIgnored(value) {
  if (value && value.then) {
    return value.then(_empty);
  }
}

function _invokeIgnored(body) {
  var result = body();

  if (result && result.then) {
    return result.then(_empty);
  }
}

function _async(f) {
  return function () {
    for (var args = [], i = 0; i < arguments.length; i++) {
      args[i] = arguments[i];
    }

    try {
      return Promise.resolve(f.apply(this, args));
    } catch (e) {
      return Promise.reject(e);
    }
  };
}

List.defaultProps = {
  offset: 300,
  direction: 'down',
  immediateCheck: true,
  autoCheck: true
};
var _default = List;
exports.default = _default;