@lostgradient/cinder 0.25.1 → 0.26.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.
Files changed (263) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/components.json +13 -6
  3. package/dist/components/alert-dialog/index.js +2 -2
  4. package/dist/components/approval-card/index.js +2 -2
  5. package/dist/components/area-chart/index.js +2 -2
  6. package/dist/components/autocomplete/index.js +2 -2
  7. package/dist/components/avatar-group/index.js +2 -2
  8. package/dist/components/backdrop/index.js +2 -2
  9. package/dist/components/bar-chart/index.js +2 -2
  10. package/dist/components/button/button.css +1 -1
  11. package/dist/components/checkbox/index.js +2 -2
  12. package/dist/components/code-block/index.js +2 -2
  13. package/dist/components/color-field/index.js +2 -2
  14. package/dist/components/combobox/index.js +2 -2
  15. package/dist/components/command-menu/index.js +2 -2
  16. package/dist/components/command-palette/command-palette.css +50 -46
  17. package/dist/components/command-palette/index.js +2 -2
  18. package/dist/components/confirm-dialog/index.js +2 -2
  19. package/dist/components/context-menu/index.js +2 -2
  20. package/dist/components/data-table/index.js +2 -2
  21. package/dist/components/date-picker/index.js +2 -2
  22. package/dist/components/date-range-field/index.js +2 -2
  23. package/dist/components/drawer/index.js +2 -2
  24. package/dist/components/dropdown/index.js +2 -2
  25. package/dist/components/dropdown-menu/index.js +2 -2
  26. package/dist/components/find-bar/find-bar.css +9 -1
  27. package/dist/components/focus-trap/index.js +2 -2
  28. package/dist/components/form-field/index.js +2 -2
  29. package/dist/components/hover-card/index.js +2 -2
  30. package/dist/components/inline-confirm/index.js +2 -2
  31. package/dist/components/input/index.js +2 -2
  32. package/dist/components/input/input.css +95 -6
  33. package/dist/components/invocation-rule-builder/index.js +2 -2
  34. package/dist/components/json-editor/index.js +2 -2
  35. package/dist/components/json-schema-editor/index.js +4 -4
  36. package/dist/components/key-value-editor/index.css +1 -1
  37. package/dist/components/line-chart/index.js +2 -2
  38. package/dist/components/matrix-chart/index.js +2 -2
  39. package/dist/components/menu-bar/index.js +3 -3
  40. package/dist/components/modal/index.js +2 -2
  41. package/dist/components/modal-region/index.css +1 -1
  42. package/dist/components/multi-select/index.js +2 -2
  43. package/dist/components/navigation-bar/index.js +2 -2
  44. package/dist/components/parameter-field/index.js +2 -2
  45. package/dist/components/permission-matrix/index.js +2 -2
  46. package/dist/components/policy-lock/index.js +2 -2
  47. package/dist/components/popover/index.js +2 -2
  48. package/dist/components/radio-group/index.js +2 -2
  49. package/dist/components/schedule-builder/index.js +2 -2
  50. package/dist/components/schema-form/index.js +2 -2
  51. package/dist/components/scroll-area/index.js +2 -2
  52. package/dist/components/select/index.js +2 -2
  53. package/dist/components/selection-popover/index.js +2 -2
  54. package/dist/components/share-card/index.js +2 -2
  55. package/dist/components/sidebar/index.js +2 -2
  56. package/dist/components/speed-dial/index.js +2 -2
  57. package/dist/components/statistic-group/index.js +2 -2
  58. package/dist/components/statistic-group/statistic-group.css +116 -66
  59. package/dist/components/table/index.js +2 -2
  60. package/dist/components/textarea/index.js +2 -2
  61. package/dist/components/time-field/index.js +2 -2
  62. package/dist/components/time-field/time-field.css +9 -8
  63. package/dist/components/toast-region/index.js +2 -2
  64. package/dist/components/tooltip/index.js +2 -2
  65. package/dist/components/transfer-list/index.js +2 -2
  66. package/dist/components/virtual-list/_internal/adaptive-overscan.d.ts +87 -0
  67. package/dist/components/virtual-list/_internal/edge-proximity.d.ts +75 -0
  68. package/dist/components/virtual-list/_internal/frame-scheduler.d.ts +76 -0
  69. package/dist/components/virtual-list/_internal/geometry.d.ts +170 -0
  70. package/dist/components/virtual-list/_internal/list-semantics.d.ts +93 -0
  71. package/dist/components/virtual-list/_internal/measurement-window.d.ts +125 -0
  72. package/dist/components/virtual-list/_internal/reverse-order.d.ts +87 -0
  73. package/dist/components/virtual-list/_internal/scroll-restoration.d.ts +98 -0
  74. package/dist/components/virtual-list/_internal/sticky-items.d.ts +48 -0
  75. package/dist/components/virtual-list/_internal/virtual-list-measurement-store.svelte.d.ts +69 -0
  76. package/dist/components/virtual-list/index.d.ts +1 -1
  77. package/dist/components/virtual-list/index.js +2 -2
  78. package/dist/components/virtual-list/virtual-list.css +153 -0
  79. package/dist/components/virtual-list/virtual-list.schema.js +69 -6
  80. package/dist/components/virtual-list/virtual-list.svelte.d.ts +11 -8
  81. package/dist/components/virtual-list/virtual-list.types.d.ts +177 -4
  82. package/dist/index.browser.css +1 -1
  83. package/dist/index.d.ts +1 -1
  84. package/dist/index.js +18 -18
  85. package/dist/server/components/alert-dialog/index.js +1 -1
  86. package/dist/server/components/approval-card/index.js +1 -1
  87. package/dist/server/components/area-chart/index.js +1 -1
  88. package/dist/server/components/autocomplete/index.js +1 -1
  89. package/dist/server/components/avatar-group/index.js +1 -1
  90. package/dist/server/components/backdrop/index.js +1 -1
  91. package/dist/server/components/bar-chart/index.js +1 -1
  92. package/dist/server/components/checkbox/index.js +1 -1
  93. package/dist/server/components/code-block/index.js +1 -1
  94. package/dist/server/components/color-field/index.js +1 -1
  95. package/dist/server/components/combobox/index.js +1 -1
  96. package/dist/server/components/command-menu/index.js +1 -1
  97. package/dist/server/components/command-palette/index.js +2 -2
  98. package/dist/server/components/confirm-dialog/index.js +1 -1
  99. package/dist/server/components/context-menu/index.js +1 -1
  100. package/dist/server/components/data-table/index.js +1 -1
  101. package/dist/server/components/date-picker/index.js +1 -1
  102. package/dist/server/components/date-range-field/index.js +1 -1
  103. package/dist/server/components/drawer/index.js +1 -1
  104. package/dist/server/components/dropdown/index.js +1 -1
  105. package/dist/server/components/dropdown-menu/index.js +2 -2
  106. package/dist/server/components/focus-trap/index.js +1 -1
  107. package/dist/server/components/form-field/index.js +1 -1
  108. package/dist/server/components/hover-card/index.js +1 -1
  109. package/dist/server/components/inline-confirm/index.js +1 -1
  110. package/dist/server/components/input/index.js +1 -1
  111. package/dist/server/components/invocation-rule-builder/index.js +1 -1
  112. package/dist/server/components/json-editor/index.js +1 -1
  113. package/dist/server/components/json-schema-editor/index.js +1 -1
  114. package/dist/server/components/line-chart/index.js +1 -1
  115. package/dist/server/components/matrix-chart/index.js +1 -1
  116. package/dist/server/components/menu-bar/index.js +2 -2
  117. package/dist/server/components/modal/index.js +1 -1
  118. package/dist/server/components/multi-select/index.js +1 -1
  119. package/dist/server/components/navigation-bar/index.js +2 -2
  120. package/dist/server/components/parameter-field/index.js +1 -1
  121. package/dist/server/components/permission-matrix/index.js +1 -1
  122. package/dist/server/components/policy-lock/index.js +1 -1
  123. package/dist/server/components/popover/index.js +1 -1
  124. package/dist/server/components/radio-group/index.js +1 -1
  125. package/dist/server/components/schedule-builder/index.js +1 -1
  126. package/dist/server/components/schema-form/index.js +1 -1
  127. package/dist/server/components/scroll-area/index.js +1 -1
  128. package/dist/server/components/select/index.js +1 -1
  129. package/dist/server/components/selection-popover/index.js +1 -1
  130. package/dist/server/components/share-card/index.js +1 -1
  131. package/dist/server/components/sidebar/index.js +1 -1
  132. package/dist/server/components/speed-dial/index.js +2 -2
  133. package/dist/server/components/statistic-group/index.js +1 -1
  134. package/dist/server/components/table/index.js +1 -1
  135. package/dist/server/components/textarea/index.js +1 -1
  136. package/dist/server/components/time-field/index.js +1 -1
  137. package/dist/server/components/toast-region/index.js +1 -1
  138. package/dist/server/components/tooltip/index.js +1 -1
  139. package/dist/server/components/transfer-list/index.js +1 -1
  140. package/dist/server/components/virtual-list/index.js +2 -2
  141. package/dist/server/index.js +2 -2
  142. package/dist/server/{index.server-skq0f5sr.js → index.server-0jw25w9w.js} +1 -1
  143. package/dist/server/index.server-0kk20wvp.js +4 -0
  144. package/dist/server/{index.server-fzsqdajc.js → index.server-2awq6q9m.js} +1 -1
  145. package/dist/server/{index.server-e4hmhaeh.js → index.server-3xwvw6w2.js} +3 -3
  146. package/dist/server/{index.server-95h7xy01.js → index.server-428dh2t9.js} +2 -2
  147. package/dist/server/{index.server-jd88r74m.js → index.server-5dq66aja.js} +2 -2
  148. package/dist/server/{index.server-dvwfhf77.js → index.server-5s94r0kk.js} +2 -2
  149. package/dist/server/{index.server-qv6z5ta3.js → index.server-80qgcjnm.js} +1 -1
  150. package/dist/server/{index.server-7k2732ky.js → index.server-81abtrsw.js} +1 -1
  151. package/dist/server/{index.server-csmqnx5w.js → index.server-83q1gv2c.js} +1 -1
  152. package/dist/server/{index.server-qw8k9rjg.js → index.server-8fyav10d.js} +1 -1
  153. package/dist/server/{index.server-4dgjj4k1.js → index.server-8h5caecr.js} +2 -2
  154. package/dist/server/{index.server-emyqytmm.js → index.server-90n8sd9e.js} +1 -1
  155. package/dist/server/{index.server-0xrdyzvh.js → index.server-99penx1m.js} +1 -1
  156. package/dist/server/{index.server-p94j3jah.js → index.server-9g9d15z1.js} +1 -1
  157. package/dist/server/{index.server-xp9hkc81.js → index.server-9kbdx511.js} +1 -1
  158. package/dist/server/index.server-a2yhk45s.js +3 -0
  159. package/dist/server/{index.server-g8d2m2tk.js → index.server-acq55gjs.js} +1 -1
  160. package/dist/server/{index.server-ewze54tv.js → index.server-afjftjmr.js} +1 -1
  161. package/dist/server/{index.server-ejyye4gv.js → index.server-bfed6a8a.js} +1 -1
  162. package/dist/server/{index.server-z5ng08q2.js → index.server-c1746s0z.js} +1 -1
  163. package/dist/server/{index.server-gt1tfc1w.js → index.server-dmeztywe.js} +1 -1
  164. package/dist/server/{index.server-kzsppq0n.js → index.server-dyj3jdx9.js} +1 -1
  165. package/dist/server/index.server-dz92zvx6.js +4 -0
  166. package/dist/server/{index.server-3md8kdcr.js → index.server-e6682k08.js} +1 -1
  167. package/dist/server/{index.server-t1pshh65.js → index.server-ewkv461x.js} +1 -1
  168. package/dist/server/{index.server-zfgwhtmp.js → index.server-fa449wd3.js} +1 -1
  169. package/dist/server/{index.server-1kgwayct.js → index.server-fhfypmgw.js} +1 -1
  170. package/dist/server/{index.server-s4z8hsby.js → index.server-ge4adxs2.js} +1 -1
  171. package/dist/server/{index.server-68xyfsg3.js → index.server-gggkq22y.js} +2 -2
  172. package/dist/server/{index.server-acgwdamx.js → index.server-j52rbk57.js} +1 -1
  173. package/dist/server/{index.server-z0nwftx6.js → index.server-jm89hxfb.js} +1 -1
  174. package/dist/server/{index.server-xa98r8p2.js → index.server-jw0v64se.js} +1 -1
  175. package/dist/server/index.server-m321p69g.js +3 -0
  176. package/dist/server/{index.server-xyervw3d.js → index.server-m7q2tc41.js} +1 -1
  177. package/dist/server/{index.server-tnrxy86j.js → index.server-mak7dmj2.js} +1 -1
  178. package/dist/server/{index.server-n5g5h5k1.js → index.server-mw5r2524.js} +1 -1
  179. package/dist/server/{index.server-caf7s6m7.js → index.server-nwq1cg55.js} +1 -1
  180. package/dist/server/{index.server-3wdvs0wr.js → index.server-p423fy4q.js} +2 -2
  181. package/dist/server/{index.server-ks7fvwxt.js → index.server-prk5syj2.js} +1 -1
  182. package/dist/server/{index.server-6w9fp018.js → index.server-q4hytsq3.js} +1 -1
  183. package/dist/server/{index.server-5w2qw8fm.js → index.server-q597a1ck.js} +1 -1
  184. package/dist/server/{index.server-fz1pkvda.js → index.server-qgne9v2w.js} +1 -1
  185. package/dist/server/{index.server-1f2app32.js → index.server-rvdavf92.js} +1 -1
  186. package/dist/server/index.server-rwq20a22.js +3 -0
  187. package/dist/server/{index.server-0rvmnrw2.js → index.server-s9tjs45r.js} +1 -1
  188. package/dist/server/{index.server-cm2prec7.js → index.server-sqgxyfsw.js} +1 -1
  189. package/dist/server/{index.server-v6777tgn.js → index.server-t761nwvb.js} +1 -1
  190. package/dist/server/index.server-tbds8nwq.js +4 -0
  191. package/dist/server/index.server-tyhta5n3.js +3 -0
  192. package/dist/server/{index.server-yw7rah51.js → index.server-v5dxham4.js} +1 -1
  193. package/dist/server/index.server-va98cpyf.js +3 -0
  194. package/dist/server/index.server-vq1k69xt.js +3 -0
  195. package/dist/server/{index.server-egd355s6.js → index.server-wnf9btp7.js} +2 -2
  196. package/dist/server/{index.server-sjcbaztf.js → index.server-y3zgdtbv.js} +1 -1
  197. package/dist/server/{index.server-4tjtgzf9.js → index.server-y6vtbmyj.js} +1 -1
  198. package/dist/server/{index.server-2p2mjzzb.js → index.server-zff2qp1v.js} +1 -1
  199. package/dist/server/tokens/registry.generated.js +2 -2
  200. package/dist/tokens/registry.generated.js +2 -2
  201. package/package.json +2 -2
  202. package/src/_internal/form-field-frame.svelte +5 -0
  203. package/src/_internal/overlay.ts +14 -1
  204. package/src/components/_internal/create-command-list-state.svelte.ts +4 -0
  205. package/src/components/button/button.css +1 -1
  206. package/src/components/command-menu/command-menu.svelte +63 -7
  207. package/src/components/command-palette/command-palette.css +50 -46
  208. package/src/components/command-palette/command-palette.svelte +68 -78
  209. package/src/components/dropdown/dropdown.svelte +73 -18
  210. package/src/components/dropdown-menu/dropdown-menu.svelte +63 -7
  211. package/src/components/find-bar/find-bar.css +9 -1
  212. package/src/components/input/input.css +95 -6
  213. package/src/components/input/input.svelte +44 -81
  214. package/src/components/menu-bar/menu-bar.svelte +12 -1
  215. package/src/components/multi-select/multi-select.svelte +7 -0
  216. package/src/components/navigation-bar/navigation-bar.svelte +82 -6
  217. package/src/components/selection-popover/selection-popover.svelte +24 -10
  218. package/src/components/share-card/share-card.svelte +24 -44
  219. package/src/components/speed-dial/speed-dial.svelte +23 -5
  220. package/src/components/statistic-group/statistic-group.css +116 -66
  221. package/src/components/statistic-group/statistic-group.examples.json +6 -0
  222. package/src/components/statistic-group/statistic-group.svelte +13 -1
  223. package/src/components/time-field/time-field.css +9 -8
  224. package/src/components/toast-region/toast-region.svelte +9 -0
  225. package/src/components/virtual-list/_internal/adaptive-overscan.ts +248 -0
  226. package/src/components/virtual-list/_internal/edge-proximity.ts +130 -0
  227. package/src/components/virtual-list/_internal/frame-scheduler.ts +136 -0
  228. package/src/components/virtual-list/_internal/geometry.ts +236 -0
  229. package/src/components/virtual-list/_internal/list-semantics.ts +151 -0
  230. package/src/components/virtual-list/_internal/measurement-window.ts +300 -0
  231. package/src/components/virtual-list/_internal/reverse-order.ts +146 -0
  232. package/src/components/virtual-list/_internal/scroll-restoration.ts +209 -0
  233. package/src/components/virtual-list/_internal/sticky-items.ts +111 -0
  234. package/src/components/virtual-list/_internal/virtual-list-measurement-store.svelte.ts +145 -0
  235. package/src/components/virtual-list/index.ts +7 -1
  236. package/src/components/virtual-list/virtual-list.css +153 -0
  237. package/src/components/virtual-list/virtual-list.examples.json +42 -0
  238. package/src/components/virtual-list/virtual-list.schema.json +53 -3
  239. package/src/components/virtual-list/virtual-list.schema.ts +64 -3
  240. package/src/components/virtual-list/virtual-list.svelte +1527 -36
  241. package/src/components/virtual-list/virtual-list.types.ts +181 -4
  242. package/src/index.ts +3 -0
  243. package/src/styles/tokens-base.css +29 -21
  244. package/src/tokens/cinder.resolver.json +8 -0
  245. package/src/tokens/index.json +1 -1
  246. package/src/tokens/registry.generated.json +29 -3
  247. package/src/tokens/registry.generated.ts +31 -3
  248. package/src/tokens/resolved/dark-reduced-motion.json +46 -16
  249. package/src/tokens/resolved/dark.json +46 -16
  250. package/src/tokens/resolved/light-reduced-motion.json +47 -17
  251. package/src/tokens/resolved/light.json +47 -17
  252. package/src/tokens/sets/semantic.tokens.json +120 -30
  253. package/src/tokens/themes/dark.tokens.json +115 -19
  254. package/src/tokens/themes/light.tokens.json +51 -3
  255. package/dist/server/index.server-191cnacw.js +0 -3
  256. package/dist/server/index.server-25dqx151.js +0 -3
  257. package/dist/server/index.server-77jyqvbv.js +0 -4
  258. package/dist/server/index.server-bgjrzr70.js +0 -3
  259. package/dist/server/index.server-khsp90vh.js +0 -3
  260. package/dist/server/index.server-ryk2pgbe.js +0 -4
  261. package/dist/server/index.server-tajr81bm.js +0 -3
  262. package/dist/server/index.server-vjzcrw3d.js +0 -4
  263. package/dist/server/index.server-zg3fx1n1.js +0 -3
