Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channel): harden channel scroll to location (#6080)
Peter Chinman94430d9dc256
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex 1fd82cc6d3..eab7acd65e 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -252,10 +252,8 @@ export function Channel(props: ChannelProps) {const messageById = () => messageIndex.byId;const keepMountedTargetThreadIndexes = createMemo(() => {const threadId = targetMessageController.activeTargetMessageId();- const hasPendingElementScroll =- targetMessageController.pendingScrollTargetId() !== undefined ||- targetMessageController.pendingTargetReplyId() !== undefined;- if (!threadId || !hasPendingElementScroll) return [];+ if (!threadId || !targetMessageController.hasPendingElementScroll())+ return [];const index = messageIndex.keys.indexOf(threadId);return index === -1 ? [] : [index];@@ -748,10 +746,7 @@ export function Channel(props: ChannelProps) {channelId={props.channelId}keys={() => messageIndex.keys}initialScrollTarget={threadListInitialScrollTarget()}- initialScrollHandledByTargetElement={- targetMessageController.pendingScrollTargetId() !==- undefined- }+ initialScrollHandledByTargetElement={targetMessageController.hasPendingElementScroll()}keepMounted={keepMountedTargetThreadIndexes}fullFrameScrollInsets={threadListScrollInsets}shift={shift}diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsxindex e7fd18cee2..41583530e3 100644--- a/apps/web/src/features/channel/Channel/ThreadList.tsx+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx@@ -1,3 +1,4 @@+import { watchTouchDrag } from '@channel/touch-drag';import { CustomScrollbar } from '@core/component/CustomScrollbar';import {createScrollIntentTracker,@@ -119,6 +120,14 @@ const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;// re-pin window absorbs that late growth so a single action lands fully down.const SCROLL_TO_BOTTOM_SETTLE_MS = 1000;+// How long the kept-mounted target row gets to put the target on screen before+// the virtualizer positions it instead. Longer than the target scroller's+// retry budget for a measured viewport, so the precise element scroll always+// wins when it can run at all. While the viewport is still unmeasured the+// fallback re-arms instead of firing: the scroller is legitimately waiting for+// a box, and an index scroll would be computed against the same zero viewport.+const TARGET_ELEMENT_FALLBACK_MS = 1500;+export const DEFAULT_INITIAL_SCROLL_TARGET: ThreadListScrollTarget = {tag: 'bottom',align: 'end',@@ -184,11 +193,19 @@ export function ThreadList(props: ThreadListProps) {let initialScrollStarted = false;let initialScrollRetried = false;let initialScrollTarget: InitialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;+ let targetElementFallbackTimer: number | undefined;++ const clearTargetElementFallback = () => {+ if (targetElementFallbackTimer === undefined) return;+ window.clearTimeout(targetElementFallbackTimer);+ targetElementFallbackTimer = undefined;+ };const resetInitialScroll = () => {initialScrollStarted = false;initialScrollRetried = false;initialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;+ clearTargetElementFallback();};const resolveTargetIndex = (target: ThreadListScrollTarget): number => {@@ -353,7 +370,7 @@ export function ThreadList(props: ThreadListProps) {if (rafId) cancelAnimationFrame(rafId);resizeObserver?.disconnect();el.removeEventListener('wheel', onWheel);- el.removeEventListener('pointerdown', onPointerDown);+ unwatchDrag();if (cancelPinToBottom === stop) cancelPinToBottom = undefined;};@@ -361,14 +378,10 @@ export function ThreadList(props: ThreadListProps) {if (event.deltaY < 0) stop();}+ el.addEventListener('wheel', onWheel, { passive: true });// A press on a message, reply button, or reaction is not a scroll and must// not cancel pinning. Only a wheel-up or a touch drag is the user scrolling.- function onPointerDown(event: PointerEvent) {- if (event.pointerType === 'touch') stop();- }-- el.addEventListener('wheel', onWheel, { passive: true });- el.addEventListener('pointerdown', onPointerDown, { passive: true });+ const unwatchDrag = watchTouchDrag(el, stop);cancelPinToBottom = stop;const tick = () => {@@ -427,6 +440,10 @@ export function ThreadList(props: ThreadListProps) {scrollToElementInItem: (id, itemElement, targetElement) => {const index = props.keys().indexOf(id);if (index === -1) return false;+ // Nothing has been measured yet (an app launched into a squished+ // viewport). Every offset below would be computed against a zero+ // viewport, so report failure instead of moving to a meaningless place.+ if (handle.viewportSize <= 0) return false;cancelPinToBottom?.();const itemRect = itemElement.getBoundingClientRect();@@ -544,12 +561,71 @@ export function ThreadList(props: ThreadListProps) {if (initialScrollStarted) return;initialScrollStarted = true;if (props.initialScrollHandledByTargetElement) {+ // The kept-mounted target row owns the viewport movement, so nothing is+ // scrolled here and the list is still sitting where it mounted — the top+ // of the loaded window. Arm a fallback in case that element scroll never+ // lands (a row that never mounts, a scroller that gives up on an+ // unmeasured viewport): a channel opened at a message must never be left+ // at the top of its history.+ initialScrollTarget = getInitialScrollTarget();completeInitialScroll(handle);+ armTargetElementFallback(handle, initialScrollTarget);return;}beginInitialTargetScroll(handle, getInitialScrollTarget());}+ /**+ * Positions the initial target through the virtualizer if the target element+ * has not put it on screen by `TARGET_ELEMENT_FALLBACK_MS`. Deliberately+ * coarse: landing on the target's row beats staying at the top.+ */+ function armTargetElementFallback(+ handle: VirtualizerHandle,+ target: InitialScrollTarget+ ) {+ clearTargetElementFallback();+ if (target.tag !== 'id' && target.tag !== 'index') return;+ targetElementFallbackTimer = window.setTimeout(() => {+ targetElementFallbackTimer = undefined;+ if (disposed) return;+ // The target is no longer pending: it either landed or the user took the+ // scroll over (a drag releases it). Either way there is nothing to+ // rescue, and moving the viewport now would be a yank.+ if (!props.initialScrollHandledByTargetElement) return;+ if (scrollIntent.isUserInteracting()) return;+ // No viewport to position against yet. The element scroller is still+ // waiting for one (it holds the target for longer than this), and an+ // index scroll here would land against the same zero viewport — so wait+ // for a box rather than move somewhere meaningless.+ if (handle.viewportSize <= 0) {+ armTargetElementFallback(handle, target);+ return;+ }+ if (resolveTargetIndex(target) < 0) {+ // The target never made it into the loaded window. No scroll can reach it, and staying where+ // the list mounted means the top of history, so show the latest+ // instead — the same answer the missing-message path gives.+ console.debug(+ 'ThreadList: target never loaded, falling back to latest',+ {+ target,+ scrollOffset: handle.scrollOffset,+ }+ );+ pinToBottom(handle);+ return;+ }+ if (isScrollPositionCorrect(handle, target)) return;+ console.debug('ThreadList: target element never landed, falling back', {+ target,+ scrollOffset: handle.scrollOffset,+ viewportSize: handle.viewportSize,+ });+ scrollToTarget(handle, target);+ }, TARGET_ELEMENT_FALLBACK_MS);+ }+const handleScrollEnd = () => {if (didInitialScroll()) return;@@ -679,6 +755,7 @@ export function ThreadList(props: ThreadListProps) {onCleanup(() => {disposed = true;cancelPinToBottom?.();+ clearTargetElementFallback();});return (diff --git a/apps/web/src/features/channel/Channel/create-target-message-controller.ts b/apps/web/src/features/channel/Channel/create-target-message-controller.tsindex 5c6419eeea..f3dc8bd5e6 100644--- a/apps/web/src/features/channel/Channel/create-target-message-controller.ts+++ b/apps/web/src/features/channel/Channel/create-target-message-controller.ts@@ -66,15 +66,22 @@ export function createTargetMessageController(flashTimeout = undefined;};+ /**+ * Whether a target element still owes the viewport a scroll — the root row,+ * a nested reply, or both. A nested target acknowledges its outer row early+ * (see the effect below) so the reply's own scroll can begin, so the root's+ * pending id alone does not answer this.+ */+ const hasPendingElementScroll = () =>+ targetMessageData['pendingScrollTargetId'] !== undefined ||+ targetMessageData['pendingTargetReplyId'] !== undefined;+const syncFlash = () => {cancelFlash();const activeTargetMessageId = targetMessageData['activeTargetMessageId'];- const hasPendingScroll =- targetMessageData['pendingScrollTargetId'] !== undefined ||- targetMessageData['pendingTargetReplyId'] !== undefined;- if (!activeTargetMessageId || hasPendingScroll) return;+ if (!activeTargetMessageId || hasPendingElementScroll()) return;flashTimeout = setTimeout(() => {flashTimeout = undefined;@@ -202,6 +209,7 @@ export function createTargetMessageController(loadAroundMessageId: () => targetMessageData['loadAroundMessageId'],pendingScrollTargetId: () => targetMessageData['pendingScrollTargetId'],pendingTargetReplyId: () => targetMessageData['pendingTargetReplyId'],+ hasPendingElementScroll,goToMessage,completePendingScroll,diff --git a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.tsindex 60b52cd223..a243b18491 100644--- a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts+++ b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts@@ -128,6 +128,14 @@ describe('createTargetMessageController', () => {expect(scrollToId).not.toHaveBeenCalled();expect(controller!.pendingScrollTargetId()).toBeUndefined();expect(controller!.pendingTargetReplyId()).toBe('reply-4');+ // The outer row is acknowledged early so the reply can scroll itself, but+ // an element still owes the viewport a scroll. Anything gated on that —+ // the kept-mounted row, the ThreadList fallback — must stay armed, or a+ // reply that never lands leaves the channel parked where it mounted.+ expect(controller!.hasPendingElementScroll()).toBe(true);++ controller!.completePendingReplyScroll('message-1', 'reply-4');+ expect(controller!.hasPendingElementScroll()).toBe(false);dispose();});diff --git a/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts b/apps/web/src/features/channel/Thread/create-target-reply-scroller.tsindex d893a6a7e5..3ba077f608 100644--- a/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts+++ b/apps/web/src/features/channel/Thread/create-target-reply-scroller.ts@@ -1,9 +1,18 @@+import { watchTouchDrag } from '@channel/touch-drag';+const CHANNEL_SCROLL_SELECTOR = '[data-channel-scroll]';const CHANNEL_THREAD_ROW_SELECTOR = '[data-channel-thread-row]';const TARGET_SCROLL_QUIET_MS = 200;const TARGET_SCROLL_TIMEOUT_MS = 1000;const TARGET_MEASUREMENT_TIMEOUT_MS = 250;const TARGET_VISIBILITY_TOLERANCE_PX = 1;+/**+ * How long to keep waiting for a scroll surface that has no box yet — an app+ * launched into a squished viewport, or a panel mounted before layout. The+ * target is only released after this, because releasing it early strands the+ * channel wherever it mounted.+ */+const TARGET_UNMEASURED_TIMEOUT_MS = 5000;const SCROLL_KEYS = new Set(['ArrowUp',@@ -56,6 +65,11 @@ export function createTargetReplyScroller(options: {let measurementMicrotaskQueued = false;let hasPositioned = false;const startedAt = performance.now();+ // When the scroll surface first had a box to position against. The+ // give-up deadline runs from here, not from `startedAt`, so time spent+ // waiting on an unmeasured viewport never burns the retry budget.+ let measuredSince: number | undefined;+ let unwatchTouchDrag: (() => void) | undefined;const getThreadRow = () =>options.getTarget(index)@@ -85,8 +99,8 @@ export function createTargetReplyScroller(options: {resizeObserver?.disconnect();positionObserver?.disconnect();scrollElement.removeEventListener('wheel', handleUserScroll);- scrollElement.removeEventListener('pointerdown', handlePointerDown);scrollElement.removeEventListener('keydown', handleKeyDown);+ unwatchTouchDrag?.();if (cancelCurrentScroll === abort) cancelCurrentScroll = undefined;};@@ -103,12 +117,25 @@ export function createTargetReplyScroller(options: {onSettled();};+ /**+ * Whether the scroll surface has a box to position against. An app that+ * launched into a squished viewport reports 0×0 for everything, and every+ * comparison against a zero rect passes trivially.+ */+ const isScrollSurfaceMeasured = () =>+ scrollElement.isConnected &&+ scrollElement.getBoundingClientRect().height > 0;+const isTargetPositioned = () => {const target = options.getTarget(index);if (!target?.isConnected || !scrollElement.isConnected) return false;const targetRect = target.getBoundingClientRect();const scrollRect = scrollElement.getBoundingClientRect();+ // Nothing is laid out yet, so the target cannot be judged as on screen.+ // Reporting it as positioned here releases the target and leaves the+ // channel parked wherever it mounted — the top of the loaded window.+ if (scrollRect.height <= 0 || targetRect.height <= 0) return false;if (targetRect.height <= scrollRect.height) {return (targetRect.top >= scrollRect.top - TARGET_VISIBILITY_TOLERANCE_PX &&@@ -132,7 +159,19 @@ export function createTargetReplyScroller(options: {return;}- if (performance.now() - startedAt < TARGET_SCROLL_TIMEOUT_MS) {+ if (!isScrollSurfaceMeasured()) {+ // Keep waiting (bounded) rather than releasing a target that was+ // never given a viewport to land in.+ if (performance.now() - startedAt < TARGET_UNMEASURED_TIMEOUT_MS) {+ scheduleVerification();+ return;+ }+ complete();+ return;+ }++ measuredSince ??= performance.now();+ if (performance.now() - measuredSince < TARGET_SCROLL_TIMEOUT_MS) {schedulePosition();return;}@@ -207,10 +246,6 @@ export function createTargetReplyScroller(options: {complete();}- function handlePointerDown(event: PointerEvent) {- if (event.pointerType === 'touch') complete();- }-function handleKeyDown(event: KeyboardEvent) {if (SCROLL_KEYS.has(event.key)) complete();}@@ -218,10 +253,11 @@ export function createTargetReplyScroller(options: {scrollElement.addEventListener('wheel', handleUserScroll, {passive: true,});- scrollElement.addEventListener('pointerdown', handlePointerDown, {- passive: true,- });scrollElement.addEventListener('keydown', handleKeyDown);+ // Only a drag hands the scroll back to the user. A tap — including the one+ // that lands while the channel is still opening — must not release the+ // target, or the navigation is abandoned before it ever moved.+ unwatchTouchDrag = watchTouchDrag(scrollElement, complete);if (threadRow) resizeObserver?.observe(threadRow);if (virtualItem) {positionObserver?.observe(virtualItem, {diff --git a/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts b/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.tsindex 2ecc9eaf42..f60bfa5042 100644--- a/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts+++ b/apps/web/src/features/channel/Thread/tests/create-target-reply-scroller.test.ts@@ -76,8 +76,9 @@ describe('createTargetReplyScroller', () => {document.body.append(scrollElement);let targetRect = rect(1000, 1050);- vi.spyOn(scrollElement, 'getBoundingClientRect').mockReturnValue(- rect(0, 600)+ let scrollRect = rect(0, 600);+ vi.spyOn(scrollElement, 'getBoundingClientRect').mockImplementation(+ () => scrollRect);vi.spyOn(target, 'getBoundingClientRect').mockImplementation(() => targetRect@@ -96,9 +97,21 @@ describe('createTargetReplyScroller', () => {setTargetRect: (next: DOMRect) => {targetRect = next;},+ setScrollRect: (next: DOMRect) => {+ scrollRect = next;+ },};};+ /** A touch event carrying one contact point, as the scroll surface sees it. */+ const touchEvent = (type: string, x: number, y: number) => {+ const event = new Event(type, { bubbles: true });+ Object.defineProperty(event, 'touches', {+ value: [{ clientX: x, clientY: y }],+ });+ return event;+ };+it('waits for the expanded thread row measurement before positioning', async () => {const fixture = createFixture();const onSettled = vi.fn();@@ -222,6 +235,60 @@ describe('createTargetReplyScroller', () => {expect(ResizeObserverMock.instances[0].disconnect).toHaveBeenCalledOnce();});+ it('waits for a measured scroll surface before releasing the target', async () => {+ const fixture = createFixture();+ // The app opened into a squished viewport: nothing has a box yet, so every+ // "is the target on screen?" comparison passes against 0x0 rects.+ fixture.setScrollRect(rect(0, 0));+ fixture.setTargetRect(rect(0, 0));+ fixture.target.scrollIntoView = vi.fn();++ const onSettled = vi.fn();+ const scroller = createTargetReplyScroller({+ getTarget: () => fixture.target,+ });++ expect(scroller.scrollToIndex(0, onSettled)).toBe(true);+ ResizeObserverMock.instances[0].trigger();+ await Promise.resolve();+ flushAnimationFrame();+ flushAnimationFrame();++ vi.advanceTimersByTime(2000);+ expect(onSettled).not.toHaveBeenCalled();++ // Layout settles and the target lands.+ fixture.setScrollRect(rect(0, 600));+ fixture.setTargetRect(rect(275, 325));+ vi.advanceTimersByTime(200);++ expect(onSettled).toHaveBeenCalledOnce();+ });++ it('keeps the target through a tap and releases it on a drag', () => {+ const fixture = createFixture();+ const onSettled = vi.fn();+ const scroller = createTargetReplyScroller({+ getTarget: () => fixture.target,+ });++ expect(scroller.scrollToIndex(0, onSettled)).toBe(true);+ flushAnimationFrame();++ // A tap — pressing a message, or the stray touch while the channel opens.+ fixture.scrollElement.dispatchEvent(touchEvent('touchstart', 100, 100));+ fixture.scrollElement.dispatchEvent(touchEvent('touchmove', 102, 103));+ fixture.scrollElement.dispatchEvent(touchEvent('touchend', 102, 103));+ expect(onSettled).not.toHaveBeenCalled();++ // A drag hands the scroll back to the user.+ fixture.scrollElement.dispatchEvent(touchEvent('touchstart', 100, 100));+ fixture.scrollElement.dispatchEvent(touchEvent('touchmove', 100, 140));++ expect(onSettled).toHaveBeenCalledOnce();+ expect(ResizeObserverMock.instances[0].disconnect).toHaveBeenCalledOnce();+ });+it('releases navigation when the user starts scrolling', () => {const fixture = createFixture();const onSettled = vi.fn();diff --git a/apps/web/src/features/channel/touch-drag.ts b/apps/web/src/features/channel/touch-drag.tsnew file mode 100644index 0000000000..7953052fab--- /dev/null+++ b/apps/web/src/features/channel/touch-drag.ts@@ -0,0 +1,56 @@+/**+ * How far a touch must travel before it counts as the user taking over the+ * scroll. Below it the gesture is a tap — opening a message, pressing a+ * reaction, or the stray touch that lands while a channel is still opening —+ * and must never cancel an in-flight programmatic scroll.+ */+const TOUCH_DRAG_THRESHOLD_PX = 8;++/**+ * Calls `onDrag` the first time a touch on `element` moves past the drag+ * threshold; taps never fire it. Returns a disposer.+ *+ * Touch events (not pointer events) because iOS fires `pointercancel` — and+ * stops sending `pointermove` — the moment the browser takes over scrolling,+ * which is exactly the gesture that has to be detected.+ */+export function watchTouchDrag(+ element: HTMLElement,+ onDrag: () => void+): () => void {+ let start: { x: number; y: number } | undefined;++ const handleTouchStart = (event: TouchEvent) => {+ const touch = event.touches[0];+ start = touch ? { x: touch.clientX, y: touch.clientY } : undefined;+ };++ const handleTouchMove = (event: TouchEvent) => {+ const touch = event.touches[0];+ if (!start || !touch) return;+ if (+ Math.abs(touch.clientX - start.x) <= TOUCH_DRAG_THRESHOLD_PX &&+ Math.abs(touch.clientY - start.y) <= TOUCH_DRAG_THRESHOLD_PX+ ) {+ return;+ }+ start = undefined;+ onDrag();+ };++ const handleTouchEnd = () => {+ start = undefined;+ };++ element.addEventListener('touchstart', handleTouchStart, { passive: true });+ element.addEventListener('touchmove', handleTouchMove, { passive: true });+ element.addEventListener('touchend', handleTouchEnd, { passive: true });+ element.addEventListener('touchcancel', handleTouchEnd, { passive: true });++ return () => {+ element.removeEventListener('touchstart', handleTouchStart);+ element.removeEventListener('touchmove', handleTouchMove);+ element.removeEventListener('touchend', handleTouchEnd);+ element.removeEventListener('touchcancel', handleTouchEnd);+ };+}