"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var __extends = void 0 && (void 0).__extends || function () {
  var _extendStatics = function extendStatics(d, b) {
    _extendStatics = Object.setPrototypeOf || {
      __proto__: []
    } instanceof Array && function (d, b) {
      d.__proto__ = b;
    } || function (d, b) {
      for (var p in b) {
        if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
      }
    };

    return _extendStatics(d, b);
  };

  return function (d, b) {
    if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");

    _extendStatics(d, b);

    function __() {
      this.constructor = d;
    }

    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
}();

var __assign = void 0 && (void 0).__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  Object.defineProperty(o, k2, {
    enumerable: true,
    get: function get() {
      return m[k];
    }
  });
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});

var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});

var __decorate = void 0 && (void 0).__decorate || function (decorators, target, key, desc) {
  var c = arguments.length,
      r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
      d;
  if ((typeof Reflect === "undefined" ? "undefined" : (0, _typeof2["default"])(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
    if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  }
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};

var __importStar = void 0 && (void 0).__importStar || function (mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k in mod) {
    if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  }

  __setModuleDefault(result, mod);

  return result;
};

var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
  return mod && mod.__esModule ? mod : {
    "default": mod
  };
};

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AffixMemo = void 0;

var jsx_runtime_1 = require("react/jsx-runtime");

var React = __importStar(require("react"));

var classnames_1 = __importDefault(require("classnames"));

var rc_resize_observer_1 = __importDefault(require("rc-resize-observer"));

var omit_1 = __importDefault(require("lodash/omit"));

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

require("./style/affix.css");

function getDefaultTarget() {
  return typeof window !== 'undefined' ? window : null;
}

var AffixStatus;

(function (AffixStatus) {
  AffixStatus[AffixStatus["None"] = 0] = "None";
  AffixStatus[AffixStatus["Prepare"] = 1] = "Prepare";
})(AffixStatus || (AffixStatus = {}));