@@ -1,94 +1,1566 @@
1
1
  <script lang="ts" module>
2
2
  export { getFixedVirtualWindow, parsePixelLength, resolveVirtualItemHeight, resolveVirtualOverscan, } from '../../utilities/fixed-virtual-window.ts';
3
+ /**
4
+ * Cached for the lifetime of the document: the convention cannot change, and the
5
+ * probe forces layout, so it must not run per instance.
6
+ */
7
+ let detectedRtlScrollType = null;
3
8
  </script>
4
9
 
5
10
  <script lang="ts" generics="Item">
6
- import { tick } from 'svelte';
11
+ import { tick, untrack } from 'svelte';
7
12
  import { classNames } from '../../utilities/class-names.ts';
13
+ import { useReducedMotion } from '../../utilities/use-reduced-motion.svelte.ts';
8
14
  import { useResizeObserver } from '../../utilities/use-resize-observer.svelte.ts';
9
15
  import { getFixedVirtualWindow, parsePixelLength, resolveVirtualItemHeight, resolveVirtualOverscan, } from '../../utilities/fixed-virtual-window.ts';
10
- let { items, itemHeight, overscan = 5, height = '20rem', stickToBottom = false, tabindex = 0, getKey, row, role = 'list', onscroll: onScroll, class: className, ...rest } = $props();
16
+ import { buildVirtualOffsets, computeScrollToIndexOffset, findOffsetIndex, getDynamicVirtualWindow, resolveMeasurementCorrectionDelta, } from './_internal/measurement-window.ts';
17
+ import { VirtualListMeasurementStore } from './_internal/virtual-list-measurement-store.svelte.ts';
18
+ import { normalizeStickyIndexes, resolveActiveStickyIndex, resolveObstructingStickyIndex, } from './_internal/sticky-items.ts';
19
+ import { resolveKeyboardTargetIndex, resolveRowSemantics } from './_internal/list-semantics.ts';
20
+ import { createVelocityTracker, resolveAdaptiveItemSize, resolveAdaptiveOverscan, trackScrollVelocity, } from './_internal/adaptive-overscan.ts';
21
+ import { loadScrollPosition, saveScrollPosition, } from './_internal/scroll-restoration.ts';
22
+ import { createEdgeLatch, resolveEdgeFireDecision, resolveEdgeProximity, } from './_internal/edge-proximity.ts';
23
+ import { classifyItemGrowth, shouldPinToEnd, } from './_internal/reverse-order.ts';
24
+ import { classifyRtlScrollType, domWritingDirectionReader, normalizeInlineScrollOffset, resolveObservedMainAxisSize, resolveRowLayoutDescriptor, resolveWritingDirection, } from './_internal/geometry.ts';
25
+ let { items, itemHeight, dynamicSize = false, horizontal = false, overscan = 5, height = '20rem', stickToBottom = false, reverse = false, onEndReached, onStartReached, scrollRestoration = false, scrollRestorationId, stickyItems, smoothScroll = false, adaptiveOverscan = false, tabindex = 0, getKey, row, role = 'list', onscroll: onScroll, onwheel: onWheel, onpointerdown: onPointerDown, ontouchstart: onTouchStart, onkeydown: onKeyDown, class: className, ref = $bindable(), ...rest } = $props();
26
+ const SCROLL_TO_INDEX_MAX_ATTEMPTS = 3;
27
+ const SCROLL_TO_INDEX_SETTLED_EPSILON = 1;
28
+ /**
29
+ * Keys the browser scrolls the BLOCK axis with. A letter keypress is not a viewport
30
+ * takeover, and neither is an arrow across an axis that does not overflow.
31
+ */
32
+ const BLOCK_AXIS_SCROLL_KEYS = new Set([
33
+ 'ArrowUp',
34
+ 'ArrowDown',
35
+ 'PageUp',
36
+ 'PageDown',
37
+ 'Home',
38
+ 'End',
39
+ ' ',
40
+ ]);
41
+ /** The inline-axis equivalent. Space still pages the block axis in either case. */
42
+ const INLINE_AXIS_SCROLL_KEYS = new Set(['ArrowLeft', 'ArrowRight', ' ']);
43
+ /** ~0.5s at 60fps: long enough for a smooth scroll to land, short enough to never hang. */
44
+ const SCROLL_SETTLE_MAX_FRAMES = 30;
45
+ /**
46
+ * How long after the last scroll event adaptive overscan returns to its floor.
47
+ * Comfortably past a fling's own event cadence, so it never fires mid-gesture.
48
+ */
49
+ const VELOCITY_IDLE_RESET_MILLISECONDS = 200;
11
50
  let scrollElement = $state();
12
51
  let scrollOffset = $state(0);
13
52
  let measuredViewportHeight = $state(0);
14
- let previousItemCount = 0;
15
53
  let hasObservedItemCount = false;
16
54
  let shouldStickAfterAppend = false;
55
+ /**
56
+ * Keys as of the last `items` change, so growth can be told apart by WHICH end
57
+ * grew rather than by the count alone. An append and a prepend both raise the
58
+ * count, and they call for opposite handling: one pins to the end, the other
59
+ * must leave the reader exactly where they were.
60
+ *
61
+ * Recomputed whenever `items` changes, which is O(n) — the same order as the
62
+ * work the caller just did building that array, and the same order as the
63
+ * cache-prune pass that already runs on this dependency.
64
+ */
65
+ let previousKeys = [];
66
+ /** Identity of the array the keys were last derived from, so measurements skip the walk. */
67
+ let previousItems;
68
+ /** Set once on mount under `reverse`, which starts at the end rather than the start. */
69
+ let needsInitialReversePin = false;
70
+ let edgeLatch = createEdgeLatch();
71
+ /**
72
+ * Item count at the last failed restore, so incremental loading can keep trying.
73
+ *
74
+ * `$state` because the edge callbacks read it to decide whether a restore is still
75
+ * imminent. As a plain binding, the effect that fetches the next page would never
76
+ * re-evaluate after the first attempt gave up waiting — and the page carrying the
77
+ * anchor would never be requested.
78
+ */
79
+ let lastRestoreAttemptCount = $state(0);
80
+ /** Which id that attempt history belongs to. */
81
+ let restoredIdInProgress;
82
+ /** The position as of the last render, so a teardown never has to re-derive it. */
83
+ let latestPosition;
84
+ /**
85
+ * The id restoration last ran for, rather than a bare flag: a parent that reuses
86
+ * this component for a different collection changes the id, and that is a new
87
+ * position to restore — not the same one already handled.
88
+ */
89
+ let restoredId;
90
+ /**
91
+ * The tracker itself is a plain binding — nothing derives from it directly. The
92
+ * velocity it produces IS `$state`, because `effectiveOverscan` reads it.
93
+ */
94
+ let velocityTracker = createVelocityTracker();
95
+ let scrollVelocity = $state(0);
96
+ /** Timer that returns overscan to its floor once scrolling stops. */
97
+ let velocityIdleTimer;
98
+ // Dynamic-size machinery. The store is also reset when `dynamicSize` goes
99
+ // false, so it is not strictly untouched in fixed mode — but nothing in fixed
100
+ // mode ever reads a measured size or queues a correction.
101
+ const measurementStore = new VirtualListMeasurementStore();
102
+ let rowResizeObserver;
103
+ let previousOffsets;
104
+ let previousTotalSize = 0;
105
+ /** Cross-axis extent at the last measurement: the width when vertical, the height when horizontal. */
106
+ let previousCrossExtent = 0;
107
+ /**
108
+ * Logical property names for the axis in play. Logical rather than physical so
109
+ * the inline axis flips correctly under RTL with no separate branch: the browser
110
+ * resolves `inset-inline-start` to the right edge on its own.
111
+ */
112
+ const rowLayout = $derived(resolveRowLayoutDescriptor(horizontal ? 'horizontal' : 'vertical'));
113
+ /**
114
+ * The shared hook rather than an inline media query, per OVERLAY-POLICY and the
115
+ * `check:no-inline-match-media` guard. It is reactive, so a preference changed
116
+ * mid-session takes effect, and it carries the SSR fallback — both of which an
117
+ * inline `matchMedia` call gets wrong.
118
+ */
119
+ const reducedMotion = useReducedMotion();
120
+ let writingDirection = $state('ltr');
121
+ let previousEstimate = 0;
122
+ let pendingReanchor = null;
123
+ let pendingScrollTarget = $state(null);
124
+ let isDestroyed = false;
125
+ // $state, not a plain let: arming the pin must itself re-run the re-pin effect.
126
+ let isPinnedToBottom = $state(false);
127
+ let scrollToIndexGeneration = 0;
17
128
  const resolvedItemHeight = $derived(resolveVirtualItemHeight(itemHeight));
