Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions apps/app/src/components/ui/scroll-position-keeper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,81 @@ describe("ScrollPositionKeeper", () => {
expect(timeline.keeper.isAttached()).toBe(false);
});

it("attaches when the viewport grows and the reader's position no longer fits above the end", () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
const timeline = createTimeline(rowsOf(10));
timeline.userScrollTo(1350);
vi.advanceTimersByTime(500);
expect(timeline.keeper.isAttached()).toBe(false);

timeline.layout.setViewportHeight(800);
timeline.layout.layoutScrollTo(timeline.layout.maxScrollTop());
timeline.keeper.reconcile();
expect(timeline.keeper.isAttached()).toBe(true);

timeline.setRows(rowsOf(11));
timeline.keeper.reconcile();
expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop());
});

it("keeps a detached reader on their row when the viewport grows but the row still fits above the end", () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
const timeline = createTimeline(rowsOf(10));
timeline.userScrollTo(400);
vi.advanceTimersByTime(500);
const before = timeline.topOf("row-3");

timeline.layout.setViewportHeight(800);
timeline.keeper.reconcile();

expect(timeline.keeper.isAttached()).toBe(false);
expect(timeline.topOf("row-3")).toBe(before);
});

it("attaches a reader left detached at the end when they drag toward the end, though the drag cannot scroll", () => {
const rows = rowsOf(10);
const timeline = createTimeline(rows);
timeline.userScrollTo(1200);
timeline.setRows(rows.slice(0, 7));
timeline.keeper.reconcile();
expect(timeline.keeper.isAttached()).toBe(false);
const touch = (type: string, clientY: number) =>
Object.assign(new Event(type), { touches: [{ clientY }] });

timeline.scrollElement.dispatchEvent(touch("touchstart", 300));
timeline.scrollElement.dispatchEvent(touch("touchmove", 280));

expect(timeline.keeper.isAttached()).toBe(true);
});

it("saves a detached reader who sits at the end as at the bottom", () => {
const rows = rowsOf(10);
const timeline = createTimeline(rows);
timeline.userScrollTo(1200);
timeline.setRows(rows.slice(0, 7));
timeline.keeper.reconcile();
expect(timeline.keeper.isAttached()).toBe(false);

expect(timeline.keeper.savedPosition()).toEqual({
rowId: "",
offsetWithinRow: 0,
atBottom: true,
});
});

it("attaches when a restored row lands at the end", () => {
const timeline = createTimeline(rowsOf(10));

timeline.keeper.restore({
rowId: "row-8",
offsetWithinRow: 0,
atBottom: false,
});

expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop());
expect(timeline.keeper.isAttached()).toBe(true);
});

it("keeps the end in view on every layout change while attached and stays attached", () => {
const timeline = createTimeline(rowsOf(10), { attached: true });
expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop());
Expand All @@ -175,6 +250,29 @@ describe("ScrollPositionKeeper", () => {
expect(timeline.keeper.isAttached()).toBe(true);
});

it("stays attached when a navigation target clamps to the end, so content that grows afterwards stays in view", () => {
const timeline = createTimeline(rowsOf(10), { attached: true });

timeline.keeper.scrollTo(timeline.topOf("row-8") + 1600, "instant");
expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop());
expect(timeline.keeper.isAttached()).toBe(true);

timeline.resize("row-9", 260);
timeline.keeper.reconcile();
expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop());
});

it("detaches when a navigation target lands above the end", () => {
const timeline = createTimeline(rowsOf(10), { attached: true });

timeline.keeper.scrollTo(400, "instant");
expect(timeline.keeper.isAttached()).toBe(false);

timeline.resize("row-9", 260);
timeline.keeper.reconcile();
expect(timeline.layout.scrollTop).toBe(400);
});

