`@effect/ui-kit` (Effect-TS/ui): `VirtualList` smooth follow (`followEnd: { behavior: "smooth" }`) for chat transcripts

Aperta
#11,052 0 commenti 0 reazioni 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@effect-bot ci sta già lavorando.

Dal 29/11/2026.

Valutazione

Questa issue non è ancora stata valutata.

Descrizione

What

A chat transcript in VirtualList with followEnd keeps the end in view with an instant jump at every growth. Chat UIs usually glide after a streaming answer instead (React's use-stick-to-bottom, resize="smooth"). We need the same in an o-o (Effect UI app) transcript, and keep the virtual list.

Proposed API

Add behavior to followEnd's struct form:

followEnd: { threshold?: number; behavior?: "instant" | "smooth" } // "instant" when omitted

Proposed semantics (as our local patch implements them)

  • Initial placement: the first scrollTo (mount, or a new dataset) jumps and holds for 500 ms while rows measure, as before.
  • Following: after that, a pinned end, followEnd growth and later scrollTo of End are followed by a glide, a step a frame: a requestAnimationFrame loop on the list's own window (list.ownerDocument.defaultView, so a list in another frame steps on that frame's clock) moves the scroll a share of the distance left each frame, with a 100 ms time constant, retargeting as the list keeps growing.
  • Jumps instead of glides:
    • when the end is more than a viewport away (estimated sizes settling);
    • under prefers-reduced-motion.
  • Taking over: wheel, touch, keys or a press end the follow (unpin). A move up that no list mutation and no height change since the follow's last own scroll explains (a script's scrollBy) ends it too, gliding or not; one they explain is the list shrinking under the scroll (the browser clamping it), so a script's move in the same frame as such a change reads as the list's own.
  • Shrinks mid-glide: a row entering the window can measure short until its content renders, moving every estimate (the average of measured sizes) with it, so the list can shrink under a glide and clamp the scroll back up. Each glide counts its own shrinks (the count starts at zero as follow() starts a glide): after the first it goes on from the clamp; a second in the same glide jumps the rest of the way, as without it we saw a glide never arrive (the window flipped back and forth with each step). So in a long list, part of the follows end up as jumps.
  • Browser anchoring: with behavior: "smooth" the viewport part writes overflow-anchor: none. Otherwise Chromium's own scroll anchoring keeps the end first, and there is nothing to glide.
  • atEnd: reports true while a glide runs.