18
129
  const resolvedOverscan = $derived(resolveVirtualOverscan(overscan));
19
130
  const viewportHeight = $derived(measuredViewportHeight || estimateViewportHeight(height, resolvedItemHeight));
20
- const virtualWindow = $derived(getFixedVirtualWindow({
21
- itemCount: items.length,
22
- itemHeight: resolvedItemHeight,
23
- scrollOffset,
24
- viewportHeight,
25
- overscan: resolvedOverscan,
26
- getKey: (index) => {
27
- const item = items[index];
28
- return item === undefined ? index : (getKey?.(item, index) ?? index);
29
- },
30
- }));
31
- const renderedItems = $derived(virtualWindow.items.flatMap((virtualItem) => {
32
- const item = items[virtualItem.index];
33
- return item === undefined ? [] : [{ ...virtualItem, item }];
34
- }));
131
+ const offsets = $derived(dynamicSize
132
+ ? buildVirtualOffsets({
133
+ itemCount: items.length,
134
+ estimateSize: resolvedItemHeight,
135
+ getKey: keyAt,
136
+ measuredSizes: measurementStore.sizes,
137
+ })
138
+ : undefined);
139
+ /**
140
+ * See `resolveAdaptiveItemSize`: the estimate is the wrong ruler once rows are
141
+ * measured.
142
+ *
143
+ * Keyed on the store's `version` and reading its running totals, rather than summing
144
+ * the cache here. The cache keeps every row the reader has visited, so re-summing it
145
+ * on each measurement would make scrolling a long list cost O(n²) overall — on the
146
+ * fast-scroll path this feature exists to protect.
147
+ */
148
+ const averageRowSize = $derived.by(() => {
149
+ void measurementStore.version;
150
+ return resolveAdaptiveItemSize({
151
+ dynamicSize,
152
+ measuredTotalSize: measurementStore.measuredTotalSize,
153
+ measuredCount: measurementStore.measuredCount,
154
+ estimateSize: resolvedItemHeight,
155
+ });
156
+ });
157
+ /**
158
+ * The overscan actually applied. `resolvedOverscan` is the floor: adaptation only
159
+ * ever renders MORE than the consumer asked for, never less, so turning it on
160
+ * cannot make pop-in worse than the configured value.
161
+ */
162
+ const effectiveOverscan = $derived(adaptiveOverscan
163
+ ? resolveAdaptiveOverscan({
164
+ baseOverscan: resolvedOverscan,
165
+ velocityInPixelsPerMillisecond: scrollVelocity,
166
+ itemSize: averageRowSize,
167
+ })
168
+ : resolvedOverscan);
169
+ const virtualWindow = $derived(dynamicSize && offsets !== undefined
170
+ ? getDynamicVirtualWindow({
171
+ offsets,
172
+ getKey: keyAt,
173
+ scrollOffset,
174
+ viewportSize: viewportHeight,
175
+ overscan: effectiveOverscan,
176
+ })
177
+ : getFixedVirtualWindow({
178
+ itemCount: items.length,
179
+ itemHeight: resolvedItemHeight,
180
+ scrollOffset,
181
+ viewportHeight,
182
+ overscan: effectiveOverscan,
183
+ getKey: keyAt,
184
+ }));
185
+ const stickyIndexes = $derived(normalizeStickyIndexes(stickyItems, items.length));
186
+ /** The sticky row currently pinned to the leading edge, if any. */
187
+ /**
188
+ * The first row the reader can actually SEE.
189
+ *
190
+ * `virtualWindow.startIndex` is the rendered edge, which carries overscan — using
191
+ * it here activated a sticky header several rows early and moved keyboard
192
+ * navigation relative to a row nobody is looking at.
193
+ */
194
+ const firstVisibleIndex = $derived(resolveAnchorIndexAtOffset(scrollOffset));
195
+ const activeStickyIndex = $derived(resolveActiveStickyIndex(stickyIndexes, firstVisibleIndex));
196
+ const pinnedStickyIndex = $derived.by(() => {
197
+ if (activeStickyIndex === null)
198
+ return null;
199
+ // Inside the window it needs nothing special: it is contiguous, and
200
+ // `position: sticky` holds it without leaving its flow box.
201
+ if (activeStickyIndex >= virtualWindow.startIndex && activeStickyIndex < virtualWindow.endIndex)
202
+ return null;
203
+ return activeStickyIndex;
204
+ });
205
+ /**
206
+ * Main-axis size of the sticky row occupying the viewport's leading edge.
207
+ *
208
+ * Keyed on the ACTIVE sticky row rather than the pinned one. `pinnedStickyIndex`
209
+ * is null while the header is still inside the overscanned window — but CSS has
210
+ * been holding it over the leading edge that whole time, so measuring the
211
+ * obstruction as zero there reported a covered row as visible. With a measured
212
+ * 100px header over 20px rows that is five rows the reader cannot see.
213
+ */
214
+ const stickyObstructionSize = $derived(activeStickyIndex === null ? 0 : locateRowSize(activeStickyIndex));
215
+ /** The first row the sticky header is not covering. */
216
+ const firstUncoveredIndex = $derived(stickyObstructionSize > 0
217
+ ? resolveAnchorIndexAtOffset(scrollOffset + stickyObstructionSize)
218
+ : firstVisibleIndex);
219
+ const renderedItems = $derived.by(() => {
220
+ const windowed = virtualWindow.items.flatMap((virtualItem) => {
221
+ const item = items[virtualItem.index];
222
+ return item === undefined ? [] : [{ ...virtualItem, item }];
223
+ });
224
+ if (pinnedStickyIndex === null)
225
+ return windowed;
226
+ const item = items[pinnedStickyIndex];
227
+ if (item === undefined)
228
+ return windowed;
229
+ // In index order, because this element is exposed to assistive technology and
230
+ // reading order is its order in the list. Ordering costs nothing visually: the
231
+ // row is absolutely positioned, so it does not lay out among these siblings, and
232
+ // it stays above them by the sticky rule's `z-index` rather than by coming last.
233
+ const pinned = {
234
+ index: pinnedStickyIndex,
235
+ key: keyAt(pinnedStickyIndex),
236
+ start: locateRowStart(pinnedStickyIndex),
237
+ size: locateRowSize(pinnedStickyIndex),
238
+ item,
239
+ };
240
+ return pinnedStickyIndex < (windowed[0]?.index ?? 0)
241
+ ? [pinned, ...windowed]
242
+ : [...windowed, pinned];
243
+ });
244
+ /**
245
+ * The sticky row to pin when it has scrolled out of the rendered window.
246
+ *
247
+ * Rendered as its own element rather than folded back into the window. The window
248
+ * lays its rows out in flow from a single offset, so inserting a non-contiguous
249
+ * row there displaced every row after it by that row's height — the headings
250
+ * stayed visible and everything else was wrong by one row.
251
+ *
252
+ * A sticky row still INSIDE the window needs none of this: it is contiguous, and
253
+ * `position: sticky` holds it without leaving its flow box.
254
+ */
255
+ /** Membership as a Set: a grouped list can have as many sticky rows as sections. */
256
+ const stickyIndexSet = $derived(new Set(stickyIndexes));
257
+ /**
258
+ * Whether the rows carry set-position semantics at all.
259
+ *
260
+ * Only when the component gives them `listitem`. A consumer overriding `role` takes
261
+ * ownership of the semantics, and `aria-posinset` on a row with no set-bearing role
262
+ * is meaningless at best — assistive technology may ignore it, or may announce a
263
+ * position within a set that does not exist.
264
+ */
265
+ const rowSemanticsApply = $derived(role === 'list');
266
+ /** Pixel offset of a row that the current window does not include. */
267
+ function locateRowStart(index) {
268
+ const table = offsets?.offsets;
269
+ if (table)
270
+ return table[index] ?? 0;
271
+ return index * resolvedItemHeight;
272
+ }
273
+ function locateRowSize(index) {
274
+ const table = offsets?.offsets;
275
+ if (table)
276
+ return Math.max(0, (table[index + 1] ?? 0) - (table[index] ?? 0));
277
+ return resolvedItemHeight;
278
+ }
35
279
  $effect(() => {
36
280
  const element = scrollElement;
37
281
  if (!element)
38
282
  return;
39
- syncViewport(element);
283
+ // Resolved here rather than in a $derived: getComputedStyle does not exist during
284
+ // server rendering, and an effect never runs there.
285
+ writingDirection = resolveWritingDirection(element, domWritingDirectionReader);
286
+ const measuredHeight = syncViewport(element);
287
+ if (needsInitialReversePin) {
288
+ needsInitialReversePin = false;
289
+ // Written here rather than by arming `shouldStickAfterAppend`: that flag is a
290
+ // plain binding, so the append-pin effect does not re-run when it changes —
291
+ // it works only because an `$effect.pre` sets it in the same items-driven
292
+ // pass. Nothing would pick it up from here.
293
+ writeScrollOffset(element, maxScrollOffset(currentTotalSize(), measuredHeight), 'auto');
294
+ scrollOffset = readScrollOffset(element);
295
+ // Under `dynamicSize` the total at mount is only an estimate, so this first
296
+ // write lands short. Marking the list pinned hands it to the re-pin effect,
297
+ // which follows the total as rows measure.
298
+ isPinnedToBottom = true;
299
+ }
300
+ });
301
+ /**
302
+ * Fires the infinite-scroll callbacks as the reader approaches either end.
303
+ *
304
+ * Depends on the window AND the item count: an append can bring the end into
305
+ * range with no scroll event at all, and the count is what re-arms the latch so
306
+ * a second page can be requested after the first arrives.
307
+ */
308
+ $effect(() => {
309
+ const currentWindow = virtualWindow;
310
+ const itemCount = items.length;
311
+ const currentViewportHeight = viewportHeight;
312
+ // Read before the guards below so the effect re-runs when the correction is
313
+ // applied and this clears.
314
+ const hasQueuedCorrection = pendingScrollTarget !== null;
315
+ if (!onEndReached && !onStartReached) {
316
+ // Drop the latch with the callbacks. Left set, re-enabling a callback while
317
+ // still near the same edge and at the same item count would find it already
318
+ // latched and never fire the approach the consumer just asked to hear about.
319
+ edgeLatch = createEdgeLatch();
320
+ return;
321
+ }
322
+ if (isDestroyed)
323
+ return;
324
+ // A correction is queued, so the reader is about to move and any proximity
325
+ // reading now is stale. Firing on it asks for another page before the last one
326
+ // has been placed — which is exactly what a prepend does, since holding the
327
+ // reader's row is what moves them away from the start edge in the first place.
328
+ // `pendingReanchor` covers the same window under `dynamicSize`; it is a plain
329
+ // binding rather than state, so it does not re-trigger this effect on its own,
330
+ // but the scroll write that consumes it updates `scrollOffset`, which does.
331
+ if (hasQueuedCorrection || pendingReanchor !== null)
332
+ return;
333
+ // A restore is about to move the reader, so the list's current position says
334
+ // nothing about which edge they are near. Firing now would ask for a page of
335
+ // history because the list happens to render at offset 0 for one frame.
336
+ if (willRestoreScrollPosition())
337
+ return;
338
+ // Read from the scroll geometry rather than recovered by undoing the window's
339
+ // overscan. Both approaches to undoing it are wrong, in opposite directions:
340
+ // subtracting the configured overscan leaves the adaptive growth in and fires the
341
+ // callbacks tens of rows early, while subtracting the effective overscan
342
+ // over-corrects at the list's own edges, where the window is CLAMPED and the
343
+ // overscan actually realized on that side is smaller than the one asked for. In a
344
+ // 100-row list `endIndex` is 100 however wide adaptation grew, so subtracting 50
345
+ // reported row 49 as the last visible one and suppressed `onEndReached` entirely
346
+ // until the idle timer shrank the window back.
347
+ //
348
+ // `resolveAnchorIndexAtOffset` answers the question directly — which row occupies
349
+ // a given offset — and is already independent of overscan and of edge clamping.
350
+ const lastRenderedIndex = Math.max(0, itemCount - 1);
351
+ const firstVisibleIndex = Math.min(resolveAnchorIndexAtOffset(scrollOffset), lastRenderedIndex);
352
+ // The last row the viewport still touches, hence the -1: at a viewport whose
353
+ // bottom edge falls exactly on a row boundary, the offset itself belongs to the
354
+ // NEXT row, which is not visible yet.
355
+ const lastVisibleIndex = Math.min(resolveAnchorIndexAtOffset(scrollOffset + Math.max(0, currentViewportHeight - 1)), lastRenderedIndex);
356
+ const proximity = resolveEdgeProximity({
357
+ scrollOffset,
358
+ viewportSize: currentViewportHeight,
359
+ totalSize: currentWindow.totalSize,
360
+ firstVisibleIndex,
361
+ lastVisibleIndex,
362
+ itemCount,
363
+ // The CONFIGURED overscan, deliberately not the effective one used just above.
364
+ // That one describes how many rows are mounted, which adaptation changes with
365
+ // scroll velocity; this one is the consumer's "within N items of the end", which
366
+ // it must not. Otherwise a fast fling would widen the trigger distance along
367
+ // with the window and fetch pages earlier the faster the reader moves.
368
+ overscan: resolvedOverscan,
369
+ });
370
+ // Masked per edge, not just when BOTH callbacks are gone. An edge without a
371
+ // callback has nothing to fire, and reporting it as near would leave its own
372
+ // latch set — so re-enabling that one callback at the same position and item
373
+ // count would find it already latched and stay silent.
374
+ const maskedProximity = {
375
+ isNearStart: onStartReached ? proximity.isNearStart : false,
376
+ isNearEnd: onEndReached ? proximity.isNearEnd : false,
377
+ };
378
+ const decision = resolveEdgeFireDecision({
379
+ proximity: maskedProximity,
380
+ previous: edgeLatch,
381
+ itemCount,
382
+ });
383
+ edgeLatch = decision.next;
384
+ // Untracked: a consumer that appends inside the callback would otherwise write
385
+ // `items` while this effect is still reading it, and Svelte would treat that as
386
+ // this effect depending on its own output.
387
+ untrack(() => {
388
+ if (decision.fireStart)
389
+ onStartReached?.();
390
+ if (decision.fireEnd)
391
+ onEndReached?.();
392
+ });
40
393
  });