it("shifts content above an attached toggle by exactly the height change", () => {
const timeline = createTimeline(rowsOf(10), { attached: true });
const lastBottom = () => timeline.topOf("row-9") + 200;
Expand Down
66 changes: 52 additions & 14 deletions apps/app/src/components/ui/scroll-position-keeper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const KEY_SESSION_MS = 500;
const PROGRAMMATIC_SMOOTH_SESSION_MS = 1_000;
const SESSION_EXTENSION_MS = 150;
const MOMENTUM_SESSION_MS = 3_000;
const TOUCH_ATTACH_DRAG_PX = 8;
const FREE: ReadingPosition = { kind: "free" };

export function getDirectTimelineRows(list: Element): NodeListOf<HTMLElement> {
Expand Down Expand Up @@ -115,6 +116,7 @@ export class ScrollPositionKeeper {
private maxScrollTop = 0;
private viewportHeight = 0;
private reconciledWidth = 0;
private reconciledViewportHeight = 0;
private reconciledScrollHeight = 0;
private topRow: TopRow | null = null;
private deferred = 0;
Expand All @@ -124,6 +126,7 @@ export class ScrollPositionKeeper {
private gestureScrolled = false;
private inputUntil = Number.NEGATIVE_INFINITY;
private touchStartScrollTop = 0;
private touchStartY: number | null = null;
private userScrolled = false;
private scrollMovedAt = Number.NEGATIVE_INFINITY;
private settleTimeout: number | null = null;
Expand Down Expand Up @@ -182,18 +185,26 @@ export class ScrollPositionKeeper {
scrollElement.style.overflowAnchor = "none";
this.ownScrollTop = scrollElement.scrollTop;
const onScroll = () => this.handleScroll();
const onTouchStart = () => {
const onTouchStart = (event: TouchEvent) => {
if (!this.touching) {
this.gestureScrolled = false;
this.touchStartScrollTop = scrollElement.scrollTop;
this.touchStartY = event.touches[0]?.clientY ?? null;
}
this.touching = true;
};
const onTouchMove = (event: TouchEvent) => {
const startY = this.touchStartY;
const y = event.touches[0]?.clientY;
if (startY === null || y === undefined) return;
if (startY - y >= TOUCH_ATTACH_DRAG_PX) this.attachIfAtEnd();
};
const activeTouchPointers = new Set<number>();
const endTouch = () => {
if (!this.touching) return;
activeTouchPointers.clear();
this.touching = false;
this.touchStartY = null;
if (Math.abs(scrollElement.scrollTop - this.touchStartScrollTop) >= 1) {
this.gestureScrolled = true;
this.scrollMovedAt = window.performance.now();
Expand Down Expand Up @@ -249,6 +260,7 @@ export class ScrollPositionKeeper {
scrollElement.addEventListener("scroll", onScroll, { passive: true });
scrollElement.addEventListener("wheel", onWheel, { passive: true });
scrollElement.addEventListener("touchstart", onTouchStart, PASSIVE_CAPTURE);
scrollElement.addEventListener("touchmove", onTouchMove, PASSIVE_CAPTURE);
scrollElement.addEventListener("touchend", onTouchEnd, PASSIVE_CAPTURE);
scrollElement.addEventListener("touchcancel", onTouchEnd, PASSIVE_CAPTURE);
scrollElement.addEventListener("pointerdown", onPointerDown, {
Expand Down Expand Up @@ -280,6 +292,11 @@ export class ScrollPositionKeeper {
onTouchStart,
PASSIVE_CAPTURE,
);
scrollElement.removeEventListener(
"touchmove",
onTouchMove,
PASSIVE_CAPTURE,
);
scrollElement.removeEventListener(
"touchend",
onTouchEnd,
Expand Down Expand Up @@ -347,7 +364,12 @@ export class ScrollPositionKeeper {
return;
}
this.write(scrollElement, top);
this.setPosition(this.capture(scrollElement) ?? FREE);
this.refreshExtent(scrollElement);
this.setPosition(
this.isAtEnd(scrollElement.scrollTop)
? { kind: "bottom" }
: (this.capture(scrollElement) ?? FREE),
);
this.notifyLists();
}

Expand Down Expand Up @@ -397,9 +419,13 @@ export class ScrollPositionKeeper {
if (position.kind === "bottom") {
return { rowId: "", offsetWithinRow: 0, atBottom: true };
}
if (position.kind === "free") return null;
const scrollElement = this.options.getScrollElement();
if (scrollElement === null) return null;
this.refreshExtent(scrollElement);
if (this.isAtEnd(scrollElement.scrollTop)) {
return { rowId: "", offsetWithinRow: 0, atBottom: true };
}
if (position.kind === "free") return null;
const anchor = this.capture(scrollElement);
if (anchor === null || anchor.kind !== "anchor") return null;
const nested =
Expand Down Expand Up @@ -483,13 +509,15 @@ export class ScrollPositionKeeper {
const scrollTop = scrollElement.scrollTop;
const max = this.refreshExtent(scrollElement);
const width = scrollElement.clientWidth;
if (
this.reconciledWidth > 0 &&
Math.abs(this.reconciledWidth - width) >= 1
) {
this.keepAnchorVisible(scrollElement);
}
const widthChanged =
this.reconciledWidth > 0 && Math.abs(this.reconciledWidth - width) >= 1;
if (widthChanged) this.keepAnchorVisible(scrollElement);
const resized =
widthChanged ||
(this.reconciledViewportHeight > 0 &&
Math.abs(this.reconciledViewportHeight - this.viewportHeight) >= 1);
this.reconciledWidth = width;
this.reconciledViewportHeight = this.viewportHeight;
const previous = this.ownScrollTop;
if (
previous !== null &&
Expand All @@ -501,7 +529,7 @@ export class ScrollPositionKeeper {
this.scrollMovedAt = window.performance.now();
}
this.ownScrollTop = scrollTop;
this.advancePendingRestore(scrollElement);
const restored = this.advancePendingRestore(scrollElement);
const scrollHeight = scrollElement.scrollHeight;
const extentChanged = scrollHeight !== this.reconciledScrollHeight;
this.reconciledScrollHeight = scrollHeight;
Expand All @@ -512,10 +540,19 @@ export class ScrollPositionKeeper {
this.position.kind === "bottom" &&
!extentChanged &&
Math.abs(max - scrollTop) <= this.options.bottomThresholdPx;
const target =
let target =
bouncing || settledAtEnd
? null
: this.targetScrollTop(scrollElement, scrollTop, max);
if (
target !== null &&
(resized || restored) &&
this.position.kind === "anchor" &&
target >= max - this.options.bottomThresholdPx
) {
this.setPosition({ kind: "bottom" });
target = max;
}
if (target !== null) {
const clamped = defer
? Math.min(
Expand Down Expand Up @@ -548,9 +585,9 @@ export class ScrollPositionKeeper {
return position.offset > -height && position.offset < viewportHeight;
}

private advancePendingRestore(scrollElement: HTMLElement): void {
private advancePendingRestore(scrollElement: HTMLElement): boolean {
const pending = this.pendingRestore;
if (pending === null) return;
if (pending === null) return false;
const element = findMountedRow(scrollElement, pending.rowId);
if (element !== null) {
this.pendingRestore = null;
Expand All @@ -569,11 +606,12 @@ export class ScrollPositionKeeper {
),
neighbors: [],
});
return;
return true;
}
if (window.performance.now() > pending.expiresAt) {
this.pendingRestore = null;
}
return false;
}

private targetScrollTop(
Expand Down
10 changes: 7 additions & 3 deletions docs/timeline-pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,11 @@ scroll that comes with a change in the scroll extent is layout, such as a clamp
after content briefly shrank, and the owner reconciles it back to the position.
A scroll without input or size change, such as find in page or focus moving to
an offscreen control, is navigation, and the position follows it. Moving down
into the last 4 px, or a wheel or End/PageDown at the end, attaches. Moving up
out of it detaches. Layout changes never attach or detach.
into the last 4 px, or a wheel, End/PageDown or a touch drag toward the end
while at the end, attaches. A navigation, a restore, or a viewport resize that
leaves the reading position at or past the end also attaches. Moving up out of
the end detaches. Content changes never attach or detach: a detached reader
whose content shrinks onto the end stays detached until they scroll toward it.

Every layout change is reconciled before paint. Triggers are ResizeObservers on
the root, its content, and every mounted row, plus each windowed list's layout
Expand Down Expand Up @@ -303,7 +306,8 @@ next page.
A thread's position is saved when the reader scrolls and when the timeline
unmounts. Saving on unmount first takes in a scroll the reader made whose scroll
event has not arrived yet; a layout change alone keeps an attached reader at the
end. Returning to the thread mounts the saved row's window and restores
end. A reader who is at the end is saved as at the bottom, attached or not.
Returning to the thread mounts the saved row's window and restores
the row at its saved offset, kept on screen if the viewport is now shorter. If
the row has not loaded yet, the timeline waits
at the bottom for up to a second. The timeline keeps the loaded pages of the
Expand Down
Loading