var Affix =
/** @class */
function (_super) {
  __extends(Affix, _super);

  function Affix() {
    var _this = _super !== null && _super.apply(this, arguments) || this;

    _this.state = {
      status: AffixStatus.None,
      lastAffix: false,
      prevTarget: null
    };

    _this.getOffsetTop = function () {
      var _a = _this.props,
          offsetBottom = _a.offsetBottom,
          offsetTop = _a.offsetTop;
      return offsetBottom === undefined && offsetTop === undefined ? 0 : offsetTop;
    };

    _this.getOffsetBottom = function () {
      return _this.props.offsetBottom;
    };

    _this.savePlaceholderNode = function (node) {
      _this.placeholderNode = node;
    };

    _this.saveFixedNode = function (node) {
      _this.fixedNode = node;
    }; // =================== Measure ===================


    _this.measure = function () {
      var _a = _this.state,
          status = _a.status,
          lastAffix = _a.lastAffix;
      var onChange = _this.props.onChange;

      var targetFunc = _this.getTargetFunc();

      if (status !== AffixStatus.Prepare || !_this.fixedNode || !_this.placeholderNode || !targetFunc) {
        return;
      }

      var offsetTop = _this.getOffsetTop();

      var offsetBottom = _this.getOffsetBottom();

      var targetNode = targetFunc();

      if (!targetNode) {
        return;
      }

      var newState = {
        status: AffixStatus.None
      };
      var targetRect = utils_1.getTargetRect(targetNode);
      var placeholderReact = utils_1.getTargetRect(_this.placeholderNode);
      var fixedTop = utils_1.getFixedTop(placeholderReact, targetRect, offsetTop);
      var fixedBottom = utils_1.getFixedBottom(placeholderReact, targetRect, offsetBottom);

      if (fixedTop !== undefined) {
        newState.affixStyle = {
          position: 'fixed',
          top: fixedTop,
          width: placeholderReact.width,
          height: placeholderReact.height
        };
        newState.placeholderStyle = {
          width: placeholderReact.width,
          height: placeholderReact.height
        };
      } else if (fixedBottom !== undefined) {
        newState.affixStyle = {
          position: 'fixed',
          bottom: fixedBottom,
          width: placeholderReact.width,
          height: placeholderReact.height
        };
        newState.placeholderStyle = {
          width: placeholderReact.width,
          height: placeholderReact.height
        };
      }

      newState.lastAffix = !!newState.affixStyle;

      if (onChange && lastAffix !== newState.lastAffix) {
        onChange(newState.lastAffix);
      }

      _this.setState(newState);
    };

    _this.prepareMeasure = function () {
      // event param is used before. Keep compatible ts define here.
      _this.setState({
        status: AffixStatus.Prepare,
        affixStyle: undefined,
        placeholderStyle: undefined
      });
    };

    return _this;
  }

  Affix.prototype.getTargetFunc = function () {
    var getTargetContainer = this.context.getTargetContainer;
    var target = this.props.target;

    if (target !== undefined) {
      return target;
    }

    return getTargetContainer || getDefaultTarget;
  }; // Event handler


  Affix.prototype.componentDidMount = function () {
    var _this = this;

    var targetFunc = this.getTargetFunc();

    if (targetFunc) {
      // [Legacy] Wait for parent component ref has its value.
      // We should use target as directly element instead of function which makes element check hard.
      this.timeout = setTimeout(function () {
        utils_1.addObserveTarget(targetFunc(), _this); // Mock Event object.

        _this.updatePosition();
      });
    }
  };

  Affix.prototype.componentDidUpdate = function (prevProps) {
    var prevTarget = this.state.prevTarget;
    var targetFunc = this.getTargetFunc();
    var newTarget = (targetFunc === null || targetFunc === void 0 ? void 0 : targetFunc()) || null;

    if (prevTarget !== newTarget) {
      utils_1.removeObserveTarget(this);

      if (newTarget) {
        utils_1.addObserveTarget(newTarget, this); // Mock Event object.

        this.updatePosition();
      } // eslint-disable-next-line react/no-did-update-set-state


      this.setState({
        prevTarget: newTarget
      });
    }

    if (prevProps.offsetTop !== this.props.offsetTop || prevProps.offsetBottom !== this.props.offsetBottom) {
      this.updatePosition();
    }

    this.measure();
  };

  Affix.prototype.componentWillUnmount = function () {
    var _a, _b;

    clearTimeout(this.timeout);
    utils_1.removeObserveTarget(this); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore

    (_a = this.updatePosition) === null || _a === void 0 ? void 0 : _a.cancel(); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore

    (_b = this.lazyUpdatePosition) === null || _b === void 0 ? void 0 : _b.cancel();
  }; // Handle realign logic


  Affix.prototype.updatePosition = function () {
    this.prepareMeasure();
  };

  Affix.prototype.lazyUpdatePosition = function () {
    var targetFunc = this.getTargetFunc();
    var affixStyle = this.state.affixStyle; // Check position change before measure to make Safari smooth

    if (targetFunc && affixStyle) {
      var offsetTop = this.getOffsetTop();
      var offsetBottom = this.getOffsetBottom();
      var targetNode = targetFunc();

      if (targetNode && this.placeholderNode) {
        var targetRect = utils_1.getTargetRect(targetNode);
        var placeholderReact = utils_1.getTargetRect(this.placeholderNode);
        var fixedTop = utils_1.getFixedTop(placeholderReact, targetRect, offsetTop);
        var fixedBottom = utils_1.getFixedBottom(placeholderReact, targetRect, offsetBottom);

        if (fixedTop !== undefined && affixStyle.top === fixedTop || fixedBottom !== undefined && affixStyle.bottom === fixedBottom) {
          return;
        }
      }
    } // Directly call prepare measure since it's already throttled.


    this.prepareMeasure();
  }; // =================== Render ===================


  Affix.prototype.render = function () {
    var _a;

    var _this = this;

    var getPrefixCls = this.context.getPrefixCls;
    var _b = this.state,
        affixStyle = _b.affixStyle,
        placeholderStyle = _b.placeholderStyle;
    var _c = this.props,
        prefixCls = _c.prefixCls,
        children = _c.children;
    var className = classnames_1["default"]((_a = {}, _a[getPrefixCls('affix', prefixCls)] = !!affixStyle, _a));
    var props = omit_1["default"](this.props, ['prefixCls', 'offsetTop', 'offsetBottom', 'target', 'onChange']); // Omit this since `onTestUpdatePosition` only works on test.

    if (process.env.NODE_ENV === 'test') {
      props = omit_1["default"](props);
    }

    return jsx_runtime_1.jsx(rc_resize_observer_1["default"], __assign({
      onResize: function onResize() {
        _this.updatePosition();
      }
    }, {
      children: jsx_runtime_1.jsxs("div", __assign({}, props, {
        ref: this.savePlaceholderNode
      }, {
        children: [affixStyle && jsx_runtime_1.jsx("div", {
          style: placeholderStyle,
          "aria-hidden": "true"
        }, void 0), jsx_runtime_1.jsx("div", __assign({
          className: className,
          ref: this.saveFixedNode,
          style: affixStyle
        }, {
          children: jsx_runtime_1.jsx(rc_resize_observer_1["default"], __assign({
            onResize: function onResize() {
              _this.updatePosition();
            }
          }, {
            children: children
          }), void 0)
        }), void 0)]
      }), void 0)
    }), void 0);
  };

  Affix.contextType = React.createContext({
    getPrefixCls: function getPrefixCls() {
      return 'dmc-affix';
    }
  });

  __decorate([utils_1.throttleByAnimationFrameDecorator()], Affix.prototype, "updatePosition", null);

  __decorate([utils_1.throttleByAnimationFrameDecorator()], Affix.prototype, "lazyUpdatePosition", null);

  return Affix;
}(React.Component);

exports["default"] = Affix;
var AffixMemo = React.memo(Affix);
exports.AffixMemo = AffixMemo;
AffixMemo.displayName = 'AffixMemo';