41
394
  const observeResize = useResizeObserver(() => {
42
395
  if (scrollElement)
43
396
  syncViewport(scrollElement);
44
397
  });
398
+ /**
399
+ * The storage scroll restoration writes to, or `undefined` when it should not
400
+ * write at all.
401
+ *
402
+ * Resolved through a guarded read: some privacy modes throw on merely ACCESSING
403
+ * `sessionStorage`, not just on writing to it, so the property access itself has
404
+ * to be inside the try.
405
+ */
406
+ function resolveRestorationStorage() {
407
+ if (!scrollRestoration)
408
+ return undefined;
409
+ try {
410
+ return typeof sessionStorage === 'undefined' ? undefined : sessionStorage;
411
+ }
412
+ catch {
413
+ return undefined;
414
+ }
415
+ }
416
+ /**
417
+ * Restores a remembered position on mount, and remembers the current one on
418
+ * teardown.
419
+ *
420
+ * Tracks the element and the item count deliberately — a list that fetches its own
421
+ * data has nothing to restore onto until those arrive. What keeps it from running
422
+ * twice is `restoredId`, not a lack of dependencies: re-applying a saved offset
423
+ * over wherever the reader had since scrolled to is the failure this guards.
424
+ */
425
+ $effect(() => {
426
+ const id = scrollRestorationId?.trim();
427
+ const element = scrollElement;
428
+ // Tracked deliberately: a list that fetches its own data renders empty first, so
429
+ // there is nothing to restore onto until its items arrive. `restoredId` is what
430
+ // makes this happen exactly once per collection — without it, re-running on every
431
+ // item change would re-apply the saved position over wherever the reader had
432
+ // since scrolled to.
433
+ const itemCount = items.length;
434
+ if (!element || !id || restoredId === id || itemCount === 0)
435
+ return;
436
+ untrack(() => {
437
+ const storage = resolveRestorationStorage();
438
+ const saved = loadScrollPosition(storage, id);
439
+ if (restoredIdInProgress !== id) {
440
+ // A different collection: its attempt history is its own.
441
+ restoredIdInProgress = id;
442
+ lastRestoreAttemptCount = 0;
443
+ }
444
+ if (!saved) {
445
+ restoredId = id;
446
+ return;
447
+ }
448
+ // By KEY first, and BEFORE judging the index. An index stops describing the
449
+ // same row once the collection changes while unmounted — which is exactly what
450
+ // a feed does — so a stale index is not evidence the row is gone. The key is.
451
+ const anchorIndex = resolveIndexForSavedAnchor(saved);
452
+ const anchorIsResolvable = anchorIndex < items.length &&
453
+ (saved.anchorKey === undefined
454
+ ? saved.startIndex < items.length
455
+ : keyAt(anchorIndex) === saved.anchorKey);
456
+ if (!anchorIsResolvable) {
457
+ // Not found is not the same as deleted. A feed that loads page by page has a
458
+ // first non-empty render that does not reach the saved row yet, and clearing
459
+ // here would delete the position before the page carrying it ever arrived.
460
+ //
461
+ // So: keep waiting while the collection is still growing, and only give up
462
+ // once a render arrives no larger than the last one that failed — at which
463
+ // point the row really is gone. `restoredId` stays unset meanwhile, so the
464
+ // next render tries again.
465
+ if (items.length > lastRestoreAttemptCount) {
466
+ lastRestoreAttemptCount = items.length;
467
+ restoredId = undefined;
468
+ return;
469
+ }
470
+ // Growth has stopped and the row never appeared, so stop looking — the key
471
+ // scan is O(n) and would otherwise run on every future update. The entry is
472
+ // deliberately NOT deleted: nothing is restored from it, and teardown
473
+ // overwrites it with the reader's real position anyway. Deleting it was only
474
+ // ever needed back when a missing anchor got clamped into range.
475
+ restoredId = id;
476
+ return;
477
+ }
478
+ restoredId = id;
479
+ // Nothing queued for the old view may land after this. Two things can be in
480
+ // flight: a correction the growth effect queued to preserve the pre-prepend
481
+ // viewport — the saved row often arrives IN that prepended page — and a settle
482
+ // loop from a `scrollToIndex` started for a collection this component has
483
+ // since been reused away from. Either would write over the restored position
484
+ // a moment later, leaving the reader where they were while loading rather
485
+ // than where they left off.
486
+ pendingScrollTarget = null;
487
+ pendingReanchor = null;
488
+ retireSettleLoop();
489
+ // The append pin too. When the saved anchor arrives in an APPENDED page — under
490
+ // `reverse`, or with `stickToBottom` still reading a short first page as being
491
+ // at the end — the growth pass has already armed it, and its effect scrolls to
492
+ // the maximum offset a tick later, after the restore has landed.
493
+ shouldStickAfterAppend = false;
494
+ isPinnedToBottom = false;
495
+ if (dynamicSize) {
496
+ // Written directly rather than through `scrollToIndex`, which lands on the
497
+ // row's start edge and would lose where the reader was WITHIN a tall row —
498
+ // the difference between reopening mid-paragraph and at the top of it.
499
+ //
500
+ // The offsets table is all estimates at mount, so this lands on the ESTIMATED
501
+ // position of the right row. That is the correct starting point: the
502
+ // measurement-correction pass then holds this row still as the rows above it
503
+ // are measured, which is precisely the job it already does.
504
+ //
505
+ // The remainder is clamped to the row's CURRENT size. While that size is
506
+ // still an estimate a larger saved remainder would overshoot into the next
507
+ // row, and the correction pass would then hold the wrong row still.
508
+ const rowStart = locateRowStartOffset(anchorIndex);
509
+ const rowSize = Math.max(0, locateRowStartOffset(anchorIndex + 1) - rowStart || resolvedItemHeight);
510
+ // Strictly inside the row. An inclusive clamp lands on exactly the next row's
511
+ // start — 30px into a 40px row becomes 20px into a 20px row, which IS row
512
+ // 201 — defeating the anchor this whole branch exists to honour.
513
+ const withinRow = Math.min(Math.max(0, saved.offsetWithinRow ?? 0), Math.max(0, rowSize - 1));
514
+ writeScrollOffset(element, rowStart + withinRow, 'auto');
515
+ scrollOffset = readScrollOffset(element);
516
+ }
517
+ else {
518
+ // From the row anchor, not the raw saved pixel offset. `itemHeight` can differ
519
+ // between visits — a density setting, a responsive breakpoint — and the old
520
+ // offset then points at a different row entirely.
521
+ const withinRow = Math.min(Math.max(0, saved.offsetWithinRow ?? 0), Math.max(0, resolvedItemHeight - 1));
522
+ writeScrollOffset(element, anchorIndex * resolvedItemHeight + withinRow, 'auto');
523
+ scrollOffset = readScrollOffset(element);
524
+ }
525
+ });
526
+ });
527
+ /**
528
+ * Saves the position on teardown.
529
+ *
530
+ * Separate from the restore effect, and depending on nothing but the id. An
531
+ * `$effect` cleanup runs on INVALIDATION as well as teardown, so folding this into
532
+ * an effect that tracks the item count meant every append ran the saver and then
533
+ * re-ran the effect — which, already having restored, returned early and registered
534
+ * no new cleanup. After the first append the teardown save was simply gone.
535
+ */
536
+ $effect(() => {
537
+ const id = scrollRestorationId?.trim();
538
+ if (!id)
539
+ return;
540
+ return () => {
541
+ const storage = resolveRestorationStorage();
542
+ if (!storage)
543
+ return;
544
+ untrack(() => {
545
+ // The snapshot, not a fresh read. When a parent swaps BOTH the id and the
546
+ // items at once, this cleanup runs after that state has already changed —
547
+ // computing here would file the incoming collection's position under the
548
+ // outgoing collection's key.
549
+ const snapshot = latestPosition;
550
+ if (!snapshot)
551
+ return;
552
+ saveScrollPosition(storage, id, snapshot);
553
+ });
554
+ };
555
+ });
556
+ /** Keeps the position saveable at any moment, independent of what changed. */
557
+ $effect(() => {
558
+ // An empty render contributes nothing. Leaving the previous snapshot in place is
559
+ // deliberate: a list emptied just before teardown — a parent swapping collections,
560
+ // or a refetch clearing while it loads — should still save where the reader
561
+ // actually was, not be treated as having no position at all.
562
+ if (items.length === 0)
563
+ return;
564
+ const anchorIndex = resolveAnchorIndexAtOffset(scrollOffset);
565
+ latestPosition = {
566
+ scrollOffset,
567
+ // Derived from the live offset, not from the rendered window. The window's
568
+ // first index carries overscan, and adding it back does not recover the
569
+ // anchor either: near the top the leading overscan is clipped against 0,
570
+ // so `startIndex + overscan` points several rows PAST the reader instead
571
+ // of at them. The offset knows where they actually are.
572
+ startIndex: anchorIndex,
573
+ offsetWithinRow: Math.max(0, scrollOffset - locateRowStartOffset(anchorIndex)),
574
+ anchorKey: keyAt(anchorIndex),
575
+ };
576
+ });
45
577
  $effect.pre(() => {
46
578
  const itemCount = items.length;
47
579
  const element = scrollElement;
580
+ // Captured under whichever mode is active RIGHT NOW, so the next run can
581
+ // evaluate the old scroll position against the geometry it was actually
582
+ // scrolled within — even if the mode changes in between.
583
+ const currentTotal = dynamicSize ? (offsets?.totalSize ?? 0) : itemCount * resolvedItemHeight;
584
+ // Only when `items` itself changed. This effect also depends on `offsets`, which
585
+ // is rebuilt on every row measurement under `dynamicSize` — walking the keys
586
+ // there would turn each measurement into an O(n) pass over the whole list, and
587
+ // the growth it would report is always "unchanged" anyway.
588
+ //
589
+ // `Array.from` over the length rather than `items.map`, which skips sparse holes
590
+ // and would leave the key sequence shorter than the list. Through `keyAt`, not a
591
+ // local getKey call: the measurement cache is keyed by exactly what `keyAt`
592
+ // returns, and a second derivation that disagreed on any item would report
593
+ // growth where there is none.
594
+ // Length as well as identity: a consumer that pushes into the same array keeps
595
+ // its reference, and treating that as unchanged would miss the growth entirely.
596
+ const itemsChanged = items !== previousItems || items.length !== previousKeys.length;
597
+ const nextKeys = itemsChanged
598
+ ? Array.from({ length: items.length }, (_unused, index) => keyAt(index))
599
+ : previousKeys;
600
+ previousItems = items;
48
601
  if (!hasObservedItemCount) {
49
- previousItemCount = itemCount;
602
+ previousTotalSize = currentTotal;
603
+ previousKeys = nextKeys;
50
604
  hasObservedItemCount = true;
51
605
  shouldStickAfterAppend = false;
606
+ // A reverse list opens at its end. Deferred to the mount effect rather than
607
+ // written here: there is no element yet on the first server-or-client pass,
608
+ // and under `dynamicSize` the total is still only an estimate.
609
+ // Not when a position is about to be restored: the reader asked to come back
610
+ // where they were, which outranks opening at the newest message.
611
+ needsInitialReversePin = reverse && !willRestoreScrollPosition();
52
612
  return;
53
613
  }
614
+ // Skipped outright when the array did not change. `classifyItemGrowth` opens with
615
+ // an O(n) equality walk, so running it on every measurement-driven pass would
616
+ // reintroduce the per-measurement cost this guard exists to remove — to reach
617
+ // the answer this branch already knows.
618
+ const growth = itemsChanged
619
+ ? classifyItemGrowth(previousKeys, nextKeys)
620
+ : { kind: 'unchanged' };
54
621
  shouldStickAfterAppend =
55
- stickToBottom &&
56
- element !== undefined &&
57
- itemCount > previousItemCount &&
58
- isAtBottom(element, previousItemCount * resolvedItemHeight, viewportHeight);
59
- previousItemCount = itemCount;
622
+ element !== undefined &&
623
+ shouldPinToEnd({
624
+ mode: reverse ? 'reverse' : stickToBottom ? 'stick-to-bottom' : 'none',
625
+ growth,
626
+ // Against the PREVIOUS run's total, not a total re-derived under the mode
627
+ // that happens to be active now. Re-deriving reads the dynamic total as 0
628
+ // for as long as fixed mode was active, which yanks a scrolled-up reader to
629
+ // the end; and skipping the check whenever the mode changed — the obvious
630
+ // guard against that — instead drops the pin for a reader who genuinely was
631
+ // at the bottom. Carrying the real previous total is correct in both
632
+ // directions and needs no mode special-case at all.
633
+ isAtEnd: isAtBottom(element, previousTotalSize, viewportHeight),
634
+ });
635
+ // A prepend inserts content ABOVE the reader. Every existing row shifts down by
636
+ // the height of what arrived, so holding `scrollOffset` still would silently
637
+ // move them to a different row — and with native scroll anchoring disabled
638
+ // under `dynamicSize`, nothing puts them back. Anchoring to the row they were
639
+ // actually on is the only thing that reads as "the list grew upward".
640
+ if (growth.kind === 'prepended' && element) {
641
+ const table = offsets?.offsets;
642
+ const liveScrollOffset = readScrollOffset(element);
643
+ if (table) {
644
+ const anchorIndex = findOffsetIndex(table, liveScrollOffset);
645
+ pendingReanchor = {
646
+ // The same row now sits `prependedCount` further along the list.
647
+ index: anchorIndex + growth.prependedCount,
648
+ offsetWithinRow: liveScrollOffset - (table[anchorIndex] ?? 0),
649
+ };
650
+ }
651
+ else {
652
+ // Fixed-height mode has no offsets table, but every row is the same size,
653
+ // so the shift is exactly arithmetic.
654
+ pendingScrollTarget = Math.max(0, liveScrollOffset + growth.prependedCount * resolvedItemHeight);
655
+ }
656
+ }
657
+ previousTotalSize = currentTotal;
658
+ previousKeys = nextKeys;
659
+ });
660
+ /**
661
+ * Drops cached sizes for rows that are no longer in the list.
662
+ *
663
+ * Without this a long-lived feed that filters or rolls over its contents keeps
664
+ * every size it has ever measured, so memory tracks history rather than the
665
+ * current collection — and a key that comes back later would start from stale
666
+ * geometry until its ResizeObserver reported again.
667
+ */
668
+ $effect(() => {
669
+ // Depends on `items` and `dynamicSize` only. Reading the cache through
670
+ // `sizes` would register the version counter and re-run this whole O(n) walk
671
+ // after every measurement; `measuredCount` reads the same Map without
672
+ // subscribing, so the walk happens when the list changes and not before
673
+ // anything has been measured at all.
674
+ const currentItems = items;
675
+ if (!dynamicSize || measurementStore.measuredCount === 0)
676
+ return;
677
+ const validKeys = new Set();
678
+ for (let index = 0; index < currentItems.length; index += 1)
679
+ validKeys.add(keyAt(index));
680
+ measurementStore.prune(validKeys);
681
+ });
682
+ /**
683
+ * Drops cached sizes when dynamic mode is switched off.
684
+ *
685
+ * Rows are no longer observed while fixed mode runs, so a row that changes
686
+ * height in the meantime — an offscreen one especially — would otherwise be
687
+ * rebuilt from its stale cached size the moment dynamic mode came back, and an
688
+ * offscreen row may never be re-observed to correct it.
689
+ *
690
+ * Note this deliberately does NOT touch `rowResizeObserver`. Observer lifetime
691
+ * is keyed to component teardown alone; keying it to a prop is what previously
692
+ * let a re-render disconnect it permanently.
693
+ */
694
+ $effect(() => {
695
+ if (dynamicSize)
696
+ return;
697
+ measurementStore.reset();
698
+ previousOffsets = undefined;
699
+ });
700
+ /**
701
+ * Releases the bottom pin whenever the option is off.
702
+ *
703
+ * `handleScroll` only maintains the flag while `stickToBottom` is true, so a
704
+ * pin taken before the option was disabled would survive scrolling away and
705
+ * re-enabling the option later would jump the viewport to the bottom with no
706
+ * append having happened.
707
+ */
708
+ $effect(() => {
709
+ if (!stickToBottom && !reverse)
710
+ isPinnedToBottom = false;
60
711
  });
