sticky-scroll-trigger 0.15.0 → 0.17.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.15.0
3
+ * StickyScrollTrigger v0.17.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
@@ -68,14 +68,18 @@ const measureDocumentHeightWithoutPinRanges = () => {
68
68
  };
69
69
  const measureDocumentMaxScroll = (viewportHeight) => Math.max(0, measureDocumentHeight() - viewportHeight);
70
70
  const measureBorderWidth = (borderStyle, width) => borderStyle === "none" || borderStyle === "hidden" ? 0 : parseFloat(width);
71
- const measureUsedHeight = (el) => {
72
- const rounded = el.offsetHeight;
71
+ const measureUsedSize = (el, axis) => {
72
+ const rounded = axis === "height" ? el.offsetHeight : el.offsetWidth;
73
73
  const style = getComputedStyle(el);
74
- const height = parseFloat(style.height);
75
- if (!Number.isFinite(height)) return rounded;
76
- const measured = style.boxSizing === "border-box" ? height : height + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + measureBorderWidth(style.borderTopStyle, style.borderTopWidth) + measureBorderWidth(style.borderBottomStyle, style.borderBottomWidth);
74
+ const size = parseFloat(style[axis]);
75
+ if (!Number.isFinite(size)) return rounded;
76
+ const [start, end] = axis === "height" ? ["Top", "Bottom"] : ["Left", "Right"];
77
+ const measured = style.boxSizing === "border-box" ? size : size + parseFloat(style[`padding${start}`]) + parseFloat(style[`padding${end}`]) + measureBorderWidth(style[`border${start}Style`], style[`border${start}Width`]) + measureBorderWidth(style[`border${end}Style`], style[`border${end}Width`]);
77
78
  return rounded > 0 && Math.abs(measured - rounded) >= 1 ? rounded : measured;
78
79
  };
80
+ const measureUsedHeight = (el) => measureUsedSize(el, "height");
81
+ const measureUsedWidth = (el) => measureUsedSize(el, "width");
82
+ const marginBoxHeight = (el, style) => measureUsedHeight(el) + parseFloat(style.marginTop) + parseFloat(style.marginBottom);
79
83
  const compareDocumentOrder = (a, b) => {
80
84
  const position = a.compareDocumentPosition(b);
81
85
  if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
@@ -83,16 +87,36 @@ const compareDocumentOrder = (a, b) => {
83
87
  return 0;
84
88
  };
85
89
  const resetStickyPosition = (el) => {
86
- el.style.position = "";
87
- el.style.top = "";
90
+ el.style.setProperty("position", "relative", "important");
91
+ el.style.setProperty("top", "auto", "important");
92
+ el.style.setProperty("bottom", "auto", "important");
93
+ };
94
+ const captureInline = (el, property) => ({
95
+ value: el.style.getPropertyValue(property),
96
+ priority: el.style.getPropertyPriority(property)
97
+ });
98
+ const restoreInline = (el, property, saved) => {
99
+ el.style.setProperty(property, saved.value, saved.priority);
88
100
  };
89
101
  const captureInlinePosition = (el) => ({
90
- position: el.style.position,
91
- top: el.style.top
102
+ position: captureInline(el, "position"),
103
+ top: captureInline(el, "top"),
104
+ bottom: captureInline(el, "bottom")
92
105
  });
93
106
  const restoreInlinePosition = (el, saved) => {
94
- el.style.position = saved.position;
95
- el.style.top = saved.top;
107
+ restoreInline(el, "position", saved.position);
108
+ restoreInline(el, "top", saved.top);
109
+ restoreIfWritten(el, "bottom", saved.bottom, "auto", "important");
110
+ };
111
+ const writeInline = (el, property, value, priority = "") => {
112
+ el.style.setProperty(property, value, priority);
113
+ return el.style.getPropertyValue(property);
114
+ };
115
+ const restoreIfWritten = (el, property, saved, written, priority = "") => {
116
+ const { style } = el;
117
+ if (style.getPropertyValue(property) !== written || style.getPropertyPriority(property) !== priority) return false;
118
+ restoreInline(el, property, saved);
119
+ return true;
96
120
  };
97
121
  const stripStickyPositions = (elements) => {
98
122
  const saved = elements.map(captureInlinePosition);
@@ -120,20 +144,72 @@ const createStructureElement = () => {
120
144
  el.style.setProperty("transition", "none", "important");
121
145
  return el;
122
146
  };
147
+ let movesUnderWay = 0;
148
+ const isMovingDom = () => movesUnderWay > 0;
149
+ const moveInto = (parent, node, before = null) => {
150
+ const target = parent;
151
+ movesUnderWay += 1;
152
+ try {
153
+ if (target.moveBefore && parent.isConnected && node.isConnected) try {
154
+ target.moveBefore(node, before);
155
+ return;
156
+ } catch {}
157
+ parent.insertBefore(node, before);
158
+ } finally {
159
+ movesUnderWay -= 1;
160
+ }
161
+ };
162
+ const transparentNodes = new WeakSet();
163
+ const isTransparent = (el, own) => transparentNodes.has(el) || own.has(el);
164
+ const logicalParent = (el, own) => {
165
+ let parent = el.parentElement;
166
+ while (parent && isTransparent(parent, own)) parent = parent.parentElement;
167
+ return parent;
168
+ };
169
+ const firstLogicalAt = (el, own) => {
170
+ if (!isTransparent(el, own)) return el;
171
+ for (const child of Array.from(el.children)) {
172
+ const found = firstLogicalAt(child, own);
173
+ if (found) return found;
174
+ }
175
+ return null;
176
+ };
177
+ const logicalNextSibling = (el, own) => {
178
+ for (let node = el;;) {
179
+ for (let sibling = node.nextElementSibling; sibling; sibling = sibling.nextElementSibling) {
180
+ const found = firstLogicalAt(sibling, own);
181
+ if (found) return found;
182
+ }
183
+ const parent = node.parentElement;
184
+ if (!parent || !isTransparent(parent, own)) return null;
185
+ node = parent;
186
+ }
187
+ };
188
+ const physicalHolder = (el) => {
189
+ let node = el;
190
+ while (node.parentElement && transparentNodes.has(node.parentElement)) node = node.parentElement;
191
+ return node;
192
+ };
123
193
  const wrapScene = (inner, holdTrailingMargin) => {
124
194
  if (!inner.parentNode) throw new Error(`StickyScrollTrigger: ${describeElement(inner)} is not attached to the document`);
125
195
  const container = createStructureElement();
126
196
  const wrapper = createStructureElement();
127
197
  const padding = createStructureElement();
198
+ [
199
+ container,
200
+ wrapper,
201
+ padding
202
+ ].forEach((node) => transparentNodes.add(node));
128
203
  padding.setAttribute("aria-hidden", "true");
129
204
  padding.style.pointerEvents = "none";
130
205
  inner.parentNode.insertBefore(container, inner);
131
206
  container.appendChild(wrapper);
132
- wrapper.appendChild(inner);
207
+ moveInto(wrapper, inner);
133
208
  container.appendChild(padding);
134
209
  if (holdTrailingMargin) {
135
210
  const sentinel = createStructureElement();
136
211
  sentinel.style.display = "flow-root";
212
+ transparentNodes.add(sentinel);
137
213
  wrapper.appendChild(sentinel);
138
214
  }
139
215
  return {
@@ -143,21 +219,22 @@ const wrapScene = (inner, holdTrailingMargin) => {
143
219
  };
144
220
  };
145
221
  const wrapCover = (trigger) => {
146
- const parent = trigger.parentNode;
222
+ const holder = physicalHolder(trigger);
223
+ const parent = holder.parentNode;
147
224
  if (!parent) throw new Error(`createOverlapScroll: trigger ${describeElement(trigger)} is not attached to the document`);
148
225
  const wrapper = createStructureElement();
149
226
  parent.insertBefore(wrapper, parent.firstChild);
150
227
  while (wrapper.nextSibling) {
151
228
  const node = wrapper.nextSibling;
152
- wrapper.appendChild(node);
153
- if (node === trigger) break;
229
+ moveInto(wrapper, node);
230
+ if (node === holder) break;
154
231
  }
155
232
  return wrapper;
156
233
  };
157
234
  const unwrapCover = (wrapper) => {
158
235
  const parent = wrapper.parentNode;
159
236
  if (!parent) return;
160
- while (wrapper.firstChild) parent.insertBefore(wrapper.firstChild, wrapper);
237
+ while (wrapper.firstChild) moveInto(parent, wrapper.firstChild, wrapper);
161
238
  wrapper.remove();
162
239
  };
163
240
  const wrapPin = (trigger) => {
@@ -165,25 +242,216 @@ const wrapPin = (trigger) => {
165
242
  const outer = createStructureElement();
166
243
  const inner = createStructureElement();
167
244
  outer.style.display = "flow-root";
245
+ transparentNodes.add(outer);
246
+ transparentNodes.add(inner);
168
247
  trigger.parentNode.insertBefore(outer, trigger);
169
248
  outer.appendChild(inner);
170
- inner.appendChild(trigger);
249
+ moveInto(inner, trigger);
171
250
  pinRanges.add(inner);
172
251
  return {
173
252
  outer,
174
253
  inner
175
254
  };
176
255
  };
256
+ const PIN_ITEM_PROPERTIES = [
257
+ "flexGrow",
258
+ "flexShrink",
259
+ "flexBasis",
260
+ "alignSelf",
261
+ "justifySelf",
262
+ "order",
263
+ "gridColumnStart",
264
+ "gridColumnEnd",
265
+ "gridRowStart",
266
+ "gridRowEnd",
267
+ "cssFloat",
268
+ "clear",
269
+ "verticalAlign"
270
+ ];
271
+ const layoutContainer = (outer) => {
272
+ let parent = outer.parentElement;
273
+ while (parent && getComputedStyle(parent).display === "contents") parent = parent.parentElement;
274
+ return parent;
275
+ };
276
+ const FLOATS = [
277
+ "left",
278
+ "right",
279
+ "inline-start",
280
+ "inline-end"
281
+ ];
282
+ const hasOwnBox = (style) => style.display !== "none" && style.display !== "contents";
283
+ const isBlockLevel = (style) => hasOwnBox(style) && !style.display.startsWith("inline");
284
+ const itemLayout = (outer, style) => {
285
+ if (!hasOwnBox(style)) return null;
286
+ const container = layoutContainer(outer);
287
+ const display = container ? getComputedStyle(container).display : "";
288
+ if (display.includes("flex")) return "flex";
289
+ if (display.includes("grid")) return "grid";
290
+ if (FLOATS.includes(style.cssFloat)) return "float";
291
+ return style.display.startsWith("inline-") ? "inline" : null;
292
+ };
293
+ const outerDisplay = (layout) => layout === "inline" ? "inline-block" : "flow-root";
294
+ const TRIGGER_BOX = [
295
+ "width",
296
+ "max-width",
297
+ "height",
298
+ "max-height",
299
+ "min-height",
300
+ "padding-top",
301
+ "padding-right",
302
+ "padding-bottom",
303
+ "padding-left",
304
+ "margin-top",
305
+ "margin-right",
306
+ "margin-bottom",
307
+ "margin-left"
308
+ ];
309
+ const BLOCK_BOX = [
310
+ "height",
311
+ "max-height",
312
+ "min-height"
313
+ ];
314
+ const PROBE_HEIGHT = "123456px";
315
+ const readHeldBox = (style, properties) => properties.map((property) => style.getPropertyValue(property.replace(/^m(ax|in)-/, "")));
316
+ const HELD_PRIORITY = "important";
317
+ const heldBoxes = new WeakMap();
318
+ const holdTriggerBox = (trigger, properties, values) => {
319
+ const authored = properties.map((property) => captureInline(trigger, property));
320
+ heldBoxes.set(trigger, {
321
+ properties,
322
+ authored,
323
+ written: properties.map((property, i) => writeInline(trigger, property, values[i], HELD_PRIORITY))
324
+ });
325
+ };
326
+ const releaseTriggerBox = (trigger) => {
327
+ const held = heldBoxes.get(trigger);
328
+ if (!held) return void 0;
329
+ held.properties.forEach((property, i) => {
330
+ restoreIfWritten(trigger, property, held.authored[i], held.written[i], HELD_PRIORITY);
331
+ });
332
+ heldBoxes.delete(trigger);
333
+ return held;
334
+ };
335
+ const fitPinsToItems = (pins) => {
336
+ const held = pins.map(({ trigger }) => releaseTriggerBox(trigger));
337
+ const enclosing = pins.map(({ trigger }) => pins.filter((other) => other.trigger !== trigger && other.trigger.contains(trigger)));
338
+ const reserved = pins.map(() => void 0);
339
+ try {
340
+ for (let depth = Math.max(0, ...enclosing.map(({ length }) => length)); depth >= 0; depth--) {
341
+ const indexes = pins.flatMap((_, i) => enclosing[i].length === depth ? [i] : []);
342
+ const around = new Set(indexes.flatMap((i) => enclosing[i]));
343
+ fitReleasedPins(indexes.map((i) => pins[i]), [...around]).forEach((height, j) => {
344
+ reserved[indexes[j]] = height;
345
+ });
346
+ }
347
+ return reserved;
348
+ } catch (error) {
349
+ pins.forEach(({ trigger }, i) => {
350
+ const box = held[i];
351
+ releaseTriggerBox(trigger);
352
+ if (box) holdTriggerBox(trigger, box.properties, box.written);
353
+ });
354
+ throw error;
355
+ }
356
+ };
357
+ const fitReleasedPins = (pins, around) => {
358
+ const styles = pins.map(({ trigger }) => getComputedStyle(trigger));
359
+ const layouts = pins.map(({ outer }, i) => itemLayout(outer, styles[i]));
360
+ const rendered = pins.map(({ trigger }) => trigger.getClientRects().length > 0);
361
+ const copied = styles.map((style, i) => PIN_ITEM_PROPERTIES.map((property) => layouts[i] || property === "clear" && isBlockLevel(style) ? style[property] : ""));
362
+ const measured = pins.flatMap((pin, index) => rendered[index] ? [{
363
+ ...pin,
364
+ index,
365
+ layout: layouts[index]
366
+ }] : []);
367
+ const aroundDisplays = around.map(({ outer, inner }) => [outer.style.display, inner.style.display]);
368
+ pins.forEach(({ outer }, i) => {
369
+ outer.style.width = "";
370
+ PIN_ITEM_PROPERTIES.forEach((property, j) => {
371
+ outer.style[property] = copied[i][j];
372
+ });
373
+ outer.style.display = rendered[i] ? "contents" : outerDisplay(layouts[i]);
374
+ });
375
+ [...measured, ...around].forEach(({ outer, inner }) => {
376
+ outer.style.display = "contents";
377
+ inner.style.display = "contents";
378
+ });
379
+ let boxes;
380
+ try {
381
+ boxes = measured.map(({ trigger, index, layout }) => {
382
+ const style = styles[index];
383
+ if (!layout) return { box: readHeldBox(style, BLOCK_BOX) };
384
+ return {
385
+ item: {
386
+ width: layout === "grid" ? void 0 : measureUsedWidth(trigger) + parseFloat(style.marginLeft) + parseFloat(style.marginRight),
387
+ height: marginBoxHeight(trigger, style)
388
+ },
389
+ box: readHeldBox(style, TRIGGER_BOX)
390
+ };
391
+ });
392
+ } finally {
393
+ measured.forEach(({ outer, inner, layout }) => {
394
+ outer.style.display = outerDisplay(layout);
395
+ inner.style.display = "";
396
+ });
397
+ around.forEach(({ outer, inner }, i) => {
398
+ [outer.style.display, inner.style.display] = aroundDisplays[i];
399
+ });
400
+ }
401
+ const inPx = boxes.map(({ box }) => box.every((value) => value.endsWith("px")));
402
+ const dependent = heightsFollowingInner(measured, boxes, inPx, styles);
403
+ const reserved = pins.map(() => void 0);
404
+ measured.forEach(({ outer, trigger, index, layout }, i) => {
405
+ const { item, box } = boxes[i];
406
+ if (!item) {
407
+ if (inPx[i] && dependent.has(i)) holdTriggerBox(trigger, BLOCK_BOX, box);
408
+ return;
409
+ }
410
+ const { width, height } = item;
411
+ if (!Number.isFinite(height) || width !== void 0 && !Number.isFinite(width)) return;
412
+ if (layout === "flex") outer.style.flex = "0 0 auto";
413
+ if (width !== void 0) outer.style.width = `${width}px`;
414
+ reserved[index] = height;
415
+ if (inPx[i]) holdTriggerBox(trigger, TRIGGER_BOX, box);
416
+ });
417
+ return reserved;
418
+ };
419
+ const heightsFollowingInner = (measured, boxes, inPx, styles) => {
420
+ const blocks = measured.flatMap((pin, i) => !boxes[i].item && inPx[i] ? [{
421
+ ...pin,
422
+ i
423
+ }] : []);
424
+ const dependent = new Set(probeInner(blocks, () => PROBE_HEIGHT, boxes));
425
+ const capped = blocks.filter(({ index, i }) => !dependent.has(i) && styles[index].maxHeight.includes("%"));
426
+ probeInner(capped, ({ i }) => boxes[i].box[0], boxes).forEach((i) => dependent.add(i));
427
+ return dependent;
428
+ };
429
+ const probeInner = (blocks, height, boxes) => {
430
+ const saved = blocks.map(({ outer, inner }) => [outer.style.height, inner.style.height]);
431
+ const outerHeights = blocks.map(({ outer }) => getComputedStyle(outer).height);
432
+ blocks.forEach((block, j) => {
433
+ block.outer.style.height = outerHeights[j];
434
+ block.inner.style.height = height(block);
435
+ });
436
+ try {
437
+ return blocks.flatMap(({ trigger, i }) => getComputedStyle(trigger).height !== boxes[i].box[0] ? [i] : []);
438
+ } finally {
439
+ blocks.forEach(({ outer, inner }, j) => {
440
+ [outer.style.height, inner.style.height] = saved[j];
441
+ });
442
+ }
443
+ };
177
444
  const unwrapPin = (outer, trigger, saved) => {
178
445
  const parent = outer.parentNode;
179
446
  restoreInlinePosition(trigger, saved);
180
- if (parent) parent.insertBefore(trigger, outer);
447
+ releaseTriggerBox(trigger);
448
+ if (parent) moveInto(parent, trigger, outer);
181
449
  if (outer.firstElementChild instanceof HTMLElement) pinRanges.delete(outer.firstElementChild);
182
450
  outer.remove();
183
451
  };
184
452
  const LIFT_VALUES = {
185
- position: "relative",
186
- zIndex: "1"
453
+ "position": "relative",
454
+ "z-index": "1"
187
455
  };
188
456
  const liftStates = new WeakMap();
189
457
  const liftAboveStickyWrapper = (cover) => {
@@ -195,12 +463,14 @@ const liftAboveStickyWrapper = (cover) => {
195
463
  if (existing) existing.count += 1;
196
464
  else {
197
465
  const computed = getComputedStyle(element);
198
- const applied = [];
199
- if (computed.position === "static") applied.push("position");
200
- if (computed.zIndex === "auto") applied.push("zIndex");
201
- applied.forEach((property) => {
202
- element.style[property] = LIFT_VALUES[property];
203
- });
466
+ const properties = [];
467
+ if (computed.position === "static") properties.push("position");
468
+ if (computed.zIndex === "auto") properties.push("z-index");
469
+ const applied = properties.map((property) => ({
470
+ property,
471
+ authored: captureInline(element, property),
472
+ written: writeInline(element, property, LIFT_VALUES[property])
473
+ }));
204
474
  liftStates.set(element, {
205
475
  count: 1,
206
476
  applied
@@ -214,8 +484,8 @@ const liftAboveStickyWrapper = (cover) => {
214
484
  if (!state) return;
215
485
  state.count -= 1;
216
486
  if (state.count > 0) return;
217
- state.applied.forEach((property) => {
218
- if (el.style[property] === LIFT_VALUES[property]) el.style[property] = "";
487
+ state.applied.forEach(({ property, authored, written }) => {
488
+ restoreIfWritten(el, property, authored, written);
219
489
  });
220
490
  liftStates.delete(el);
221
491
  });
@@ -629,15 +899,15 @@ const rebuildDormancy = (scrollTriggerClass) => {
629
899
  return;
630
900
  }
631
901
  const toMeasure = all.filter((r) => owned.has(r.el) || holdsOwned.has(r) || r.state !== "in");
632
- const authorStyle = new Map(toMeasure.filter((r) => !owned.has(r.el) && r.state === "in").map(({ el }) => [el, el.getAttribute("style")]));
902
+ const authorStyle = new Map(toMeasure.filter((r) => !owned.has(r.el) && r.state === "in").map(({ el }) => [el, el.hasAttribute("style") ? captureInline(el, "position") : null]));
633
903
  const restorePositions = () => toMeasure.forEach((record) => {
634
904
  if (!authorStyle.has(record.el)) {
635
905
  promote(record, true);
636
906
  return;
637
907
  }
638
908
  const saved = authorStyle.get(record.el);
639
- if (saved === null || saved === void 0) record.el.removeAttribute("style");
640
- else record.el.setAttribute("style", saved);
909
+ if (saved) restoreInline(record.el, "position", saved);
910
+ else record.el.removeAttribute("style");
641
911
  });
642
912
  toMeasure.forEach(({ el }) => {
643
913
  el.style.position = "static";
@@ -717,12 +987,14 @@ const commitSticky = (el, topPx) => {
717
987
  el.style.top = `${topPx}px`;
718
988
  };
719
989
  const commitPosition = (el, saved) => {
720
- el.style.position = saved.position;
721
- el.style.top = saved.top;
990
+ restoreInlinePosition(el, saved);
722
991
  };
723
992
  const commitHeight = (el, height) => {
724
993
  el.style.height = height;
725
994
  };
995
+ const commitCssText = (el, cssText) => {
996
+ el.style.cssText = cssText;
997
+ };
726
998
  const commitInert = (wrapper, padding) => {
727
999
  wrapper.style.position = "";
728
1000
  wrapper.style.top = "";
@@ -735,6 +1007,209 @@ const clearStickyForRead = (el) => {
735
1007
  const clearHeightForRead = (el) => {
736
1008
  el.style.height = "";
737
1009
  };
1010
+ let scrollZeroReturn = null;
1011
+ const scrollZeroReturnTop = () => scrollZeroReturn;
1012
+ const moveScrollZeroReturn = (top) => {
1013
+ scrollZeroReturn = top;
1014
+ };
1015
+ let ownScrollTop = null;
1016
+ let ownScrollAt = -Infinity;
1017
+ const markOwnScroll = (fromRest) => {
1018
+ ownScrollTop = fromRest ? window.scrollY : null;
1019
+ ownScrollAt = performance.now();
1020
+ };
1021
+ const isOwnTripOnly = () => {
1022
+ if (ownScrollTop !== null && (Math.abs(window.scrollY - ownScrollTop) >= .5 || performance.now() - ownScrollAt >= 500)) ownScrollTop = null;
1023
+ return ownScrollTop !== null;
1024
+ };
1025
+ const isPageScrolling = (cls) => (isRefreshing(cls) ? isScrolling(cls) : isScrollingOrUpdating(cls)) && !isOwnTripOnly();
1026
+ const isUserScrolling = (cls) => isScrolling(cls) && !isOwnTripOnly();
1027
+ const scrollBackTo = (top) => {
1028
+ if (Math.abs(window.scrollY - top) >= .5) window.scrollTo({
1029
+ top,
1030
+ behavior: "instant"
1031
+ });
1032
+ };
1033
+ const enterScrollZero = (cls) => {
1034
+ if (scrollZeroReturn !== null) {
1035
+ scrollBackTo(0);
1036
+ dormancyAtScrollZero();
1037
+ return () => {};
1038
+ }
1039
+ const fromRest = !isUserScrolling(cls);
1040
+ scrollZeroReturn = window.scrollY;
1041
+ dormancyAtScrollZero();
1042
+ window.scrollTo({
1043
+ top: 0,
1044
+ behavior: "instant"
1045
+ });
1046
+ return () => {
1047
+ const back = scrollZeroReturn ?? 0;
1048
+ scrollZeroReturn = null;
1049
+ window.scrollTo({
1050
+ top: back,
1051
+ behavior: "instant"
1052
+ });
1053
+ markOwnScroll(fromRest);
1054
+ syncScrollCache(cls);
1055
+ dormancyAfterScrollZero(window.scrollY);
1056
+ };
1057
+ };
1058
+ let gsapAtZero = false;
1059
+ let gsapZeroReturn = 0;
1060
+ const gsapScrollToZero = (cls) => {
1061
+ if (gsapAtZero) {
1062
+ const back = window.scrollY;
1063
+ if (back === 0) return () => {};
1064
+ const fromRest = !isUserScrolling(cls);
1065
+ window.scrollTo({
1066
+ top: 0,
1067
+ behavior: "instant"
1068
+ });
1069
+ return () => {
1070
+ window.scrollTo({
1071
+ top: back,
1072
+ behavior: "instant"
1073
+ });
1074
+ markOwnScroll(fromRest);
1075
+ };
1076
+ }
1077
+ const record = scrollRecord(cls, true);
1078
+ if (!record || record.read() === 0) return () => {};
1079
+ const fromRest = !isUserScrolling(cls);
1080
+ gsapZeroReturn = record.read();
1081
+ dormancyAtScrollZero();
1082
+ window.scrollTo({
1083
+ top: 0,
1084
+ behavior: "instant"
1085
+ });
1086
+ gsapAtZero = true;
1087
+ return () => {
1088
+ gsapAtZero = false;
1089
+ window.scrollTo({
1090
+ top: record.read(),
1091
+ behavior: "instant"
1092
+ });
1093
+ markOwnScroll(fromRest);
1094
+ };
1095
+ };
1096
+ const isGsapAtZero = () => gsapAtZero;
1097
+ const realScroll = () => scrollZeroReturn ?? (gsapAtZero ? gsapZeroReturn : null);
1098
+ const mayBeStuckAround = (from, own) => {
1099
+ const seen = new Set();
1100
+ const moved = movedPastFreeze();
1101
+ return from.some((el) => {
1102
+ for (let current = el; current && !seen.has(current) && current !== document.body && current !== document.documentElement; current = current.parentElement) {
1103
+ seen.add(current);
1104
+ if (own.has(current)) continue;
1105
+ if (moved.has(current) || getComputedStyle(current).position === "sticky") return true;
1106
+ }
1107
+ return false;
1108
+ });
1109
+ };
1110
+ const afterFunction = () => {
1111
+ if (gsapAtZero || scrollZeroReturn !== null) scrollBackTo(0);
1112
+ if (scrollZeroReturn !== null) dormancyAtScrollZero();
1113
+ };
1114
+ const withAfterFunction = (value) => {
1115
+ if (typeof value !== "function") return value;
1116
+ return () => {
1117
+ try {
1118
+ return value();
1119
+ } finally {
1120
+ afterFunction();
1121
+ }
1122
+ };
1123
+ };
1124
+ const suspendLiveEvaluations = (evaluation, resolving) => {
1125
+ const resumes = [];
1126
+ for (let current = evaluation; current; current = current.outer) resumes.unshift(current.suspend(resolving && current === evaluation));
1127
+ return () => resumes.forEach((resume) => resume());
1128
+ };
1129
+ let liveEvaluation = null;
1130
+ let layerHandlerDepth = 0;
1131
+ const asLayerHandler = (handle) => {
1132
+ layerHandlerDepth += 1;
1133
+ try {
1134
+ return handle();
1135
+ } finally {
1136
+ layerHandlerDepth -= 1;
1137
+ }
1138
+ };
1139
+ const inLayerHandler = () => layerHandlerDepth > 0;
1140
+ const holdLiveEvaluationForGsapRefresh = (cls) => {
1141
+ const evaluation = liveEvaluation;
1142
+ const real = realScroll();
1143
+ if (real !== null && !evaluation) {
1144
+ const zeroRecord = scrollRecord(cls, true);
1145
+ if (zeroRecord && Math.abs(zeroRecord.read() - real) >= .5) {
1146
+ zeroRecord.write(real);
1147
+ setGsapRefreshReturn(real);
1148
+ }
1149
+ }
1150
+ if (!evaluation) return;
1151
+ const resume = suspendLiveEvaluations(evaluation, false);
1152
+ const record = scrollRecord(cls, true);
1153
+ if (record && Math.abs(record.read() - evaluation.scroll) >= .5) {
1154
+ scrollBackTo(Math.round(evaluation.scroll));
1155
+ syncScrollCache(cls);
1156
+ const unclamped = window.scrollY >= Math.round(evaluation.scroll) - .5;
1157
+ const reached = realScroll() !== null && unclamped ? evaluation.scroll : window.scrollY;
1158
+ record.write(reached);
1159
+ setGsapRefreshReturn(reached);
1160
+ }
1161
+ const depth = layerHandlerDepth - 1;
1162
+ let held = true;
1163
+ liveEvaluation = null;
1164
+ const onRefresh = () => {
1165
+ if (!held || layerHandlerDepth > depth) return;
1166
+ held = false;
1167
+ resume();
1168
+ if (!evaluation.ended) liveEvaluation = evaluation;
1169
+ };
1170
+ addGsapListener(cls, "refresh", onRefresh);
1171
+ queueMicrotask(() => removeGsapListener(cls, "refresh", onRefresh));
1172
+ };
1173
+ const evaluateLive = (setUp, scroll, call) => {
1174
+ let takeDown = () => {};
1175
+ let holds = 0;
1176
+ const evaluation = {
1177
+ resolved: false,
1178
+ ended: false,
1179
+ outer: liveEvaluation,
1180
+ scroll: liveEvaluation?.scroll ?? scroll,
1181
+ suspend: (resolving) => {
1182
+ if (resolving) evaluation.resolved = true;
1183
+ holds += 1;
1184
+ if (holds === 1) {
1185
+ takeDown();
1186
+ takeDown = () => {};
1187
+ }
1188
+ return () => {
1189
+ holds -= 1;
1190
+ if (holds === 0 && !evaluation.ended) takeDown = setUp();
1191
+ };
1192
+ }
1193
+ };
1194
+ try {
1195
+ takeDown = setUp();
1196
+ liveEvaluation = evaluation;
1197
+ const next = call();
1198
+ return evaluation.resolved ? null : next;
1199
+ } finally {
1200
+ evaluation.ended = true;
1201
+ liveEvaluation = evaluation.outer;
1202
+ takeDown();
1203
+ }
1204
+ };
1205
+ const resolveOutsideEvaluation = (read) => {
1206
+ const resume = liveEvaluation && suspendLiveEvaluations(liveEvaluation, true);
1207
+ try {
1208
+ return read();
1209
+ } finally {
1210
+ resume?.();
1211
+ }
1212
+ };
738
1213
  const resolveMaybeFn = (value) => typeof value === "function" ? value() : value;
739
1214
  const KEYWORD_FRACTIONS = {
740
1215
  top: 0,
@@ -1324,6 +1799,8 @@ const planLayers = (measurements, deps) => {
1324
1799
  return finalPlans;
1325
1800
  };
1326
1801
  const OFFSET_PROPERTY = "--sst-scroll-margin-top-offset";
1802
+ const PRIORITY = "important";
1803
+ const snapshots = new WeakMap();
1327
1804
  let nextInstanceSuffix = 0;
1328
1805
  const supportsScrollDrivenAnimations = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("animation-timeline", "scroll()");
1329
1806
  const supportsConstructedStyleSheets = typeof CSSStyleSheet === "function" && typeof CSSStyleSheet.prototype.replaceSync === "function" && typeof document !== "undefined" && Array.isArray(document.adoptedStyleSheets);
@@ -1347,7 +1824,6 @@ const buildStylesheet = (instanceId, scenes) => {
1347
1824
  const createScrollMarginSync = (rootElement, targetSelector) => {
1348
1825
  const instanceId = `sst${nextInstanceSuffix++}`;
1349
1826
  const usesJsRamp = !usesCssRamp && targetSelector !== null;
1350
- const snapshots = new WeakMap();
1351
1827
  let written = new Set();
1352
1828
  let sheet = null;
1353
1829
  let animationHost = null;
@@ -1364,7 +1840,7 @@ const createScrollMarginSync = (rootElement, targetSelector) => {
1364
1840
  if (usesJsRamp) window.addEventListener("scroll", onScroll, { passive: true });
1365
1841
  const restoreTarget = (target) => {
1366
1842
  const snapshot = snapshots.get(target);
1367
- target.style.scrollMarginTop = snapshot ? snapshot.inline : "";
1843
+ if (snapshot?.owner === instanceId) restoreIfWritten(target, "scroll-margin-top", snapshot.authored, snapshot.written, PRIORITY);
1368
1844
  };
1369
1845
  const stopRamps = () => {
1370
1846
  if (sheet) {
@@ -1411,8 +1887,12 @@ const createScrollMarginSync = (rootElement, targetSelector) => {
1411
1887
  const naturalTops = measureNaturalTops(targets);
1412
1888
  targets.forEach((target) => {
1413
1889
  const existing = snapshots.get(target);
1414
- if (!existing) snapshots.set(target, { inline: target.style.scrollMarginTop });
1415
- else if (written.has(target)) target.style.scrollMarginTop = existing.inline;
1890
+ if (existing && restoreIfWritten(target, "scroll-margin-top", existing.authored, existing.written, PRIORITY)) return;
1891
+ snapshots.set(target, {
1892
+ authored: captureInline(target, "scroll-margin-top"),
1893
+ written: "",
1894
+ owner: instanceId
1895
+ });
1416
1896
  });
1417
1897
  const consumed = ramps.map((_, index) => `var(--${instanceId}-c${index}, 0px)`).join(" + ");
1418
1898
  targets.forEach((target, targetIndex) => {
@@ -1423,7 +1903,9 @@ const createScrollMarginSync = (rootElement, targetSelector) => {
1423
1903
  earlierDwell += freezeEnd - freezeStart;
1424
1904
  return `clamp(0px, (${margin}px - var(${OFFSET_PROPERTY}, 0px)) * 1000000, ${freezeEnd - freezeStart}px)`;
1425
1905
  }).join(" + ");
1426
- target.style.scrollMarginTop = `calc(${authorPx}px + var(${OFFSET_PROPERTY}, 0px) + ${consumed} - (${lag}))`;
1906
+ const snapshot = snapshots.get(target);
1907
+ snapshot.written = writeInline(target, "scroll-margin-top", `calc(${authorPx}px + var(${OFFSET_PROPERTY}, 0px) + ${consumed} - (${lag}))`, PRIORITY);
1908
+ snapshot.owner = instanceId;
1427
1909
  });
1428
1910
  const next = new Set(targets);
1429
1911
  written.forEach((target) => {
@@ -1470,7 +1952,8 @@ const unbuildCover = (layer) => {
1470
1952
  };
1471
1953
  const unbuildStructure = (rootElement, layers, outermostContainer) => {
1472
1954
  if (outermostContainer) {
1473
- outermostContainer.parentNode?.insertBefore(rootElement, outermostContainer);
1955
+ const parent = outermostContainer.parentNode;
1956
+ if (parent) moveInto(parent, rootElement, outermostContainer);
1474
1957
  outermostContainer.remove();
1475
1958
  }
1476
1959
  for (let i = layers.length - 1; i >= 0; i -= 1) {
@@ -1598,11 +2081,6 @@ const removeItem = (list, item) => {
1598
2081
  const index = list.indexOf(item);
1599
2082
  if (index !== -1) list.splice(index, 1);
1600
2083
  };
1601
- const suspendLiveEvaluations = (evaluation, resolving) => {
1602
- const resumes = [];
1603
- for (let current = evaluation; current; current = current.outer) resumes.unshift(current.suspend(resolving && current === evaluation));
1604
- return () => resumes.forEach((resume) => resume());
1605
- };
1606
2084
  const liveEndValue = (spec) => {
1607
2085
  if (spec.mode === "dwell") return spec.distancePx;
1608
2086
  return spec.mode === "absolute" ? spec.value : 0;
@@ -1616,152 +2094,9 @@ const pendingCatchUps = new Map();
1616
2094
  let structureChanges = 0;
1617
2095
  let refreshedInGsapRefresh = null;
1618
2096
  const armedInstances = new Set();
1619
- let scrollZeroReturn = null;
1620
2097
  let lastScrollTriggerClass = null;
1621
- let ownScrollTop = null;
1622
- let ownScrollAt = -Infinity;
1623
- const markOwnScroll = (fromRest) => {
1624
- ownScrollTop = fromRest ? window.scrollY : null;
1625
- ownScrollAt = performance.now();
1626
- };
1627
- const isOwnTripOnly = () => {
1628
- if (ownScrollTop !== null && (Math.abs(window.scrollY - ownScrollTop) >= .5 || performance.now() - ownScrollAt >= 500)) ownScrollTop = null;
1629
- return ownScrollTop !== null;
1630
- };
1631
- const isPageScrolling = (cls) => (isRefreshing(cls) ? isScrolling(cls) : isScrollingOrUpdating(cls)) && !isOwnTripOnly();
1632
- const isUserScrolling = (cls) => isScrolling(cls) && !isOwnTripOnly();
1633
- const scrollBackTo = (top) => {
1634
- if (Math.abs(window.scrollY - top) >= .5) window.scrollTo({
1635
- top,
1636
- behavior: "instant"
1637
- });
1638
- };
1639
- const enterScrollZero = (cls) => {
1640
- if (scrollZeroReturn !== null) {
1641
- scrollBackTo(0);
1642
- dormancyAtScrollZero();
1643
- return () => {};
1644
- }
1645
- const fromRest = !isUserScrolling(cls);
1646
- scrollZeroReturn = window.scrollY;
1647
- dormancyAtScrollZero();
1648
- window.scrollTo({
1649
- top: 0,
1650
- behavior: "instant"
1651
- });
1652
- return () => {
1653
- const back = scrollZeroReturn ?? 0;
1654
- scrollZeroReturn = null;
1655
- window.scrollTo({
1656
- top: back,
1657
- behavior: "instant"
1658
- });
1659
- markOwnScroll(fromRest);
1660
- syncScrollCache(cls);
1661
- dormancyAfterScrollZero(window.scrollY);
1662
- };
1663
- };
1664
- let gsapAtZero = false;
1665
- let gsapZeroReturn = 0;
1666
- const gsapScrollToZero = (cls) => {
1667
- if (gsapAtZero) {
1668
- const back = window.scrollY;
1669
- if (back === 0) return () => {};
1670
- const fromRest = !isUserScrolling(cls);
1671
- window.scrollTo({
1672
- top: 0,
1673
- behavior: "instant"
1674
- });
1675
- return () => {
1676
- window.scrollTo({
1677
- top: back,
1678
- behavior: "instant"
1679
- });
1680
- markOwnScroll(fromRest);
1681
- };
1682
- }
1683
- const record = scrollRecord(cls, true);
1684
- if (!record || record.read() === 0) return () => {};
1685
- const fromRest = !isUserScrolling(cls);
1686
- gsapZeroReturn = record.read();
1687
- dormancyAtScrollZero();
1688
- window.scrollTo({
1689
- top: 0,
1690
- behavior: "instant"
1691
- });
1692
- gsapAtZero = true;
1693
- return () => {
1694
- gsapAtZero = false;
1695
- window.scrollTo({
1696
- top: record.read(),
1697
- behavior: "instant"
1698
- });
1699
- markOwnScroll(fromRest);
1700
- };
1701
- };
1702
- const realScroll = () => scrollZeroReturn ?? (gsapAtZero ? gsapZeroReturn : null);
1703
- const mayBeStuckAround = (from, own) => {
1704
- const seen = new Set();
1705
- const moved = movedPastFreeze();
1706
- return from.some((el) => {
1707
- for (let current = el; current && !seen.has(current) && current !== document.body && current !== document.documentElement; current = current.parentElement) {
1708
- seen.add(current);
1709
- if (own.has(current)) continue;
1710
- if (moved.has(current) || getComputedStyle(current).position === "sticky") return true;
1711
- }
1712
- return false;
1713
- });
1714
- };
1715
- const afterFunction = () => {
1716
- if (gsapAtZero || scrollZeroReturn !== null) scrollBackTo(0);
1717
- if (scrollZeroReturn !== null) dormancyAtScrollZero();
1718
- };
1719
- const withAfterFunction = (value) => {
1720
- if (typeof value !== "function") return value;
1721
- return () => {
1722
- try {
1723
- return value();
1724
- } finally {
1725
- afterFunction();
1726
- }
1727
- };
1728
- };
1729
- let liveEvaluation = null;
1730
- let layerHandlerDepth = 0;
1731
- const holdLiveEvaluationForGsapRefresh = (cls) => {
1732
- const evaluation = liveEvaluation;
1733
- const real = realScroll();
1734
- if (real !== null && !evaluation) {
1735
- const zeroRecord = scrollRecord(cls, true);
1736
- if (zeroRecord && Math.abs(zeroRecord.read() - real) >= .5) {
1737
- zeroRecord.write(real);
1738
- setGsapRefreshReturn(real);
1739
- }
1740
- }
1741
- if (!evaluation) return;
1742
- const resume = suspendLiveEvaluations(evaluation, false);
1743
- const record = scrollRecord(cls, true);
1744
- if (record && Math.abs(record.read() - evaluation.scroll) >= .5) {
1745
- scrollBackTo(Math.round(evaluation.scroll));
1746
- syncScrollCache(cls);
1747
- const unclamped = window.scrollY >= Math.round(evaluation.scroll) - .5;
1748
- const reached = realScroll() !== null && unclamped ? evaluation.scroll : window.scrollY;
1749
- record.write(reached);
1750
- setGsapRefreshReturn(reached);
1751
- }
1752
- const depth = layerHandlerDepth - 1;
1753
- let held = true;
1754
- liveEvaluation = null;
1755
- const onRefresh = () => {
1756
- if (!held || layerHandlerDepth > depth) return;
1757
- held = false;
1758
- resume();
1759
- if (!evaluation.ended) liveEvaluation = evaluation;
1760
- };
1761
- addGsapListener(cls, "refresh", onRefresh);
1762
- queueMicrotask(() => removeGsapListener(cls, "refresh", onRefresh));
1763
- };
1764
2098
  const REST_POLL_MS = 100;
2099
+ const refreshedDuringMove = new Map();
1765
2100
  const runEach = (...steps) => {
1766
2101
  let failure = null;
1767
2102
  steps.forEach((step) => {
@@ -1791,6 +2126,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
1791
2126
  #refreshInitNestedUsed = false;
1792
2127
  #measureAgain = false;
1793
2128
  #keepContentPending = false;
2129
+ #refreshOwed = false;
1794
2130
  #deferredRun = null;
1795
2131
  #restTimer = null;
1796
2132
  #pendingKeep = null;
@@ -2045,14 +2381,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2045
2381
  const restoreDormancy = takeGsapRefreshRestore();
2046
2382
  return restoreDormancy ? revertAfterMeasure(restoreDormancy, result) : result;
2047
2383
  };
2048
- return (self) => {
2049
- layerHandlerDepth += 1;
2050
- try {
2051
- return handle(self);
2052
- } finally {
2053
- layerHandlerDepth -= 1;
2054
- }
2055
- };
2384
+ return (self) => asLayerHandler(() => handle(self));
2056
2385
  }
2057
2386
  #watchGsapRefresh() {
2058
2387
  if (this.#dispatchObserver) {
@@ -2116,16 +2445,28 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2116
2445
  });
2117
2446
  }
2118
2447
  #reservePinSpace() {
2119
- const wrapped = this.#pinLayers.flatMap(({ outer, inner }) => outer && inner ? [{
2448
+ const wrapped = this.#pinLayers.flatMap(({ outer, inner, trigger }) => outer && inner ? [{
2120
2449
  outer,
2121
2450
  inner,
2451
+ trigger,
2452
+ savedStyle: outer.style.cssText,
2122
2453
  range: inner.style.height
2123
2454
  }] : []);
2124
2455
  wrapped.forEach(({ outer, inner }) => {
2125
2456
  clearHeightForRead(outer);
2126
2457
  clearHeightForRead(inner);
2127
2458
  });
2128
- const reserved = wrapped.map(({ outer }) => measureUsedHeight(outer));
2459
+ let reserved;
2460
+ try {
2461
+ const itemHeights = fitPinsToItems(wrapped);
2462
+ reserved = wrapped.map(({ outer }, index) => itemHeights[index] ?? measureUsedHeight(outer));
2463
+ } catch (error) {
2464
+ wrapped.forEach(({ outer, inner, savedStyle, range }) => {
2465
+ commitCssText(outer, savedStyle);
2466
+ commitHeight(inner, range);
2467
+ });
2468
+ throw error;
2469
+ }
2129
2470
  wrapped.forEach(({ outer }, index) => {
2130
2471
  commitHeight(outer, `${reserved[index]}px`);
2131
2472
  });
@@ -2153,10 +2494,10 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2153
2494
  static #resetStickyAround(self, from) {
2154
2495
  const withClass = self ?? [...armedInstances].find((instance) => instance.#scrollTriggerClass);
2155
2496
  const cls = (withClass ? withClass.#scrollTriggerClass : null) ?? lastScrollTriggerClass;
2156
- if (scrollZeroReturn !== null) return enterScrollZero(cls);
2497
+ if (scrollZeroReturnTop() !== null) return enterScrollZero(cls);
2157
2498
  const refreshing = isRefreshing(cls);
2158
- if (refreshing && gsapAtZero) return gsapScrollToZero(cls);
2159
- if (!(refreshing && layerHandlerDepth > 0) && !isPageScrolling(cls) && window.scrollY !== 0) {
2499
+ if (refreshing && isGsapAtZero()) return gsapScrollToZero(cls);
2500
+ if (!(refreshing && inLayerHandler()) && !isPageScrolling(cls) && window.scrollY !== 0) {
2160
2501
  const own = new Set(self ? self.#ownedStickyElements() : []);
2161
2502
  return mayBeStuckAround(from, own) ? enterScrollZero(cls) : () => {};
2162
2503
  }
@@ -2264,10 +2605,11 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2264
2605
  const releaseScroll = resolvePinReleaseScroll(layer.endTrigger, classifiedEnd, toScroll(layer.trigger, triggerTop - topPx), viewportHeight, toScroll);
2265
2606
  const height = releaseScroll - (this.#rootElement.contains(layer.trigger) ? dwellConsumedAt(releaseScroll, this.#engagedWindows()) : 0) - triggerTop + topPx + triggerHeight + triggerMarginBottom;
2266
2607
  const room = documentHeight > 0 ? documentHeight - triggerTop : Infinity;
2608
+ const still = triggerHeight + triggerMarginBottom;
2267
2609
  return [{
2268
2610
  layer,
2269
2611
  topPx,
2270
- range: Math.max(0, Math.min(height, room))
2612
+ range: Math.max(0, Math.min(Math.max(height, still), room))
2271
2613
  }];
2272
2614
  });
2273
2615
  }
@@ -2376,39 +2718,10 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2376
2718
  });
2377
2719
  };
2378
2720
  };
2379
- let takeDown = () => {};
2380
- let holds = 0;
2381
- const evaluation = {
2382
- resolved: false,
2383
- ended: false,
2384
- outer: liveEvaluation,
2385
- scroll: liveEvaluation?.scroll ?? scroll,
2386
- suspend: (resolving) => {
2387
- if (resolving) evaluation.resolved = true;
2388
- holds += 1;
2389
- if (holds === 1) {
2390
- takeDown();
2391
- takeDown = () => {};
2392
- }
2393
- return () => {
2394
- holds -= 1;
2395
- if (holds === 0 && !evaluation.ended) takeDown = setUp();
2396
- };
2397
- }
2398
- };
2399
- try {
2400
- takeDown = setUp();
2401
- liveEvaluation = evaluation;
2402
- const next = liveEnd();
2403
- return evaluation.resolved ? null : next;
2404
- } finally {
2405
- evaluation.ended = true;
2406
- liveEvaluation = evaluation.outer;
2407
- takeDown();
2408
- }
2721
+ return evaluateLive(setUp, scroll, liveEnd);
2409
2722
  }
2410
2723
  refresh() {
2411
- if (this.#depth > 0 || isRefreshing(this.#scrollTriggerClass) || this.#destroyed || !this.#armed || pendingDisarms.has(this) || window.scrollY === 0 || this.#measuresInPlace()) {
2724
+ if (this.#depth > 0 || isRefreshing(this.#scrollTriggerClass) || this.#destroyed || !this.#armed || pendingDisarms.has(this) || isMovingDom() || window.scrollY === 0 || this.#measuresInPlace()) {
2412
2725
  this.#refreshFrom(false);
2413
2726
  return;
2414
2727
  }
@@ -2429,6 +2742,13 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2429
2742
  this.#runRefresh();
2430
2743
  }
2431
2744
  #runRefresh() {
2745
+ if (isMovingDom()) {
2746
+ const cls = isRefreshing(this.#scrollTriggerClass) ? this.#scrollTriggerClass : null;
2747
+ this.#refreshOwed = true;
2748
+ if (refreshedDuringMove.size === 0) queueMicrotask(StickyScrollTrigger.#runRefreshesOwed);
2749
+ refreshedDuringMove.set(this, refreshedDuringMove.get(this) ?? cls);
2750
+ return;
2751
+ }
2432
2752
  if (this.#depth > 0) this.#measureAgain = true;
2433
2753
  if (this.#destroyed || !this.#armed || pendingDisarms.has(this)) return;
2434
2754
  let failure = null;
@@ -2445,6 +2765,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2445
2765
  if (this.#depth === 0) {
2446
2766
  this.#refreshInitNestedUsed = false;
2447
2767
  this.#measureAgain = false;
2768
+ this.#refreshOwed = false;
2448
2769
  }
2449
2770
  }
2450
2771
  try {
@@ -2459,12 +2780,19 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2459
2780
  this.#scrollMarginSync?.applyRamps(realScroll() ?? scrollRecord(this.#scrollTriggerClass)?.read());
2460
2781
  if (failure) throw failure.error;
2461
2782
  }
2783
+ static #runRefreshesOwed() {
2784
+ const owed = [...refreshedDuringMove];
2785
+ refreshedDuringMove.clear();
2786
+ const classes = new Set(owed.flatMap(([, cls]) => cls ? [cls] : []));
2787
+ const direct = owed.flatMap(([instance, cls]) => !cls && instance.#refreshOwed ? [instance] : []);
2788
+ runEach(...[...classes].map((cls) => () => refreshAll(cls)), ...direct.map((instance) => () => instance.refresh()));
2789
+ }
2462
2790
  #naturalScrollTop(layers) {
2463
2791
  const measured = this.#measuredStructure;
2464
2792
  const container = this.#outermostContainer;
2465
- const containerTop = (el) => readThenRestore(isRefreshing(this.#scrollTriggerClass) && layerHandlerDepth > 0 ? gsapScrollToZero(this.#scrollTriggerClass) : StickyScrollTrigger.#resetStickyAround(this, [el]), () => documentTop(el));
2793
+ const containerTop = (el) => readThenRestore(isRefreshing(this.#scrollTriggerClass) && inLayerHandler() ? gsapScrollToZero(this.#scrollTriggerClass) : StickyScrollTrigger.#resetStickyAround(this, [el]), () => documentTop(el));
2466
2794
  const moved = measured && container && measured.changes !== structureChanges ? containerTop(container) - measured.top : 0;
2467
- const scroll = (scrollRecord(this.#scrollTriggerClass)?.read() ?? scrollZeroReturn ?? window.scrollY) - moved;
2795
+ const scroll = (scrollRecord(this.#scrollTriggerClass)?.read() ?? scrollZeroReturnTop() ?? window.scrollY) - moved;
2468
2796
  const consumed = new Map();
2469
2797
  layers.forEach((layer) => {
2470
2798
  if (layer.kind !== "scene") return;
@@ -2482,8 +2810,9 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2482
2810
  record.write(target);
2483
2811
  return;
2484
2812
  }
2485
- if (scrollZeroReturn !== null) {
2486
- if (Math.abs(scrollZeroReturn - target) >= .5) scrollZeroReturn = Math.round(target);
2813
+ const zeroReturn = scrollZeroReturnTop();
2814
+ if (zeroReturn !== null) {
2815
+ if (Math.abs(zeroReturn - target) >= .5) moveScrollZeroReturn(Math.round(target));
2487
2816
  return;
2488
2817
  }
2489
2818
  if (isRefreshing(cls)) return;
@@ -2528,8 +2857,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2528
2857
  }
2529
2858
  #liftCovers() {
2530
2859
  this.#coverLayers().forEach((layer) => {
2531
- const pin = this.#pinLayers.find(({ trigger }) => trigger === layer.cover);
2532
- this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(pin?.outer ?? layer.cover));
2860
+ this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(physicalHolder(layer.cover)));
2533
2861
  });
2534
2862
  }
2535
2863
  #syncScrollMargins(tops) {
@@ -2616,9 +2944,10 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2616
2944
  const trigger = resolveElement(triggerInput, "createOverlapScroll");
2617
2945
  this.#assertTriggerInsideRoot(trigger, "createOverlapScroll");
2618
2946
  const endTrigger = resolveEndTrigger(trigger, endTriggerInput, "createOverlapScroll");
2619
- const coverElement = cover === void 0 ? trigger.nextElementSibling : resolveElement(cover, "createOverlapScroll");
2620
- if (!(coverElement instanceof HTMLElement)) throw new Error(`createOverlapScroll: cover element (trigger.nextElementSibling) not found for trigger ${describeElement(trigger)}`);
2621
- if (coverElement.parentNode !== trigger.parentNode) throw new Error(`createOverlapScroll: cover ${describeElement(coverElement)} must be a sibling of trigger ` + describeElement(trigger));
2947
+ const ownWrappers = new Set(this.#coverLayers().flatMap(({ wrapper }) => wrapper ? [wrapper] : []));
2948
+ const coverElement = cover === void 0 ? logicalNextSibling(trigger, ownWrappers) : resolveElement(cover, "createOverlapScroll");
2949
+ if (!(coverElement instanceof HTMLElement)) throw new Error(`createOverlapScroll: cover element (trigger's next sibling) not found for trigger ${describeElement(trigger)}`);
2950
+ if (logicalParent(coverElement, ownWrappers) !== logicalParent(trigger, ownWrappers)) throw new Error(`createOverlapScroll: cover ${describeElement(coverElement)} must be a sibling of trigger ` + describeElement(trigger));
2622
2951
  const layer = {
2623
2952
  kind: "cover",
2624
2953
  trigger,
@@ -2637,7 +2966,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2637
2966
  unbuildCover(layer);
2638
2967
  onKill?.(self);
2639
2968
  }, rest);
2640
- this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(coverElement));
2969
+ this.#coverRestoreByLayer.set(layer, liftAboveStickyWrapper(physicalHolder(coverElement)));
2641
2970
  return vars;
2642
2971
  }
2643
2972
  createStickyPin({ trigger: triggerInput, start, top, endTrigger: endTriggerInput, end = "bottom top", onKill, ...rest }) {
@@ -2676,12 +3005,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2676
3005
  };
2677
3006
  }
2678
3007
  resolveScrollPosition(elementInput, position) {
2679
- const resume = liveEvaluation && suspendLiveEvaluations(liveEvaluation, true);
2680
- try {
2681
- return this.#resolveScrollPosition(elementInput, position);
2682
- } finally {
2683
- resume?.();
2684
- }
3008
+ return resolveOutsideEvaluation(() => this.#resolveScrollPosition(elementInput, position));
2685
3009
  }
2686
3010
  #resolveScrollPosition(elementInput, position) {
2687
3011
  const element = resolveElement(elementInput, "resolveScrollPosition");
@@ -2718,7 +3042,7 @@ var StickyScrollTrigger = class StickyScrollTrigger {
2718
3042
  try {
2719
3043
  return readThenRestore(StickyScrollTrigger.#resetStickyAround(null, [element]), () => documentTop(element));
2720
3044
  } finally {
2721
- restores.forEach((restore) => restore());
3045
+ restores.reverse().forEach((restore) => restore());
2722
3046
  }
2723
3047
  }
2724
3048
  createResolvedTrigger({ trigger: triggerInput, start = "top bottom", end = "bottom top", endTrigger: endTriggerInput, ...rest }) {