Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: tanstack virtual safari/ios scroll issues (#6338)

Peter Chinmanab205f443349
diff --git a/apps/web/patches/@tanstack%[email protected] b/apps/web/patches/@tanstack%[email protected]
new file mode 100644
index 0000000000..36c0bf1054
--- /dev/null
+++ b/apps/web/patches/@tanstack%[email protected]
@@ -0,0 +1,146 @@
+diff --git a/src/index.ts b/src/index.ts
+--- a/src/index.ts
++++ b/src/index.ts
+@@ -367,6 +367,8 @@
+ followOnAppend?: FollowOnAppend
+ scrollEndThreshold?: number
+ isScrollingResetDelay?: number
++ /** Disable only when scrollToFn provides its own touch-safe compensation. */
++ useIOSScrollDeferral?: boolean
+ useScrollendEvent?: boolean
+ enabled?: boolean
+ isRtl?: boolean
+@@ -553,6 +555,7 @@
+ isScrollingResetDelay: 150,
+ enabled: true,
+ isRtl: false,
++ useIOSScrollDeferral: true,
+ useScrollendEvent: false,
+ useAnimationFrameWithResizeObserver: false,
+ laneAssignmentMode: 'estimate',
+@@ -617,7 +620,8 @@
+
+ if (
+ behavior &&
+- nextCount > prevCount &&
++ // Server acknowledgements can replace the last key without adding a row.
++ nextCount >= prevCount &&
+ this.isAtEnd(prevOptions.scrollEndThreshold) &&
+ (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)
+ ) {
+@@ -700,6 +704,7 @@
+ }
+
+ if (
++ this.options.useIOSScrollDeferral &&
+ isIOSWebKit() &&
+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
+ ) {
+@@ -962,6 +967,7 @@
+ // applyScrollAdjustment does — accumulate the delta and let
+ // _flushIosDeferredIfReady handle it once the scroll settles.
+ if (
++ this.options.useIOSScrollDeferral &&
+ isIOSWebKit() &&
+ (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)
+ ) {
+diff --git a/dist/esm/index.js b/dist/esm/index.js
+--- a/dist/esm/index.js
++++ b/dist/esm/index.js
+@@ -274,6 +274,7 @@
+ isScrollingResetDelay: 150,
+ enabled: true,
+ isRtl: false,
++ useIOSScrollDeferral: true,
+ useScrollendEvent: false,
+ useAnimationFrameWithResizeObserver: false,
+ laneAssignmentMode: "estimate",
+@@ -302,7 +303,7 @@
+ anchor = [item.key, this.getScrollOffset() - item.start];
+ }
+ const behavior = merged.followOnAppend === true ? "auto" : merged.followOnAppend || null;
+- if (behavior && nextCount > prevCount && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
++ if (behavior && nextCount >= prevCount && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
+ followOnAppend = behavior;
+ }
+ }
+@@ -487,7 +488,7 @@
+ if (anchor && this.scrollElement && this.options.enabled) {
+ const [key, _offset, followOnAppend, anchorDelta] = anchor;
+ if (key !== null && !followOnAppend) {
+- if (isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
++ if (this.options.useIOSScrollDeferral && isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
+ if (anchorDelta !== 0) {
+ this._iosDeferredAdjustment += anchorDelta;
+ }
+@@ -1132,7 +1133,7 @@
+ if (process.env.NODE_ENV !== "production" && this.options.debug) {
+ console.info("correction", delta);
+ }
+- if (isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
++ if (this.options.useIOSScrollDeferral && isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
+ this._iosDeferredAdjustment += delta;
+ return false;
+ } else {
+diff --git a/dist/cjs/index.cjs b/dist/cjs/index.cjs
+--- a/dist/cjs/index.cjs
++++ b/dist/cjs/index.cjs
+@@ -276,6 +276,7 @@
+ isScrollingResetDelay: 150,
+ enabled: true,
+ isRtl: false,
++ useIOSScrollDeferral: true,
+ useScrollendEvent: false,
+ useAnimationFrameWithResizeObserver: false,
+ laneAssignmentMode: "estimate",
+@@ -304,7 +305,7 @@
+ anchor = [item.key, this.getScrollOffset() - item.start];
+ }
+ const behavior = merged.followOnAppend === true ? "auto" : merged.followOnAppend || null;
+- if (behavior && nextCount > prevCount && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
++ if (behavior && nextCount >= prevCount && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
+ followOnAppend = behavior;
+ }
+ }
+@@ -489,7 +490,7 @@
+ if (anchor && this.scrollElement && this.options.enabled) {
+ const [key, _offset, followOnAppend, anchorDelta] = anchor;
+ if (key !== null && !followOnAppend) {
+- if (isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
++ if (this.options.useIOSScrollDeferral && isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
+ if (anchorDelta !== 0) {
+ this._iosDeferredAdjustment += anchorDelta;
+ }
+@@ -1134,7 +1135,7 @@
+ if (process.env.NODE_ENV !== "production" && this.options.debug) {
+ console.info("correction", delta);
+ }
+- if (isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
++ if (this.options.useIOSScrollDeferral && isIOSWebKit() && (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)) {
+ this._iosDeferredAdjustment += delta;
+ return false;
+ } else {
+diff --git a/dist/esm/index.d.ts b/dist/esm/index.d.ts
+--- a/dist/esm/index.d.ts
++++ b/dist/esm/index.d.ts
+@@ -81,6 +81,8 @@
+ followOnAppend?: FollowOnAppend;
+ scrollEndThreshold?: number;
+ isScrollingResetDelay?: number;
++ /** Disable only when scrollToFn provides its own touch-safe compensation. */
++ useIOSScrollDeferral?: boolean;
+ useScrollendEvent?: boolean;
+ enabled?: boolean;
+ isRtl?: boolean;
+diff --git a/dist/cjs/index.d.cts b/dist/cjs/index.d.cts
+--- a/dist/cjs/index.d.cts
++++ b/dist/cjs/index.d.cts
+@@ -81,6 +81,8 @@
+ followOnAppend?: FollowOnAppend;
+ scrollEndThreshold?: number;
+ isScrollingResetDelay?: number;
++ /** Disable only when scrollToFn provides its own touch-safe compensation. */
++ useIOSScrollDeferral?: boolean;
+ useScrollendEvent?: boolean;
+ enabled?: boolean;
+ isRtl?: boolean;
diff --git a/apps/web/src/features/block-agent/component/Transcript.test.tsx b/apps/web/src/features/block-agent/component/Transcript.test.tsx
index 09f3cf741f..9337d6dad1 100644
--- a/apps/web/src/features/block-agent/component/Transcript.test.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.test.tsx
@@ -243,7 +243,9 @@ describe('Transcript with the shared TanStack ThreadList', () => {
const view = mount([message(0)]);
await settle();
const row = view.container.querySelector<HTMLElement>('[data-index="0"]')!;
- expect(row.style.transform).toBe('translateY(224px)');
+ expect(row.style.transform).toBe(
+ 'translateY(calc(224px - var(--channel-scroll-adjustment, 0px)))'
+ );
expect(view.scroller.scrollTop).toBe(0);
const reply = view.getByText('Reply to selection');
expect(reply.getAttribute('data-selection-connected')).toBe('true');
@@ -259,7 +261,9 @@ describe('Transcript with the shared TanStack ThreadList', () => {
resize();
await settle();
const row = view.container.querySelector<HTMLElement>('[data-index="0"]')!;
- expect(row.style.transform).toBe('translateY(40px)');
+ expect(row.style.transform).toBe(
+ 'translateY(calc(40px - var(--channel-scroll-adjustment, 0px)))'
+ );
expect(view.scroller.scrollHeight).toBe(40 + 500 + 80);
});
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index c9afbed29d..0d224448a5 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -4,6 +4,7 @@ import {
type ScrollDirection,
} from '@core/util/scroll-intent';
import { Key } from '@solid-primitives/keyed';
+import { isIOS, isSafari } from '@solid-primitives/platform';
import {
createVirtualizer,
defaultRangeExtractor,
@@ -26,6 +27,7 @@ import {
onMount,
} from 'solid-js';
import { NEAR_BOTTOM_THRESHOLD } from './constants';
+import { createScrollCompensation } from './create-scroll-compensation';
import { createScrollLifecycle } from './create-scroll-lifecycle';
type ScrollAlignment = NonNullable<ScrollToOptions['align']>;
@@ -97,6 +99,8 @@ type ThreadListProps = {
};
const NEAR_TOP_THRESHOLD = 800;
+const HISTORY_BUFFER_VIEWPORTS = 3;
+const WEBKIT_HISTORY_BUFFER_VIEWPORTS = 6;
const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;
const clamp = (value: number, min: number, max: number) =>
@@ -131,13 +135,39 @@ export function ThreadList(props: ThreadListProps) {
snapshot?.measurements?.map(({ key, size }) => [key, size])
);
let programmaticOffset: number | undefined;
- let userScrollActive = false;
let stateQueued = false;
- let nearTopFired = false;
+ let nearTopKey: string | undefined;
let nearBottomFired = false;
let previousScrollOffset = snapshot?.scrollOffset ?? 0;
let explicitScrollDownDistance = 0;
let releaseNavigation: void | (() => void);
+ const scrollCompensation =
+ isSafari || isIOS
+ ? createScrollCompensation({
+ getElement: () => scrollEl(),
+ setAdjustment: (adjustment) => {
+ if (!contentRef) return;
+ contentRef.style.setProperty(
+ '--channel-scroll-adjustment',
+ `${adjustment}px`
+ );
+ // Shifted rows must not change the logical scroll extent.
+ contentRef.style.overflow = adjustment === 0 ? '' : 'clip';
+ },
+ writeOffset: (offset) => {
+ const element = scrollEl();
+ if (!element) return;
+ element.scrollTo({ top: offset });
+ programmaticOffset = element.scrollTop;
+ scheduleScrollState();
+ },
+ })
+ : undefined;
+ const historyBufferViewports = scrollCompensation
+ ? WEBKIT_HISTORY_BUFFER_VIEWPORTS
+ : HISTORY_BUFFER_VIEWPORTS;
+ const logicalScrollOffset = (offset: number) =>
+ scrollCompensation?.logicalOffset(offset) ?? offset;
// Publish after Solid has committed the virtual rows and spacer height.
// Geometry notifications also cover reactions, streamed content and resizes
@@ -198,6 +228,8 @@ export function ThreadList(props: ThreadListProps) {
// next frame exposes stale geometry and can lose the end anchor on send.
useAnimationFrameWithResizeObserver: false,
useScrollendEvent: true,
+ // The patched core delegates iOS deferral to our visual compensation.
+ useIOSScrollDeferral: !scrollCompensation,
anchorTo: 'end',
get followOnAppend() {
return lifecycle.isReady() && (props.followOnAppend ?? true);
@@ -249,36 +281,52 @@ export function ThreadList(props: ThreadListProps) {
if (contentRef) {
contentRef.style.height = `${Math.max(viewportSize(), instance.getTotalSize())}px`;
}
- // A deferred prepend has already advanced the logical offset while
- // the DOM is still at the old position. Positive corrections in that
- // state must start at the DOM offset; normal corrections (including
- // shrink clamping) still use TanStack's requested offset.
- const domOffset = instance.scrollElement?.scrollTop ?? offset;
- const deferredPrepend =
- (options.adjustments ?? 0) > 0 &&
- offset > domOffset + 1.5 &&
- (userScrollActive || scrollIntent.isUserInteracting());
- elementScroll(deferredPrepend ? domOffset : offset, options, instance);
+ // WebKit ends native momentum on scrollTo writes. Keep TanStack's logical
+ // offset, but counter-shift the rows until wheel/touch scrolling settles.
+ // Explicit navigation finishes compensation before calculating its target.
+ if (
+ lifecycle.isReady() &&
+ scrollCompensation?.defer(offset + (options.adjustments ?? 0))
+ ) {
+ return;
+ }
+ elementScroll(offset, options, instance);
programmaticOffset =
options.behavior === 'smooth'
? undefined
: instance.scrollElement?.scrollTop;
},
- observeElementOffset: (instance, callback) =>
- observeElementOffset(instance, (offset, isScrolling) => {
- // An instant navigation/correction is not touch momentum. Reporting
- // its scroll event as momentum makes iOS defer size compensation and
- // replay it after scrollToIndex has already reconciled the same sizes.
+ observeElementOffset: (instance, callback) => {
+ const element = instance.scrollElement;
+ const onWheel = scrollCompensation?.onWheel;
+ const onTouchStart = scrollCompensation?.onTouchStart;
+ if (onWheel)
+ element?.addEventListener('wheel', onWheel, { passive: true });
+ if (onTouchStart)
+ element?.addEventListener('touchstart', onTouchStart, {
+ passive: true,
+ });
+ const cleanup = observeElementOffset(instance, (offset, isScrolling) => {
+ // An instant navigation/correction must not extend gesture compensation.
const isOwnScroll =
programmaticOffset !== undefined &&
Math.abs(offset - programmaticOffset) < 1.5;
programmaticOffset = undefined;
- if (isScrolling && !isOwnScroll) userScrollActive = true;
- callback(offset, isScrolling && !isOwnScroll);
- // Keep the gesture active while the end callback flushes any deferred
- // correction, including momentum lasting past the input-event timeout.
- if (!isScrolling || isOwnScroll) userScrollActive = false;
- }),
+ if (isScrolling && !isOwnScroll) scrollIntent.observeScroll();
+ const logicalOffset =
+ scrollCompensation?.observeOffset(
+ offset,
+ isScrolling && !isOwnScroll
+ ) ?? offset;
+ callback(logicalOffset, isScrolling && !isOwnScroll);
+ });
+ return () => {
+ cleanup?.();
+ if (onWheel) element?.removeEventListener('wheel', onWheel);
+ if (onTouchStart)
+ element?.removeEventListener('touchstart', onTouchStart);
+ };
+ },
observeElementRect: (instance, callback) =>
observeElementRect(instance, (rect) => {
const previousHeight = instance.scrollRect?.height ?? 0;
@@ -293,12 +341,29 @@ export function ThreadList(props: ThreadListProps) {
// The core anchors item resizes; viewport resizes (composer, keyboard,
// split pane) need an explicit end scroll when previously pinned.
if (previousHeight > 0 && previousHeight !== rect.height && wasAtEnd) {
+ scrollCompensation?.finish();
instance.scrollToEnd();
}
}),
onChange: scheduleScrollState,
});
+ if (scrollCompensation) {
+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (
+ item,
+ _delta,
+ instance
+ ) => {
+ const offset = (instance.scrollOffset ?? 0) + instance.scrollAdjustments;
+ // The core skips remeasurement corrections while scrolling backward.
+ // Our counter-translation makes these safe: a late-loading image above
+ // the viewport must preserve the reading anchor in either direction.
+ return instance.itemSizeCache.has(item.key)
+ ? item.end <= offset
+ : item.start < offset;
+ };
+ }
+
const shortListOffset = () =>
Math.max(0, viewportSize() - virtualizer.getTotalSize());
// The adapter mutates its store by index. Snapshot those values and let Key
@@ -314,6 +379,7 @@ export function ThreadList(props: ThreadListProps) {
): boolean => {
const index = props.keys().indexOf(id);
if (index < 0) return false;
+ scrollCompensation?.finish();
virtualizer.scrollToIndex(index, { align });
scheduleScrollState();
return true;
@@ -328,6 +394,7 @@ export function ThreadList(props: ThreadListProps) {
scrollToLatest: () => {
if (!canNavigate() || !props.keys().length) return false;
lifecycle.send('navigate');
+ scrollCompensation?.finish();
virtualizer.scrollToEnd();
scheduleScrollState();
return true;
@@ -342,6 +409,7 @@ export function ThreadList(props: ThreadListProps) {
const el = scrollEl();
if (!canNavigate() || !el || !el.contains(targetElement)) return false;
lifecycle.send('navigate');
+ scrollCompensation?.finish();
// Both rects come from the same committed layout, including short-list
// bottom alignment and floating chrome. No stale estimate is involved.
const targetRect = targetElement.getBoundingClientRect();
@@ -366,9 +434,14 @@ export function ThreadList(props: ThreadListProps) {
if (!el) return;
// This microtask runs after synchronous row measurements, before paint.
lifecycle.send('layout');
- const distanceFromTop = el.scrollTop;
+ const distanceFromTop = logicalScrollOffset(el.scrollTop);
const distanceFromBottom = virtualizer.getDistanceFromEnd();
- const nearTop = distanceFromTop <= NEAR_TOP_THRESHOLD;
+ // WebKit cannot move the native top boundary during a fling without a
+ // scroll write. Fill a bounded history buffer ahead of the next gesture,
+ // including after initial positioning or navigation into older messages.
+ const nearTop =
+ distanceFromTop <=
+ Math.max(NEAR_TOP_THRESHOLD, el.clientHeight * historyBufferViewports);
const nearBottom = distanceFromBottom <= NEAR_BOTTOM_THRESHOLD;
const hasUserIntent = scrollIntent.isUserInteracting();
const delta = distanceFromTop - previousScrollOffset;
@@ -398,10 +471,14 @@ export function ThreadList(props: ThreadListProps) {
: undefined;
props.onScroll?.(state, snapshot);
if (!lifecycle.isReady()) return;
- if (nearTop && !nearTopFired && hasUserIntent) {
- nearTopFired = true;
+ if (
+ nearTop &&
+ (hasUserIntent || scrollCompensation) &&
+ nearTopKey !== props.keys()[0]
+ ) {
+ nearTopKey = props.keys()[0];
props.onScrollNearTop?.();
- } else if (!nearTop) nearTopFired = false;
+ } else if (!nearTop) nearTopKey = undefined;
if (nearBottom && !nearBottomFired && hasUserIntent) {
nearBottomFired = true;
props.onScrollNearBottom?.();
@@ -420,6 +497,7 @@ export function ThreadList(props: ThreadListProps) {
viewportSize() -
(virtualizer.scrollOffset ?? 0);
if (delta !== 0 && previousDistance <= NEAR_BOTTOM_THRESHOLD) {
+ scrollCompensation?.finish();
virtualizer.scrollToEnd();
}
scheduleScrollState();
@@ -441,6 +519,7 @@ export function ThreadList(props: ThreadListProps) {
onCleanup(() => attachmentObserver.disconnect());
});
onCleanup(() => {
+ scrollCompensation?.dispose();
lifecycle.send('dispose');
releaseNavigation?.();
});
@@ -493,7 +572,7 @@ export function ThreadList(props: ThreadListProps) {
top: 0,
left: 0,
width: '100%',
- transform: `translateY(${item().start + shortListOffset()}px)`,
+ transform: `translateY(calc(${item().start + shortListOffset()}px - var(--channel-scroll-adjustment, 0px)))`,
'overflow-anchor': 'none',
}}
>
@@ -507,9 +586,10 @@ export function ThreadList(props: ThreadListProps) {
<CustomScrollbar
scrollContainer={scrollEl}
watchContent
- onScrollIntent={(delta) =>
- scrollIntent.markUserIntent(delta > 0 ? 'down' : 'up')
- }
+ onScrollIntent={(delta) => {
+ scrollCompensation?.finish();
+ scrollIntent.markUserIntent(delta > 0 ? 'down' : 'up');
+ }}
/>
</>
);
diff --git a/apps/web/src/features/channel/Channel/create-scroll-compensation.ts b/apps/web/src/features/channel/Channel/create-scroll-compensation.ts
new file mode 100644
index 0000000000..f4429b4188
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/create-scroll-compensation.ts
@@ -0,0 +1,130 @@
+const SCROLL_IDLE_MS = 150;
+
+type ScrollCompensationOptions = {
+ getElement: () => HTMLElement | undefined;
+ setAdjustment: (adjustment: number) => void;
+ writeOffset: (offset: number) => void;
+};
+
+/**
+ * Keeps a virtual list's logical offset separate from native gesture scrolling.
+ * Rows subtract the adjustment from their positions until the gesture settles.
+ */
+export function createScrollCompensation(options: ScrollCompensationOptions) {
+ let adjustment = 0;
+ let reportedOffset: number | undefined;
+ let active = false;
+ const touchTargets = new Set<EventTarget>();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const clearTimer = () => {
+ clearTimeout(timer);
+ timer = undefined;
+ };
+
+ const finish = () => {
+ clearTimer();
+ active = false;
+ const element = options.getElement();
+ const offset = (element?.scrollTop ?? 0) + adjustment;
+ const needsWrite = adjustment !== 0 && element?.isConnected;
+ adjustment = 0;
+ options.setAdjustment(0);
+ if (needsWrite) options.writeOffset(offset);
+ };
+
+ const scheduleFinish = () => {
+ clearTimer();
+ if (touchTargets.size > 0) return;
+ timer = setTimeout(() => {
+ const element = options.getElement();
+ // Do not interrupt iOS rubber-banding. Retry even without another scroll event.
+ if (
+ element &&
+ (element.scrollTop < 0 ||
+ element.scrollTop > element.scrollHeight - element.clientHeight)
+ ) {
+ scheduleFinish();
+ return;
+ }
+ finish();
+ }, SCROLL_IDLE_MS);
+ };
+
+ const releaseTouchTargets = () => {
+ for (const target of touchTargets) {
+ target.removeEventListener('touchend', onTouchEnd);
+ target.removeEventListener('touchcancel', onTouchEnd);
+ }
+ touchTargets.clear();
+ };
+ const onTouchEnd = (event: Event) => {
+ if ((event as TouchEvent).touches.length > 0) return;
+ releaseTouchTargets();
+ if (active) scheduleFinish();
+ };
+
+ return {
+ onTouchStart: (event: TouchEvent) => {
+ active = true;
+ clearTimer();
+ // Touch events retain their original target even after a virtual row
+ // unmounts. Listen there so touchend/cancel cannot strand compensation.
+ if (event.target) {
+ touchTargets.add(event.target);
+ event.target.addEventListener('touchend', onTouchEnd, {
+ passive: true,
+ });
+ event.target.addEventListener('touchcancel', onTouchEnd, {
+ passive: true,
+ });
+ }
+ },
+ onWheel: (event: WheelEvent) => {
+ if (event.ctrlKey || event.deltaY === 0) return;
+ active = true;
+ scheduleFinish();
+ },
+ observeOffset: (offset: number, isScrolling: boolean) => {
+ const element = options.getElement();
+ const logicalOffset = offset + adjustment;
+ if (
+ adjustment !== 0 &&
+ element &&
+ offset >= 0 &&
+ offset <= element.scrollHeight - element.clientHeight &&
+ (offset <= 0 ||
+ offset >= element.scrollHeight - element.clientHeight ||
+ logicalOffset <= 0 ||
+ logicalOffset >= element.scrollHeight - element.clientHeight)
+ ) {
+ // Release the shifted origin at either edge so all history remains reachable.
+ finish();
+ reportedOffset = element.scrollTop;
+ return reportedOffset;
+ }
+ if (active && isScrolling) scheduleFinish();
+ reportedOffset = logicalOffset;
+ return logicalOffset;
+ },
+ defer: (offset: number) => {
+ const element = options.getElement();
+ const previousOffset =
+ reportedOffset ?? (element?.scrollTop ?? 0) + adjustment;
+ reportedOffset = offset;
+ if (!active || !element) return false;
+ // Native scrolling can advance before its event reaches TanStack. Apply
+ // only the layout delta; an absolute target would undo that unreported motion.
+ adjustment += offset - previousOffset;
+ options.setAdjustment(adjustment);
+ return true;
+ },
+ logicalOffset: (offset: number) => offset + adjustment,
+ finish,
+ dispose: () => {
+ clearTimer();
+ releaseTouchTargets();
+ active = false;
+ },
+ };
+}
diff --git a/apps/web/src/features/channel/Channel/tests/create-scroll-compensation.test.ts b/apps/web/src/features/channel/Channel/tests/create-scroll-compensation.test.ts
new file mode 100644
index 0000000000..d7e091290e
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/create-scroll-compensation.test.ts
@@ -0,0 +1,240 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createScrollCompensation } from '../create-scroll-compensation';
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ vi.useRealTimers();
+ document.body.replaceChildren();
+});
+
+function setup() {
+ const element = document.createElement('div');
+ document.body.append(element);
+ element.scrollTop = 1000;
+ Object.defineProperties(element, {
+ scrollHeight: { value: 5000 },
+ clientHeight: { value: 500 },
+ });
+ let shift = 0;
+ const writeOffset = vi.fn((offset: number) => {
+ element.scrollTop = offset;
+ });
+ const compensation = createScrollCompensation({
+ getElement: () => element,
+ setAdjustment: (value) => {
+ shift = value;
+ },
+ writeOffset,
+ });
+ const wheel = () =>
+ compensation.onWheel(new WheelEvent('wheel', { deltaY: -20 }));
+ return { element, compensation, writeOffset, wheel, shift: () => shift };
+}
+
+describe('gesture scroll compensation', () => {
+ it('preserves native motion that has not reached the offset observer yet', () => {
+ const f = setup();
+ f.compensation.observeOffset(1000, false);
+ f.wheel();
+ f.element.scrollTop = 935;
+ // TanStack prepends 2880px using its last reported offset of 1000px.
+ f.compensation.defer(3880);
+ expect(f.shift()).toBe(2880);
+ // Another measurement before a scroll event shares the updated logical offset.
+ f.compensation.defer(3980);
+ expect(f.shift()).toBe(2980);
+ expect(f.compensation.observeOffset(935, true)).toBe(3915);
+ vi.advanceTimersByTime(150);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(3915);
+ });
+
+ it('keeps the reading anchor while measurements and native scrolling accumulate', () => {
+ const f = setup();
+ f.wheel();
+ // A row above the viewport grows by 200px.
+ expect(f.compensation.defer(1200)).toBe(true);
+ expect(1300 - f.shift() - f.element.scrollTop).toBe(100);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+
+ f.element.scrollTop -= 50;
+ expect(f.compensation.observeOffset(950, true)).toBe(1150);
+ // A second correction adds 80px to the same logical coordinate system.
+ f.compensation.defer(1230);
+ expect(f.shift()).toBe(280);
+ expect(1380 - f.shift() - f.element.scrollTop).toBe(150);
+
+ vi.advanceTimersByTime(150);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(1230);
+ expect(f.shift()).toBe(0);
+ expect(1380 - f.element.scrollTop).toBe(150);
+ });
+
+ it('preserves a shrinking-row adjustment and writes it once after momentum', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(800);
+ vi.advanceTimersByTime(100);
+ f.element.scrollTop = 970;
+ expect(f.compensation.observeOffset(970, true)).toBe(770);
+ // A native scrollend notification alone must not flush recent wheel input.
+ f.compensation.observeOffset(970, false);
+ vi.advanceTimersByTime(100);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(50);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(770);
+ });
+
+ it('flushes before explicit navigation and does not replay the adjustment', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(1400);
+ f.compensation.finish();
+ f.element.scrollTop = 3000;
+ expect(f.compensation.defer(3200)).toBe(false);
+ vi.advanceTimersByTime(1000);
+ expect(f.writeOffset).toHaveBeenCalledTimes(1);
+ expect(f.compensation.logicalOffset(f.element.scrollTop)).toBe(3000);
+ });
+
+ it('does not extend the gesture when only async content keeps resizing', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(1200);
+ vi.advanceTimersByTime(100);
+ f.compensation.defer(1300);
+ vi.advanceTimersByTime(50);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(1300);
+ });
+
+ it('releases the shifted origin when native scrolling reaches the top', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(1200);
+ f.element.scrollTop = 0;
+ expect(f.compensation.observeOffset(0, true)).toBe(200);
+ expect(f.shift()).toBe(0);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(200);
+ });
+
+ it('does not write after disposal or detachment', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(1200);
+ f.compensation.dispose();
+ vi.advanceTimersByTime(1000);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ f.element.remove();
+ f.compensation.finish();
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ });
+
+ it('releases negative compensation at the physical bottom', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(800);
+ f.element.scrollTop = 4500;
+ expect(f.compensation.observeOffset(4500, true)).toBe(4300);
+ expect(f.shift()).toBe(0);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(4300);
+ });
+
+ it('leaves idle corrections and pinch zoom alone', () => {
+ const f = setup();
+ expect(f.compensation.defer(1200)).toBe(false);
+ f.compensation.onWheel(
+ new WheelEvent('wheel', { deltaY: 10, ctrlKey: true })
+ );
+ expect(f.compensation.defer(1200)).toBe(false);
+ });
+
+ it('waits for a held touch and its momentum, even after its row unmounts', () => {
+ const f = setup();
+ const row = document.createElement('div');
+ f.element.append(row);
+ f.element.addEventListener('touchstart', f.compensation.onTouchStart);
+ row.dispatchEvent(new TouchEvent('touchstart', { bubbles: true }));
+ f.compensation.defer(1200);
+ vi.advanceTimersByTime(1000);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+
+ row.remove();
+ row.dispatchEvent(new TouchEvent('touchend', { touches: [] }));
+ vi.advanceTimersByTime(100);
+ f.element.scrollTop = 950;
+ expect(f.compensation.observeOffset(950, true)).toBe(1150);
+ vi.advanceTimersByTime(100);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(50);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(1150);
+ });
+
+ it('releases a cancelled touch and waits for the last finger', () => {
+ const f = setup();
+ f.element.addEventListener('touchstart', f.compensation.onTouchStart);
+ f.element.dispatchEvent(new TouchEvent('touchstart'));
+ f.compensation.defer(1200);
+ f.element.dispatchEvent(
+ new TouchEvent('touchend', { touches: [{} as Touch] })
+ );
+ vi.advanceTimersByTime(200);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ f.element.dispatchEvent(new TouchEvent('touchcancel', { touches: [] }));
+ vi.advanceTimersByTime(150);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(1200);
+ });
+
+ it('waits for rubber-banding to return in bounds before flushing', () => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(1200);
+ f.element.scrollTop = -40;
+ expect(f.compensation.observeOffset(-40, true)).toBe(160);
+ vi.advanceTimersByTime(500);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ f.element.scrollTop = 0;
+ expect(f.compensation.observeOffset(0, true)).toBe(200);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(200);
+ });
+
+ it.each([
+ { overscroll: -40, settled: 0, target: 1200, expected: 200 },
+ { overscroll: 4540, settled: 4500, target: 800, expected: 4300 },
+ ])(
+ 'retries rubber-banding at $overscroll without another scroll event',
+ ({ overscroll, settled, target, expected }) => {
+ const f = setup();
+ f.wheel();
+ f.compensation.defer(target);
+ f.element.scrollTop = overscroll;
+ vi.advanceTimersByTime(600);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ expect(f.shift()).toBe(target - 1000);
+
+ f.element.scrollTop = settled;
+ vi.advanceTimersByTime(150);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(expected);
+ expect(f.shift()).toBe(0);
+ expect(f.compensation.defer(expected + 100)).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ );
+
+ it('tracks fingers on different rows until the final finger lifts', () => {
+ const f = setup();
+ const first = document.createElement('div');
+ const second = document.createElement('div');
+ f.element.append(first, second);
+ f.element.addEventListener('touchstart', f.compensation.onTouchStart);
+ first.dispatchEvent(new TouchEvent('touchstart', { bubbles: true }));
+ second.dispatchEvent(new TouchEvent('touchstart', { bubbles: true }));
+ f.compensation.defer(1200);
+ second.dispatchEvent(
+ new TouchEvent('touchend', { touches: [{} as Touch] })
+ );
+ vi.advanceTimersByTime(200);
+ expect(f.writeOffset).not.toHaveBeenCalled();
+ first.dispatchEvent(new TouchEvent('touchend', { touches: [] }));
+ vi.advanceTimersByTime(150);
+ expect(f.writeOffset).toHaveBeenCalledExactlyOnceWith(1200);
+ });
+});
diff --git a/apps/web/src/features/channel/Channel/tests/ios-scroll-deferral.test.ts b/apps/web/src/features/channel/Channel/tests/ios-scroll-deferral.test.ts
new file mode 100644
index 0000000000..a8669a90e7
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/ios-scroll-deferral.test.ts
@@ -0,0 +1,89 @@
+import { Virtualizer } from '@tanstack/solid-virtual';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+beforeEach(() => {
+ vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('iPhone');
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.replaceChildren();
+});
+
+function setup(useIOSScrollDeferral?: boolean) {
+ const element = document.createElement('div');
+ document.body.append(element);
+ let observeOffset: (offset: number, scrolling: boolean) => void = () => {};
+ const scrollToFn = vi.fn();
+ const virtualizer = new Virtualizer<HTMLDivElement, HTMLDivElement>({
+ count: 100,
+ getItemKey: (index) => String(index),
+ getScrollElement: () => element,
+ estimateSize: () => 100,
+ initialOffset: 1000,
+ anchorTo: 'end',
+ useIOSScrollDeferral,
+ scrollToFn,
+ observeElementRect: (_instance, callback) => {
+ callback({ width: 375, height: 500 });
+ },
+ observeElementOffset: (_instance, callback) => {
+ observeOffset = callback;
+ callback(1000, false);
+ },
+ });
+ const cleanup = virtualizer._didMount();
+ virtualizer._willUpdate();
+ observeOffset(1000, true);
+ scrollToFn.mockClear();
+ return { virtualizer, scrollToFn, cleanup };
+}
+
+describe('channel-owned iOS scroll compensation', () => {
+ it.each([undefined, false])(
+ 'delegates resize corrections only when core deferral is disabled (%s)',
+ (useIOSScrollDeferral) => {
+ const f = setup(useIOSScrollDeferral);
+ try {
+ f.virtualizer.resizeItem(0, 180);
+ if (useIOSScrollDeferral === false) {
+ expect(f.scrollToFn).toHaveBeenCalledWith(
+ 1000,
+ expect.objectContaining({ adjustments: 80 }),
+ f.virtualizer
+ );
+ expect(f.virtualizer.scrollOffset).toBe(1080);
+ } else {
+ expect(f.scrollToFn).not.toHaveBeenCalled();
+ }
+ } finally {
+ f.cleanup();
+ }
+ }
+ );
+
+ it.each([undefined, false])(
+ 'delegates prepend corrections only when core deferral is disabled (%s)',
+ (useIOSScrollDeferral) => {
+ const f = setup(useIOSScrollDeferral);
+ try {
+ f.virtualizer.setOptions({
+ ...f.virtualizer.options,
+ count: 110,
+ getItemKey: (index) => String(index - 10),
+ });
+ f.virtualizer._willUpdate();
+ if (useIOSScrollDeferral === false) {
+ expect(f.scrollToFn).toHaveBeenCalledWith(
+ 2000,
+ expect.objectContaining({ adjustments: undefined }),
+ f.virtualizer
+ );
+ } else {
+ expect(f.scrollToFn).not.toHaveBeenCalled();
+ }
+ } finally {
+ f.cleanup();
+ }
+ }
+ );
+});
diff --git a/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
new file mode 100644
index 0000000000..d1b9439a2b
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
@@ -0,0 +1,180 @@
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ThreadList, type ThreadListNavigation } from '../ThreadList';
+
+const rowHeights = new Map<string, number>();
+
+const platform = vi.hoisted(() => ({ safari: true }));
+vi.mock('@solid-primitives/platform', () => ({
+ get isSafari() {
+ return platform.safari;
+ },
+ isIOS: false,
+}));
+vi.mock('@core/component/CustomScrollbar', () => ({
+ CustomScrollbar: () => null,
+}));
+
+beforeEach(() => {
+ platform.safari = true;
+ rowHeights.clear();
+ // Supply layout for the real virtualizer; jsdom does not measure DOM nodes.
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return this.hasAttribute('data-index')
+ ? (rowHeights.get(this.textContent ?? '') ?? 96)
+ : 400;
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(400);
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(400);
+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return Number.parseFloat(
+ (this.firstElementChild as HTMLElement)?.style.height ?? '0'
+ );
+ }
+ );
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollTo', {
+ configurable: true,
+ value(this: HTMLElement, options: ScrollToOptions) {
+ const offset = Math.max(
+ 0,
+ Math.min(options.top ?? 0, this.scrollHeight - this.clientHeight)
+ );
+ if (offset === this.scrollTop) return;
+ this.scrollTop = offset;
+ queueMicrotask(() => this.dispatchEvent(new Event('scroll')));
+ },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollTo');
+});
+
+function setup(followOnAppend = true) {
+ const [keys, setKeys] = createSignal(
+ Array.from({ length: 20 }, (_, index) => String(index))
+ );
+ const paginate = vi.fn();
+ let navigation: ThreadListNavigation | undefined;
+ const { container } = render(() => (
+ <ThreadList
+ keys={keys}
+ followOnAppend={followOnAppend}
+ onReady={(value) => {
+ navigation = value;
+ }}
+ onScrollNearTop={paginate}
+ >
+ {({ id }) => <div>{id}</div>}
+ </ThreadList>
+ ));
+ const element = container.querySelector<HTMLDivElement>(
+ '[data-channel-scroll]'
+ )!;
+ const prepend = (count: number) => {
+ const first = Number(keys()[0]);
+ setKeys((previous) => [
+ ...Array.from({ length: count }, (_, index) =>
+ String(first - count + index)
+ ),
+ ...previous,
+ ]);
+ };
+ return { element, paginate, prepend, setKeys, navigation: () => navigation };
+}
+
+describe('history loading ahead of scrolling', () => {
+ it('fills a bounded Safari buffer before a gesture and preserves the bottom pin', async () => {
+ const f = setup();
+ await waitFor(() => expect(f.paginate).toHaveBeenCalledOnce());
+ expect(f.element.scrollTop).toBe(1520);
+ // A short page rearms the request without requiring another scroll event.
+ f.prepend(2);
+ await waitFor(() => expect(f.paginate).toHaveBeenCalledTimes(2));
+ f.prepend(10);
+ await waitFor(() => expect(f.element.scrollTop).toBe(2672));
+ expect(f.paginate).toHaveBeenCalledTimes(2);
+ expect(
+ f.element.scrollHeight - f.element.clientHeight - f.element.scrollTop
+ ).toBe(0);
+ // Revisiting history refills the buffer while keeping the reading position.
+ f.navigation()?.scrollToMessage('0', { align: 'start' });
+ await waitFor(() => expect(f.paginate).toHaveBeenCalledTimes(3));
+ const before = f.element.scrollTop;
+ f.prepend(20);
+ await waitFor(() => expect(f.element.scrollTop).toBe(before + 20 * 96));
+ expect(f.paginate).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not repeat a request for an unchanged boundary', async () => {
+ const f = setup();
+ await waitFor(() => expect(f.paginate).toHaveBeenCalledOnce());
+ f.element.dispatchEvent(new Event('scroll'));
+ f.navigation()?.scrollToLatest();
+ await new Promise((resolve) => queueMicrotask(() => resolve(undefined)));
+ expect(f.paginate).toHaveBeenCalledOnce();
+ });
+
+ it('still requires user intent on browsers without compensation', async () => {
+ platform.safari = false;
+ const f = setup();
+ await waitFor(() => expect(f.navigation()).toBeDefined());
+ f.navigation()?.scrollToMessage('0', { align: 'start' });
+ await waitFor(() => expect(f.element.scrollTop).toBe(0));
+ expect(f.paginate).not.toHaveBeenCalled();
+ f.element.dispatchEvent(
+ new WheelEvent('wheel', { deltaY: -100, bubbles: true })
+ );
+ f.element.dispatchEvent(new Event('scroll'));
+ await waitFor(() => expect(f.paginate).toHaveBeenCalledOnce());
+ });
+});
+
+describe('server acknowledgement scroll anchoring', () => {
+ it.each([0, 10])(
+ 'preserves the pin only when already at the end (%ipx gap)',
+ async (gap) => {
+ rowHeights.set('19', 64);
+ rowHeights.set('ack', 160);
+ const f = setup();
+ await waitFor(() => expect(f.navigation()).toBeDefined());
+ f.element.scrollTop -= gap;
+ f.element.dispatchEvent(new Event('scroll'));
+ await new Promise((resolve) => queueMicrotask(() => resolve(undefined)));
+ const before = f.element.scrollTop;
+ f.setKeys((keys) => [...keys.slice(0, -1), 'ack']);
+ await waitFor(() => expect(f.element.scrollHeight).toBe(19 * 96 + 160));
+ await waitFor(() =>
+ expect(f.element.scrollTop).toBe(
+ gap === 0 ? f.element.scrollHeight - 400 : before
+ )
+ );
+ }
+ );
+
+ it('does not follow replacements in a window without the latest page', async () => {
+ rowHeights.set('19', 64);
+ rowHeights.set('ack', 160);
+ const f = setup(false);
+ await waitFor(() => expect(f.navigation()).toBeDefined());
+ const before = f.element.scrollTop;
+ f.setKeys((keys) => [...keys.slice(0, -1), 'ack']);
+ await waitFor(() => expect(f.element.scrollHeight).toBe(19 * 96 + 160));
+ expect(f.element.scrollTop).toBe(before);
+ });
+});
diff --git a/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts b/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
index 6440b41f65..ac4b16b2ce 100644
--- a/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
+++ b/apps/web/src/features/channel/Channel/tests/thread-list-scroll.test.ts
@@ -40,6 +40,29 @@ describe('createScrollIntentTracker', () => {
expect(tracker.isUserInteracting(Date.now() + 1000)).toBe(false);
});
+ it('keeps pagination intent through a fling and expires after native scrolling stops', () => {
+ vi.useFakeTimers();
+ try {
+ const onUserIntent = vi.fn();
+ const { tracker, dispatch } = scrollSurface(onUserIntent);
+ dispatch('pointerdown', { pointerType: 'touch', clientY: 100 });
+ dispatch('touchmove', { touches: [{ clientY: 150 }] });
+ dispatch('touchend');
+ for (let i = 0; i < 10; i++) {
+ vi.advanceTimersByTime(100);
+ tracker.observeScroll();
+ expect(tracker.lastDirection()).toBe('up');
+ }
+ expect(onUserIntent).toHaveBeenCalledOnce();
+ vi.advanceTimersByTime(301);
+ expect(tracker.isUserInteracting()).toBe(false);
+ tracker.observeScroll();
+ expect(tracker.isUserInteracting()).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('is not interacting by default', () => {
const tracker = createScrollIntentTracker();
expect(tracker.isUserInteracting()).toBe(false);
diff --git a/apps/web/src/features/channel/Channel/tests/virtualizer-follow-on-append.test.ts b/apps/web/src/features/channel/Channel/tests/virtualizer-follow-on-append.test.ts
new file mode 100644
index 0000000000..ec5e98efc4
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/virtualizer-follow-on-append.test.ts
@@ -0,0 +1,40 @@
+import { Virtualizer } from '@tanstack/solid-virtual';
+import { expect, it, vi } from 'vitest';
+
+it('does not follow empty-to-empty updates but follows the first append', () => {
+ const element = document.createElement('div');
+ document.body.append(element);
+ const virtualizer = new Virtualizer<HTMLDivElement, HTMLDivElement>({
+ count: 0,
+ getScrollElement: () => element,
+ estimateSize: () => 100,
+ anchorTo: 'end',
+ followOnAppend: true,
+ scrollToFn: vi.fn(),
+ observeElementRect: (_instance, callback) => {
+ callback({ width: 375, height: 500 });
+ },
+ observeElementOffset: (_instance, callback) => {
+ callback(0, false);
+ },
+ });
+ const cleanup = virtualizer._didMount();
+ const scrollToEnd = vi.spyOn(virtualizer, 'scrollToEnd');
+ try {
+ virtualizer._willUpdate();
+ expect(virtualizer.isAtEnd()).toBe(true);
+ const getItemKey = vi.fn((index: number) => String(index));
+ virtualizer.setOptions({ ...virtualizer.options, count: 0, getItemKey });
+ virtualizer._willUpdate();
+ expect(scrollToEnd).not.toHaveBeenCalled();
+ expect(getItemKey).not.toHaveBeenCalled();
+
+ virtualizer.setOptions({ ...virtualizer.options, count: 1 });
+ virtualizer._willUpdate();
+ expect(scrollToEnd).toHaveBeenCalledExactlyOnceWith({ behavior: 'auto' });
+ } finally {
+ scrollToEnd.mockRestore();
+ cleanup();
+ element.remove();
+ }
+});
diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsx
index bf42d23c38..72e252cbeb 100644
--- a/apps/web/src/features/channel/Input/ChannelInput.tsx
+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx
@@ -29,7 +29,6 @@ import {
} from '@core/util/upload';
import type { EntityData } from '@entity';
import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';
-import { isIOS } from '@solid-primitives/platform';
import { CollapsedInput, cn, Surface } from '@ui';
import { $getRoot } from 'lexical';
import {
@@ -70,6 +69,7 @@ import type {
} from './types';
import { isReplyInput } from './types';
import { uploadInputAttachments } from './upload-attachments';
+import { clearComposer as clearComposerPreservingFocus } from './utils/clear-composer';
import { entityToDocumentMentionInfo } from './utils/entity-mention';
import { applyInlineFormat, applyNodeFormat } from './utils/formatting';
import { $selectTrailingParagraph } from './utils/select-trailing-paragraph';
@@ -356,21 +356,15 @@ export function ChannelInput(props: ChannelInputProps) {
coordinates.clientY <= rect.bottom
);
};
- // On iOS, blur before clearing so dictation finalizes and discards its buffer
- // (otherwise it re-injects the sent text into the cleared editor). Re-focus
- // via rAF so the keyboard stays up: rAF fires after Lexical's update commits,
- // avoiding a conflict where clear()'s $setSelection(null) undoes the focus.
clearComposer = () => {
- if (isIOS) {
- isInternalRefocus = true;
- markdownEditor.controls.blur();
- markdownEditor.controls.clear();
- requestAnimationFrame(() => {
- markdownEditor.controls.focus();
- isInternalRefocus = false;
- });
- } else {
- markdownEditor.controls.clear();
+ isInternalRefocus = true;
+ try {
+ clearComposerPreservingFocus(
+ lexicalEditor(),
+ markdownEditor.controls.clear
+ );
+ } finally {
+ isInternalRefocus = false;
}
};
diff --git a/apps/web/src/features/channel/Input/create-input-state.ts b/apps/web/src/features/channel/Input/create-input-state.ts
index 39e7acb911..fc55cd08cc 100644
--- a/apps/web/src/features/channel/Input/create-input-state.ts
+++ b/apps/web/src/features/channel/Input/create-input-state.ts
@@ -45,11 +45,9 @@ export function createInputState(options: CreateInputStateOptions): InputState {
snapshot: view.snapshot,
setIsSending: view.setIsSending,
setShowFormatRibbon: view.setShowFormatRibbon,
- clearComposer: options.clearComposer,
- reset: () => {
- view.reset();
- options.clearInput?.();
- },
+ // Sending/closing clears the editor once, through the focus-preserving path.
+ clearComposer: options.clearComposer ?? options.clearInput,
+ reset: view.reset,
removeTrackedAttachment: (id) =>
options.attachmentTracker.removeAttachment(id),
attachFiles: options.attachFiles,
diff --git a/apps/web/src/features/channel/Input/tests/clear-composer.test.ts b/apps/web/src/features/channel/Input/tests/clear-composer.test.ts
new file mode 100644
index 0000000000..1803a292bf
--- /dev/null
+++ b/apps/web/src/features/channel/Input/tests/clear-composer.test.ts
@@ -0,0 +1,158 @@
+import { createEmptyHistoryState, registerHistory } from '@lexical/history';
+import {
+ $addUpdateTag,
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $setSelection,
+ CLEAR_HISTORY_COMMAND,
+ createEditor,
+ HISTORY_PUSH_TAG,
+ SKIP_DOM_SELECTION_TAG,
+ UNDO_COMMAND,
+} from 'lexical';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { clearComposer } from '../utils/clear-composer';
+
+vi.mock('@solid-primitives/platform', () => ({ isIOS: true }));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.replaceChildren();
+});
+
+function setup() {
+ const root = document.createElement('div');
+ root.contentEditable = 'true';
+ root.tabIndex = 0;
+ document.body.append(root);
+ const editor = createEditor({
+ onError: (error) => {
+ throw error;
+ },
+ });
+ editor.setRootElement(root);
+ const history = createEmptyHistoryState();
+ const unregisterHistory = registerHistory(editor, history, 400);
+ editor.update(
+ () => {
+ $addUpdateTag(SKIP_DOM_SELECTION_TAG);
+ $getRoot().append(
+ $createParagraphNode().append($createTextNode('Sent text'))
+ );
+ },
+ { discrete: true }
+ );
+ // This is the selection-clearing update used by the Markdown controls.
+ const clear = vi.fn(() => {
+ editor.update(() => {
+ $addUpdateTag(SKIP_DOM_SELECTION_TAG);
+ $getRoot().clear().append($createParagraphNode());
+ $setSelection(null);
+ });
+ editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined);
+ });
+ return {
+ root,
+ editor,
+ clear,
+ history,
+ dispose: () => {
+ unregisterHistory();
+ editor.setRootElement(null);
+ },
+ };
+}
+
+describe('iOS composer clearing', () => {
+ it('restores the caret without scrolling the viewport', async () => {
+ const f = setup();
+ try {
+ f.root.focus();
+ // The composer lies below the viewport while the keyboard is resizing.
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(0, window.innerHeight + 100, 300, 20)
+ );
+ const scrollBy = vi
+ .spyOn(window, 'scrollBy')
+ .mockImplementation(() => {});
+ clearComposer(f.editor, f.clear);
+ await Promise.resolve();
+ expect(document.activeElement).toBe(f.root);
+ f.editor
+ .getEditorState()
+ .read(() => expect($getSelection()).not.toBeNull());
+ expect(scrollBy).not.toHaveBeenCalled();
+ } finally {
+ f.dispose();
+ }
+ });
+
+ it('cannot undo a send back to the sent message', async () => {
+ const f = setup();
+ try {
+ f.editor.update(
+ () => {
+ $getRoot()
+ .clear()
+ .append(
+ $createParagraphNode().append($createTextNode('Edited sent text'))
+ );
+ $getRoot().selectEnd();
+ },
+ { discrete: true, tag: [HISTORY_PUSH_TAG, SKIP_DOM_SELECTION_TAG] }
+ );
+ expect(f.history.undoStack.length).toBeGreaterThan(0);
+ f.root.focus();
+ clearComposer(f.editor, f.clear);
+ await Promise.resolve();
+ expect(f.history.undoStack).toEqual([]);
+ expect(f.history.redoStack).toEqual([]);
+ f.editor.dispatchCommand(UNDO_COMMAND, undefined);
+ await Promise.resolve();
+ expect(f.root.textContent).toBe('');
+ } finally {
+ f.dispose();
+ }
+ });
+
+ it('ends the editing session and clears before restoring focus in the same task', async () => {
+ const f = setup();
+ try {
+ f.root.focus();
+ const atBlur: string[] = [];
+ f.root.addEventListener('blur', () =>
+ atBlur.push(f.root.textContent ?? '')
+ );
+ clearComposer(f.editor, f.clear);
+ expect(atBlur).toEqual(['Sent text']);
+ expect(f.clear).toHaveBeenCalledOnce();
+ expect(f.root.textContent).toBe('');
+ expect(document.activeElement).toBe(f.root);
+ await Promise.resolve();
+ expect(document.activeElement).toBe(f.root);
+ f.editor
+ .getEditorState()
+ .read(() => expect($getSelection()).not.toBeNull());
+ } finally {
+ f.dispose();
+ }
+ });
+
+ it('does not steal focus back after the user has left the composer', async () => {
+ const f = setup();
+ try {
+ const other = document.createElement('input');
+ document.body.append(other);
+ other.focus();
+ clearComposer(f.editor, f.clear);
+ await Promise.resolve();
+ expect(f.clear).toHaveBeenCalledOnce();
+ expect(f.root.textContent).toBe('');
+ expect(document.activeElement).toBe(other);
+ } finally {
+ f.dispose();
+ }
+ });
+});
diff --git a/apps/web/src/features/channel/Input/tests/create-input-state.test.ts b/apps/web/src/features/channel/Input/tests/create-input-state.test.ts
new file mode 100644
index 0000000000..1a65083227
--- /dev/null
+++ b/apps/web/src/features/channel/Input/tests/create-input-state.test.ts
@@ -0,0 +1,52 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { createInputAttachmentTracker } from '../attachment-tracker';
+import { createInputState } from '../create-input-state';
+
+describe('composer reset on send', () => {
+ it('clears once through the composer path, while an explicit reset still clears normally', async () => {
+ const clearInput = vi.fn();
+ const clearComposer = vi.fn();
+ const f = createRoot((dispose) => ({
+ dispose,
+ state: createInputState({
+ initialInput: { mode: 'channel', value: 'Message' },
+ mentions: () => [],
+ attachmentTracker: createInputAttachmentTracker(),
+ callbacks: { onSend: vi.fn() },
+ clearInput,
+ clearComposer,
+ }),
+ }));
+ try {
+ await expect(f.state.commands.send()).resolves.toBe(true);
+ expect(f.state.view().value).toBe('');
+ expect(clearComposer).toHaveBeenCalledOnce();
+ expect(clearInput).not.toHaveBeenCalled();
+ f.state.reset();
+ expect(clearInput).toHaveBeenCalledOnce();
+ } finally {
+ f.dispose();
+ }
+ });
+
+ it('uses the ordinary clear when no composer-specific clear is provided', async () => {
+ const clearInput = vi.fn();
+ const f = createRoot((dispose) => ({
+ dispose,
+ state: createInputState({
+ initialInput: { mode: 'channel', value: 'Message' },
+ mentions: () => [],
+ attachmentTracker: createInputAttachmentTracker(),
+ callbacks: { onSend: vi.fn() },
+ clearInput,
+ }),
+ }));
+ try {
+ await f.state.commands.send();
+ expect(clearInput).toHaveBeenCalledOnce();
+ } finally {
+ f.dispose();
+ }
+ });
+});
diff --git a/apps/web/src/features/channel/Input/utils/clear-composer.ts b/apps/web/src/features/channel/Input/utils/clear-composer.ts
new file mode 100644
index 0000000000..3635c22d69
--- /dev/null
+++ b/apps/web/src/features/channel/Input/utils/clear-composer.ts
@@ -0,0 +1,20 @@
+import { isIOS } from '@solid-primitives/platform';
+import { type LexicalEditor, SKIP_SCROLL_INTO_VIEW_TAG } from 'lexical';
+
+export function clearComposer(editor: LexicalEditor, clear: () => void) {
+ const root = editor.getRootElement();
+ if (!isIOS || !root || root.ownerDocument.activeElement !== root) {
+ clear();
+ return;
+ }
+
+ // End iOS dictation before clearing so its buffer cannot restore sent text.
+ // Commit the clear before restoring selection, in the same task: leaving
+ // focus unset until rAF lets the keyboard hide and changes the chat viewport.
+ // It also makes the touchend focus-preservation handler skip the send tap.
+ root.blur();
+ editor.update(clear, { discrete: true });
+ root.focus({ preventScroll: true });
+ // Lexical also scrolls the restored caret, separately from DOM focus.
+ editor.update(() => editor.focus(), { tag: SKIP_SCROLL_INTO_VIEW_TAG });
+}
diff --git a/apps/web/src/features/channel/Media/MediaGrid.tsx b/apps/web/src/features/channel/Media/MediaGrid.tsx
index 5d6ac08feb..ed950630d7 100644
--- a/apps/web/src/features/channel/Media/MediaGrid.tsx
+++ b/apps/web/src/features/channel/Media/MediaGrid.tsx
@@ -29,17 +29,21 @@ function MessageImageTile(props: {
return (
<button
type="button"
- class="relative flex rounded-2xl"
+ class="relative flex rounded-2xl border border-edge"
+ style={{
+ width: dimensions() ? `${dimensions()!.width}px` : undefined,
+ 'max-width': '100%',
+ }}
onClick={props.onOpen}
aria-label="Open image viewer"
>
<MediaImage.Image
src={props.item.src}
previewSrc={props.item.previewSrc}
- class="max-h-[80vh] w-full select-none rounded-2xl border border-edge object-contain"
+ class="max-h-[80vh] w-full select-none rounded-2xl object-contain"
width={dimensions()?.width ?? props.item.width ?? undefined}
height={dimensions()?.height ?? props.item.height ?? undefined}
- fallback={<MediaImage.Fallback dims={dimensions()} />}
+ fallback={<MediaImage.Fallback fill={!!dimensions()} />}
style={{
...(dimensions()
? {
diff --git a/apps/web/src/features/channel/Media/MediaImage.tsx b/apps/web/src/features/channel/Media/MediaImage.tsx
index 53fee3dd19..2327da6418 100644
--- a/apps/web/src/features/channel/Media/MediaImage.tsx
+++ b/apps/web/src/features/channel/Media/MediaImage.tsx
@@ -84,6 +84,7 @@ function Image(props: {
fallback?: JSX.Element;
}) {
const [loaded, setLoaded] = createSignal(false);
+ const hasDimensions = () => (props.width ?? 0) > 0 && (props.height ?? 0) > 0;
createEffect(
on(
@@ -97,24 +98,33 @@ function Image(props: {
return (
<>
<Show when={!loaded()}>
- <Show when={props.previewSrc} fallback={props.fallback}>
- {(previewSrc) => (
- <img
- class={cn(props.class)}
- src={previewSrc()}
- alt="preview"
- width={props.width}
- height={props.height}
- style={props.style}
- loading={props.loading}
- onClick={() => props.onOpen?.()}
- />
- )}
- </Show>
+ <div
+ classList={{ absolute: hasDimensions(), 'inset-0': hasDimensions() }}
+ >
+ <Show when={props.previewSrc} fallback={props.fallback}>
+ {(previewSrc) => (
+ <img
+ class={cn(props.class)}
+ src={previewSrc()}
+ alt="preview"
+ width={props.width}
+ height={props.height}
+ style={props.style}
+ loading={props.loading}
+ onClick={() => props.onOpen?.()}
+ />
+ )}
+ </Show>
+ </div>
</Show>
<img
class={cn(props.class)}
- classList={{ invisible: !loaded(), absolute: !loaded() }}
+ // Keep the same responsive image box in flow before and after load.
+ // Swapping a fixed-size placeholder for it changes virtual row heights.
+ classList={{
+ invisible: !loaded(),
+ absolute: !loaded() && !hasDimensions(),
+ }}
src={props.src}
alt="preview"
width={props.width}
diff --git a/apps/web/src/features/channel/docs/sticky-scrolling.md b/apps/web/src/features/channel/docs/sticky-scrolling.md
index 1c7efe3175..21b666ff0c 100644
--- a/apps/web/src/features/channel/docs/sticky-scrolling.md
+++ b/apps/web/src/features/channel/docs/sticky-scrolling.md
@@ -10,7 +10,11 @@ Use the same 1px end tolerance for TanStack, composer/viewport resizing, and sav
positions. Scrolling up beyond rounding tolerance stops following, even a few pixels
from the bottom; returning to the end resumes it.
Acknowledging a send replaces the optimistic message ID, temporarily replacing its
-measured height with an estimate. A loose end threshold treats that intermediate
+measured height with an estimate. The core patch also allows bottom following when
+the last key changes without increasing the row count (`nextCount >= prevCount`),
+so acknowledgement keeps the end anchor through remeasurement. Following still
+requires an existing bottom pin and `followOnAppend`; readers in history retain
+their position. A loose end threshold treats that intermediate
layout as pinned and applies the estimate-to-measurement delta as a backward scroll.
ResizeObserver measurements also run in the current frame: delaying them with
`useAnimationFrameWithResizeObserver` exposes stale row and composer geometry.
@@ -49,8 +53,30 @@ correction, `scrollToFn` synchronously commits the current total to the sizer;
otherwise a growing last row can clamp the scroll against the old DOM extent.
Viewport and inset changes explicitly scroll to the end only if previously pinned.
The offset observer distinguishes instant programmatic scrolls from user scrolling,
-so iOS does not replay deferred momentum adjustments after a navigation has already
-accounted for those measurements. Actual touch/momentum deferral remains in the core.
+so our own corrections do not prolong gesture compensation.
+
+Safari wheel scrolling and iOS touch scrolling use a separate logical offset while a gesture is
+active. Size and prepend corrections counter-shift the rows instead of writing
+`scrollTop`, which interrupts native momentum. Scroll observations and saved
+snapshots include that adjustment. After touch release and 150ms without input or scrolling,
+the adjustment is removed and committed to the DOM offset in the same task.
+The sizer retains its logical height and clips shifted overflow during this period.
+Reaching either scroll boundary releases the shifted origin; explicit message,
+reply, latest, and pinned viewport/inset navigation flush it before computing targets.
+Elastic overscroll must return in bounds before a correction is committed. Touch end
+and cancellation listeners stay on the original event target even if its row unmounts.
+The `@tanstack/virtual-core` patch adds `useIOSScrollDeferral`, enabled by default.
+This list disables it because core deferral updates row positions without applying
+the matching scroll correction, which jumps to unrelated messages during a prepend.
+Channel compensation keeps logical row positions and offsets synchronized instead.
+While compensation is active, remeasuring a row entirely above the viewport also
+preserves the anchor when scrolling upward. The core's default backward-scroll
+exception otherwise lets late-loading images move the message being read. A row
+that spans the viewport's top is not compensated when its lower content grows.
+
+Message images reserve a responsive box from attachment dimensions, with the loading
+placeholder overlaid inside it. Keep the border on the frame: a border on the image
+can change portrait/landscape sizing when intrinsic dimensions become available.
Message IDs also key Solid's rendered components, preserving editors and expanded
threads across pagination. `Key` owns each row's virtual-item accessor; a shared
@@ -62,5 +88,23 @@ with floating mobile insets. Later size changes belong to ResizeObserver.
`targetId` keeps the pending thread mounted for precise navigation to nested replies;
only the list translates that ID into a virtual index. Snapshot
restoration pairs the offset with `takeSnapshot()`.
-Pagination callbacks require user scroll intent; measurement corrections alone
-must not fetch more history.
+Native scroll events extend existing user intent through momentum, rather than
+expiring 300ms after finger release. History requests start within three viewport
+heights (at least 800px) on other browsers and still require user intent there.
+Safari/iOS proactively fill six viewport heights of older history, including after
+initial positioning and explicit navigation, so idle-time prepends establish native
+scroll headroom before the next gesture. Each new oldest key rearms the request if
+the buffer is still short; once full, loading stops. The paginator guards against
+concurrent requests and stops at the actual beginning of history.
+
+This retains the normal top-origin scroller and its bottom-pinning behavior. It
+reduces pagination stops, but a fling can still exhaust the native headroom that
+existed when it started: prepends during momentum remain visually compensated
+until idle or the boundary. This is a bounded preloading strategy, not a guarantee
+of uninterrupted scrolling through arbitrarily many pages.
+
+On iOS, sending clears the composer once and commits that clear before restoring
+focus in the same task. Blur still terminates the dictation session, but refocusing
+must not wait until the next animation frame, which permits the virtual keyboard
+to hide and resize the chat. Only refocus when that editor was focused before the
+clear; an asynchronous completion must not steal focus after the user leaves.
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index edddbbbbe9..069ea0336d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -82,7 +82,10 @@ import { ConnectApp as ConnectAppDecorator } from '../decorator/ConnectApp';
import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';
import { DateMention as DateMentionDecorator } from '../decorator/DateMention';
import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCard';
-import { DocumentMention as DocumentMentionDecorator } from '../decorator/DocumentMention';
+import {
+ DocumentMention as DocumentMentionDecorator,
+ DocumentMentionStatic,
+} from '../decorator/DocumentMention';
import { Equation as EquationDecorator } from '../decorator/Equation';
import { GroupMention as GroupMentionDecorator } from '../decorator/GroupMention';
import { LazyDecorator } from '../decorator/LazyDecorator';
@@ -359,13 +362,6 @@ const UserMention: TypedRenderableEntity<UserMentionNode> = {
),
};
-const MentionPlaceholder = () => (
- <span class="pointer-events-none inline-block align-baseline opacity-60">
- <span class="relative top-[0.125em] size-[1em] inline-block mx-1 bg-current/15 rounded-xs" />
- <span class="inline-block w-12 h-[0.9em] align-baseline bg-current/10 rounded-sm" />
- </span>
-);
-
const DocumentMention: TypedRenderableEntity<DocumentMentionNode> = {
guard: (node: LexicalNode): node is DocumentMentionNode =>
node.__type === 'document-mention',
@@ -384,7 +380,13 @@ const DocumentMention: TypedRenderableEntity<DocumentMentionNode> = {
<span class={getTextClassName(props.node, props.theme)}>
{shouldRenderLazy ? (
<LazyDecorator
- placeholder={<MentionPlaceholder />}
+ placeholder={
+ <DocumentMentionStatic
+ {...componentProps}
+ key={key}
+ theme={props.theme}
+ />
+ }
render={mention}
/>
) : (
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
index 9974ad2896..33ffd0e36d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
@@ -166,6 +166,26 @@ export function calendarMentionTimeLabel(
return startDate ? formatDate(startDate) : undefined;
}
+function MentionAccessories(props: {
+ blockName: BlockName | BlockAlias;
+ blockParams?: Record<string, string>;
+}) {
+ const accessories = () =>
+ mentionsAccessories(props.blockName as BlockName, props.blockParams ?? {});
+ return (
+ <span class="relative text-[0.8em] text-current/50 rounded-xs">
+ <Show when={accessories()}>
+ {(value) => (
+ <>
+ {` ${value().note ?? ''}`}
+ {getMentionsIcon(value().icon)}
+ </>
+ )}
+ </Show>
+ </span>
+ );
+}
+
function InlinePreview(props: {
previewData: ReturnType<typeof useItemPreviewData>;
entity: ItemEntity;
@@ -212,6 +232,10 @@ function InlinePreview(props: {
<Show when={props.documentName} fallback={'Loading...'}>
{(name) => name().replaceAll('\n', ' ').trim()}
</Show>
+ <MentionAccessories
+ blockName={props.blockName}
+ blockParams={props.blockParams}
+ />
</span>
}
collapsed={props.collapsed}
@@ -244,22 +268,10 @@ function InlinePreview(props: {
<Show when={props.documentName} fallback={'Unknown'}>
{(name) => name().replaceAll('\n', ' ').trim()}
</Show>
- <span class="relative text-[0.8em] text-current/50 rounded-md">
- {(() => {
- const accessories = mentionsAccessories(
- props.blockName as BlockName,
- props.blockParams
- );
- if (accessories) {
- return (
- <>
- {` ${accessories.note ?? ''}`}
- {getMentionsIcon(accessories.icon)}
- </>
- );
- }
- })()}
- </span>
+ <MentionAccessories
+ blockName={props.blockName}
+ blockParams={props.blockParams}
+ />
</span>
}
collapsed={props.collapsed}
@@ -325,22 +337,10 @@ function InlinePreview(props: {
</Show>
)}
</Show>
- <span class="relative text-[0.8em] text-current/50 rounded-xs">
- {(() => {
- const accessories = mentionsAccessories(
- props.blockName as BlockName,
- props.blockParams
- );
- if (accessories) {
- return (
- <>
- {` ${accessories.note ?? ''}`}
- {getMentionsIcon(accessories.icon)}
- </>
- );
- }
- })()}
- </span>
+ <MentionAccessories
+ blockName={props.blockName}
+ blockParams={props.blockParams}
+ />
<Show when={props.blockName === 'task'}>
<Suspense>
<InlineTaskProperties
@@ -384,7 +384,7 @@ export function DocumentMention(props: DocumentMentionDecoratorProps) {
<Show
when={props.blockName === 'skill'}
fallback={
- <Suspense>
+ <Suspense fallback={<DocumentMentionStatic {...props} />}>
<DocumentMentionInner {...props} />
</Suspense>
}
@@ -408,7 +408,7 @@ function SkillDocumentMention(props: DocumentMentionDecoratorProps) {
<DocumentMentionStatic {...props} />
</Match>
<Match when={true}>
- <Suspense>
+ <Suspense fallback={<DocumentMentionStatic {...props} />}>
<DocumentMentionInner {...props} />
</Suspense>
</Match>
@@ -434,18 +434,20 @@ function SystemSkillMention(
}
/** Lightweight mention display that skips all backend fetches. Uses only the stored name. */
-function DocumentMentionStatic(props: DocumentMentionDecoratorProps) {
+export function DocumentMentionStatic(props: DocumentMentionDecoratorProps) {
if (props.blockName === 'skill') {
return (
<SkillSlashText
documentId={props.documentId}
name={props.documentName ?? ''}
+ collapsed={props.collapsed}
/>
);
}
return (
<MentionContainer
icon={<EntityIcon targetType={props.blockName as any} size="fill" />}
+ collapsed={props.collapsed}
text={
<span
data-document-mention="true"
@@ -453,7 +455,11 @@ function DocumentMentionStatic(props: DocumentMentionDecoratorProps) {
data-block-name={props.blockName}
data-document-name={props.documentName}
>
- {props.documentName ?? props.documentId}
+ {(props.documentName || 'Loading...').replaceAll('\n', ' ').trim()}
+ <MentionAccessories
+ blockName={verifyBlockName(props.blockName)}
+ blockParams={props.blockParams}
+ />
</span>
}
/>
diff --git a/apps/web/src/lib/core/util/scroll-intent.ts b/apps/web/src/lib/core/util/scroll-intent.ts
index 25be124633..c61388708b 100644
--- a/apps/web/src/lib/core/util/scroll-intent.ts
+++ b/apps/web/src/lib/core/util/scroll-intent.ts
@@ -9,6 +9,8 @@ const TOUCH_DRAG_THRESHOLD_PX = 6;
export type ScrollDirection = 'up' | 'down';
type ScrollIntentTracker = {
+ /** Extend an existing gesture through native momentum scroll events. */
+ observeScroll: () => void;
/**
* Signal that a user-initiated navigation is about to cause a
* programmatic scroll (e.g. hotkey-driven `scrollToId`).
@@ -138,5 +140,15 @@ export function createScrollIntentTracker(
},
};
- return { markUserIntent, isUserInteracting, lastDirection, handlers };
+ const observeScroll = () => {
+ if (isUserInteracting()) activeUntil = Date.now() + INTERACTION_TIMEOUT_MS;
+ };
+
+ return {
+ markUserIntent,
+ isUserInteracting,
+ lastDirection,
+ handlers,
+ observeScroll,
+ };
}
diff --git a/bun.lock b/bun.lock
index f3de10ffd9..86f4ee3676 100644
--- a/bun.lock
+++ b/bun.lock
@@ -411,6 +411,7 @@
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
+ "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
"@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index ee122c773a..2e7b4a7bcb 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -88,6 +88,19 @@ when only slightly above the bottom. Composer and viewport resizing respect the
same boundary. Returning to the bottom resumes following; loading older messages
preserves the reading position.
+On Safari and iOS, open or navigate near the oldest loaded messages and allow the
+history buffer to fill, then flick into older history. Loading should stop once
+roughly six screens are available above the viewport and resume as you approach
+that buffer. Check that pagination retains the visible message, and that latest
+stays pinned when messages arrive, images load, or the composer resizes. Verify
+message/reply navigation, restoration, and the custom scrollbar after pagination.
+Very long flings or slow responses can still exhaust the available scroll range.
+
+Inline document mentions should show their stored title before entering the viewport
+and while preview requests are pending. With a slow preview response, check that a
+long, unchanged title retains its line wrapping as the preview loads; a renamed
+document should update to its fetched title afterward.
+
Message and reply links reveal the target inside its thread. Keyboard message
navigation scrolls only when the selected message is outside the usable viewport.
Returning through split navigation restores the saved message position and expanded
@@ -149,3 +162,11 @@ instead.
New users get `Macro Support x <name>` seeded with a welcome message that @mentions them —
useful as a guaranteed-existing channel in tests.
+
+For mobile send regressions, keep the software keyboard open and send several
+short and multiline messages consecutively. The keyboard should remain open,
+the cleared composer should retain focus, and a pinned chat should remain at the
+bottom through composer resizing and server acknowledgement. Check that restoring
+the caret after send does not pan the page while the keyboard resizes. Repeat with dictation
+and check that sent text does not return. Scroll into history before an incoming
+message or acknowledgement and verify that it does not pull you to latest.
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index d87e2abdba..9dfd23ebc3 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-7ZvwLUFReCp0oAJEtXXYQn7EGnEFsmb3MGJNmKxOKtY=",
- "x86_64-linux": "sha256-N4Tnz5s9gMuoIig8nNQ1h1sjlitPR2+OX4xNjzgpWZU="
+ "aarch64-darwin": "sha256-9ne2SHrYZr7qGUaF+SHQx0lf7cR18uW4YsvmMl55Gpg=",
+ "x86_64-linux": "sha256-X+qDhkwrx+rrX5Khclx1/+uSiaQ3MLS/XTleVW9zxoA="
}
}
diff --git a/package.json b/package.json
index c05f3a40f1..275aa63f7e 100644
--- a/package.json
+++ b/package.json
@@ -41,7 +41,8 @@
"[email protected]": "apps/web/patches/[email protected]",
"@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
- "[email protected]": "apps/web/patches/[email protected]"
+ "[email protected]": "apps/web/patches/[email protected]",
+ "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]"
},
"private": true,
"scripts": {