"use strict";

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

function _react() {
  const data = _interopRequireWildcard(require("react"));

  _react = function () {
    return data;
  };

  return data;
}

function _jsxRuntime() {
  const data = require("react/jsx-runtime");

  _jsxRuntime = function () {
    return data;
  };

  return data;
}

function _clsx() {
  const data = _interopRequireDefault(require("clsx"));

  _clsx = function () {
    return data;
  };

  return data;
}

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

var _raf = require("../utils/raf");

var _useMergedState = _interopRequireDefault(require("../hooks/use-merged-state"));

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

let uid = 0;

function format(rate) {
  return Math.min(Math.max(+rate, 0), 100);
}

function getPath(clockwise, viewBoxSize) {
  const sweepFlag = clockwise ? 1 : 0;
  return `M ${viewBoxSize / 2} ${viewBoxSize / 2} m 0, -500 a 500, 500 0 1, ${sweepFlag} 0, 1000 a 500, 500 0 1, ${sweepFlag} 0, -1000`;
}

const ROTATE_ANGLE_MAP = {
  top: 0,
  right: 90,
  bottom: 180,
  left: 270
};

const Circle = props => {
  const {
    prefixCls,
    createNamespace
  } = (0, _react().useContext)(_ConfigProviderContext.default);
  const [bem] = createNamespace('circle', prefixCls); // eslint-disable-next-line no-plusplus

  const id = `van-circle-${uid++}`;
  const [currentRate, setCurrentRate] = (0, _react().useState)(() => props.defaultRate || 0);
  const [current] = (0, _useMergedState.default)({
    defaultValue: props.defaultRate,
    value: props.rate
  });
  const viewBoxSize = (0, _react().useMemo)(() => +props.strokeWidth + 1000, [props.strokeWidth]);
  const path = (0, _react().useMemo)(() => getPath(props.clockwise, viewBoxSize), [props.clockwise, viewBoxSize]);
  const svgStyle = (0, _react().useMemo)(() => {
    const angleValue = ROTATE_ANGLE_MAP[props.startPosition];

    if (angleValue) {
      return {
        transform: `rotate(${angleValue}deg)`
      };
    }

    return undefined;
  }, [props.startPosition]);
  (0, _react().useEffect)(() => {
    let rafId;
    const startTime = Date.now();
    const startRate = currentRate;
    const endRate = format(current);
    const duration = Math.abs((startRate - endRate) * 1000 / +props.speed);

    const animate = () => {
      var _a;

      const now = Date.now();
      const progress = Math.min((now - startTime) / duration, 1);
      const rate = progress * (endRate - startRate) + startRate;
      const crate = format(parseFloat(rate.toFixed(1)));
      setCurrentRate(crate);

      if (endRate > startRate ? rate < endRate : rate > endRate) {
        rafId = (0, _raf.raf)(animate);
      } else {
        (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, crate);
      }
    };

    if (props.speed) {
      if (rafId) {
        (0, _raf.cancelRaf)(rafId);
      }

      rafId = (0, _raf.raf)(animate);
    } else {
      setCurrentRate(endRate);
    }
  }, [current]);

  const renderHover = () => {
    const PERIMETER = 3140;
    const {
      strokeWidth
    } = props;
    const offset = PERIMETER * currentRate / 100;
    const color = (0, _utils.isObject)(props.color) ? `url(#${id})` : props.color;
    const style = {
      stroke: color,
      strokeWidth: `${+strokeWidth + 1}px`,
      strokeLinecap: props.strokeLinecap,
      strokeDasharray: `${offset}px ${PERIMETER}px`
    };
    return (0, _jsxRuntime().jsx)("path", {
      d: path,
      style: style,
      className: (0, _clsx().default)(bem('hover')),
      stroke: color
    });
  };

  const renderLayer = () => {
    const style = {
      fill: props.fill,
      stroke: props.layerColor,
      strokeWidth: `${props.strokeWidth}px`
    };
    return (0, _jsxRuntime().jsx)("path", {
      className: (0, _clsx().default)(bem('layer')),
      style: style,
      d: path
    });
  };

  const renderGradient = () => {
    const {
      color
    } = props;

    if (!(0, _utils.isObject)(color)) {
      return null;
    }

    const Stops = Object.keys(color).sort((a, b) => parseFloat(a) - parseFloat(b)) // eslint-disable-next-line react/no-array-index-key
    .map((key, index) => (0, _jsxRuntime().jsx)("stop", {
      offset: key,
      stopColor: color[key]
    }, index));
    return (0, _jsxRuntime().jsx)("defs", {
      children: (0, _jsxRuntime().jsx)("linearGradient", Object.assign({
        id: id,
        x1: "100%",
        y1: "0%",
        x2: "0%",
        y2: "0%"
      }, {
        children: Stops
      }))
    });
  };

  const renderText = () => {
    if (props.text) {
      return (0, _jsxRuntime().jsx)("div", Object.assign({
        className: (0, _clsx().default)(bem('text'))
      }, {
        children: props.text
      }));
    }

    return props.children;
  };

  return (0, _jsxRuntime().jsxs)("div", Object.assign({
    className: (0, _clsx().default)(bem(), props.className),
    style: Object.assign(Object.assign({}, props.style), (0, _utils.getSizeStyle)(props.size))
  }, {
    children: [(0, _jsxRuntime().jsxs)("svg", Object.assign({
      viewBox: `0 0 ${viewBoxSize} ${viewBoxSize}`,
      style: svgStyle
    }, {
      children: [renderGradient(), renderLayer(), renderHover()]
    })), renderText()]
  }));
};

Circle.defaultProps = {
  clockwise: true,
  speed: 100,
  fill: 'none',
  strokeWidth: 40,
  startPosition: 'top'
};
var _default = Circle;
exports.default = _default;