import '../../../../utils/index.mjs';
import { raf } from '../../../../utils/vue/raf.mjs';

function useScrollTo(containerRef, mergedData, heights, props, getKey, collectHeight, syncScrollTop, triggerFlash) {
  let scroll;
  return (arg) => {
    if (arg === null || arg === void 0) {
      triggerFlash();
      return;
    }
    raf.cancel(scroll);
    const data = mergedData.value;
    const itemHeight = props.itemHeight;
    if (typeof arg === "number") {
      syncScrollTop(arg);
    } else if (arg && typeof arg === "object") {
      let index;
      const {
        align
      } = arg;
      if ("index" in arg)
        ({
          index
        } = arg);
      else
        index = data.findIndex((item) => getKey(item) === arg.key);
      const {
        offset = 0
      } = arg;
      const syncScroll = (times, targetAlign) => {
        if (times < 0 || !containerRef.value)
          return;
        const height = containerRef.value.clientHeight;
        let needCollectHeight = false;
        let newTargetAlign = targetAlign;
        if (height) {
          const mergedAlign = targetAlign || align;
          let stackTop = 0;
          let itemTop = 0;
          let itemBottom = 0;
          const maxLen = Math.min(data.length, index);
          for (let i = 0; i <= maxLen; i += 1) {
            const key = getKey(data[i]);
            itemTop = stackTop;
            const cacheHeight = heights.get(key);
            itemBottom = itemTop + (cacheHeight === void 0 ? itemHeight : cacheHeight);
            stackTop = itemBottom;
            if (i === index && cacheHeight === void 0)
              needCollectHeight = true;
          }
          const scrollTop = containerRef.value.scrollTop;
          let targetTop = null;
          switch (mergedAlign) {
            case "top":
              targetTop = itemTop - offset;
              break;
            case "bottom":
              targetTop = itemBottom - height + offset;
              break;
            default: {
              const scrollBottom = scrollTop + height;
              if (itemTop < scrollTop)
                newTargetAlign = "top";
              else if (itemBottom > scrollBottom)
                newTargetAlign = "bottom";
            }
          }
          if (targetTop !== null && targetTop !== scrollTop)
            syncScrollTop(targetTop);
        }
        scroll = raf(() => {
          if (needCollectHeight)
            collectHeight();
          syncScroll(times - 1, newTargetAlign);
        }, 2);
      };
      syncScroll(5);
    }
  };
}

export { useScrollTo as default };
//# sourceMappingURL=useScrollTo.mjs.map
