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

未关闭
#11,052 0 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 1 天内回复

@effect-bot 已经在做这个了。

开始于 2026年11月29日。

评估

这个 Issue 还没有评估数据。

描述

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.
主要语言
TypeScript
星标
16.7k
派生
808
平均合并
21 小时 22 分钟
30 天内合并 PR
486

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

Effect-TS/effect 的其他 Issue

查看 Effect-TS/effect 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。