"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const index_esm = require("../../../@vant/use/dist/index.esm.js");
const useTouch = require("../composables/use-touch.js");
const useExpose = require("../composables/use-expose.js");
const onPopupReopen = require("../composables/on-popup-reopen.js");
const props = require("../utils/props.js");
const create = require("../utils/create.js");
const dom = require("../utils/dom.js");
const format = require("../utils/format.js");
const [name, bem] = create.createNamespace("swipe");
const swipeProps = {
  loop: props.truthProp,
  width: props.numericProp,
  height: props.numericProp,
  vertical: Boolean,
  autoplay: props.makeNumericProp(0),
  duration: props.makeNumericProp(500),
  touchable: props.truthProp,
  lazyRender: Boolean,
  initialSwipe: props.makeNumericProp(0),
  indicatorColor: String,
  showIndicators: props.truthProp,
  stopPropagation: props.truthProp
};
const SWIPE_KEY = Symbol(name);
var stdin_default = Vue.defineComponent({
  name,
  props: swipeProps,
  emits: ["change", "dragStart", "dragEnd"],
  setup(props2, {
    emit,
    slots
  }) {
    const root = Vue.ref();
    const track = Vue.ref();
    const state = Vue.reactive({
      rect: null,
      width: 0,
      height: 0,
      offset: 0,
      active: 0,
      swiping: false
    });
    let dragging = false;
    const touch = useTouch.useTouch();
    const {
      children,
      linkChildren
    } = index_esm.useChildren(SWIPE_KEY);
    const count = Vue.computed(() => children.length);
    const size = Vue.computed(() => state[props2.vertical ? "height" : "width"]);
    const delta = Vue.computed(() => props2.vertical ? touch.deltaY.value : touch.deltaX.value);
    const minOffset = Vue.computed(() => {
      if (state.rect) {
        const base = props2.vertical ? state.rect.height : state.rect.width;
        return base - size.value * count.value;
      }
      return 0;
    });
    const maxCount = Vue.computed(() => size.value ? Math.ceil(Math.abs(minOffset.value) / size.value) : count.value);
    const trackSize = Vue.computed(() => count.value * size.value);
    const activeIndicator = Vue.computed(() => (state.active + count.value) % count.value);
    const isCorrectDirection = Vue.computed(() => {
      const expect = props2.vertical ? "vertical" : "horizontal";
      return touch.direction.value === expect;
    });
    const trackStyle = Vue.computed(() => {
      const style = {
        transitionDuration: `${state.swiping ? 0 : props2.duration}ms`,
        transform: `translate${props2.vertical ? "Y" : "X"}(${+state.offset.toFixed(2)}px)`
      };
      if (size.value) {
        const mainAxis = props2.vertical ? "height" : "width";
        const crossAxis = props2.vertical ? "width" : "height";
        style[mainAxis] = `${trackSize.value}px`;
        style[crossAxis] = props2[crossAxis] ? `${props2[crossAxis]}px` : "";
      }
      return style;
    });
    const getTargetActive = (pace) => {
      const {
        active
      } = state;
      if (pace) {
        if (props2.loop) {
          return format.clamp(active + pace, -1, count.value);
        }
        return format.clamp(active + pace, 0, maxCount.value);
      }
      return active;
    };
    const getTargetOffset = (targetActive, offset = 0) => {
      let currentPosition = targetActive * size.value;
      if (!props2.loop) {
        currentPosition = Math.min(currentPosition, -minOffset.value);
      }
      let targetOffset = offset - currentPosition;
      if (!props2.loop) {
        targetOffset = format.clamp(targetOffset, minOffset.value, 0);
      }
      return targetOffset;
    };
    const move = ({
      pace = 0,
      offset = 0,
      emitChange
    }) => {
      if (count.value <= 1) {
        return;
      }
      const {
        active
      } = state;
      const targetActive = getTargetActive(pace);
      const targetOffset = getTargetOffset(targetActive, offset);
      if (props2.loop) {
        if (children[0] && targetOffset !== minOffset.value) {
          const outRightBound = targetOffset < minOffset.value;
          children[0].setOffset(outRightBound ? trackSize.value : 0);
        }
        if (children[count.value - 1] && targetOffset !== 0) {
          const outLeftBound = targetOffset > 0;
          children[count.value - 1].setOffset(outLeftBound ? -trackSize.value : 0);
        }
      }
      state.active = targetActive;
      state.offset = targetOffset;
      if (emitChange && targetActive !== active) {
        emit("change", activeIndicator.value);
      }
    };
    const correctPosition = () => {
      state.swiping = true;
      if (state.active <= -1) {
        move({
          pace: count.value
        });
      } else if (state.active >= count.value) {
        move({
          pace: -count.value
        });
      }
    };
    const prev = () => {
      correctPosition();
      touch.reset();
      index_esm.doubleRaf(() => {
        state.swiping = false;
        move({
          pace: -1,
          emitChange: true
        });
      });
    };
    const next = () => {
      correctPosition();
      touch.reset();
      index_esm.doubleRaf(() => {
        state.swiping = false;
        move({
          pace: 1,
          emitChange: true
        });
      });
    };
    let autoplayTimer;
    const stopAutoplay = () => clearTimeout(autoplayTimer);
    const autoplay = () => {
      stopAutoplay();
      if (+props2.autoplay > 0 && count.value > 1) {
        autoplayTimer = setTimeout(() => {
          next();
          autoplay();
        }, +props2.autoplay);
      }
    };
    const initialize = (active = +props2.initialSwipe) => {
      if (!root.value) {
        return;
      }
      const cb = () => {
        var _a, _b;
        if (!dom.isHidden(root)) {
          const rect = {
            width: root.value.offsetWidth,
            height: root.value.offsetHeight
          };
          state.rect = rect;
          state.width = +((_a = props2.width) != null ? _a : rect.width);
          state.height = +((_b = props2.height) != null ? _b : rect.height);
        }
        if (count.value) {
          active = Math.min(count.value - 1, active);
          if (active === -1) {
            active = count.value - 1;
          }
        }
        state.active = active;
        state.swiping = true;
        state.offset = getTargetOffset(active);
        children.forEach((swipe) => {
          swipe.setOffset(0);
        });
        autoplay();
      };
      if (dom.isHidden(root)) {
        Vue.nextTick().then(cb);
      } else {
        cb();
      }
    };
    const resize = () => initialize(state.active);
    let touchStartTime;
    const onTouchStart = (event) => {
      if (!props2.touchable || // avoid resetting position on multi-finger touch
      event.touches.length > 1) return;
      touch.start(event);
      dragging = false;
      touchStartTime = Date.now();
      stopAutoplay();
      correctPosition();
    };
    const onTouchMove = (event) => {
      if (props2.touchable && state.swiping) {
        touch.move(event);
        if (isCorrectDirection.value) {
          const isEdgeTouch = !props2.loop && (state.active === 0 && delta.value > 0 || state.active === count.value - 1 && delta.value < 0);
          if (!isEdgeTouch) {
            dom.preventDefault(event, props2.stopPropagation);
            move({
              offset: delta.value
            });
            if (!dragging) {
              emit("dragStart", {
                index: activeIndicator.value
              });
              dragging = true;
            }
          }
        }
      }
    };
    const onTouchEnd = () => {
      if (!props2.touchable || !state.swiping) {
        return;
      }
      const duration = Date.now() - touchStartTime;
      const speed = delta.value / duration;
      const shouldSwipe = Math.abs(speed) > 0.25 || Math.abs(delta.value) > size.value / 2;
      if (shouldSwipe && isCorrectDirection.value) {
        const offset = props2.vertical ? touch.offsetY.value : touch.offsetX.value;
        let pace = 0;
        if (props2.loop) {
          pace = offset > 0 ? delta.value > 0 ? -1 : 1 : 0;
        } else {
          pace = -Math[delta.value > 0 ? "ceil" : "floor"](delta.value / size.value);
        }
        move({
          pace,
          emitChange: true
        });
      } else if (delta.value) {
        move({
          pace: 0
        });
      }
      dragging = false;
      state.swiping = false;
      emit("dragEnd", {
        index: activeIndicator.value
      });
      autoplay();
    };
    const swipeTo = (index, options = {}) => {
      correctPosition();
      touch.reset();
      index_esm.doubleRaf(() => {
        let targetIndex;
        if (props2.loop && index === count.value) {
          targetIndex = state.active === 0 ? 0 : index;
        } else {
          targetIndex = index % count.value;
        }
        if (options.immediate) {
          index_esm.doubleRaf(() => {
            state.swiping = false;
          });
        } else {
          state.swiping = false;
        }
        move({
          pace: targetIndex - state.active,
          emitChange: true
        });
      });
    };
    const renderDot = (_, index) => {
      const active = index === activeIndicator.value;
      const style = active ? {
        backgroundColor: props2.indicatorColor
      } : void 0;
      return Vue.createVNode("i", {
        "style": style,
        "class": bem("indicator", {
          active
        })
      }, null);
    };
    const renderIndicator = () => {
      if (slots.indicator) {
        return slots.indicator({
          active: activeIndicator.value,
          total: count.value
        });
      }
      if (props2.showIndicators && count.value > 1) {
        return Vue.createVNode("div", {
          "class": bem("indicators", {
            vertical: props2.vertical
          })
        }, [Array(count.value).fill("").map(renderDot)]);
      }
    };
    useExpose.useExpose({
      prev,
      next,
      state,
      resize,
      swipeTo
    });
    linkChildren({
      size,
      props: props2,
      count,
      activeIndicator
    });
    Vue.watch(() => props2.initialSwipe, (value) => initialize(+value));
    Vue.watch(count, () => initialize(state.active));
    Vue.watch(() => props2.autoplay, autoplay);
    Vue.watch([dom.windowWidth, dom.windowHeight, () => props2.width, () => props2.height], resize);
    Vue.watch(index_esm.usePageVisibility(), (visible) => {
      if (visible === "visible") {
        autoplay();
      } else {
        stopAutoplay();
      }
    });
    Vue.onMounted(initialize);
    Vue.onActivated(() => initialize(state.active));
    onPopupReopen.onPopupReopen(() => initialize(state.active));
    Vue.onDeactivated(stopAutoplay);
    Vue.onBeforeUnmount(stopAutoplay);
    index_esm.useEventListener("touchmove", onTouchMove, {
      target: track
    });
    return () => {
      var _a;
      return Vue.createVNode("div", {
        "ref": root,
        "class": bem()
      }, [Vue.createVNode("div", {
        "ref": track,
        "style": trackStyle.value,
        "class": bem("track", {
          vertical: props2.vertical
        }),
        "onTouchstartPassive": onTouchStart,
        "onTouchend": onTouchEnd,
        "onTouchcancel": onTouchEnd
      }, [(_a = slots.default) == null ? void 0 : _a.call(slots)]), renderIndicator()]);
    };
  }
});
exports.SWIPE_KEY = SWIPE_KEY;
exports.default = stdin_default;
exports.swipeProps = swipeProps;
