sticky-scroll-trigger 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @license
3
- * StickyScrollTrigger v0.12.0
3
+ * StickyScrollTrigger v0.14.0
4
4
  * Copyright (c) 2026 Kuninori Ogino
5
5
  * Released under the MIT License
6
6
  * https://github.com/kuninori-ogino/sticky-scroll-trigger
@@ -87,10 +87,6 @@ var StickyScrollTrigger = (function() {
87
87
  el.style.position = "";
88
88
  el.style.top = "";
89
89
  };
90
- const applyStickyPosition = (el, topPx) => {
91
- el.style.position = "sticky";
92
- el.style.top = `${topPx}px`;
93
- };
94
90
  const captureInlinePosition = (el) => ({
95
91
  position: el.style.position,
96
92
  top: el.style.top
@@ -104,6 +100,15 @@ var StickyScrollTrigger = (function() {
104
100
  elements.forEach(resetStickyPosition);
105
101
  return () => elements.forEach((el, i) => restoreInlinePosition(el, saved[i]));
106
102
  };
103
+ const insertSpacers = (spacers) => {
104
+ const inserted = spacers.map(({ after, height }) => {
105
+ const spacer = document.createElement("div");
106
+ spacer.style.cssText = `height:${height}px;margin:0;padding:0;border:0`;
107
+ after.after(spacer);
108
+ return spacer;
109
+ });
110
+ return () => inserted.forEach((spacer) => spacer.remove());
111
+ };
107
112
  const wrapScene = (inner, holdTrailingMargin) => {
108
113
  if (!inner.parentNode) throw new Error(`StickyScrollTrigger: ${describeElement(inner)} is not attached to the document`);
109
114
  const container = document.createElement("div");
@@ -206,6 +211,41 @@ var StickyScrollTrigger = (function() {
206
211
  lifted.length = 0;
207
212
  };
208
213
  };
214
+ const classOf = (self) => self.constructor;
215
+ const isRefreshing = (cls) => cls?.isRefreshing === true;
216
+ const isScrolling = (cls) => Boolean(cls?.isScrolling?.());
217
+ const isScrollingOrUpdating = (cls) => Boolean(cls?.isScrolling?.() || cls?.isUpdating === true);
218
+ const addGsapListener = (cls, type, callback) => {
219
+ cls?.addEventListener?.(type, callback);
220
+ };
221
+ const removeGsapListener = (cls, type, callback) => {
222
+ cls?.removeEventListener?.(type, callback);
223
+ };
224
+ const refreshAll = (cls) => {
225
+ if (typeof cls?.refresh === "function") cls.refresh();
226
+ };
227
+ const scrollRecord = (cls, zero = false) => {
228
+ if (!cls || !isRefreshing(cls)) return null;
229
+ const scrollFunc = cls.getScrollFunc?.(window);
230
+ if (!(scrollFunc && typeof scrollFunc.rec === "number" && (zero || scrollFunc.rec))) return null;
231
+ const record = scrollFunc;
232
+ return {
233
+ read: () => record.rec,
234
+ write: (value) => {
235
+ record.rec = value;
236
+ }
237
+ };
238
+ };
239
+ const syncScrollCache = (cls) => {
240
+ const scrollFunc = cls?.getScrollFunc?.(window);
241
+ if (typeof scrollFunc !== "function") return;
242
+ const cached = scrollFunc();
243
+ if (typeof cached !== "number" || Math.abs(cached - window.scrollY) >= .5) scrollFunc(window.scrollY);
244
+ };
245
+ const revertAfterMeasure = (restore, result) => ({ render: (time) => {
246
+ result?.render?.(time);
247
+ restore();
248
+ } });
209
249
  const AUTO_MIN_DEPTH = 7;
210
250
  const MAX_CHAIN_IN_BAND = 4;
211
251
  const BUFFER_FLOOR_PX = 325;
@@ -281,7 +321,7 @@ var StickyScrollTrigger = (function() {
281
321
  let adoptedMidRefresh = false;
282
322
  let scannedThisTask = null;
283
323
  const gsapClasses = new Set();
284
- const gsapRefreshing = () => Array.from(gsapClasses).some((cls) => cls.isRefreshing === true);
324
+ const gsapRefreshing = () => Array.from(gsapClasses).some((cls) => isRefreshing(cls));
285
325
  const stateAt = (record, scroll) => {
286
326
  if (!record.demotable) return "in";
287
327
  if (scroll < record.lo - buffer) return "before";
@@ -359,22 +399,22 @@ var StickyScrollTrigger = (function() {
359
399
  queueMicrotask(onGsapRefreshDone);
360
400
  if (records.length) update(0);
361
401
  }
362
- return { render: restoreAfterGsapMeasure };
402
+ return revertAfterMeasure(restoreAfterGsapMeasure);
363
403
  };
364
404
  const adoptGsapClass = (cls) => {
365
405
  if (gsapClasses.has(cls)) return;
366
- if (cls.isRefreshing === true) adoptedMidRefresh = true;
406
+ if (isRefreshing(cls)) adoptedMidRefresh = true;
367
407
  gsapClasses.add(cls);
368
- cls.addEventListener?.("refresh", onGsapRefreshDone);
369
- cls.addEventListener?.("refreshInit", onGsapRefreshInit);
408
+ addGsapListener(cls, "refresh", onGsapRefreshDone);
409
+ addGsapListener(cls, "refreshInit", onGsapRefreshInit);
370
410
  };
371
411
  const dropGsapClassesLater = () => {
372
412
  if (!gsapClasses.size) return;
373
413
  queueMicrotask(() => {
374
414
  if (liveClients().length) return;
375
415
  gsapClasses.forEach((cls) => {
376
- cls.removeEventListener?.("refresh", onGsapRefreshDone);
377
- cls.removeEventListener?.("refreshInit", onGsapRefreshInit);
416
+ removeGsapListener(cls, "refresh", onGsapRefreshDone);
417
+ removeGsapListener(cls, "refreshInit", onGsapRefreshInit);
378
418
  });
379
419
  gsapClasses.clear();
380
420
  });
@@ -607,7 +647,14 @@ var StickyScrollTrigger = (function() {
607
647
  update(gsapPhase === "measuring" ? 0 : (gsapPhase === "restored" ? scrollBeforeGsapRefresh : null) ?? scroll);
608
648
  listen(true);
609
649
  };
610
- const takeGsapRefreshRestore = () => adoptedMidRefresh && gsapRefreshing() ? onGsapRefreshInit().render : null;
650
+ const takeGsapRefreshRestore = () => {
651
+ if (!adoptedMidRefresh || !gsapRefreshing()) return null;
652
+ onGsapRefreshInit();
653
+ return restoreAfterGsapMeasure;
654
+ };
655
+ const setGsapRefreshReturn = (scroll) => {
656
+ if (gsapPhase !== "idle") scrollBeforeGsapRefresh = scroll;
657
+ };
611
658
  const clearDormancy = clearTable;
612
659
  const releaseDormant = (elements) => {
613
660
  const released = new Set(elements);
@@ -638,6 +685,24 @@ var StickyScrollTrigger = (function() {
638
685
  if (liveClients().length) queueRebuild();
639
686
  else teardown();
640
687
  };
688
+ const commitSticky = (el, topPx) => {
689
+ el.style.position = "sticky";
690
+ el.style.top = `${topPx}px`;
691
+ };
692
+ const commitPosition = (el, saved) => {
693
+ el.style.position = saved.position;
694
+ el.style.top = saved.top;
695
+ };
696
+ const commitHeight = (el, height) => {
697
+ el.style.height = height;
698
+ };
699
+ const clearStickyForRead = (el) => {
700
+ el.style.position = "";
701
+ el.style.top = "";
702
+ };
703
+ const clearHeightForRead = (el) => {
704
+ el.style.height = "";
705
+ };
641
706
  const resolveMaybeFn = (value) => typeof value === "function" ? value() : value;
642
707
  const KEYWORD_FRACTIONS = {
643
708
  top: 0,
@@ -1288,7 +1353,6 @@ var StickyScrollTrigger = (function() {
1288
1353
  if (usesJsRamp) {
1289
1354
  jsRamps = ramps;
1290
1355
  jsHost = host;
1291
- applyJsRamp();
1292
1356
  return;
1293
1357
  }
1294
1358
  if (!sheet) {
@@ -1303,6 +1367,7 @@ var StickyScrollTrigger = (function() {
1303
1367
  stopRamps();
1304
1368
  };
1305
1369
  return {
1370
+ targets: () => targetSelector === null ? [] : Array.from(rootElement.querySelectorAll(targetSelector)),
1306
1371
  sync(scenes, host, measureNaturalTops) {
1307
1372
  const ramps = scenes.filter((scene) => scene.freezeEnd > scene.freezeStart).sort((a, b) => a.freezeStart - b.freezeStart);
1308
1373
  if (targetSelector === null || !ramps.length || !host) {
@@ -1334,6 +1399,9 @@ var StickyScrollTrigger = (function() {
1334
1399
  });
1335
1400
  written = next;
1336
1401
  },
1402
+ applyRamps() {
1403
+ applyJsRamp();
1404
+ },
1337
1405
  restore() {
1338
1406
  if (usesJsRamp) window.removeEventListener("scroll", applyJsRamp);
1339
1407
  release();
@@ -1363,6 +1431,11 @@ var StickyScrollTrigger = (function() {
1363
1431
  }
1364
1432
  return outermost;
1365
1433
  };
1434
+ const unbuildCover = (layer) => {
1435
+ if (!layer.wrapper) return;
1436
+ unwrapCover(layer.wrapper);
1437
+ layer.wrapper = null;
1438
+ };
1366
1439
  const unbuildStructure = (rootElement, layers, outermostContainer) => {
1367
1440
  if (outermostContainer) {
1368
1441
  outermostContainer.parentNode?.insertBefore(rootElement, outermostContainer);
@@ -1370,15 +1443,13 @@ var StickyScrollTrigger = (function() {
1370
1443
  }
1371
1444
  for (let i = layers.length - 1; i >= 0; i -= 1) {
1372
1445
  const layer = layers[i];
1373
- if (layer.kind === "cover" && layer.wrapper) unwrapCover(layer.wrapper);
1374
- }
1375
- layers.forEach((layer) => {
1376
- layer.wrapper = null;
1377
- if (layer.kind === "scene") {
1446
+ if (layer.kind === "cover") unbuildCover(layer);
1447
+ else {
1448
+ layer.wrapper = null;
1378
1449
  layer.container = null;
1379
1450
  layer.padding = null;
1380
1451
  }
1381
- });
1452
+ }
1382
1453
  };
1383
1454
  const resolveEndSpec = (rootElement, viewportHeight, layer, endResolved, ownIndex, endTriggerIndex) => {
1384
1455
  if (endResolved === null) return { mode: "auto" };
@@ -1440,6 +1511,8 @@ var StickyScrollTrigger = (function() {
1440
1511
  const end = resolveEndSpec(rootElement, viewportHeight, layer, endResolved, ownIndex, endTriggerIndex);
1441
1512
  const endTriggerInContainer = end.mode === "clause" && !end.measureLive && !endTriggerIsSelf;
1442
1513
  const start = resolveStartSpec(layer, startResolved, elementHeight, viewportHeight);
1514
+ const { end: endInput } = layer;
1515
+ const liveEnd = layer.kind === "scene" && typeof endInput === "function" && (end.mode === "dwell" || end.mode === "absolute") ? () => resolveEndSpec(rootElement, viewportHeight, layer, prefixSpacedRelativeEnd(startResolved, endInput()), ownIndex, endTriggerIndex) : void 0;
1443
1516
  return {
1444
1517
  kind: layer.kind,
1445
1518
  start,
@@ -1455,7 +1528,8 @@ var StickyScrollTrigger = (function() {
1455
1528
  height: end.mode === "clause" ? measureUsedHeight(layer.endTrigger) : 0,
1456
1529
  enclosedBy: endTriggerInContainer ? indicesWhere((trigger) => trigger.contains(layer.endTrigger)) : [],
1457
1530
  nests: endTriggerInContainer ? indicesWhere((other) => other !== layer.endTrigger && layer.endTrigger.contains(other)) : []
1458
- }
1531
+ },
1532
+ liveEnd
1459
1533
  };
1460
1534
  };
1461
1535
  const EXCLUDED_VAR_KEYS = [
@@ -1492,20 +1566,94 @@ var StickyScrollTrigger = (function() {
1492
1566
  const index = list.indexOf(item);
1493
1567
  if (index !== -1) list.splice(index, 1);
1494
1568
  };
1569
+ const suspendLiveEvaluations = (evaluation, resolving) => {
1570
+ const resumes = [];
1571
+ for (let current = evaluation; current; current = current.outer) resumes.unshift(current.suspend(resolving && current === evaluation));
1572
+ return () => resumes.forEach((resume) => resume());
1573
+ };
1574
+ const liveEndValue = (spec) => {
1575
+ if (spec.mode === "dwell") return spec.distancePx;
1576
+ return spec.mode === "absolute" ? spec.value : 0;
1577
+ };
1578
+ const LIVE_END_ROUNDS = 6;
1579
+ const LIVE_END_TOLERANCE_PX = .5;
1495
1580
  const hasDuplicateTrigger = (list, trigger) => list.some((existing) => existing.trigger === trigger);
1581
+ const pendingDisarms = new Set();
1582
+ const pendingKeeps = new Set();
1583
+ const pendingCatchUps = new Map();
1584
+ let unbuildCount = 0;
1585
+ let refreshedInGsapRefresh = null;
1586
+ const armedInstances = new Set();
1587
+ let liveEvaluation = null;
1588
+ let layerHandlerDepth = 0;
1589
+ const scrollBackTo = (top) => {
1590
+ if (Math.abs(window.scrollY - top) >= .5) window.scrollTo({
1591
+ top,
1592
+ behavior: "instant"
1593
+ });
1594
+ };
1595
+ const holdLiveEvaluationForGsapRefresh = (cls) => {
1596
+ const evaluation = liveEvaluation;
1597
+ if (!evaluation) return;
1598
+ const resume = suspendLiveEvaluations(evaluation, false);
1599
+ const record = scrollRecord(cls, true);
1600
+ if (record && Math.abs(record.read() - evaluation.scroll) >= .5) {
1601
+ scrollBackTo(Math.round(evaluation.scroll));
1602
+ syncScrollCache(cls);
1603
+ record.write(window.scrollY);
1604
+ setGsapRefreshReturn(window.scrollY);
1605
+ }
1606
+ const depth = layerHandlerDepth - 1;
1607
+ let held = true;
1608
+ liveEvaluation = null;
1609
+ const onRefresh = () => {
1610
+ if (!held || layerHandlerDepth > depth) return;
1611
+ held = false;
1612
+ resume();
1613
+ if (!evaluation.ended) liveEvaluation = evaluation;
1614
+ };
1615
+ addGsapListener(cls, "refresh", onRefresh);
1616
+ queueMicrotask(() => removeGsapListener(cls, "refresh", onRefresh));
1617
+ };
1618
+ const REST_POLL_MS = 100;
1619
+ const runEach = (...steps) => {
1620
+ let failure = null;
1621
+ steps.forEach((step) => {
1622
+ try {
1623
+ step();
1624
+ } catch (error) {
1625
+ if (!failure) failure = { error };
1626
+ else queueMicrotask(() => {
1627
+ throw error;
1628
+ });
1629
+ }
1630
+ });
1631
+ if (failure) throw failure.error;
1632
+ };
1496
1633
  var StickyScrollTrigger = class {
1497
1634
  #rootElement;
1498
1635
  #layers = [];
1499
1636
  #builtLayers = [];
1637
+ #measuredStructure = null;
1500
1638
  #coverRestoreByLayer = new WeakMap();
1501
1639
  #built = false;
1502
1640
  #dirty = false;
1503
1641
  #outermostContainer = null;
1504
1642
  #destroyed = false;
1505
- #rebuildScheduled = false;
1643
+ #depth = 0;
1644
+ #refreshInitNestedUsed = false;
1645
+ #measureAgain = false;
1646
+ #keepContentPending = false;
1647
+ #deferredRun = null;
1648
+ #restTimer = null;
1649
+ #pendingKeep = null;
1506
1650
  #scrollTriggerClass = null;
1507
1651
  #pinLayers = [];
1508
- #scrollMarginSync;
1652
+ #scrollMarginSync = null;
1653
+ #scrollMarginTargets;
1654
+ #armed = false;
1655
+ #dispatchObserver = null;
1656
+ #readsPageHeight = false;
1509
1657
  #dormancyClient = null;
1510
1658
  constructor(root, options = {}) {
1511
1659
  this.#rootElement = resolveRoot(root);
@@ -1521,15 +1669,101 @@ var StickyScrollTrigger = (function() {
1521
1669
  "always",
1522
1670
  "off"
1523
1671
  ].includes(optimization)) throw new Error(`StickyScrollTrigger: nestedStickyOptimization must be 'auto', 'always' or 'off', got ${String(optimization)}.`);
1524
- this.#scrollMarginSync = createScrollMarginSync(this.#rootElement, scrollMarginTargets);
1525
- if (optimization === "always" || optimization === "auto" && isWebKit()) {
1526
- this.#dormancyClient = {
1527
- mode: optimization,
1528
- ownedElements: () => this.#ownedStickyElements()
1529
- };
1530
- registerDormancyClient(this.#dormancyClient);
1672
+ this.#scrollMarginTargets = scrollMarginTargets;
1673
+ if (optimization === "always" || optimization === "auto" && isWebKit()) this.#dormancyClient = {
1674
+ mode: optimization,
1675
+ ownedElements: () => this.#ownedStickyElements()
1676
+ };
1677
+ }
1678
+ #arm() {
1679
+ if (pendingDisarms.delete(this)) this.#keepContentPending = false;
1680
+ if (this.#armed) return;
1681
+ this.#armed = true;
1682
+ armedInstances.add(this);
1683
+ pendingKeeps.forEach((keep) => {
1684
+ if (keep.owner.#overlaps(this)) keep.cancelled = true;
1685
+ });
1686
+ this.#scrollMarginSync = createScrollMarginSync(this.#rootElement, this.#scrollMarginTargets);
1687
+ if (this.#dormancyClient) registerDormancyClient(this.#dormancyClient);
1688
+ }
1689
+ #disarmIfEmpty() {
1690
+ if (this.#armed && !this.#destroyed && !this.#layers.length && !this.#pinLayers.length) {
1691
+ if (pendingDisarms.has(this)) return;
1692
+ const cls = this.#scrollTriggerClass;
1693
+ if (!isRefreshing(cls) && isScrollingOrUpdating(cls)) {
1694
+ pendingDisarms.add(this);
1695
+ queueMicrotask(() => this.#settleWhenAtRest());
1696
+ return;
1697
+ }
1698
+ this.#disarmKeepingContent(true, true);
1531
1699
  }
1532
1700
  }
1701
+ #flushOverlappingDisarms() {
1702
+ if (this.#destroyed) return;
1703
+ pendingDisarms.forEach((other) => {
1704
+ if (other !== this && other.#overlaps(this)) other.#flushPendingDisarmForRevert();
1705
+ });
1706
+ }
1707
+ #disarmKeepingContent(keepContent, onlyAtRest = false) {
1708
+ const position = keepContent && this.#built ? this.#naturalScrollTop(this.#builtLayers) : null;
1709
+ this.#keepContentPending = false;
1710
+ this.#disarm();
1711
+ if (!position) return;
1712
+ if (scrollRecord(this.#scrollTriggerClass)) {
1713
+ this.#keepContent(position);
1714
+ return;
1715
+ }
1716
+ if (this.#pendingKeep) pendingKeeps.delete(this.#pendingKeep);
1717
+ this.#pendingKeep = {
1718
+ owner: this,
1719
+ position,
1720
+ cls: this.#scrollTriggerClass,
1721
+ onlyAtRest,
1722
+ cancelled: false
1723
+ };
1724
+ pendingKeeps.add(this.#pendingKeep);
1725
+ queueMicrotask(() => this.#applyPendingKeep());
1726
+ }
1727
+ #applyPendingKeep() {
1728
+ const keep = this.#pendingKeep;
1729
+ if (!keep) return;
1730
+ this.#pendingKeep = null;
1731
+ pendingKeeps.delete(keep);
1732
+ if (keep.cancelled || keep.onlyAtRest && isScrolling(keep.cls)) return;
1733
+ this.#keepContent(keep.position, keep.cls);
1734
+ }
1735
+ #overlaps(other) {
1736
+ return this.#rootElement.contains(other.#rootElement) || other.#rootElement.contains(this.#rootElement);
1737
+ }
1738
+ #settleWhenAtRest() {
1739
+ if (this.#destroyed || this.#restTimer !== null) return;
1740
+ if (isScrolling(this.#scrollTriggerClass)) {
1741
+ this.#restTimer = setTimeout(() => {
1742
+ this.#restTimer = null;
1743
+ this.#settleWhenAtRest();
1744
+ }, REST_POLL_MS);
1745
+ return;
1746
+ }
1747
+ const run = this.#deferredRun;
1748
+ this.#deferredRun = null;
1749
+ runEach(() => this.#flushPendingDisarm(), () => run?.());
1750
+ }
1751
+ #flushPendingDisarm(keepContent = true, onlyAtRest = false) {
1752
+ if (pendingDisarms.delete(this) && !this.#destroyed && !this.#layers.length && !this.#pinLayers.length) this.#disarmKeepingContent(keepContent, onlyAtRest);
1753
+ }
1754
+ #flushPendingDisarmForRevert() {
1755
+ this.#flushPendingDisarm(!isScrolling(this.#scrollTriggerClass), true);
1756
+ }
1757
+ #disarm() {
1758
+ this.#armed = false;
1759
+ armedInstances.delete(this);
1760
+ unregisterDormancyClient(this.#dormancyClient);
1761
+ this.#scrollMarginSync?.restore();
1762
+ this.#scrollMarginSync = null;
1763
+ this.#restoreCoverLifts();
1764
+ this.#unbuild();
1765
+ this.#builtLayers = [];
1766
+ }
1533
1767
  #ownedStickyElements() {
1534
1768
  return [...this.#builtLayers.flatMap((layer) => layer.wrapper ? [layer.wrapper] : []), ...this.#wrappedPinTriggers()];
1535
1769
  }
@@ -1539,6 +1773,8 @@ var StickyScrollTrigger = (function() {
1539
1773
  #unbuild() {
1540
1774
  if (!this.#built) return;
1541
1775
  unbuildStructure(this.#rootElement, this.#builtLayers, this.#outermostContainer);
1776
+ unbuildCount += 1;
1777
+ this.#measuredStructure = null;
1542
1778
  this.#outermostContainer = null;
1543
1779
  this.#built = false;
1544
1780
  }
@@ -1548,39 +1784,151 @@ var StickyScrollTrigger = (function() {
1548
1784
  this.#built = true;
1549
1785
  this.#dirty = false;
1550
1786
  }
1787
+ #catchUp() {
1788
+ this.#flushPendingDisarm();
1789
+ this.#runRefresh();
1790
+ this.#applyPendingKeep();
1791
+ }
1551
1792
  #scheduleRebuild() {
1552
- if (this.#rebuildScheduled || this.#destroyed) return;
1553
- this.#rebuildScheduled = true;
1793
+ if (this.#destroyed) return;
1794
+ if (this.#built) this.#keepContentPending = true;
1795
+ if (pendingCatchUps.has(this)) return;
1796
+ const cls = this.#scrollTriggerClass;
1797
+ const pending = () => pendingCatchUps.get(this) === catchUpNow;
1798
+ const catchUpNow = () => {
1799
+ if (!pending()) return false;
1800
+ pendingCatchUps.delete(this);
1801
+ if (this.#destroyed) return false;
1802
+ try {
1803
+ this.#catchUp();
1804
+ } catch (error) {
1805
+ queueMicrotask(() => {
1806
+ throw error;
1807
+ });
1808
+ }
1809
+ return true;
1810
+ };
1811
+ pendingCatchUps.set(this, catchUpNow);
1812
+ const onRefreshInit = () => {
1813
+ if (!catchUpNow()) return void 0;
1814
+ const restoreDormancy = takeGsapRefreshRestore();
1815
+ return restoreDormancy ? revertAfterMeasure(restoreDormancy) : void 0;
1816
+ };
1817
+ addGsapListener(cls, "refreshInit", onRefreshInit);
1818
+ const run = () => {
1819
+ try {
1820
+ if (pending() && !this.#destroyed) refreshAll(this.#scrollTriggerClass);
1821
+ } finally {
1822
+ removeGsapListener(cls, "refreshInit", onRefreshInit);
1823
+ catchUpNow();
1824
+ }
1825
+ };
1554
1826
  queueMicrotask(() => {
1555
- this.#rebuildScheduled = false;
1556
- if (this.#destroyed) return;
1557
- this.refresh();
1558
- if (typeof this.#scrollTriggerClass?.refresh === "function") this.#scrollTriggerClass.refresh();
1827
+ if (pending() && !this.#destroyed && isScrolling(cls)) {
1828
+ const earlier = this.#deferredRun;
1829
+ this.#deferredRun = earlier ? () => runEach(earlier, run) : run;
1830
+ this.#settleWhenAtRest();
1831
+ return;
1832
+ }
1833
+ run();
1559
1834
  });
1560
1835
  }
1561
1836
  #captureScrollTriggerClass(self) {
1562
1837
  if (this.#destroyed) return;
1563
- this.#scrollTriggerClass = self.constructor;
1838
+ this.#scrollTriggerClass = classOf(self);
1564
1839
  }
1565
1840
  #createAutoRefreshHandler(userOnRefreshInit) {
1566
- return (self) => {
1841
+ const handle = (self) => {
1567
1842
  this.#captureScrollTriggerClass(self);
1843
+ if (isRefreshing(this.#scrollTriggerClass)) holdLiveEvaluationForGsapRefresh(this.#scrollTriggerClass);
1568
1844
  const result = userOnRefreshInit?.(self);
1845
+ const inGsapRefresh = isRefreshing(this.#scrollTriggerClass);
1846
+ let caughtUp = false;
1847
+ let refreshed = false;
1848
+ if (inGsapRefresh) {
1849
+ [...pendingCatchUps].forEach(([owner, catchUpNow]) => owner !== this && catchUpNow());
1850
+ caughtUp = pendingCatchUps.get(this)?.() === true;
1851
+ if (caughtUp) this.#dispatchObserver?.takeRecords();
1852
+ }
1853
+ const unchanged = inGsapRefresh && !userOnRefreshInit && !this.#dirty && (caughtUp || this.#dispatchObserver !== null && this.#dispatchObserver.takeRecords().length === 0);
1569
1854
  try {
1570
- this.refresh();
1855
+ if (!unchanged) {
1856
+ refreshed = true;
1857
+ this.#refreshFrom(true);
1858
+ }
1571
1859
  } catch (error) {
1572
1860
  queueMicrotask(() => {
1573
1861
  throw error;
1574
1862
  });
1575
1863
  }
1864
+ if (inGsapRefresh) {
1865
+ this.#watchGsapRefresh();
1866
+ if (refreshed || caughtUp) this.#remeasureEarlierInGsapRefresh();
1867
+ }
1576
1868
  const restoreDormancy = takeGsapRefreshRestore();
1577
- if (!restoreDormancy) return result;
1578
- return { render: (time) => {
1579
- result?.render?.(time);
1580
- restoreDormancy();
1581
- } };
1869
+ return restoreDormancy ? revertAfterMeasure(restoreDormancy, result) : result;
1870
+ };
1871
+ return (self) => {
1872
+ layerHandlerDepth += 1;
1873
+ try {
1874
+ return handle(self);
1875
+ } finally {
1876
+ layerHandlerDepth -= 1;
1877
+ }
1582
1878
  };
1583
1879
  }
1880
+ #watchGsapRefresh() {
1881
+ if (this.#dispatchObserver) {
1882
+ this.#dispatchObserver.takeRecords();
1883
+ return;
1884
+ }
1885
+ const observer = new MutationObserver(() => {});
1886
+ const cls = this.#scrollTriggerClass;
1887
+ const end = () => {
1888
+ observer.disconnect();
1889
+ if (this.#dispatchObserver === observer) this.#dispatchObserver = null;
1890
+ queueMicrotask(() => removeGsapListener(cls, "refresh", end));
1891
+ };
1892
+ observer.observe(document, {
1893
+ subtree: true,
1894
+ childList: true,
1895
+ attributes: true,
1896
+ characterData: true
1897
+ });
1898
+ this.#dispatchObserver = observer;
1899
+ addGsapListener(cls, "refresh", end);
1900
+ queueMicrotask(end);
1901
+ }
1902
+ #remeasureEarlierInGsapRefresh() {
1903
+ const refreshed = refreshedInGsapRefresh ?? new Map();
1904
+ if (!refreshedInGsapRefresh) {
1905
+ refreshedInGsapRefresh = refreshed;
1906
+ queueMicrotask(() => {
1907
+ if (refreshedInGsapRefresh === refreshed) refreshedInGsapRefresh = null;
1908
+ });
1909
+ }
1910
+ refreshed.set(this, this.#outsideReads());
1911
+ refreshed.forEach((reads, other) => {
1912
+ if (other.#destroyed || reads === other.#outsideReads()) return;
1913
+ try {
1914
+ other.#refreshFrom(true);
1915
+ } catch (error) {
1916
+ queueMicrotask(() => {
1917
+ throw error;
1918
+ });
1919
+ }
1920
+ other.#dispatchObserver?.takeRecords();
1921
+ refreshed.set(other, other.#outsideReads());
1922
+ });
1923
+ }
1924
+ #outsideReads() {
1925
+ const reads = [documentTop(this.#rootElement)];
1926
+ if (this.#readsPageHeight) reads.push(measureDocumentHeightWithoutPinRanges());
1927
+ [...this.#layers, ...this.#pinLayers].forEach(({ endTrigger }) => {
1928
+ if (!this.#rootElement.contains(endTrigger)) reads.push(documentTop(endTrigger));
1929
+ });
1930
+ return reads.join(",");
1931
+ }
1584
1932
  #wrapUnwrappedPins() {
1585
1933
  this.#pinLayers.forEach((layer) => {
1586
1934
  if (layer.outer) return;
@@ -1597,16 +1945,14 @@ var StickyScrollTrigger = (function() {
1597
1945
  range: inner.style.height
1598
1946
  }] : []);
1599
1947
  wrapped.forEach(({ outer, inner }) => {
1600
- outer.style.height = "";
1601
- inner.style.height = "";
1948
+ clearHeightForRead(outer);
1949
+ clearHeightForRead(inner);
1602
1950
  });
1603
1951
  const reserved = wrapped.map(({ outer }) => measureUsedHeight(outer));
1604
1952
  wrapped.forEach(({ outer }, index) => {
1605
- outer.style.height = `${reserved[index]}px`;
1606
- });
1607
- wrapped.forEach(({ inner, range }) => {
1608
- inner.style.height = range;
1953
+ commitHeight(outer, `${reserved[index]}px`);
1609
1954
  });
1955
+ wrapped.forEach(({ inner, range }) => commitHeight(inner, range));
1610
1956
  }
1611
1957
  #unwrapPinLayer(layer) {
1612
1958
  if (!layer.outer) return false;
@@ -1617,10 +1963,16 @@ var StickyScrollTrigger = (function() {
1617
1963
  return true;
1618
1964
  }
1619
1965
  #resetSceneCoverStickyState() {
1620
- return stripStickyPositions(this.#layers.flatMap(({ wrapper }) => wrapper ? [wrapper] : []));
1966
+ return stripStickyPositions(this.#builtLayers.flatMap(({ wrapper }) => wrapper ? [wrapper] : []));
1621
1967
  }
1622
1968
  #resetPinStickyState() {
1623
- return stripStickyPositions(this.#wrappedPinTriggers());
1969
+ const restores = this.#pinLayers.filter(({ inner }) => inner).map((layer) => ({
1970
+ layer,
1971
+ restore: stripStickyPositions([layer.trigger])
1972
+ }));
1973
+ return () => restores.forEach(({ layer, restore }) => {
1974
+ if (layer.inner) restore();
1975
+ });
1624
1976
  }
1625
1977
  #resetStickyState() {
1626
1978
  const restoreSceneCoverStickyState = this.#resetSceneCoverStickyState();
@@ -1630,43 +1982,63 @@ var StickyScrollTrigger = (function() {
1630
1982
  restoreSceneCoverStickyState();
1631
1983
  };
1632
1984
  }
1633
- #resetPinState() {
1634
- const snapshots = this.#pinLayers.map((layer) => ({
1985
+ #refreshGeometry(viewportHeight) {
1986
+ const active = this.#layers.filter((layer) => layer.wrapper !== null);
1987
+ const wrappers = active.flatMap(({ wrapper }) => wrapper ? [wrapper] : []);
1988
+ const savedWrappers = wrappers.map(captureInlinePosition);
1989
+ const pins = this.#pinLayers.map((layer) => ({
1635
1990
  layer,
1636
1991
  position: captureInlinePosition(layer.trigger),
1637
- height: layer.inner ? layer.inner.style.height : ""
1992
+ range: layer.inner ? layer.inner.style.height : ""
1638
1993
  }));
1639
- snapshots.forEach(({ layer }) => {
1640
- resetStickyPosition(layer.trigger);
1641
- if (layer.inner) layer.inner.style.height = "";
1642
- });
1643
- return () => {
1644
- snapshots.forEach(({ layer, position, height }) => {
1645
- restoreInlinePosition(layer.trigger, position);
1646
- if (layer.inner) layer.inner.style.height = height;
1994
+ wrappers.forEach(clearStickyForRead);
1995
+ pins.forEach(({ layer }) => clearStickyForRead(layer.trigger));
1996
+ let stickyTops;
1997
+ let marginTops;
1998
+ try {
1999
+ const measured = active.length ? this.#measureLayers(viewportHeight, active) : null;
2000
+ marginTops = this.#measureScrollMarginTargets(active);
2001
+ stickyTops = measured ? this.#planLayerPositions(viewportHeight, active, measured) : new Map();
2002
+ this.#readsPageHeight = pins.length > 0 || (measured?.measured.some(({ end }) => end.mode === "max") ?? false);
2003
+ } catch (error) {
2004
+ wrappers.forEach((wrapper, i) => commitPosition(wrapper, savedWrappers[i]));
2005
+ pins.forEach(({ layer, position }) => {
2006
+ if (layer.inner) commitPosition(layer.trigger, position);
1647
2007
  });
1648
- };
1649
- }
1650
- #refreshPins(viewportHeight) {
1651
- if (!this.#pinLayers.length) return;
1652
- const restoreSceneCoverStickyState = this.#resetSceneCoverStickyState();
1653
- const restorePinState = this.#resetPinState();
2008
+ throw error;
2009
+ }
2010
+ let plannedPins = [];
1654
2011
  try {
1655
- this.#refreshPinLayers(viewportHeight, measureDocumentHeightWithoutPinRanges());
2012
+ if (pins.length) {
2013
+ pins.forEach(({ layer }) => {
2014
+ if (layer.inner) clearHeightForRead(layer.inner);
2015
+ });
2016
+ plannedPins = this.#planPinLayers(viewportHeight, measureDocumentHeightWithoutPinRanges());
2017
+ }
1656
2018
  } catch (error) {
1657
- restorePinState();
2019
+ stickyTops.forEach((top, wrapper) => commitSticky(wrapper, top));
2020
+ pins.forEach(({ layer, position, range }) => {
2021
+ if (!layer.inner) return;
2022
+ commitPosition(layer.trigger, position);
2023
+ commitHeight(layer.inner, range);
2024
+ });
1658
2025
  throw error;
1659
- } finally {
1660
- restoreSceneCoverStickyState();
1661
2026
  }
1662
- }
1663
- #refreshPinLayers(viewportHeight, documentHeight) {
1664
- this.#pinLayers.forEach((layer) => {
2027
+ stickyTops.forEach((top, wrapper) => commitSticky(wrapper, top));
2028
+ plannedPins.forEach(({ layer, topPx, range }) => {
1665
2029
  if (!layer.inner) return;
2030
+ commitSticky(layer.trigger, topPx);
2031
+ commitHeight(layer.inner, `${range}px`);
2032
+ });
2033
+ this.#syncScrollMargins(marginTops);
2034
+ }
2035
+ #planPinLayers(viewportHeight, documentHeight) {
2036
+ return this.#pinLayers.flatMap((layer) => {
2037
+ if (!layer.inner) return [];
1666
2038
  const resolvedStart = resolveMaybeFn(layer.start);
1667
2039
  const resolvedEnd = prefixSpacedRelativeEnd(resolvedStart, resolveMaybeFn(layer.end));
1668
2040
  const classifiedEnd = classifyPosition(resolvedEnd);
1669
- if (classifiedEnd.kind === "max") throw new Error(`StickyScrollTrigger: createStickyPin's end "${resolvedEnd}" uses GSAP's 'max' keyword, which isn't supported here: the pin's own spacer height adds to the document's max scroll position, so it would depend on itself. Use a position clause against endTrigger, such as 'top top'.`);
2041
+ if (classifiedEnd.kind === "max") throw new Error(`StickyScrollTrigger: createStickyPin's end "${resolvedEnd}" uses GSAP's 'max' keyword, which isn't supported here. Use a position clause against endTrigger, such as 'top top'.`);
1670
2042
  const triggerTop = documentTop(layer.trigger);
1671
2043
  const triggerHeight = measureUsedHeight(layer.trigger);
1672
2044
  const triggerMarginBottom = parseFloat(getComputedStyle(layer.trigger).marginBottom) || 0;
@@ -1677,38 +2049,39 @@ var StickyScrollTrigger = (function() {
1677
2049
  const releaseScroll = resolvePinReleaseScroll(layer.endTrigger, classifiedEnd, toScroll(layer.trigger, triggerTop - topPx), viewportHeight, toScroll);
1678
2050
  const height = releaseScroll - (this.#rootElement.contains(layer.trigger) ? dwellConsumedAt(releaseScroll, this.#engagedWindows()) : 0) - triggerTop + topPx + triggerHeight + triggerMarginBottom;
1679
2051
  const room = documentHeight > 0 ? documentHeight - triggerTop : Infinity;
1680
- applyStickyPosition(layer.trigger, topPx);
1681
- layer.inner.style.height = `${Math.max(0, Math.min(height, room))}px`;
2052
+ return [{
2053
+ layer,
2054
+ topPx,
2055
+ range: Math.max(0, Math.min(height, room))
2056
+ }];
1682
2057
  });
1683
2058
  }
1684
- #refreshScenesAndCovers(viewportHeight) {
1685
- if (!this.#layers.length) return;
1686
- const active = this.#layers.filter((layer) => layer.wrapper !== null);
1687
- if (!active.length) return;
1688
- const restoreStickyState = this.#resetSceneCoverStickyState();
1689
- const restorePinStickyState = this.#resetPinStickyState();
1690
- try {
1691
- this.#planLayerPositions(viewportHeight, active);
1692
- } catch (error) {
1693
- restoreStickyState();
1694
- throw error;
1695
- } finally {
1696
- restorePinStickyState();
1697
- }
1698
- }
1699
- #planLayerPositions(viewportHeight, active) {
2059
+ #measureLayers(viewportHeight, active) {
1700
2060
  const structureTop = this.#outermostContainer ? documentTop(this.#outermostContainer) : 0;
2061
+ this.#measuredStructure = {
2062
+ top: structureTop,
2063
+ unbuilds: unbuildCount
2064
+ };
1701
2065
  const indexByTrigger = new Map();
1702
2066
  active.forEach((layer, index) => {
1703
2067
  indexByTrigger.set(layer.trigger, index);
1704
2068
  });
1705
- const measured = active.map((layer, ownIndex) => measureLayer(this.#rootElement, viewportHeight, layer, ownIndex, indexByTrigger));
2069
+ return {
2070
+ structureTop,
2071
+ measured: active.map((layer, ownIndex) => measureLayer(this.#rootElement, viewportHeight, layer, ownIndex, indexByTrigger))
2072
+ };
2073
+ }
2074
+ #planLayerPositions(viewportHeight, active, { structureTop, measured }) {
2075
+ const needsLiveRemeasure = measured.some((measurement) => measurement.end.mode === "clause" && measurement.end.measureLive);
2076
+ const needsMaxRemeasure = measured.some((measurement) => measurement.end.mode === "max");
1706
2077
  let documentMaxScroll = 0;
2078
+ let measureLive = false;
2079
+ const stickyTops = new Map();
1707
2080
  const applyLayers = () => planLayers(measured, {
1708
2081
  viewportHeight,
1709
2082
  structureTop,
1710
2083
  documentMaxScroll,
1711
- measureLiveEndTriggerTop: (index) => documentTop(active[index].endTrigger),
2084
+ measureLiveEndTriggerTop: (index) => measureLive ? documentTop(active[index].endTrigger) : 0,
1712
2085
  onPlanned: (index, plan) => {
1713
2086
  const layer = active[index];
1714
2087
  layer.freezeStart = plan.freezeStart;
@@ -1716,23 +2089,138 @@ var StickyScrollTrigger = (function() {
1716
2089
  layer.engagedStart = plan.engagedStart;
1717
2090
  layer.engagedEnd = plan.engagedEnd;
1718
2091
  if (!layer.wrapper) return;
1719
- applyStickyPosition(layer.wrapper, plan.stickyTop);
1720
- if (layer.kind === "scene" && layer.padding && plan.paddingHeight !== null) layer.padding.style.height = `${plan.paddingHeight}px`;
2092
+ stickyTops.set(layer.wrapper, plan.stickyTop);
2093
+ if (layer.kind === "scene" && layer.padding && plan.paddingHeight !== null) commitHeight(layer.padding, `${plan.paddingHeight}px`);
1721
2094
  }
1722
2095
  });
2096
+ this.#reevaluateLiveEnds(active, measured, () => {
2097
+ const heights = active.map(() => 0);
2098
+ planLayers(measured, {
2099
+ viewportHeight,
2100
+ structureTop,
2101
+ documentMaxScroll,
2102
+ measureLiveEndTriggerTop: () => 0,
2103
+ onPlanned: (index, plan) => {
2104
+ heights[index] = plan.paddingHeight ?? 0;
2105
+ }
2106
+ });
2107
+ return heights;
2108
+ });
1723
2109
  applyLayers();
1724
- const needsLiveRemeasure = measured.some((measurement) => measurement.end.mode === "clause" && measurement.end.measureLive);
1725
- const needsMaxRemeasure = measured.some((measurement) => measurement.end.mode === "max");
1726
- if (needsMaxRemeasure) documentMaxScroll = measureDocumentMaxScroll(viewportHeight);
2110
+ if (needsMaxRemeasure) documentMaxScroll = Math.max(0, measureDocumentHeightWithoutPinRanges() - viewportHeight);
2111
+ measureLive = true;
1727
2112
  if (needsLiveRemeasure || needsMaxRemeasure) applyLayers();
2113
+ return stickyTops;
2114
+ }
2115
+ #reevaluateLiveEnds(active, measured, planPaddings) {
2116
+ const live = measured.flatMap(({ liveEnd }, index) => liveEnd ? [{
2117
+ index,
2118
+ liveEnd
2119
+ }] : []);
2120
+ if (!live.length) return;
2121
+ const scrollBefore = window.scrollY;
2122
+ try {
2123
+ for (let round = 0; round < LIVE_END_ROUNDS; round += 1) {
2124
+ const planned = planPaddings();
2125
+ let moved = false;
2126
+ live.forEach(({ index, liveEnd }) => {
2127
+ const next = this.#evaluateLiveEnd(active, planned, index, liveEnd, scrollBefore);
2128
+ const current = measured[index].end;
2129
+ if (!next || next.mode !== current.mode) return;
2130
+ if (Math.abs(liveEndValue(next) - liveEndValue(current)) <= LIVE_END_TOLERANCE_PX) return;
2131
+ measured[index] = {
2132
+ ...measured[index],
2133
+ end: next
2134
+ };
2135
+ moved = true;
2136
+ });
2137
+ if (!moved) break;
2138
+ }
2139
+ } finally {
2140
+ scrollBackTo(scrollBefore);
2141
+ }
2142
+ }
2143
+ #evaluateLiveEnd(active, planned, index, liveEnd, scroll) {
2144
+ const spacers = active.flatMap((layer, k) => k < index && layer.kind === "scene" && planned[k] ? [{
2145
+ after: layer.trigger,
2146
+ height: planned[k]
2147
+ }] : []);
2148
+ const setUp = () => {
2149
+ const later = [...armedInstances].filter((other) => other !== this && compareDocumentOrder(this.#rootElement, other.#rootElement) < 0);
2150
+ const paddings = [this, ...later].flatMap((instance) => instance.#layers.flatMap((layer) => layer.kind === "scene" && layer.padding ? [layer.padding] : []));
2151
+ const heights = paddings.map((padding) => padding.style.height);
2152
+ paddings.forEach((padding) => commitHeight(padding, "0px"));
2153
+ const removeSpacers = insertSpacers(spacers);
2154
+ return () => {
2155
+ removeSpacers();
2156
+ paddings.forEach((padding, k) => {
2157
+ if (padding.style.height === "0px") commitHeight(padding, heights[k]);
2158
+ });
2159
+ };
2160
+ };
2161
+ let takeDown = () => {};
2162
+ let holds = 0;
2163
+ const evaluation = {
2164
+ resolved: false,
2165
+ ended: false,
2166
+ outer: liveEvaluation,
2167
+ scroll: liveEvaluation?.scroll ?? scroll,
2168
+ suspend: (resolving) => {
2169
+ if (resolving) evaluation.resolved = true;
2170
+ holds += 1;
2171
+ if (holds === 1) {
2172
+ takeDown();
2173
+ takeDown = () => {};
2174
+ }
2175
+ return () => {
2176
+ holds -= 1;
2177
+ if (holds === 0 && !evaluation.ended) takeDown = setUp();
2178
+ };
2179
+ }
2180
+ };
2181
+ try {
2182
+ takeDown = setUp();
2183
+ liveEvaluation = evaluation;
2184
+ const next = liveEnd();
2185
+ return evaluation.resolved ? null : next;
2186
+ } finally {
2187
+ evaluation.ended = true;
2188
+ liveEvaluation = evaluation.outer;
2189
+ takeDown();
2190
+ }
1728
2191
  }
1729
2192
  refresh() {
1730
- if (this.#destroyed) return;
2193
+ this.#refreshFrom(false);
2194
+ }
2195
+ #refreshFrom(refreshInit) {
2196
+ if (this.#depth > 0 && !this.#dirty) {
2197
+ if (!refreshInit) {
2198
+ this.#measureAgain = true;
2199
+ return;
2200
+ }
2201
+ if (this.#refreshInitNestedUsed) return;
2202
+ this.#refreshInitNestedUsed = true;
2203
+ }
2204
+ this.#runRefresh();
2205
+ }
2206
+ #runRefresh() {
2207
+ if (this.#depth > 0) this.#measureAgain = true;
2208
+ if (this.#destroyed || !this.#armed || pendingDisarms.has(this)) return;
1731
2209
  let failure = null;
2210
+ const position = this.#keepContentPending ? this.#naturalScrollTop(this.#builtLayers) : null;
2211
+ this.#keepContentPending = false;
2212
+ this.#depth += 1;
1732
2213
  try {
1733
2214
  this.#refreshLayout();
2215
+ if (this.#depth === 1 && this.#measureAgain && !this.#destroyed && this.#armed && !pendingDisarms.has(this)) this.#refreshLayout();
1734
2216
  } catch (error) {
1735
2217
  failure = { error };
2218
+ } finally {
2219
+ this.#depth -= 1;
2220
+ if (this.#depth === 0) {
2221
+ this.#refreshInitNestedUsed = false;
2222
+ this.#measureAgain = false;
2223
+ }
1736
2224
  }
1737
2225
  try {
1738
2226
  rebuildDormancy(this.#scrollTriggerClass);
@@ -1742,8 +2230,50 @@ var StickyScrollTrigger = (function() {
1742
2230
  throw error;
1743
2231
  });
1744
2232
  }
2233
+ this.#scrollMarginSync?.applyRamps();
2234
+ if (!failure && position !== null) this.#keepContent(position);
1745
2235
  if (failure) throw failure.error;
1746
2236
  }
2237
+ #naturalScrollTop(layers) {
2238
+ const measured = this.#measuredStructure;
2239
+ const moved = measured && this.#outermostContainer && measured.unbuilds !== unbuildCount ? documentTop(this.#outermostContainer) - measured.top : 0;
2240
+ const scroll = (scrollRecord(this.#scrollTriggerClass)?.read() ?? window.scrollY) - moved;
2241
+ const consumed = new Map();
2242
+ layers.forEach((layer) => {
2243
+ if (layer.kind !== "scene") return;
2244
+ consumed.set(layer.trigger, scroll > layer.engagedEnd ? Infinity : dwellConsumedAt(scroll, this.#engagedWindows([layer])));
2245
+ });
2246
+ return {
2247
+ natural: scroll - dwellConsumedAt(scroll, this.#engagedWindows(layers)) + moved,
2248
+ consumed
2249
+ };
2250
+ }
2251
+ #keepContent(position, cls = this.#scrollTriggerClass) {
2252
+ const target = this.#keptScrollTop(position);
2253
+ const record = scrollRecord(this.#scrollTriggerClass);
2254
+ if (record) {
2255
+ record.write(target);
2256
+ return;
2257
+ }
2258
+ if (isRefreshing(cls)) return;
2259
+ if (Math.abs(window.scrollY - target) >= .5) window.scrollTo({
2260
+ top: Math.round(target),
2261
+ behavior: "instant"
2262
+ });
2263
+ syncScrollCache(cls);
2264
+ }
2265
+ #keptScrollTop({ natural, consumed }) {
2266
+ let earlierDwell = 0;
2267
+ let target = natural;
2268
+ this.#builtLayers.flatMap((layer) => layer.kind === "scene" ? [layer] : []).sort((a, b) => a.engagedStart - b.engagedStart).forEach((layer) => {
2269
+ const dwell = layer.engagedEnd - layer.engagedStart;
2270
+ const before = consumed.get(layer.trigger);
2271
+ if (before !== void 0) target += Math.min(before, dwell);
2272
+ else if (layer.engagedStart < natural + earlierDwell - .05) target += dwell;
2273
+ earlierDwell += dwell;
2274
+ });
2275
+ return target;
2276
+ }
1747
2277
  #refreshLayout() {
1748
2278
  if (this.#dirty || !this.#built || isDomOrderStale(this.#layers)) {
1749
2279
  this.#unbuild();
@@ -1757,9 +2287,7 @@ var StickyScrollTrigger = (function() {
1757
2287
  this.#liftCovers();
1758
2288
  }
1759
2289
  const viewportHeight = this.#layers.length || this.#pinLayers.length ? measureViewportHeight() : 0;
1760
- this.#refreshScenesAndCovers(viewportHeight);
1761
- this.#refreshPins(viewportHeight);
1762
- this.#syncScrollMargins();
2290
+ this.#refreshGeometry(viewportHeight);
1763
2291
  }
1764
2292
  #coverLayers() {
1765
2293
  return this.#layers.filter((layer) => layer.kind === "cover");
@@ -1773,15 +2301,21 @@ var StickyScrollTrigger = (function() {
1773
2301
  this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(pin?.outer ?? layer.cover));
1774
2302
  });
1775
2303
  }
1776
- #syncScrollMargins() {
1777
- this.#scrollMarginSync.sync(this.#engagedWindows(), this.#outermostContainer, (targets) => {
1778
- if (!targets.length) return [];
1779
- const restoreStickyState = this.#resetStickyState();
1780
- const tops = targets.map((target) => documentTop(target));
1781
- restoreStickyState();
1782
- return tops;
2304
+ #syncScrollMargins(tops) {
2305
+ this.#scrollMarginSync?.sync(this.#engagedWindows(), this.#outermostContainer, (targets) => {
2306
+ const late = targets.filter((target) => !tops.has(target));
2307
+ if (late.length) {
2308
+ const restoreStickyState = this.#resetStickyState();
2309
+ late.forEach((target) => tops.set(target, documentTop(target)));
2310
+ restoreStickyState();
2311
+ }
2312
+ return targets.map((target) => tops.get(target));
1783
2313
  });
1784
2314
  }
2315
+ #measureScrollMarginTargets(active) {
2316
+ const targets = this.#scrollMarginSync && active.some(({ kind }) => kind === "scene") ? this.#scrollMarginSync.targets() : [];
2317
+ return new Map(targets.map((target) => [target, documentTop(target)]));
2318
+ }
1785
2319
  #assertNoExcludedVars(rest, context) {
1786
2320
  const found = EXCLUDED_VAR_KEYS.filter((key) => key in rest);
1787
2321
  if (found.length === 0) return;
@@ -1803,8 +2337,10 @@ var StickyScrollTrigger = (function() {
1803
2337
  if (this.#destroyed) throw new Error("StickyScrollTrigger: cannot register a new layer after destroy() has been called.");
1804
2338
  this.#assertTriggerAvailable(this.#layers, layer.trigger, `StickyScrollTrigger: ${describeElement(layer.trigger)} is already registered as a trigger for another layer. Each element can be used once per controller instance, across createStickyTrigger and createOverlapScroll: reusing one makes endTrigger resolution ambiguous.`);
1805
2339
  this.#assertTriggerAvailable(this.#pinLayers, layer.trigger, `StickyScrollTrigger: ${describeElement(layer.trigger)} is already registered as a pin trigger (createStickyPin). Using the same element as both a Scene/Cover trigger and a pin trigger wraps it twice and produces conflicting position:sticky behavior.`);
2340
+ this.#arm();
1806
2341
  this.#layers.push(layer);
1807
2342
  this.#dirty = true;
2343
+ if (this.#depth > 0) this.#measureAgain = true;
1808
2344
  return {
1809
2345
  ...rest,
1810
2346
  trigger: layer.trigger,
@@ -1813,9 +2349,14 @@ var StickyScrollTrigger = (function() {
1813
2349
  invalidateOnRefresh: rest.invalidateOnRefresh ?? true,
1814
2350
  onKill: (self) => {
1815
2351
  this.#captureScrollTriggerClass(self);
2352
+ if (!this.#layers.includes(layer)) {
2353
+ onKill?.(self);
2354
+ return;
2355
+ }
1816
2356
  removeItem(this.#layers, layer);
1817
2357
  this.#dirty = true;
1818
2358
  this.#scheduleRebuild();
2359
+ this.#disarmIfEmpty();
1819
2360
  onKill?.(self);
1820
2361
  },
1821
2362
  onRefreshInit: this.#createAutoRefreshHandler(rest.onRefreshInit)
@@ -1823,6 +2364,7 @@ var StickyScrollTrigger = (function() {
1823
2364
  }
1824
2365
  createStickyTrigger({ trigger: triggerInput, start = "0 0", end = "100% 0", endTrigger: endTriggerInput, onKill, ...rest }) {
1825
2366
  this.#assertNoExcludedVars(rest, "createStickyTrigger");
2367
+ this.#flushOverlappingDisarms();
1826
2368
  const trigger = resolveElement(triggerInput, "createStickyTrigger");
1827
2369
  this.#assertTriggerInsideRoot(trigger, "createStickyTrigger");
1828
2370
  const endTrigger = resolveEndTrigger(trigger, endTriggerInput, "createStickyTrigger");
@@ -1843,6 +2385,7 @@ var StickyScrollTrigger = (function() {
1843
2385
  }
1844
2386
  createOverlapScroll({ trigger: triggerInput, cover, start = "bottom bottom", end = null, endTrigger: endTriggerInput, onKill, ...rest }) {
1845
2387
  this.#assertNoExcludedVars(rest, "createOverlapScroll");
2388
+ this.#flushOverlappingDisarms();
1846
2389
  const trigger = resolveElement(triggerInput, "createOverlapScroll");
1847
2390
  this.#assertTriggerInsideRoot(trigger, "createOverlapScroll");
1848
2391
  const endTrigger = resolveEndTrigger(trigger, endTriggerInput, "createOverlapScroll");
@@ -1864,6 +2407,7 @@ var StickyScrollTrigger = (function() {
1864
2407
  };
1865
2408
  const vars = this.#registerLayer(layer, (self) => {
1866
2409
  this.#coverRestoreByLayer.get(layer)?.();
2410
+ unbuildCover(layer);
1867
2411
  onKill?.(self);
1868
2412
  }, rest);
1869
2413
  this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(coverElement));
@@ -1871,6 +2415,7 @@ var StickyScrollTrigger = (function() {
1871
2415
  }
1872
2416
  createStickyPin({ trigger: triggerInput, start, top, endTrigger: endTriggerInput, end = "bottom top", onKill, ...rest }) {
1873
2417
  this.#assertNoExcludedVars(rest, "createStickyPin");
2418
+ this.#flushOverlappingDisarms();
1874
2419
  if (this.#destroyed) throw new Error("StickyScrollTrigger: cannot register a new pin after destroy() has been called.");
1875
2420
  if (start !== void 0 && top !== void 0) throw new Error("StickyScrollTrigger: createStickyPin accepts either start or top, not both (top: 20 is start: 'top 20px'). Use top for a plain px distance from the viewport's top edge, start for anything else.");
1876
2421
  const trigger = resolveElement(triggerInput, "createStickyPin");
@@ -1887,7 +2432,9 @@ var StickyScrollTrigger = (function() {
1887
2432
  endTrigger,
1888
2433
  end
1889
2434
  };
2435
+ this.#arm();
1890
2436
  this.#pinLayers.push(layer);
2437
+ if (this.#depth > 0) this.#measureAgain = true;
1891
2438
  return {
1892
2439
  ...rest,
1893
2440
  trigger,
@@ -1895,12 +2442,21 @@ var StickyScrollTrigger = (function() {
1895
2442
  this.#captureScrollTriggerClass(self);
1896
2443
  removeItem(this.#pinLayers, layer);
1897
2444
  if (this.#unwrapPinLayer(layer)) this.#scheduleRebuild();
2445
+ this.#disarmIfEmpty();
1898
2446
  onKill?.(self);
1899
2447
  },
1900
2448
  onRefreshInit: this.#createAutoRefreshHandler(rest.onRefreshInit)
1901
2449
  };
1902
2450
  }
1903
2451
  resolveScrollPosition(elementInput, position) {
2452
+ const resume = liveEvaluation && suspendLiveEvaluations(liveEvaluation, true);
2453
+ try {
2454
+ return this.#resolveScrollPosition(elementInput, position);
2455
+ } finally {
2456
+ resume?.();
2457
+ }
2458
+ }
2459
+ #resolveScrollPosition(elementInput, position) {
1904
2460
  const element = resolveElement(elementInput, "resolveScrollPosition");
1905
2461
  const resolved = resolveMaybeFn(position);
1906
2462
  const viewportHeight = measureViewportHeight();
@@ -1923,8 +2479,8 @@ var StickyScrollTrigger = (function() {
1923
2479
  if (!this.#rootElement.contains(element)) return reachedAt;
1924
2480
  return reachedAt + dwellBeforeReach(reachedAt, this.#engagedWindows());
1925
2481
  }
1926
- #engagedWindows() {
1927
- return this.#layers.flatMap((layer) => layer.kind === "scene" ? [{
2482
+ #engagedWindows(layers = this.#builtLayers) {
2483
+ return layers.flatMap((layer) => layer.kind === "scene" ? [{
1928
2484
  freezeStart: layer.engagedStart,
1929
2485
  freezeEnd: layer.engagedEnd
1930
2486
  }] : []);
@@ -1940,6 +2496,7 @@ var StickyScrollTrigger = (function() {
1940
2496
  }
1941
2497
  createResolvedTrigger({ trigger: triggerInput, start = "top bottom", end = "bottom top", endTrigger: endTriggerInput, ...rest }) {
1942
2498
  this.#assertNoExcludedVars(rest, "createResolvedTrigger");
2499
+ this.#flushOverlappingDisarms();
1943
2500
  const trigger = resolveElement(triggerInput, "createResolvedTrigger");
1944
2501
  const endTrigger = resolveEndTrigger(trigger, endTriggerInput, "createResolvedTrigger");
1945
2502
  return {
@@ -1956,13 +2513,17 @@ var StickyScrollTrigger = (function() {
1956
2513
  }
1957
2514
  destroy() {
1958
2515
  if (this.#destroyed) return;
2516
+ runEach(() => this.#flushPendingDisarmForRevert(), () => this.#tearDown());
2517
+ }
2518
+ #tearDown() {
2519
+ if (this.#restTimer !== null) clearTimeout(this.#restTimer);
2520
+ this.#restTimer = null;
1959
2521
  this.#destroyed = true;
1960
- unregisterDormancyClient(this.#dormancyClient);
1961
- this.#scrollMarginSync.restore();
1962
- this.#restoreCoverLifts();
1963
- this.#unbuild();
2522
+ const run = this.#deferredRun;
2523
+ this.#deferredRun = null;
2524
+ run?.();
2525
+ if (this.#armed) this.#disarm();
1964
2526
  this.#layers.length = 0;
1965
- this.#builtLayers = [];
1966
2527
  this.#pinLayers.forEach((layer) => this.#unwrapPinLayer(layer));
1967
2528
  this.#pinLayers.length = 0;
1968
2529
  this.#scrollTriggerClass = null;