Proposal (the patch's source hunks, against dec1ca9)

src/Virtualizer.ts and src/VirtualList.ts
diff --git a/src/Virtualizer.ts b/src/Virtualizer.ts
index adb8011bcd88676c4fab78c8fe62174e9d30dbec..420146c3e0352dfba00fd4d422f85a7179bdeb18 100644
--- a/src/Virtualizer.ts
+++ b/src/Virtualizer.ts
@@ -144,12 +144,20 @@ export const Props = Schema.Struct({
   scrollTo: Schema.optional(ScrollTo),
   /**
    * Keeps the end of the list in view as it grows or resizes while the user
-   * is within `threshold` of it, 1 when omitted.
+   * is within `threshold` of it, 1 when omitted. `behavior: "smooth"` glides
+   * there a step a frame (each a share of the distance left, with a 100 ms
+   * time constant), as a chat does while an answer streams in; it jumps while
+   * the user prefers reduced motion or the end is more than a viewport away.
+   * A `scrollTo` of the end glides too once the list has first been placed.
+   * `"instant"` when omitted.
    */
   followEnd: Schema.optional(
     Schema.Union([
       Schema.Boolean,
-      Schema.Struct({ threshold: Schema.optional(Schema.Number) })
+      Schema.Struct({
+        threshold: Schema.optional(Schema.Number),
+        behavior: Schema.optional(Schema.Literals(["instant", "smooth"]))
+      })
     ])
   ),
   /**
diff --git a/src/VirtualList.ts b/src/VirtualList.ts
index 638ef09a1331c773c957f3b1d026ba6cf12f449c..ddd3f29ceb50fb5ceb1242cca53d8b43be8dc1e4 100644
--- a/src/VirtualList.ts
+++ b/src/VirtualList.ts
@@ -200,6 +200,11 @@ const viewportAttr = "data-virtual-list-viewport"
 const itemAttr = "data-virtual-list-item"
 const spacerAttr = "data-virtual-list-spacer"
 const scrollEndDelay = 100
+// How long the first jump to a target holds while the rows around it measure, before the end
+// is followed by a glide.
+const initialHold = 500
+// A glide's time constant: the distance left to the end shrinks by e every this many ms.
+const glideTime = 100
 const layoutAttributes = ["class", "style", "hidden", "open"]
 const focusableSelector =
   "a[href],button,input,select,textarea,summary,iframe,[tabindex],[contenteditable]:not([contenteditable=\"false\"])"
@@ -386,7 +391,8 @@ const TrackVirtualListArgs = {
   waiting: Schema.Boolean,
   scrollContainer: Schema.NullOr(VirtualListScrollContainer),
   track: Schema.Boolean,
-  absolute: Schema.Boolean
+  absolute: Schema.Boolean,
+  smooth: Schema.Boolean
 }
 
 type TrackVirtualListArgs = Schema.Struct<typeof TrackVirtualListArgs>["Type"]
@@ -474,18 +480,66 @@ const TrackVirtualList = Mount.makeStream(
         const scrollTop = () =>
           viewport === null ? window.scrollY : viewport.scrollTop
         const origin = () => listTop() + args.inset
+        // A smooth follow under way: one step a frame towards the end, wherever the end is by
+        // then, until it is reached or the user takes over.
+        // Frames are the list's own window's, so a list in another frame steps on that frame's
+        // clock.
+        let gliding = false
+        let glideFrame = 0
+        let glideAt = 0
+        // What the list was at the smooth follow's last own scroll: how many times its rows or
+        // padding changed since, and its height. A move up with neither changed is the user's (a
+        // script's; a wheel, touch, key or press ends the follow at once); one that came with a
+        // change is the list shrinking under it, rows swapped in and out between two frames
+        // clamping the scroll.
+        let glideSyncs = 0
+        let glideHeight = 0
+        // How many times the list shrank under this glide, clamping the scroll back up. A row
+        // coming into the window can measure short until its content renders, moving every
+        // estimate with it: once is common, and the glide goes on from where the clamp left it.
+        // Twice, the window and the sizes are flipping back and forth with the glide's steps,
+        // and it would never arrive: it jumps instead.
+        let glideBacks = 0
+        const stopGlide = () => {
+          gliding = false
+          glideBacks = 0
+          if (glideFrame !== 0) window.cancelAnimationFrame(glideFrame)
+          glideFrame = 0
+        }
+        // Whether the list has been placed since it mounted or its dataset changed: the first
+        // `scrollTo` jumps, as a chat opens at its end at once.
+        let placed = false
+        let placedEpoch = args.epoch
+        // Until when the first jump holds.
+        let holdUntil = 0
         const scrollBy = (delta: number) => {
           if (Math.abs(delta) < 0.5) return
+          stopGlide()
           const top = scrollTop() + delta
           if (viewport === null) window.scrollTo({ top, behavior: "instant" })
           else viewport.scrollTo({ top, behavior: "instant" })
           seen = scrollTop()
+          glideSyncs = 0
+          glideHeight = scroller().scrollHeight
         }
         const scroller = () =>
           viewport ?? document.scrollingElement ?? document.documentElement
+        const movedUpUnexplained = (top: number) =>
+          top < seen - 0.5 && glideSyncs === 0 && scroller().scrollHeight === glideHeight
         const movedByUser = () => {
           const top = scrollTop()
           const element = scroller()
+          // While the smooth follow keeps the end, the user takes over by input (`unpin`), or by
+          // a move up the list's changes can't explain (a script's). One they explain is the list
+          // shrinking under the scroll: a glide jumps the rest of the way, a kept end is followed
+          // back (`onScroll`).
+          if (args.smooth && (gliding || (pinned !== null && isEnd(pinned)))) {
+            const user = movedUpUnexplained(top)
+            if (gliding && !user && top < seen - 0.5) glideBacks++
+            seen = top
+            if (user) stopGlide()
+            return user
+          }
           const moved = !Virtualizer.same(
             top,
             Math.min(seen, element.scrollHeight - element.clientHeight)
@@ -568,7 +622,8 @@ const TrackVirtualList = Mount.makeStream(
           const next = metrics()
           const { height, length, offset: start } = next
           const atStart = start <= Virtualizer.edgeThreshold
-          atEnd = toEnd() <= (args.threshold ?? Virtualizer.edgeThreshold)
+          atEnd = gliding ||
+            toEnd() <= (args.threshold ?? Virtualizer.edgeThreshold)
           const overflowing = viewport !== null &&
             (viewport.scrollHeight > viewport.clientHeight ||
               viewport.scrollWidth > viewport.clientWidth)
@@ -661,10 +716,14 @@ const TrackVirtualList = Mount.makeStream(
           : new ResizeObserver(() => sync())
         const mutationObserver = typeof MutationObserver === "undefined"
           ? null
-          : new MutationObserver(() => sync())
+          : new MutationObserver(() => {
+            glideSyncs++
+            sync()
+          })
         const structureObserver = typeof MutationObserver === "undefined" ?
           null :
           new MutationObserver(() => {
+            glideSyncs++
             watchOutside()
             sync()
           })
@@ -754,12 +813,83 @@ const TrackVirtualList = Mount.makeStream(
 
         const unpin = () => {
           pinned = null
+          stopGlide()
+        }
+
+        const reducedMotion = () =>
+          window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true
+
+        const isEnd = (request: Virtualizer.ScrollRequest) => request.scrollTo.target._tag === "End"
+
+        // One frame of a glide: the distance left eases out over `glideTime`, so a list still
+        // growing is caught up with as it grows, as a spring would.
+        const glideStep = (now: number) => {
+          glideFrame = 0
+          if (!gliding || disposed) return
+          const current = scrollTop()
+          if (movedUpUnexplained(current)) {
+            pinned = null
+            stopGlide()
+            seen = current
+            if (args.waiting) send(Virtualizer.Message.ScrolledByUser())
+            capture()
+            report(null)
+            return
+          }
+          if (current < seen - 0.5) glideBacks++
+          if (glideBacks >= 2) {
+            stopGlide()
+            scrollBy(toEnd())
+            return
+          }
+          const delta = toEnd()
+          if (delta < 0.5) {
+            gliding = false
+            return
+          }
+          if (delta > box().height) return scrollBy(delta)
+          const elapsed = glideAt === 0 ? 1000 / 60 : Math.min(64, now - glideAt)
+          glideAt = now
+          const move = delta <= 1
+            ? delta
+            : Math.max(1, delta * (1 - Math.exp(-elapsed / glideTime)))
+          const top = scrollTop() + move
+          if (viewport === null) window.scrollTo({ top, behavior: "instant" })
+          else viewport.scrollTo({ top, behavior: "instant" })
+          seen = scrollTop()
+          glideSyncs = 0
+          glideHeight = scroller().scrollHeight
+          glideFrame = window.requestAnimationFrame(glideStep)
+        }
+
+        // Keeps the end in view: a glide to it that a later growth goes on with, or one jump while
+        // the user prefers reduced motion or the end is more than a viewport away (sizes
+        // estimated for rows not yet measured settling, not the list growing).
+        const follow = () => {
+          const delta = toEnd()
+          if (!args.smooth || reducedMotion() || delta > box().height) return scrollBy(delta)
+          if (gliding || delta < 0.5) return
+          gliding = true
+          // Each glide counts its own shrinks: one a glide before it arrived with does not count
+          // here.
+          glideBacks = 0
+          glideAt = 0
+          glideSyncs = 0
+          glideHeight = scroller().scrollHeight
+          glideFrame = window.requestAnimationFrame(glideStep)
         }
 
         const onScroll = () => {
           if (movedByUser()) {
             pinned = null
             if (args.waiting) send(Virtualizer.Message.ScrolledByUser())
+          } else if (
+            args.smooth && !gliding && pinned !== null && isEnd(pinned) &&
+            performance.now() >= holdUntil
+          ) {
+            // Kept at the end: a move nothing reports (a wheel's animation still running, sizes
+            // settling) is followed back, as a resize is.
+            follow()
           }
           startScroll()
           capture()
@@ -804,11 +934,21 @@ const TrackVirtualList = Mount.makeStream(
 
         const sync = () => {
           if (disposed) return
+          // Where the follow left it, with the list as it is now: changes since start again
+          // from here.
+          if (Virtualizer.same(scrollTop(), seen)) {
+            glideSyncs = 0
+            glideHeight = scroller().scrollHeight
+          }
           bind()
           refocus()
           const request = args.request
           const fresh = args.fresh
           if (request === null) applied = null
+          if (args.epoch !== placedEpoch) {
+            placedEpoch = args.epoch
+            placed = false
+          }
           if (
             fresh !== null &&
             (request === null ||
@@ -823,12 +963,22 @@ const TrackVirtualList = Mount.makeStream(
           ) {
             applied = request.scrollTo
             pinned = request
-            go(request)
+            if (args.smooth && placed && isEnd(request)) follow()
+            else {
+              holdUntil = performance.now() + (placed ? 0 : initialHold)
+              placed = true
+              go(request)
+            }
             capture()
             report(request.scrollTo)
           } else {
-            if (pinned !== null) go(pinned)
-            else if (args.threshold !== null && atEnd) scrollBy(toEnd())
+            // A pinned end is kept by the smooth follow once its first jump has held.
+            if (
+              pinned !== null && args.smooth && isEnd(pinned) &&
+              performance.now() >= holdUntil
+            ) follow()
+            else if (pinned !== null) go(pinned)
+            else if (args.threshold !== null && atEnd) follow()
             else keepAnchor()
             capture()
             report(null)
@@ -937,6 +1087,7 @@ const TrackVirtualList = Mount.makeStream(
         yield* Effect.addFinalizer(() =>
           Effect.sync(() => {
             disposed = true
+            stopGlide()
             clearTimeout(focusTimer)
             clearTimeout(endTimer)
             resizeObserver?.disconnect()
@@ -1033,6 +1184,8 @@ export const VirtualList = Html.component({
       : 0
     const inset = reserve + fill
     const absolute = props.layout === "absolute"
+    const smooth = typeof props.followEnd === "object" &&
+      props.followEnd.behavior === "smooth"
     const first = props.firstPosition ?? 1
     const setSize = String(props.setSize ?? count)
 
@@ -1109,11 +1262,15 @@ export const VirtualList = Html.component({
       atStart: model.position !== null && model.atStart,
       atEnd: model.position !== null && model.atEnd,
       scrolling: model.scrolling,
+      // A smooth follow keeps the end itself: the browser's own scroll anchoring would jump there
+      // first, leaving nothing to glide.
       viewport: p.part(["div", "ul", "ol"], (b) =>
         b.attrs({
           [viewportAttr]: id,
           tabindex: model.overflowing ? "0" : "-1"
-        })),
+        }).forward((node) =>
+          smooth ? ownStyle("overflow-anchor:none")(node) : node
+        )),
       table: p.part(
         ["table", "div"],
         (b) =>
@@ -1145,7 +1302,8 @@ export const VirtualList = Html.component({
             waiting: plan.waiting,
             scrollContainer: props.scrollContainer ?? null,
             track: props.trackScroll === true,
-            absolute
+            absolute,
+            smooth
           }))
           .forward((node) => {
             if (table) {

Notes

  • Tests: our e2e covers the behaviour against the real app. It requires two scroll steps in a row short of the end, each further down (an instant jump can't make two), after a send and a streamed reply; a script's scrollBy up from a frame callback that runs before the glide's step in the same frame releases the follow through the step's own check; a script's scroll and the wheel while a reply waits release it too, and "scroll to bottom" returns to the exact end. Another case shrinks the last row under glides: one shrink glides on, two in one glide jump, and the next glide starts afresh. The glide cases fail with the patch reverted.
  • Cost: on our streaming bench (a 2,128-row history plus a 30 batches/s replay at 4× CPU throttle, instant and smooth interleaved in one session, on a loaded machine), the two were within run-to-run noise (dropped frames 5–21% smooth, 10–18% instant). In one run of nine at a heavier load, smooth lost the end of the replay; we have not reproduced it yet. A cheaper glide (fewer layout reads per step) would still be welcome.
Lingua principale
TypeScript
Stelle
16.7k
Fork
808
Merge medio
21h 22m
PR unite (30g)
486

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di Effect-TS/effect

Tutte le issue di Effect-TS/effect

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.