61
712
  $effect(() => {
62
713
  const itemCount = items.length;
63
714
  const element = scrollElement;
64
- if (!stickToBottom || !shouldStickAfterAppend || !element)
715
+ if ((!stickToBottom && !reverse) || !shouldStickAfterAppend || !element)
65
716
  return;
66
717
  void tick().then(() => {
67
- element.scrollTop = maxScrollOffset(itemCount * resolvedItemHeight, viewportHeight);
68
- syncViewport(element);
718
+ // Re-read the prop: it can be disabled between the append and this callback,
719
+ // and the disabled-mode effect will already have cleared the pin. Arming it
720
+ // again here would leave a stale flag that no later scroll clears, so
721
+ // re-enabling the option would jump to the end with no append behind it.
722
+ if (!stickToBottom && !reverse) {
723
+ shouldStickAfterAppend = false;
724
+ return;
725
+ }
726
+ // Measure first. An update that appends AND shrinks `height` in one go would
727
+ // otherwise compute the bottom from the pre-patch viewport and land short —
728
+ // and in fixed mode there is no re-pin effect afterwards to rescue it.
729
+ const currentViewportHeight = syncViewport(element);
730
+ writeScrollOffset(element, maxScrollOffset(dynamicSize ? (offsets?.totalSize ?? 0) : itemCount * resolvedItemHeight, currentViewportHeight), 'auto');
731
+ scrollOffset = readScrollOffset(element);
69
732
  shouldStickAfterAppend = false;
733
+ isPinnedToBottom = true;
70
734
  });
71
735
  });
736
+ /**
737
+ * Holds the viewport at the bottom while an appended row is still being measured.
738
+ *
739
+ * Under `dynamicSize` the append pin above scrolls to the total as it is
740
+ * currently estimated. A row that then measures taller than `itemHeight` — the
741
+ * common case for the wrapping and media rows this mode exists for — grows the
742
+ * total without changing the item count, so nothing re-pins, and the anchor
743
+ * correction deliberately ignores it because it sits below the anchor. The
744
+ * viewport would sit short of the bottom, contradicting what `stickToBottom`
745
+ * promises. Re-pinning on total-size growth closes that window.
746
+ */
747
+ $effect(() => {
748
+ // Both reactive reads happen BEFORE any early return. Guarding first would
749
+ // skip them on the run where the pin is not yet armed, so the effect would
750
+ // never register the total size as a dependency and would never re-run when a
751
+ // measurement changed it — which is the entire case this exists to handle.
752
+ const totalSize = offsets?.totalSize ?? 0;
753
+ const currentViewportHeight = viewportHeight;
754
+ // `reverse` routes through the same `isPinnedToBottom` flag rather than
755
+ // bypassing it. Scrolling up clears the flag, so a measurement that grows the
756
+ // total does NOT drag a reader out of history; an append then re-arms it, and
757
+ // the row appended under `dynamicSize` measures after the pin write — which is
758
+ // exactly the window this effect covers.
759
+ if ((!stickToBottom && !reverse) || !dynamicSize || !isPinnedToBottom)
760
+ return;
761
+ const element = scrollElement;
762
+ if (!element)
763
+ return;
764
+ const target = maxScrollOffset(totalSize, currentViewportHeight);
765
+ if (Math.abs(readScrollOffset(element) - target) <= 1)
766
+ return;
767
+ writeScrollOffset(element, target, 'auto');
768
+ scrollOffset = readScrollOffset(element);
769
+ });
770
+ /**
771
+ * Resolves the scroll correction a batch of measurements implies, against the
772
+ * offsets table as it stood BEFORE those measurements landed.
773
+ *
774
+ * `offsets` is derived off the same version counter `record()` bumps, so by the
775
+ * time this runs it has already rebuilt to include the very measurements being
776
+ * corrected for. Binary-searching it would find the anchor against
777
+ * post-mutation geometry and mis-identify it, so the pre-mutation snapshot in
778
+ * `previousOffsets` is the only correct table to search.
779
+ *
780
+ * The correction is computed here, pre-patch, but written in the paired
781
+ * `$effect` below — after Svelte patches the DOM, still before paint. A
782
+ * relative `scrollTop += delta` written here instead would be clamped by the
783
+ * browser against the stale, pre-patch content size and partially lost.
784
+ */
785
+ $effect.pre(() => {
786
+ if (!dynamicSize)
787
+ return;
788
+ void measurementStore.pendingCorrectionsVersion;
789
+ const corrections = measurementStore.consumePendingCorrections();
790
+ const currentOffsets = offsets?.offsets;
791
+ const currentEstimate = resolvedItemHeight;
792
+ const element = scrollElement;
793
+ const estimateChanged = previousEstimate > 0 && currentEstimate !== previousEstimate;
794
+ previousEstimate = currentEstimate;
795
+ if (!element || !currentOffsets) {
796
+ previousOffsets = currentOffsets;
797
+ return;
798
+ }
799
+ // Live, not the `scrollOffset` state: during a smooth scroll, after an external
800
+ // write, or before a throttled scroll event lands, the state trails the real
801
+ // position, and every calculation below is relative to where the reader is NOW.
802
+ const liveScrollOffset = readScrollOffset(element);
803
+ // Every wholesale rebuild of the offsets table funnels through one re-anchor.
804
+ // There are three triggers — a width-driven cache reset, an `itemHeight` change,
805
+ // and (historically) each new one someone adds — and each moves the reader
806
+ // unless the row they are on is restored, because this mode turns off the
807
+ // browser's native scroll anchoring in order to own that itself. Handling them
808
+ // as separate branches is what let the third one overwrite the others.
809
+ let anchor = pendingReanchor;
810
+ pendingReanchor = null;
811
+ if (anchor === null && estimateChanged && previousOffsets) {
812
+ // A reset captured its anchor before discarding the cache; an estimate change
813
+ // can still read the pre-change table here.
814
+ const index = findOffsetIndex(previousOffsets, liveScrollOffset);
815
+ anchor = { index, offsetWithinRow: liveScrollOffset - (previousOffsets[index] ?? 0) };
816
+ }
817
+ let target = null;
818
+ if (anchor !== null) {
819
+ const anchorStart = currentOffsets[anchor.index] ?? 0;
820
+ // Clamp to the row as it exists in the REBUILT table. The reader may have been
821
+ // deep inside a measured row that the rebuild replaced with a small estimate;
822
+ // carrying the raw offset across would land many rows past the anchor, and the
823
+ // anchor row would then unmount and never be remeasured to correct it.
824
+ const anchorSize = Math.max(0, (currentOffsets[anchor.index + 1] ?? anchorStart) - anchorStart);
825
+ const offsetWithinRow = Math.min(Math.max(0, anchor.offsetWithinRow), anchorSize);
826
+ target = Math.max(0, anchorStart + offsetWithinRow);
827
+ }
828
+ // Measurement corrections apply ONLY when no re-anchor ran. A re-anchor is
829
+ // computed from the rebuilt table, which already contains this flush's
830
+ // measurements, so adding the delta on top would count them twice and overshoot
831
+ // by exactly the measured difference. Previously the correction simply
832
+ // overwrote the re-anchored target, which lost the estimate adjustment instead —
833
+ // both are wrong, and which one wins is not a matter of ordering.
834
+ if (target === null && corrections.length > 0 && previousOffsets) {
835
+ const anchorIndex = findOffsetIndex(previousOffsets, liveScrollOffset);
836
+ const delta = resolveMeasurementCorrectionDelta(corrections, anchorIndex);
837
+ if (delta !== 0)
838
+ target = liveScrollOffset + delta;
839
+ }
840
+ if (target !== null)
841
+ pendingScrollTarget = Math.max(0, target);
842
+ previousOffsets = currentOffsets;
843
+ });
844
+ /**
845
+ * Whether a saved position is going to be applied on this mount.
846
+ *
847
+ * Consulted before arming the initial `reverse` pin, and before letting the edge
848
+ * callbacks fire: both assume the list opens where it renders, and restoration is
849
+ * about to move it somewhere else entirely.
850
+ */
851
+ function willRestoreScrollPosition() {
852
+ const id = scrollRestorationId?.trim();
853
+ if (!scrollRestoration || !id || restoredId === id)
854
+ return false;
855
+ // Only while a restore is IMMINENT. Once an attempt has failed and the component
856
+ // is waiting for more data, the edge callbacks are exactly what fetches the page
857
+ // carrying the anchor — suppressing them there deadlocks the two features
858
+ // against each other: no pagination, so no anchor, so no restore, forever.
859
+ if (lastRestoreAttemptCount > 0)
860
+ return false;
861
+ // Same deadlock at the other end. An empty list has nothing to restore ONTO, and
862
+ // the restore effect returns before recording an attempt — so a list that mounts
863
+ // empty and fetches its first page from these very callbacks would wait forever.
864
+ if (items.length === 0)
865
+ return false;
866
+ return loadScrollPosition(resolveRestorationStorage(), id) !== null;
867
+ }
868
+ /**
869
+ * The index a saved anchor refers to NOW.
870
+ *
871
+ * The key wins when the list has one and it is still present: the collection may
872
+ * have grown at the front while the list was unmounted, which moves every index
873
+ * without moving any row. Falls back to the saved index, clamped.
874
+ */
875
+ function resolveIndexForSavedAnchor(saved) {
876
+ const lastIndex = Math.max(0, items.length - 1);
877
+ if (saved.anchorKey !== undefined) {
878
+ for (let index = 0; index < items.length; index += 1) {
879
+ if (keyAt(index) === saved.anchorKey)
880
+ return index;
881
+ }
882
+ }
883
+ return Math.min(Math.max(0, saved.startIndex), lastIndex);
884
+ }
885
+ /**
886
+ * Inline style for one row: its main-axis size under fixed sizing, plus the offset
887
+ * that pins it when it is the active sticky row outside the window.
888
+ *
889
+ * The pinned row keeps its size even under `dynamicSize`, where rows are normally
890
+ * left unsized so they can be measured — out of flow it has no siblings to size it
891
+ * against, so without this it would collapse to its content.
892
+ */
893
+ function resolveRowStyle(index, size) {
894
+ const isPinned = index === pinnedStickyIndex;
895
+ const declarations = [];
896
+ // Under `dynamicSize` the row carries no main-axis size at all, pinned or not.
897
+ //
898
+ // A definite size froze the observed border box, so a header growing while pinned
899
+ // could never be remeasured. A minimum fixed that and froze the opposite direction:
900
+ // a header that SHRINKS — collapsible content, an async replacement — kept its old
901
+ // extent, held empty space, and left `stickyObstructionSize` reporting the larger
902
+ // value to every keyboard and scroll destination.
903
+ //
904
+ // Both came from special-casing the pinned row. Every other dynamic row is left
905
+ // unsized precisely so it can be measured; out of flow this one is sized by its own
906
+ // content, which is the intrinsic extent the observer is there to read.
907
+ if (!dynamicSize)
908
+ declarations.push(`${rowLayout.sizeProperty}:${size}px`);
909
+ if (isPinned) {
910
+ // Relative to the WINDOW, which is itself already translated by its leading
911
+ // size. Writing the raw scroll offset here compounded the two and put the row
912
+ // at `leadingSize + scrollOffset` — with no overscan and 20px rows at a scroll
913
+ // of 4000, that is 8000px, nowhere near the viewport.
914
+ const offsetWithinWindow = Math.max(0, scrollOffset - virtualWindow.leadingSize);
915
+ declarations.push(`${rowLayout.offsetProperty}:${offsetWithinWindow}px`);
916
+ }
917
+ return declarations.length > 0 ? `${declarations.join(';')};` : undefined;
918
+ }
919
+ /** Where a row begins, from the measured table when there is one. */
920
+ function locateRowStartOffset(index) {
921
+ const table = offsets?.offsets;
922
+ if (table)
923
+ return table[index] ?? 0;
924
+ return index * resolvedItemHeight;
925
+ }
926
+ /**
927
+ * The index of the row occupying a given scroll offset — the row the reader is
928
+ * looking at, independent of overscan and of any clamping at the list's edges.
929
+ */
930
+ function resolveAnchorIndexAtOffset(offset) {
931
+ const lastIndex = Math.max(0, items.length - 1);
932
+ const table = offsets?.offsets;
933
+ if (table)
934
+ return Math.min(findOffsetIndex(table, Math.max(0, offset)), lastIndex);
935
+ return Math.min(Math.floor(Math.max(0, offset) / Math.max(1, resolvedItemHeight)), lastIndex);
936
+ }
937
+ $effect(() => {
938
+ if (pendingScrollTarget === null)
939
+ return;
940
+ const element = scrollElement;
941
+ const target = pendingScrollTarget;
942
+ pendingScrollTarget = null;
943
+ if (!element)
944
+ return;
945
+ // The bottom pin wins. A batch containing resizes both above and below the
946
+ // anchor makes the two mechanisms disagree: the pin moves to the new total
947
+ // using every delta, while this correction accounts only for the ones before
948
+ // the anchor. Writing it afterwards would land short of the bottom and the
949
+ // resulting scroll event could disarm the pin entirely.
950
+ if (isPinnedToBottom)
951
+ return;
952
+ // Never animated: a smooth correction would visibly show the jump it exists to hide.
953
+ writeScrollOffset(element, Math.max(0, target), 'auto');
954
+ scrollOffset = readScrollOffset(element);
955
+ });
956
+ const virtualListRef = { scrollToIndex };
957
+ $effect(() => {
958
+ ref = virtualListRef;
959
+ return () => {
960
+ ref = undefined;
961
+ };
962
+ });
963
+ /**
964
+ * The component's only teardown hook. Deliberately has NO dependencies, so its
965
+ * cleanup runs exactly once, when the component is actually destroyed.
966
+ *
967
+ * Tying this to `dynamicSize` instead is a trap worth naming: a parent that
968
+ * re-renders with an unchanged `dynamicSize` can still re-run the effect, whose
969
+ * cleanup would disconnect the shared row observer — and because the row
970
+ * attachments themselves did not change, nothing would ever re-observe. Every
971
+ * row then goes silently unmeasured while the component still looks healthy.
972
+ *
973
+ * Mode changes need no teardown here: when `dynamicSize` goes false each row's
974
+ * own attachment re-runs and unobserves itself, and keeping the observer and the
975
+ * size cache alive across a toggle avoids re-measuring rows that never changed.
976
+ */
977
+ $effect(() => () => {
978
+ isDestroyed = true;
979
+ if (velocityIdleTimer !== undefined)
980
+ clearTimeout(velocityIdleTimer);
981
+ rowResizeObserver?.disconnect();
982
+ rowResizeObserver = undefined;
983
+ measurementStore.reset();
984
+ previousOffsets = undefined;
985
+ });
986
+ function keyAt(index) {
987
+ const item = items[index];
988
+ return item === undefined ? index : (getKey?.(item, index) ?? index);
989
+ }
72
990
  function estimateViewportHeight(value, resolvedRowHeight) {
73
991
  return parsePixelLength(value) ?? resolvedRowHeight * 10;
74
992
  }
