"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");

var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");

var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");

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

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

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));

var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/taggedTemplateLiteral"));

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

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _rxjs = require("rxjs");

var op = _interopRequireWildcard(require("rxjs/operators"));

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

var _internals = require("../../internals");

var _styles = require("../../base/styles");

var _templateObject, _templateObject2;

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; }

var TableHeaderCellResize = _styledComponents.default.div(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  position: absolute;\n  top: 0;\n  right: -5px;\n  height: 100%;\n  width: 10px;\n  cursor: ew-resize;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  z-index:1;\n\n  &:after {\n    content: \"\";\n    position: absolute;\n    display: block;\n    left: calc(50% - 1px);\n    width: 1px;\n    height: calc(100% - 14px);\n    top: 7px;\n    background-color: var(--border-color);\n  }\n"])));

var TableHeaderGroupCellResize = (0, _styledComponents.default)(TableHeaderCellResize)(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2.default)(["\n  &:after {\n    height: 100%;\n    top: 0;\n  }\n"])));

function clamp(min, x, max) {
  return Math.max(min, Math.min(max, x));
}

function disableSelect(event) {
  event.preventDefault();
}

function columnResize() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var _a, _b, _c;

  var stateKey = 'columnResize';
  var minSize = (_a = opts.minSize) !== null && _a !== void 0 ? _a : 60;
  var fallbackSize = (_b = opts.fallbackSize) !== null && _b !== void 0 ? _b : 150;
  var maxSize = (_c = opts.maxSize) !== null && _c !== void 0 ? _c : 1000;
  return function columnResizeFeature(pipeline) {
    var _a, _b, _c;

    var columnSize = (_b = (_a = opts.columnSize) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : {};
    var leafColumns = (0, _utils.collectNodes)(pipeline.getColumns(), 'leaf-only');
    leafColumns.forEach(function (_ref) {
      var code = _ref.code,
          width = _ref.width;

      if (columnSize[code] === undefined) {
        if (typeof width === 'number') {
          columnSize[code] = width;
        } else {
          columnSize[code] = fallbackSize;
        }
      }
    }); // 初始化 || opts.columnSize发生变化（为了autofill时能取到最新值）

    if (!pipeline.getStateAtKey(stateKey) || ((_c = pipeline.ref) === null || _c === void 0 ? void 0 : _c.current.lastOptColumnSize) !== opts.columnSize) {
      pipeline.setStateAtKey(stateKey, columnSize);
    }

    if (pipeline.ref) {
      pipeline.ref.current.lastOptColumnSize = opts.columnSize;
    }

    var onChangeSize = function onChangeSize(nextColumnSize) {
      window.requestAnimationFrame(function () {
        var _a;

        pipeline.setStateAtKey(stateKey, nextColumnSize);
        (_a = opts === null || opts === void 0 ? void 0 : opts.onChangeSize) === null || _a === void 0 ? void 0 : _a.call(opts, nextColumnSize);

        if (opts.columnSize) {
          if (pipeline.ref) {
            pipeline.ref.current.lastOptColumnSize = nextColumnSize; // 这里记录由列宽拖拽导致的opts.columnSize变化,避免重复渲染
          }
        }
      });
    };

    var handleDoubleClick = function handleDoubleClick(e, col) {
      opts === null || opts === void 0 ? void 0 : opts.doubleClickCallback(e, col);
    };

    var handleMouseDown = function handleMouseDown(e, col) {
      window.addEventListener('selectstart', disableSelect);
      var changedColumnSize = {};
      var startX = e.clientX;
      var children = col.children,
          code = col.code;
      var recordColumnSize = columnSize;
      e.stopPropagation();
      var nextSize$ = (0, _rxjs.fromEvent)(window, 'mousemove').pipe(op.takeUntil((0, _rxjs.fromEvent)(window, 'mouseup')), op.map(function (e) {
        var movingX = e.clientX;
        var nextColumnSize = (0, _extends2.default)({}, columnSize);
        var deltaSum = movingX - startX;
        var deltaRemaining = deltaSum;

        if ((children === null || children === void 0 ? void 0 : children.length) > 0) {
          var leafChildColumns = (0, _utils.collectNodes)(children, 'leaf-only');
          var childrenWidthSum = leafChildColumns.reduce(function (sum, _ref2) {
            var code = _ref2.code;
            return sum + columnSize[code];
          }, 0);
          leafChildColumns.forEach(function (_ref3, index) {
            var code = _ref3.code;
            var startSize = columnSize[code];
            var currentDeltaWidth = Math.round(deltaSum * startSize / childrenWidthSum);

            if (index < leafChildColumns.length - 1) {
              nextColumnSize[code] = clamp(minSize, startSize + currentDeltaWidth, maxSize);
              changedColumnSize[code] = nextColumnSize[code];
              deltaRemaining -= currentDeltaWidth;
            } else {
              nextColumnSize[code] = clamp(minSize, startSize + deltaRemaining, maxSize);
              changedColumnSize[code] = nextColumnSize[code];
            }
          });
        } else {
          var startSize = columnSize[code];
          nextColumnSize[code] = clamp(minSize, startSize + deltaSum, maxSize);
          changedColumnSize[code] = nextColumnSize[code];
        }

        recordColumnSize = nextColumnSize;
        return nextColumnSize;
      }));
      nextSize$.subscribe({
        next: onChangeSize,
        complete: function complete() {
          var _context;

          var changedColumnSizes = (0, _map.default)(_context = (0, _keys.default)(changedColumnSize)).call(_context, function (code) {
            return {
              code: code,
              width: changedColumnSize[code]
            };
          });
          window.requestAnimationFrame(function () {
            var _a;

            (_a = opts === null || opts === void 0 ? void 0 : opts.afterChangeSize) === null || _a === void 0 ? void 0 : _a.call(opts, recordColumnSize, changedColumnSizes);
          });
          window.removeEventListener('selectstart', disableSelect);
        }
      });
    };

    var isGroup = (0, _utils.isGroupColumn)(pipeline.getColumns());
    return pipeline.mapColumns((0, _utils.makeRecursiveMapper)(function (col) {
      var _a;

      var prevTitle = _internals.internals.safeRenderHeader(col);

      var code = col.code,
          features = col.features,
          width = col.width;
      return (0, _extends2.default)((0, _extends2.default)({}, col), {
        width: (_a = columnSize[code]) !== null && _a !== void 0 ? _a : width,
        title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, prevTitle, (features === null || features === void 0 ? void 0 : features.resizeable) !== false && (isGroup ? /*#__PURE__*/_react.default.createElement(TableHeaderGroupCellResize, {
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        }) : /*#__PURE__*/_react.default.createElement(TableHeaderCellResize, {
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        }))),
        headerCellProps: (0, _utils.mergeCellProps)(col.headerCellProps, {
          className: 'resizeable'
        })
      });
    }));
  };
}