import { memo as d, notUndefined as m, approxEqual as z, debounce as I } from "./utils.js";
const M = (r) => r, y = (r) => {
  const h = Math.max(r.startIndex - r.overscan, 0), t = Math.min(r.endIndex + r.overscan, r.count - 1), s = [];
  for (let e = h; e <= t; e++)
    s.push(e);
  return s;
}, R = (r, h) => {
  const t = r.scrollElement;
  if (!t)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  const e = (n) => {
    const { width: o, height: l } = n;
    h({ width: Math.round(o), height: Math.round(l) });
  };
  if (e(t.getBoundingClientRect()), !s.ResizeObserver)
    return () => {
    };
  const i = new s.ResizeObserver((n) => {
    const o = () => {
      const l = n[0];
      if (l != null && l.borderBoxSize) {
        const a = l.borderBoxSize[0];
        if (a) {
          e({ width: a.inlineSize, height: a.blockSize });
          return;
        }
      }
      e(t.getBoundingClientRect());
    };
    r.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(o) : o();
  });
  return i.observe(t, { box: "border-box" }), () => {
    i.unobserve(t);
  };
}, b = {
  passive: !0
}, E = typeof window > "u" ? !0 : "onscrollend" in window, _ = (r, h) => {
  const t = r.scrollElement;
  if (!t)
    return;
  const s = r.targetWindow;
  if (!s)
    return;
  let e = 0;
  const i = r.options.useScrollendEvent && E ? () => {
  } : I(
    s,
    () => {
      h(e, !1);
    },
    r.options.isScrollingResetDelay
  ), n = (c) => () => {
    const { horizontal: f, isRtl: u } = r.options;
    e = f ? t.scrollLeft * (u && -1 || 1) : t.scrollTop, i(), h(e, c);
  }, o = n(!0), l = n(!1);
  l(), t.addEventListener("scroll", o, b);
  const a = r.options.useScrollendEvent && E;
  return a && t.addEventListener("scrollend", l, b), () => {
    t.removeEventListener("scroll", o), a && t.removeEventListener("scrollend", l);
  };
}, w = (r, h, t) => {
  if (h != null && h.borderBoxSize) {
    const s = h.borderBoxSize[0];
    if (s)
      return Math.round(
        s[t.options.horizontal ? "inlineSize" : "blockSize"]
      );
  }
  return Math.round(
    r.getBoundingClientRect()[t.options.horizontal ? "width" : "height"]
  );
}, A = (r, {
  adjustments: h = 0,
  behavior: t
}, s) => {
  var e, i;
  const n = r + h;
  (i = (e = s.scrollElement) == null ? void 0 : e.scrollTo) == null || i.call(e, {
    [s.options.horizontal ? "left" : "top"]: n,
    behavior: t
  });
};
class F {
  constructor(h) {
    this.unsubs = [], this.scrollElement = null, this.targetWindow = null, this.isScrolling = !1, this.scrollToIndexTimeoutId = null, this.measurementsCache = [], this.itemSizeCache = /* @__PURE__ */ new Map(), this.pendingMeasuredCacheIndexes = [], this.scrollRect = null, this.scrollOffset = null, this.scrollDirection = null, this.scrollAdjustments = 0, this.elementsCache = /* @__PURE__ */ new Map(), this.observer = /* @__PURE__ */ (() => {
      let t = null;
      const s = () => t || (!this.targetWindow || !this.targetWindow.ResizeObserver ? null : t = new this.targetWindow.ResizeObserver((e) => {
        e.forEach((i) => {
          const n = () => {
            this._measureElement(i.target, i);
          };
          this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(n) : n();
        });
      }));
      return {
        disconnect: () => {
          var e;
          (e = s()) == null || e.disconnect(), t = null;
        },
        observe: (e) => {
          var i;
          return (i = s()) == null ? void 0 : i.observe(e, { box: "border-box" });
        },
        unobserve: (e) => {
          var i;
          return (i = s()) == null ? void 0 : i.unobserve(e);
        }
      };
    })(), this.range = null, this.setOptions = (t) => {
      Object.entries(t).forEach(([s, e]) => {
        typeof e > "u" && delete t[s];
      }), this.options = {
        debug: !1,
        initialOffset: 0,
        overscan: 1,
        paddingStart: 0,
        paddingEnd: 0,
        scrollPaddingStart: 0,
        scrollPaddingEnd: 0,
        horizontal: !1,
        getItemKey: M,
        rangeExtractor: y,
        onChange: () => {
        },
        measureElement: w,
        initialRect: { width: 0, height: 0 },
        scrollMargin: 0,
        gap: 0,
        indexAttribute: "data-index",
        initialMeasurementsCache: [],
        lanes: 1,
        isScrollingResetDelay: 150,
        enabled: !0,
        isRtl: !1,
        useScrollendEvent: !0,
        useAnimationFrameWithResizeObserver: !1,
        ...t
      };
    }, this.notify = (t) => {
      var s, e;
      (e = (s = this.options).onChange) == null || e.call(s, this, t);
    }, this.maybeNotify = d(
      () => (this.calculateRange(), [
        this.isScrolling,
        this.range ? this.range.startIndex : null,
        this.range ? this.range.endIndex : null
      ]),
      (t) => {
        this.notify(t);
      },
      {
        key: process.env.NODE_ENV !== "production" && "maybeNotify",
        debug: () => this.options.debug,
        initialDeps: [
          this.isScrolling,
          this.range ? this.range.startIndex : null,
          this.range ? this.range.endIndex : null
        ]
      }
    ), this.cleanup = () => {
      this.unsubs.filter(Boolean).forEach((t) => t()), this.unsubs = [], this.observer.disconnect(), this.scrollElement = null, this.targetWindow = null;
    }, this._didMount = () => () => {
      this.cleanup();
    }, this._willUpdate = () => {
      var t;
      const s = this.options.enabled ? this.options.getScrollElement() : null;
      if (this.scrollElement !== s) {
        if (this.cleanup(), !s) {
          this.maybeNotify();
          return;
        }
        this.scrollElement = s, this.scrollElement && "ownerDocument" in this.scrollElement ? this.targetWindow = this.scrollElement.ownerDocument.defaultView : this.targetWindow = ((t = this.scrollElement) == null ? void 0 : t.window) ?? null, this.elementsCache.forEach((e) => {
          this.observer.observe(e);
        }), this._scrollToOffset(this.getScrollOffset(), {
          adjustments: void 0,
          behavior: void 0
        }), this.unsubs.push(
          this.options.observeElementRect(this, (e) => {
            this.scrollRect = e, this.maybeNotify();
          })
        ), this.unsubs.push(
          this.options.observeElementOffset(this, (e, i) => {
            this.scrollAdjustments = 0, this.scrollDirection = i ? this.getScrollOffset() < e ? "forward" : "backward" : null, this.scrollOffset = e, this.isScrolling = i, this.maybeNotify();
          })
        );
      }
    }, this.getSize = () => this.options.enabled ? (this.scrollRect = this.scrollRect ?? this.options.initialRect, this.scrollRect[this.options.horizontal ? "width" : "height"]) : (this.scrollRect = null, 0), this.getScrollOffset = () => this.options.enabled ? (this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset == "function" ? this.options.initialOffset() : this.options.initialOffset), this.scrollOffset) : (this.scrollOffset = null, 0), this.getFurthestMeasurement = (t, s) => {
      const e = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
      for (let n = s - 1; n >= 0; n--) {
        const o = t[n];
        if (e.has(o.lane))
          continue;
        const l = i.get(
          o.lane
        );
        if (l == null || o.end > l.end ? i.set(o.lane, o) : o.end < l.end && e.set(o.lane, !0), e.size === this.options.lanes)
          break;
      }
      return i.size === this.options.lanes ? Array.from(i.values()).sort((n, o) => n.end === o.end ? n.index - o.index : n.end - o.end)[0] : void 0;
    }, this.getMeasurementOptions = d(
      () => [
        this.options.count,
        this.options.paddingStart,
        this.options.scrollMargin,
        this.options.getItemKey,
        this.options.enabled
      ],
      (t, s, e, i, n) => (this.pendingMeasuredCacheIndexes = [], {
        count: t,
        paddingStart: s,
        scrollMargin: e,
        getItemKey: i,
        enabled: n
      }),
      {
        key: !1
      }
    ), this.getMeasurements = d(
      () => [this.getMeasurementOptions(), this.itemSizeCache],
      ({ count: t, paddingStart: s, scrollMargin: e, getItemKey: i, enabled: n }, o) => {
        if (!n)
          return this.measurementsCache = [], this.itemSizeCache.clear(), [];
        this.measurementsCache.length === 0 && (this.measurementsCache = this.options.initialMeasurementsCache, this.measurementsCache.forEach((c) => {
          this.itemSizeCache.set(c.key, c.size);
        }));
        const l = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
        this.pendingMeasuredCacheIndexes = [];
        const a = this.measurementsCache.slice(0, l);
        for (let c = l; c < t; c++) {
          const f = i(c), u = this.options.lanes === 1 ? a[c - 1] : this.getFurthestMeasurement(a, c), g = u ? u.end + this.options.gap : s + e, p = o.get(f), v = typeof p == "number" ? p : this.options.estimateSize(c), S = g + v, x = u ? u.lane : c % this.options.lanes;
          a[c] = {
            index: c,
            start: g,
            size: v,
            end: S,
            key: f,
            lane: x
          };
        }
        return this.measurementsCache = a, a;
      },
      {
        key: process.env.NODE_ENV !== "production" && "getMeasurements",
        debug: () => this.options.debug
      }
    ), this.calculateRange = d(
      () => [this.getMeasurements(), this.getSize(), this.getScrollOffset()],
      (t, s, e) => this.range = t.length > 0 && s > 0 ? C({
        measurements: t,
        outerSize: s,
        scrollOffset: e
      }) : null,
      {
        key: process.env.NODE_ENV !== "production" && "calculateRange",
        debug: () => this.options.debug
      }
    ), this.getVirtualIndexes = d(
      () => {
        let t = null, s = null;
        const e = this.calculateRange();
        return e && (t = e.startIndex, s = e.endIndex), [
          this.options.rangeExtractor,
          this.options.overscan,
          this.options.count,
          t,
          s
        ];
      },
      (t, s, e, i, n) => i === null || n === null ? [] : t({
        startIndex: i,
        endIndex: n,
        overscan: s,
        count: e
      }),
      {
        key: process.env.NODE_ENV !== "production" && "getVirtualIndexes",
        debug: () => this.options.debug
      }
    ), this.indexFromElement = (t) => {
      const s = this.options.indexAttribute, e = t.getAttribute(s);
      return e ? parseInt(e, 10) : (console.warn(
        `Missing attribute name '${s}={index}' on measured element.`
      ), -1);
    }, this._measureElement = (t, s) => {
      const e = this.indexFromElement(t), i = this.measurementsCache[e];
      if (!i)
        return;
      const n = i.key, o = this.elementsCache.get(n);
      o !== t && (o && this.observer.unobserve(o), this.observer.observe(t), this.elementsCache.set(n, t)), t.isConnected && this.resizeItem(e, this.options.measureElement(t, s, this));
    }, this.resizeItem = (t, s) => {
      const e = this.measurementsCache[t];
      if (!e)
        return;
      const i = this.itemSizeCache.get(e.key) ?? e.size, n = s - i;
      n !== 0 && ((this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(e, n, this) : e.start < this.getScrollOffset() + this.scrollAdjustments) && (process.env.NODE_ENV !== "production" && this.options.debug && console.info("correction", n), this._scrollToOffset(this.getScrollOffset(), {
        adjustments: this.scrollAdjustments += n,
        behavior: void 0
      })), this.pendingMeasuredCacheIndexes.push(e.index), this.itemSizeCache = new Map(this.itemSizeCache.set(e.key, s)), this.notify(!1));
    }, this.measureElement = (t) => {
      if (!t) {
        this.elementsCache.forEach((s, e) => {
          s.isConnected || (this.observer.unobserve(s), this.elementsCache.delete(e));
        });
        return;
      }
      this._measureElement(t, void 0);
    }, this.getVirtualItems = d(
      () => [this.getVirtualIndexes(), this.getMeasurements()],
      (t, s) => {
        const e = [];
        for (let i = 0, n = t.length; i < n; i++) {
          const o = t[i], l = s[o];
          e.push(l);
        }
        return e;
      },
      {
        key: process.env.NODE_ENV !== "production" && "getVirtualItems",
        debug: () => this.options.debug
      }
    ), this.getVirtualItemForOffset = (t) => {
      const s = this.getMeasurements();
      if (s.length !== 0)
        return m(
          s[O(
            0,
            s.length - 1,
            (e) => m(s[e]).start,
            t
          )]
        );
    }, this.getOffsetForAlignment = (t, s) => {
      const e = this.getSize(), i = this.getScrollOffset();
      s === "auto" && t >= i + e && (s = "end"), s === "end" && (t -= e);
      const n = this.options.horizontal ? "scrollWidth" : "scrollHeight", l = (this.scrollElement ? "document" in this.scrollElement ? this.scrollElement.document.documentElement[n] : this.scrollElement[n] : 0) - e;
      return Math.max(Math.min(l, t), 0);
    }, this.getOffsetForIndex = (t, s = "auto") => {
      t = Math.max(0, Math.min(t, this.options.count - 1));
      const e = this.measurementsCache[t];
      if (!e)
        return;
      const i = this.getSize(), n = this.getScrollOffset();
      if (s === "auto")
        if (e.end >= n + i - this.options.scrollPaddingEnd)
          s = "end";
        else if (e.start <= n + this.options.scrollPaddingStart)
          s = "start";
        else
          return [n, s];
      const o = e.start - this.options.scrollPaddingStart + (e.size - i) / 2;
      switch (s) {
        case "center":
          return [this.getOffsetForAlignment(o, s), s];
        case "end":
          return [
            this.getOffsetForAlignment(
              e.end + this.options.scrollPaddingEnd,
              s
            ),
            s
          ];
        default:
          return [
            this.getOffsetForAlignment(
              e.start - this.options.scrollPaddingStart,
              s
            ),
            s
          ];
      }
    }, this.isDynamicMode = () => this.elementsCache.size > 0, this.cancelScrollToIndex = () => {
      this.scrollToIndexTimeoutId !== null && this.targetWindow && (this.targetWindow.clearTimeout(this.scrollToIndexTimeoutId), this.scrollToIndexTimeoutId = null);
    }, this.scrollToOffset = (t, { align: s = "start", behavior: e } = {}) => {
      this.cancelScrollToIndex(), e === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      ), this._scrollToOffset(this.getOffsetForAlignment(t, s), {
        adjustments: void 0,
        behavior: e
      });
    }, this.scrollToIndex = (t, { align: s = "auto", behavior: e } = {}) => {
      t = Math.max(0, Math.min(t, this.options.count - 1)), this.cancelScrollToIndex(), e === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      );
      const i = this.getOffsetForIndex(t, s);
      if (!i) return;
      const [n, o] = i;
      this._scrollToOffset(n, { adjustments: void 0, behavior: e }), e !== "smooth" && this.isDynamicMode() && this.targetWindow && (this.scrollToIndexTimeoutId = this.targetWindow.setTimeout(() => {
        if (this.scrollToIndexTimeoutId = null, this.elementsCache.has(
          this.options.getItemKey(t)
        )) {
          const [a] = m(
            this.getOffsetForIndex(t, o)
          );
          z(a, this.getScrollOffset()) || this.scrollToIndex(t, { align: o, behavior: e });
        } else
          this.scrollToIndex(t, { align: o, behavior: e });
      }));
    }, this.scrollBy = (t, { behavior: s } = {}) => {
      this.cancelScrollToIndex(), s === "smooth" && this.isDynamicMode() && console.warn(
        "The `smooth` scroll behavior is not fully supported with dynamic size."
      ), this._scrollToOffset(this.getScrollOffset() + t, {
        adjustments: void 0,
        behavior: s
      });
    }, this.getTotalSize = () => {
      var t;
      const s = this.getMeasurements();
      let e;
      return s.length === 0 ? e = this.options.paddingStart : e = this.options.lanes === 1 ? ((t = s[s.length - 1]) == null ? void 0 : t.end) ?? 0 : Math.max(
        ...s.slice(-this.options.lanes).map((i) => i.end)
      ), Math.max(
        e - this.options.scrollMargin + this.options.paddingEnd,
        0
      );
    }, this._scrollToOffset = (t, {
      adjustments: s,
      behavior: e
    }) => {
      this.options.scrollToFn(t, { behavior: e, adjustments: s }, this);
    }, this.measure = () => {
      this.itemSizeCache = /* @__PURE__ */ new Map(), this.notify(!1);
    }, this.setOptions(h);
  }
}
const O = (r, h, t, s) => {
  for (; r <= h; ) {
    const e = (r + h) / 2 | 0, i = t(e);
    if (i < s)
      r = e + 1;
    else if (i > s)
      h = e - 1;
    else
      return e;
  }
  return r > 0 ? r - 1 : 0;
};
function C({
  measurements: r,
  outerSize: h,
  scrollOffset: t
}) {
  const s = r.length - 1, i = O(0, s, (o) => r[o].start, t);
  let n = i;
  for (; n < s && r[n].end < t + h; )
    n++;
  return { startIndex: i, endIndex: n };
}
export {
  F as Virtualizer,
  z as approxEqual,
  I as debounce,
  M as defaultKeyExtractor,
  y as defaultRangeExtractor,
  A as elementScroll,
  w as measureElement,
  d as memo,
  m as notUndefined,
  _ as observeElementOffset,
  R as observeElementRect
};
//# sourceMappingURL=index.js.map