993
+ /**
994
+ * Reads the scroll offset along whichever axis is active, as a distance from the
995
+ * start edge that always grows away from it.
996
+ *
997
+ * Under `horizontal` + RTL that is not simply `scrollLeft`: browsers disagree on
998
+ * its sign and origin, so the raw value is normalized through the convention this
999
+ * browser was measured to use. See `resolveRtlScrollType`.
1000
+ */
1001
+ function readScrollOffset(element) {
1002
+ if (!horizontal)
1003
+ return Math.max(0, element.scrollTop);
1004
+ // Normalization is the identity under ltr, and resolving the convention costs a
1005
+ // layout-forcing probe. Short-circuit so a left-to-right page never pays for an
1006
+ // answer it would discard.
1007
+ if (writingDirection === 'ltr')
1008
+ return Math.max(0, element.scrollLeft);
1009
+ return Math.max(0, normalizeInlineScrollOffset(element.scrollLeft, element.scrollWidth, element.clientWidth, writingDirection, resolveRtlScrollType()));
1010
+ }
1011
+ /** Writes a start-edge-relative offset back along the active axis. */
1012
+ function writeScrollOffset(element, offset, behavior) {
1013
+ if (!horizontal) {
1014
+ if (behavior === 'smooth' && typeof element.scrollTo === 'function') {
1015
+ element.scrollTo({ top: offset, behavior: 'smooth' });
1016
+ }
1017
+ else {
1018
+ element.scrollTop = offset;
1019
+ }
1020
+ return;
1021
+ }
1022
+ // Convert back out of the normalized space into whatever this browser expects.
1023
+ // `normalizeInlineScrollOffset` is its own inverse for every convention here:
1024
+ // 'default' is identity, 'negative' negates, and 'reverse' subtracts from the
1025
+ // maximum — each of which undoes itself when applied twice.
1026
+ const raw = writingDirection === 'ltr'
1027
+ ? offset
1028
+ : normalizeInlineScrollOffset(offset, element.scrollWidth, element.clientWidth, writingDirection, resolveRtlScrollType());
1029
+ if (behavior === 'smooth' && typeof element.scrollTo === 'function') {
1030
+ element.scrollTo({ left: raw, behavior: 'smooth' });
1031
+ }
1032
+ else {
1033
+ element.scrollLeft = raw;
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Measures, once per document, which RTL `scrollLeft` convention this browser
1038
+ * implements.
1039
+ *
1040
+ * Detected rather than assumed. The three conventions are only distinguishable by
1041
+ * behaviour, and choosing one by name is how the sign silently inverts —
1042
+ * `'default'` reads as the safe choice and is in fact the legacy Edge/IE
1043
+ * behaviour, while current browsers use `'negative'`.
1044
+ */
1045
+ function resolveRtlScrollType() {
1046
+ if (detectedRtlScrollType !== null)
1047
+ return detectedRtlScrollType;
1048
+ if (typeof document === 'undefined')
1049
+ return 'negative';
1050
+ const probe = document.createElement('div');
1051
+ probe.setAttribute('dir', 'rtl');
1052
+ probe.style.position = 'absolute';
1053
+ probe.style.insetBlockStart = '-9999px';
1054
+ probe.style.inlineSize = '1px';
1055
+ probe.style.blockSize = '1px';
1056
+ probe.style.overflow = 'scroll';
1057
+ const content = document.createElement('div');
1058
+ content.style.inlineSize = '2px';
1059
+ content.style.blockSize = '1px';
1060
+ probe.append(content);
1061
+ document.body.append(probe);
1062
+ const startScrollLeft = probe.scrollLeft;
1063
+ probe.scrollLeft = -1;
1064
+ const afterNegativeWrite = probe.scrollLeft;
1065
+ probe.remove();
1066
+ detectedRtlScrollType = classifyRtlScrollType(startScrollLeft, afterNegativeWrite);
1067
+ return detectedRtlScrollType;
1068
+ }
1069
+ /**
1070
+ * Re-reads the container's size and scroll position, and returns the size it
1071
+ * measured so a caller acting in the same turn can use the fresh value rather
1072
+ * than the `viewportHeight` derived, which still holds the pre-patch number.
1073
+ */
75
1074
  function syncViewport(element) {
76
1075
  const rect = element.getBoundingClientRect();
77
- measuredViewportHeight =
78
- rect.height || element.clientHeight || parsePixelLength(height) || resolvedItemHeight * 10;
79
- scrollOffset = Math.max(0, element.scrollTop);
1076
+ // The MAIN axis — the one being scrolled and windowed. Under `horizontal` that
1077
+ // is the inline extent: the container's block-size is `auto` and collapses to
1078
+ // one row's height, which would badly under-report the viewport and render too
1079
+ // few columns. The `height` prop is reinterpreted as the inline size in that
1080
+ // mode, so the fallback stays correct without a branch.
1081
+ const measured = (horizontal ? rect.width || element.clientWidth : rect.height || element.clientHeight) ||
1082
+ parsePixelLength(height) ||
1083
+ resolvedItemHeight * 10;
1084
+ // A CROSS-axis change re-wraps every row, so every cached main-axis size taken
1085
+ // at the old cross extent is now wrong. Offscreen rows would keep those stale
1086
+ // sizes until they happened to remount, leaving the spacer and every scroll
1087
+ // target off by the accumulated difference. Dropping the cache forces
1088
+ // re-measurement.
1089
+ // The client extent first: it is what is actually available to rows, excluding
1090
+ // the scrollbar. A measurement that makes the list start or stop overflowing
1091
+ // adds or removes a non-overlay scrollbar and re-wraps every row while the
1092
+ // border-box extent never changes — so comparing the rect would miss it
1093
+ // entirely and leave offscreen rows holding sizes measured at the other extent.
1094
+ invalidateOnCrossAxisChange(element, rect);
1095
+ measuredViewportHeight = measured;
1096
+ scrollOffset = readScrollOffset(element);
1097
+ return measured;
1098
+ }
1099
+ /**
1100
+ * Drops cached row sizes when the CROSS axis changed, because that re-wraps every
1101
+ * row and every size measured at the old extent is now wrong.
1102
+ */
1103
+ function invalidateOnCrossAxisChange(element, rect) {
1104
+ // The client extent first: it is what is actually available to rows, excluding
1105
+ // the scrollbar. A measurement that makes the list start or stop overflowing
1106
+ // adds or removes a non-overlay scrollbar and re-wraps every row while the
1107
+ // border-box extent never changes — so comparing the rect would miss it
1108
+ // entirely and leave offscreen rows holding sizes measured at the other extent.
1109
+ const measuredCrossExtent = horizontal
1110
+ ? element.clientHeight || rect.height || 0
1111
+ : element.clientWidth || rect.width || 0;
1112
+ if (dynamicSize &&
1113
+ measuredCrossExtent > 0 &&
1114
+ previousCrossExtent > 0 &&
1115
+ measuredCrossExtent !== previousCrossExtent) {
1116
+ // Capture where the reader is BEFORE discarding the cache. The reset rebuilds
1117
+ // every row from the estimate and drops `previousOffsets`, so the correction
1118
+ // effect would have no old geometry to anchor against — and with native
1119
+ // anchoring disabled, an unchanged scrollTop then resolves to a different row
1120
+ // and stays there until the rows above happen to be measured again, which for
1121
+ // offscreen rows may be never.
1122
+ const table = offsets?.offsets;
1123
+ if (table) {
1124
+ const liveScrollOffset = readScrollOffset(element);
1125
+ const anchorIndex = findOffsetIndex(table, liveScrollOffset);
1126
+ pendingReanchor = {
1127
+ index: anchorIndex,
1128
+ offsetWithinRow: liveScrollOffset - (table[anchorIndex] ?? 0),
1129
+ };
1130
+ }
1131
+ measurementStore.reset();
1132
+ previousOffsets = undefined;
1133
+ }
1134
+ if (measuredCrossExtent > 0)
1135
+ previousCrossExtent = measuredCrossExtent;
80
1136
  }
81
1137
  function handleScroll(event) {
82
1138
  if (typeof onScroll === 'function')
83
1139
  onScroll(event);
84
1140
  const element = event.currentTarget;
85
- scrollOffset = Math.max(0, element.scrollTop);
1141
+ scrollOffset = readScrollOffset(element);
1142
+ if (adaptiveOverscan) {
1143
+ // `event.timeStamp` rather than a clock read: it is the time the browser
1144
+ // associated with the scroll itself, so a handler delayed behind a long task
1145
+ // does not report the delay as a slower scroll.
1146
+ velocityTracker = trackScrollVelocity(velocityTracker, {
1147
+ scrollOffset,
1148
+ timestamp: event.timeStamp,
1149
+ });
1150
+ scrollVelocity = velocityTracker.velocityInPixelsPerMillisecond;
1151
+ // Velocity only updates when ANOTHER scroll event arrives, so a reader who
1152
+ // stops mid-fling would otherwise hold the enlarged overscan indefinitely —
1153
+ // exactly the oversized DOM this feature exists to avoid. The last event is
1154
+ // the one that has to schedule the decay.
1155
+ if (velocityIdleTimer !== undefined)
1156
+ clearTimeout(velocityIdleTimer);
1157
+ velocityIdleTimer = setTimeout(() => {
1158
+ if (isDestroyed)
1159
+ return;
1160
+ velocityTracker = createVelocityTracker();
1161
+ scrollVelocity = 0;
1162
+ }, VELOCITY_IDLE_RESET_MILLISECONDS);
1163
+ }
1164
+ // Scrolling away from the bottom releases the pin; scrolling back re-arms it.
1165
+ if (stickToBottom || reverse) {
1166
+ isPinnedToBottom = isAtBottom(element, currentTotalSize(), viewportHeight);
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Abandons any in-flight `scrollToIndex` settle loop, because the user has taken
1171
+ * over the viewport.
1172
+ *
1173
+ * Keyed on INPUT events rather than on scroll offsets. Inferring takeover by
1174
+ * comparing the offset against the last programmatic target cannot work: a smooth
1175
+ * scroll emits intermediate events whose offsets differ from the final one by
1176
+ * construction, so the first animation step reads as interruption and cancels the
1177
+ * settle pass that smooth scrolling most needs. A wheel, pointer, touch, or key
1178
+ * event is unambiguous — nothing but the user produces one.
1179
+ */
1180
+ function retireSettleLoop() {
1181
+ scrollToIndexGeneration += 1;
1182
+ }
1183
+ function handleWheel(event) {
1184
+ retireSettleLoop();
1185
+ if (typeof onWheel === 'function')
1186
+ onWheel(event);
1187
+ }
1188
+ function handlePointerDown(event) {
1189
+ retireSettleLoop();
1190
+ if (typeof onPointerDown === 'function')
1191
+ onPointerDown(event);
1192
+ }
1193
+ function handleTouchStart(event) {
1194
+ retireSettleLoop();
1195
+ if (typeof onTouchStart === 'function')
1196
+ onTouchStart(event);
1197
+ }
1198
+ /**
1199
+ * Whether a key scrolls the axis THIS list scrolls on.
1200
+ *
1201
+ * The cross axis does not overflow, so the arrows across it move nothing here: Left
1202
+ * and Right in a vertical list, Up and Down in a horizontal one. Treating those as a
1203
+ * takeover retires a settle loop that is still correcting a destination, and under
1204
+ * `dynamicSize` the correction those later measurements were going to make never
1205
+ * happens.
1206
+ */
1207
+ function scrollsMainAxis(key) {
1208
+ return horizontal ? INLINE_AXIS_SCROLL_KEYS.has(key) : BLOCK_AXIS_SCROLL_KEYS.has(key);
1209
+ }
1210
+ function handleKeyDown(event) {
1211
+ if (typeof onKeyDown === 'function')
1212
+ onKeyDown(event);
1213
+ if (event.defaultPrevented)
1214
+ return;
1215
+ // A modified navigation key is a browser shortcut, not list movement. Alt with the
1216
+ // arrows is back and forward — which a horizontal list would otherwise swallow
1217
+ // whole, moving one row instead of leaving the page — and Ctrl or Meta with Home
1218
+ // and End is the browser's own. Shift is deliberately not here: nothing in this
1219
+ // list claims it, and Shift+Space is an ordinary native scroll.
1220
+ if (event.altKey || event.ctrlKey || event.metaKey)
1221
+ return;
1222
+ // Keys that came from something inside a row belong to that control, not to this
1223
+ // list. A text input, slider, or select uses the arrow keys itself, so the event
1224
+ // scrolls nothing here — and retiring the settle loop for it silently cancels a
1225
+ // correction the destination is still owed, finishing a jump on a stale estimate.
1226
+ //
1227
+ // A row control that does NOT consume the key (a link, a button) does let the
1228
+ // container scroll, and this leaves the loop running through that. Between the
1229
+ // two, keeping a correction that a rare native scroll then overrides is the
1230
+ // smaller error: typing in a row is ordinary, and arrowing on a button mid-jump
1231
+ // is not.
1232
+ if (event.target !== event.currentTarget)
1233
+ return;
1234
+ if (scrollsMainAxis(event.key))
1235
+ retireSettleLoop();
1236
+ // Only take over the keys when there is a sticky row to keep in view or the
1237
+ // list is virtualized past what the browser can reach. Otherwise the native
1238
+ // scroll container already handles every one of these correctly, and
1239
+ // intercepting them would replace smooth native scrolling with a jump.
1240
+ if (!stickyIndexes.length)
1241
+ return;
1242
+ // Page keys move by PIXELS, not by a row count, and do not go through
1243
+ // `scrollToIndex` at all.
1244
+ //
1245
+ // Three rounds of review found three defects in the index-based version, each one
1246
+ // the next approximation of the same thing: dividing the whole viewport rather than
1247
+ // the uncovered part, dividing by the estimate rather than measured geometry, and
1248
+ // counting a partly-visible row as a whole one. The last of those has a mirror
1249
+ // image going backwards — a partly COVERED leading row — and fixing that in index
1250
+ // space would have been the fourth approximation.
1251
+ //
1252
+ // They share a cause. An index-based step cannot express "one page of pixels" when
1253
+ // rows vary in height: it has to guess a row count, and every guess is wrong at
1254
+ // some boundary. Moving the scroll by the uncovered viewport height instead is
1255
+ // exact, symmetric between the two directions by construction, and skips nothing:
1256
+ // whatever sat just past the visible bottom sits just below the header afterwards.
1257
+ if (event.key === 'PageDown' || event.key === 'PageUp') {
1258
+ const element = scrollElement;
1259
+ if (!element)
1260
+ return;
1261
+ event.preventDefault();
1262
+ // Explicitly, rather than relying on the key sets above. Those describe which
1263
+ // keys the BROWSER scrolls an element with, and the Page keys are absent from the
1264
+ // inline-axis set because a horizontal container is not what they scroll — but
1265
+ // this branch claims them in either orientation, and a settle loop left running
1266
+ // can write its own destination back afterwards and undo the page.
1267
+ retireSettleLoop();
1268
+ const furthest = maxScrollOffset(currentTotalSize(), viewportHeight);
1269
+ const clampToScrollRange = (offset) => Math.min(Math.max(0, offset), furthest);
1270
+ if (event.key === 'PageUp') {
1271
+ // Backwards, the reader's current uncovered top should end up at the new
1272
+ // viewport's bottom edge — so the header in play is the one covering them now.
1273
+ writeScrollOffset(element, clampToScrollRange(scrollOffset + stickyObstructionSize - viewportHeight), smoothScroll && !reducedMotion.current ? 'smooth' : 'auto');
1274
+ scrollOffset = readScrollOffset(element);
1275
+ return;
1276
+ }
1277
+ // Forwards, what sat just past the visible bottom should end up just below the
1278
+ // header — which is the header active AT THE DESTINATION, not the one here. They
1279
+ // differ whenever the page crosses into another section, and assuming they match
1280
+ // hides the difference: stepping 180px with a 20px header into a section whose
1281
+ // header is 100px leaves the first 80px covered and never read.
1282
+ //
1283
+ // Resolved by settling once. The destination depends on its own obstruction, so
1284
+ // the first estimate picks the section and the second uses that section's header.
1285
+ // A further pass would only matter if the correction crossed into a THIRD
1286
+ // section, which needs a header taller than the viewport.
1287
+ const visibleBottom = scrollOffset + viewportHeight;
1288
+ const estimated = clampToScrollRange(visibleBottom - stickyObstructionSize);
1289
+ const destinationObstruction = resolveObstructionAtOffset(estimated);
1290
+ writeScrollOffset(element, clampToScrollRange(visibleBottom - destinationObstruction), smoothScroll && !reducedMotion.current ? 'smooth' : 'auto');
1291
+ scrollOffset = readScrollOffset(element);
1292
+ return;
1293
+ }
1294
+ const target = resolveKeyboardTargetIndex({
1295
+ key: event.key,
1296
+ // The row the reader can see, not the rendered edge: `virtualWindow.startIndex`
1297
+ // carries overscan, so the first arrow press jumped relative to a row several
1298
+ // above the viewport.
1299
+ // The first row the header is not covering. A sticky header occupies the
1300
+ // viewport's leading edge, so `firstVisibleIndex` IS that header — and
1301
+ // advancing from it moves to the row underneath it rather than past it.
1302
+ currentIndex: firstUncoveredIndex,
1303
+ itemCount: items.length,
1304
+ orientation: horizontal ? 'horizontal' : 'vertical',
1305
+ writingDirection,
1306
+ stickyIndexes: stickyIndexSet,
1307
+ });
1308
+ if (target === null)
1309
+ return;
1310
+ event.preventDefault();
1311
+ // Through the normal path, which applies the header inset and keeps the settle
1312
+ // loop. An earlier version wrote the offset directly here to apply that inset, and
1313
+ // in doing so skipped the loop — so under `dynamicSize` an End or Page jump into
1314
+ // rows whose estimates changed as they mounted stopped wherever the first write
1315
+ // happened to land.
1316
+ scrollToIndex(target, { align: 'start' });
86
1317
  }
87
1318
  function maxScrollOffset(totalSize, height) {
88
1319
  return Math.max(0, totalSize - height);
89
1320
  }
90
1321
  function isAtBottom(element, totalSize, height) {
91
- return element.scrollTop >= maxScrollOffset(totalSize, height) - 1;
1322
+ // Start-edge-relative, so this reads "at the far end of the scroll axis"
1323
+ // regardless of orientation or writing direction.
1324
+ return readScrollOffset(element) >= maxScrollOffset(totalSize, height) - 1;
1325
+ }
1326
+ /**
1327
+ * Reads each measured row and folds its real size into the measurement cache.
1328
+ * The row's index comes from the `data-cinder-virtual-index` attribute the
1329
+ * template already sets, so no per-row attachment identity has to be tracked;
1330
+ * the key is re-derived from that index against the current `items`.
1331
+ */
1332
+ function handleRowResize(entries) {
1333
+ for (const entry of entries) {
1334
+ const element = entry.target;
1335
+ const rawIndex = element.dataset['cinderVirtualIndex'];
1336
+ if (rawIndex === undefined)
1337
+ continue;
1338
+ const index = Number.parseInt(rawIndex, 10);
1339
+ if (!Number.isInteger(index) || index < 0 || index >= items.length)
1340
+ continue;
1341
+ const mainAxisSize = resolveObservedMainAxisSize(entry.borderBoxSize?.[0], entry.contentRect, horizontal ? 'horizontal' : 'vertical');
1342
+ // Zero is a legitimate measurement — a row can collapse to nothing. Discarding
1343
+ // it would leave the offsets table reserving space the row no longer occupies,
1344
+ // shifting every later offset and scroll target until it grew again.
1345
+ if (!Number.isFinite(mainAxisSize) || mainAxisSize < 0)
1346
+ continue;
1347
+ measurementStore.record(keyAt(index), index, mainAxisSize, resolvedItemHeight);
1348
+ }
1349
+ }
1350
+ /**
1351
+ * Observes one mounted row. A single component-owned `ResizeObserver` watches
1352
+ * every row rather than one observer per row, and this attachment is a stable
1353
+ * function reference so rows are not re-observed on every render.
1354
+ *
1355
+ * Constructed lazily and only here, which is what keeps the fixed-height path
1356
+ * free of any `ResizeObserver` at all, and keeps the module importable during
1357
+ * server rendering — Svelte never runs attachments there.
1358
+ */
1359
+ function observeRow(node) {
1360
+ if (!dynamicSize)
1361
+ return undefined;
1362
+ if (!rowResizeObserver) {
1363
+ // Resolved from the node's own document, matching `useResizeObserver`. A list
1364
+ // mounted inside an iframe has its ResizeObserver on that document's window;
1365
+ // the outer `globalThis` one is either absent or bound to the wrong document,
1366
+ // either of which leaves every row silently unmeasured.
1367
+ const ResizeObserverConstructor = typeof document !== 'undefined' && node.ownerDocument === document
1368
+ ? globalThis.ResizeObserver
1369
+ : node.ownerDocument.defaultView?.ResizeObserver;
1370
+ if (typeof ResizeObserverConstructor !== 'function')
1371
+ return undefined;
1372
+ rowResizeObserver = new ResizeObserverConstructor(handleRowResize);
1373
+ }
1374
+ const observer = rowResizeObserver;
1375
+ observer.observe(node, { box: 'border-box' });
1376
+ return () => {
1377
+ observer.unobserve(node);
1378
+ };
1379
+ }
1380
+ function currentLocator() {
1381
+ const table = offsets?.offsets;
1382
+ if (dynamicSize && table) {
1383
+ return {
1384
+ getStart: (index) => table[index] ?? 0,
1385
+ getSize: (index) => (table[index + 1] ?? 0) - (table[index] ?? 0),
1386
+ };
1387
+ }
1388
+ return {
1389
+ getStart: (index) => index * resolvedItemHeight,
1390
+ getSize: () => resolvedItemHeight,
1391
+ };
1392
+ }
1393
+ function currentTotalSize() {
1394
+ return dynamicSize ? (offsets?.totalSize ?? 0) : items.length * resolvedItemHeight;
1395
+ }
1396
+ function nextAnimationFrame() {
1397
+ return new Promise((resolve) => {
1398
+ if (typeof globalThis.requestAnimationFrame !== 'function') {
1399
+ resolve();
1400
+ return;
1401
+ }
1402
+ // Called through globalThis so the Window receiver is preserved. Copying the
1403
+ // method into a local and invoking it bare throws "Illegal invocation" in
1404
+ // browsers that enforce the Web API receiver — which would reject this
1405
+ // promise on every dynamic scrollToIndex and silently skip every settle pass.
1406
+ globalThis.requestAnimationFrame(() => {
1407
+ resolve();
1408
+ });
1409
+ });
1410
+ }
1411
+ /**
1412
+ * Waits until the container's scroll position stops moving, bounded.
1413
+ *
1414
+ * A single frame is not enough: with `behavior: 'smooth'` the browser is still
1415
+ * animating a frame later, so every retry would be spent mid-flight and the
1416
+ * loop would give up before the destination rows ever mounted and measured.
1417
+ * Waiting for the position to hold still covers both that and a late
1418
+ * measurement, and the frame cap keeps a continuously-scrolling container
1419
+ * (a user dragging, an ongoing animation) from holding the loop open.
1420
+ */
1421
+ async function waitForScrollSettled(element) {
1422
+ await tick();
1423
+ let previousOffset = Number.NaN;
1424
+ for (let frame = 0; frame < SCROLL_SETTLE_MAX_FRAMES; frame += 1) {
1425
+ await nextAnimationFrame();
1426
+ if (isDestroyed)
1427
+ return;
1428
+ // Axis-aware: reading scrollTop on a horizontal list sees a value that never
1429
+ // moves, so the loop would report "settled" after two frames and skip the
1430
+ // settle pass entirely.
1431
+ const currentOffset = readScrollOffset(element);
1432
+ if (currentOffset === previousOffset)
1433
+ return;
1434
+ previousOffset = currentOffset;
1435
+ }
1436
+ }
1437
+ function scrollToIndex(index, options) {
1438
+ void runScrollToIndex(index, options);
1439
+ }
1440
+ /**
1441
+ * Main-axis size of the sticky header that will cover row `index` once it reaches
1442
+ * the leading edge. Without it every destination lands underneath the header.
1443
+ *
1444
+ * Keyed on the DESTINATION rather than on the current scroll position. A
1445
+ * position-keyed inset changes as the scroll moves, so the settle loop below would
1446
+ * compute a different target on each pass; with a header taller than a row it
1447
+ * oscillates between the header's start and the row's, and the attempt cap decides
1448
+ * where the reader ends up.
1449
+ */
1450
+ /**
1451
+ * How much of the leading edge a sticky header would cover at `offset`.
1452
+ *
1453
+ * The same question `stickyObstructionSize` answers for the current position, asked
1454
+ * about somewhere the reader is not yet — which is what a page forward needs, since
1455
+ * the header waiting at the destination is what will cover the content it lands on.
1456
+ */
1457
+ function resolveObstructionAtOffset(offset) {
1458
+ if (stickyIndexes.length === 0)
1459
+ return 0;
1460
+ const header = resolveActiveStickyIndex(stickyIndexes, resolveAnchorIndexAtOffset(Math.max(0, offset)));
1461
+ return header === null ? 0 : locateRowSize(header);
1462
+ }
1463
+ /** The index `computeScrollToIndexOffset` will actually resolve, clamped the same way. */
1464
+ function clampedScrollIndex(index) {
1465
+ return Math.max(0, Math.min(items.length - 1, Math.floor(index)));
1466
+ }
1467
+ function resolveLeadingInset(index) {
1468
+ if (stickyIndexes.length === 0 || items.length === 0)
1469
+ return 0;
1470
+ const clampedIndex = Math.max(0, Math.min(items.length - 1, Math.floor(index)));
1471
+ const header = resolveObstructingStickyIndex(stickyIndexes, clampedIndex);
1472
+ return header === null ? 0 : locateRowSize(header);
1473
+ }
1474
+ /**
1475
+ * Under `dynamicSize` a scroll target can move while the scroll is happening:
1476
+ * rows that were only estimated get mounted, measured, and resized, shifting
1477
+ * everything after them. Each pass re-derives the target from the freshly
1478
+ * measured table and re-issues the scroll, capped so this can never spin.
1479
+ */
1480
+ async function runScrollToIndex(index, options) {
1481
+ if (isDestroyed || items.length === 0)
1482
+ return;
1483
+ const align = options?.align ?? 'auto';
1484
+ // An explicit behavior in the call always wins; `smoothScroll` only supplies
1485
+ // the default — and only for readers who have not asked for less motion.
1486
+ const behavior = options?.behavior ?? (smoothScroll && !reducedMotion.current ? 'smooth' : 'auto');
1487
+ // Each call supersedes any settle loop still running. Without this, two
1488
+ // overlapping loops write competing targets and the older one can land last,
1489
+ // finishing rapid navigation on the wrong item.
1490
+ scrollToIndexGeneration += 1;
1491
+ const generation = scrollToIndexGeneration;
1492
+ for (let attempt = 0; attempt < SCROLL_TO_INDEX_MAX_ATTEMPTS; attempt += 1) {
1493
+ const element = scrollElement;
1494
+ if (!element)
1495
+ return;
1496
+ if (generation !== scrollToIndexGeneration)
1497
+ return;
1498
+ const target = computeScrollToIndexOffset({
1499
+ index,
1500
+ itemCount: items.length,
1501
+ locator: currentLocator(),
1502
+ totalSize: currentTotalSize(),
1503
+ viewportSize: viewportHeight,
1504
+ // Read live from the element, not from `scrollOffset` state. During a
1505
+ // smooth scroll, a throttled scroll event, or an external write, the state
1506
+ // lags the real position — and `align: 'auto'` decides whether to move at
1507
+ // all by comparing against it.
1508
+ currentScrollOffset: readScrollOffset(element),
1509
+ align,
1510
+ // Re-read each pass: the header's identity is fixed by the destination, but
1511
+ // under `dynamicSize` its SIZE changes as it mounts and is measured.
1512
+ leadingInset: resolveLeadingInset(index),
1513
+ // What is covering the reader right now, which `align: 'auto'` needs to judge
1514
+ // whether the target is already in view. A different header from the one above
1515
+ // whenever the target is in another section.
1516
+ currentLeadingInset: stickyObstructionSize,
1517
+ // Asking for the header the reader is already looking at. Its logical start is
1518
+ // above the scroll offset, so without this `align: 'auto'` reads it as
1519
+ // offscreen and jumps back to the top of its section.
1520
+ targetIsStuckAtLeadingEdge: clampedScrollIndex(index) === activeStickyIndex,
1521
+ });
1522
+ writeScrollOffset(element, target, behavior);
1523
+ scrollOffset = readScrollOffset(element);
1524
+ // Fixed rows never change size, so the first write always lands exactly.
1525
+ if (!dynamicSize)
1526
+ return;
1527
+ await waitForScrollSettled(element);
1528
+ // The component can be torn down, or a newer call issued, while those frames
1529
+ // were pending. Reading derived state past teardown would read a destroyed
1530
+ // effect's, and continuing past a newer call would fight it.
1531
+ if (isDestroyed || generation !== scrollToIndexGeneration)
1532
+ return;
1533
+ const settled = computeScrollToIndexOffset({
1534
+ index,
1535
+ itemCount: items.length,
1536
+ locator: currentLocator(),
1537
+ totalSize: currentTotalSize(),
1538
+ viewportSize: viewportHeight,
1539
+ // Read live from the element, not from `scrollOffset` state. During a
1540
+ // smooth scroll, a throttled scroll event, or an external write, the state
1541
+ // lags the real position — and `align: 'auto'` decides whether to move at
1542
+ // all by comparing against it.
1543
+ currentScrollOffset: readScrollOffset(element),
1544
+ align,
1545
+ // Re-read each pass: the header's identity is fixed by the destination, but
1546
+ // under `dynamicSize` its SIZE changes as it mounts and is measured.
1547
+ leadingInset: resolveLeadingInset(index),
1548
+ // What is covering the reader right now, which `align: 'auto'` needs to judge
1549
+ // whether the target is already in view. A different header from the one above
1550
+ // whenever the target is in another section.
1551
+ currentLeadingInset: stickyObstructionSize,
1552
+ // Asking for the header the reader is already looking at. Its logical start is
1553
+ // above the scroll offset, so without this `align: 'auto'` reads it as
1554
+ // offscreen and jumps back to the top of its section.
1555
+ targetIsStuckAtLeadingEdge: clampedScrollIndex(index) === activeStickyIndex,
1556
+ });
1557
+ // Compared against the element, not the state, for the same reason the target
1558
+ // is computed from it: the state lags a smooth or externally-driven scroll,
1559
+ // which both wastes retries and can stop retrying while still in flight.
1560
+ const settledScrollOffset = readScrollOffset(element);
1561
+ if (Math.abs(settled - settledScrollOffset) <= SCROLL_TO_INDEX_SETTLED_EPSILON)
1562
+ return;
1563
+ }
92
1564
  }
93
1565
  </script>
94
1566
 
@@ -101,21 +1573,40 @@ function isAtBottom(element, totalSize, height) {
101
1573
  {role}
102
1574
  {tabindex}
103
1575
  data-cinder-stick-to-bottom={stickToBottom ? 'true' : undefined}
1576
+ data-cinder-dynamic-size={dynamicSize ? 'true' : undefined}
1577
+ data-cinder-orientation={horizontal ? 'horizontal' : undefined}
104
1578
  style:--cinder-virtual-list-height={height}
105
1579
  onscroll={handleScroll}
1580
+ onwheel={handleWheel}
1581
+ onpointerdown={handlePointerDown}
1582
+ ontouchstart={handleTouchStart}
1583
+ onkeydown={handleKeyDown}
106
1584
  >
107
1585
  <div
108
1586
  class="cinder-virtual-list__spacer"
109
- style:height={`${virtualWindow.totalSize}px`}
1587
+ style={`${rowLayout.sizeProperty}:${virtualWindow.totalSize}px;`}
110
1588
  aria-hidden={items.length === 0 ? 'true' : undefined}
111
1589
  >
112
- <div class="cinder-virtual-list__window" style:top={`${virtualWindow.leadingSize}px`}>
1590
+ <div
1591
+ class="cinder-virtual-list__window"
1592
+ style={`${rowLayout.offsetProperty}:${virtualWindow.leadingSize}px;`}
1593
+ >
113
1594
  {#each renderedItems as virtualItem (virtualItem.key)}
114
1595
  <div
115
1596
  class="cinder-virtual-list__row"
116
1597
  role={role === 'list' ? 'listitem' : undefined}
117
1598
  data-cinder-virtual-index={virtualItem.index}
118
- style:height={`${virtualItem.size}px`}
1599
+ data-cinder-sticky={stickyIndexSet.has(virtualItem.index) ? 'true' : undefined}
1600
+ data-cinder-sticky-active={virtualItem.index === activeStickyIndex ? 'true' : undefined}
1601
+ data-cinder-sticky-pinned={virtualItem.index === pinnedStickyIndex ? 'true' : undefined}
1602
+ aria-posinset={rowSemanticsApply
1603
+ ? resolveRowSemantics(virtualItem.index, items.length).ariaPosInSet
1604
+ : undefined}
1605
+ aria-setsize={rowSemanticsApply
1606
+ ? resolveRowSemantics(virtualItem.index, items.length).ariaSetSize
1607
+ : undefined}
1608
+ style={resolveRowStyle(virtualItem.index, virtualItem.size)}
1609
+ {@attach observeRow}
119
1610
  >
120
1611
  {@render row(virtualItem.item, {
121
1612
  index: virtualItem.index,