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.

28.3 KB
Raw Blame
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import {
  createScrollIntentTracker,
  type ScrollDirection,
} from '@core/util/scroll-intent';
import { MessageReadVisibilityProvider } from '@notifications/components/MessageReadVisibility';
import { Key } from '@solid-primitives/keyed';
import { isIOS, isSafari } from '@solid-primitives/platform';
import {
  createVirtualizer,
  defaultRangeExtractor,
  elementScroll,
  measureElement,
  observeElementOffset,
  observeElementRect,
  type Range,
  type ScrollToOptions,
  type VirtualItem,
  type VirtualizerOptions,
} from '@tanstack/solid-virtual';
import {
  type Accessor,
  createEffect,
  createMemo,
  createSignal,
  type JSX,
  on,
  onCleanup,
  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']>;
type ScrollToFn = NonNullable<
  VirtualizerOptions<HTMLDivElement, HTMLDivElement>['scrollToFn']
>;

const BASE_ITEM_SIZE = 96;
const OVERSCAN = 6;

export type ThreadListInitialPosition =
  | { type: 'latest' }
  | { type: 'element'; id: string }
  | { type: 'restore'; snapshot: ThreadListScrollSnapshot };

export type ThreadListNavigation = {
  /** Publish geometry after registered destinations finish mounting/unmounting. */
  requestLayoutUpdate: () => void;
  scrollToLatest: (behavior?: ScrollBehavior) => boolean;
  scrollToMessage: (
    id: string,
    options?: { align?: ScrollAlignment; userIntent?: ScrollDirection }
  ) => boolean;
  /** Center a mounted message or reply inside the unobscured viewport. */
  scrollToElement: (element: HTMLElement) => boolean;
};

export type ThreadListScrollState = {
  didInitialScroll: boolean;
  isNearBottom: boolean;
  isScrollingDown: boolean;
  distanceFromTop: number;
  distanceFromBottom: number;
  viewportSize: number;
  /** Intersecting rows, excluding overscan and floating header/composer insets. */
  visibleRange?: { first: string; last: string };
};

export type ThreadListScrollSnapshot = {
  scrollOffset: number;
  measurements?: VirtualItem[];
  isNearBottom: boolean;
};

type ScrollInsets = {
  /** Space reserved before the first message (e.g. status bar + floating header). */
  start: number;
  /** Space reserved after the last message (e.g. floating input + dock). */
  end: number;
};

type ThreadListProps = {
  keys: Accessor<string[]>;
  children: (item: { id: string }) => JSX.Element;
  initialPosition?: ThreadListInitialPosition;
  onScrollNearTop?: () => void;
  onScrollNearBottom?: () => void;
  /** Physical gestures and keyboard navigation supersede pending page jumps. */
  onUserNavigation?: () => void;
  /** Called after initial layout; its optional cleanup releases the handle. */
  onReady?: (navigation: ThreadListNavigation) => void | (() => void);
  /** State and snapshot describe the same committed position. */
  onScroll?: (
    state: ThreadListScrollState,
    snapshot: ThreadListScrollSnapshot | undefined
  ) => void;
  /** Follow live messages only when the loaded window includes the latest page. */
  followOnAppend?: boolean;
  /** Position messages when they do not fill the viewport. Defaults to end. */
  shortListAlign?: 'start' | 'end';
  /** Keep this thread mounted while its message or reply is being positioned. */
  targetId?: string;
  /**
   * For full-frame insets where the scroll surface spans the whole screen and content
   * scrolls behind the floating chrome. Included in virtual measurements and navigation.
   */
  insets?: ScrollInsets;
};

const NEAR_TOP_THRESHOLD = 800;
const HISTORY_BUFFER_VIEWPORTS = 3;
const WEBKIT_HISTORY_BUFFER_VIEWPORTS = 6;
// How far above the reading position WebKit keeps rows measured: about as far
// as one long momentum fling travels.
const WEBKIT_MEASURED_HISTORY_VIEWPORTS = 12;
const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;

const clamp = (value: number, min: number, max: number) =>
  Math.max(min, Math.min(value, max));

const NO_SCROLL_INSETS: ScrollInsets = { start: 0, end: 0 };

export function ThreadList(props: ThreadListProps) {
  // Publish the ref on mount: Solid template nodes can still belong to an
  // inert document (no defaultView) when the ref callback runs.
  let scrollRef: HTMLDivElement | undefined;
  let contentRef: HTMLDivElement | undefined;
  const [scrollEl, setScrollEl] = createSignal<HTMLDivElement>();
  const [viewportSize, setViewportSize] = createSignal(0);
  const insets = () => props.insets ?? NO_SCROLL_INSETS;
  // Capture each key array so the previous virtualizer options still describe
  // the previous page while TanStack resolves its prepend anchor.
  const getItemKey = createMemo(() => {
    const keys = [...props.keys()];
    return (index: number) => keys[index];
  });
  const scrollIntent = createScrollIntentTracker(() => {
    lifecycle.send('user-scroll');
    props.onUserNavigation?.();
  });
  const initialPosition = props.initialPosition ?? { type: 'latest' };
  const snapshot =
    initialPosition.type === 'restore' ? initialPosition.snapshot : undefined;
  // Seed the first range with cached sizes too: tall saved rows can put the
  // actual end far beyond the default estimate, before any DOM is measured.
  const initialSizes = new Map(
    snapshot?.measurements?.map(({ key, size }) => [key, size])
  );
  let programmaticOffset: number | undefined;
  // A scroll event dispatched while our own scrollTo runs is ours as well.
  // Native scrolling activates gesture compensation, so it must not be mistaken.
  let writingScroll = false;
  let stateQueued = false;
  let nearTopKey: string | undefined;
  let nearBottomFired = false;
  let previousScrollOffset = snapshot?.scrollOffset ?? 0;
  let explicitScrollDownDistance = 0;
  let releaseNavigation: void | (() => void);
  // Rows that mounted or moved in the current tick, measured together.
  const pendingRows = new Set<HTMLDivElement>();
  // Heights read for the batch being applied; see flushRowMeasurements.
  const batchHeights = new Map<Element, number>();
  let applyingBatch = false;
  let deferredScroll: Parameters<ScrollToFn> | undefined;
  // Rows shift by the gesture adjustment. The sizer's end moves with them, so
  // native scrolling stops at the latest row instead of blank space past it.
  let gestureAdjustment = 0;
  const sizerHeight = (total: number) =>
    Math.max(viewportSize(), total - gestureAdjustment);
  const scrollCompensation =
    isSafari || isIOS
      ? createScrollCompensation({
          getElement: () => scrollEl(),
          setAdjustment: (adjustment) => {
            gestureAdjustment = adjustment;
            if (!contentRef) return;
            contentRef.style.setProperty(
              '--channel-scroll-adjustment',
              `${adjustment}px`
            );
          },
          writeOffset: (offset) => {
            const element = scrollEl();
            if (!element) return;
            // Restore the logical extent before the offset replaces the adjustment.
            if (contentRef) {
              contentRef.style.height = `${sizerHeight(virtualizer.getTotalSize())}px`;
            }
            writingScroll = true;
            try {
              element.scrollTo({ top: offset });
            } finally {
              writingScroll = false;
            }
            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
  // that do not produce a browser scroll event.
  const scheduleScrollState = () => {
    if (stateQueued) return;
    stateQueued = true;
    queueMicrotask(() => {
      stateQueued = false;
      if (!lifecycle.isDisposed()) emitScrollState();
    });
  };

  const lifecycle = createScrollLifecycle({
    hasLayout: () => viewportSize() > 0 && props.keys().length > 0,
    waitForElement: initialPosition.type === 'element',
    positionInitial: () => {
      // Restored history has already been positioned by initialOffset. Replaying
      // its offset here would undo corrections for rows measured during mount.
      if (!snapshot || snapshot.isNearBottom) {
        virtualizer.scrollToEnd();
      }
    },
    positionFallback: () => {
      if (
        initialPosition.type === 'element' &&
        !scrollToMessage(initialPosition.id)
      ) {
        virtualizer.scrollToEnd();
      }
    },
    onReady: () => {
      releaseNavigation = props.onReady?.(navigation);
    },
  });

  // Assigned once the virtualizer exists; its first range is computed inside
  // the constructor, before the binding below is initialized.
  let measured: { instance: typeof virtualizer } | undefined;
  // The core reuses extracted indexes while the visible range holds still,
  // so a pass that stopped at its unmeasured-row cap would not resume once
  // those rows are measured. Measurements past such a pass start the next.
  const [historyPass, setHistoryPass] = createSignal(0);
  let resumeHistoryAfter: number | undefined;

  // A WebKit gesture cannot move the native top boundary, so rows above that
  // are taller than their estimate grow only the visual adjustment, and a
  // fling stops at scrollTop 0 with history still above it. Keep the rows a
  // fling can reach mounted and measured before it starts, a few unmeasured
  // rows per pass, so the native extent above them is the real one.
  function withMeasuredHistory(range: Range): number[] {
    const indexes = defaultRangeExtractor(range);
    const instance = measured?.instance;
    const first = indexes[0];
    const visibleStart = instance?.measurementsCache[range.startIndex]?.start;
    if (
      !scrollCompensation ||
      !instance ||
      first === undefined ||
      visibleStart === undefined
    )
      return indexes;
    const buffer = viewportSize() * WEBKIT_MEASURED_HISTORY_VIEWPORTS;
    const added: number[] = [];
    let unmeasured = 0;
    let top = instance.measurementsCache[first]?.start ?? visibleStart;
    for (let index = first - 1; index >= 0; index--) {
      const item = instance.measurementsCache[index];
      if (!item || visibleStart - top >= buffer || unmeasured >= OVERSCAN)
        break;
      added.unshift(index);
      top = item.start;
      if (!instance.itemSizeCache.has(item.key)) unmeasured += 1;
    }
    resumeHistoryAfter =
      unmeasured >= OVERSCAN ? instance.itemSizeCache.size : undefined;
    return added.length === 0 ? indexes : [...added, ...indexes];
  }

  const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
    // Do not consume initialOffset against an empty query result. Enabling
    // with the first page lets TanStack render the latest rows immediately.
    get enabled() {
      return props.keys().length > 0;
    },
    get count() {
      return props.keys().length;
    },
    getScrollElement: () => scrollEl() ?? null,
    get getItemKey() {
      return getItemKey();
    },
    estimateSize: () => BASE_ITEM_SIZE,
    overscan: OVERSCAN,
    // A restored snapshot or a newly remounted message can have a different
    // height. The default sync path returns cached sizes, exposing the old
    // layout until ResizeObserver fires. Read mounted rows before first paint.
    measureElement: (element, entry, instance) =>
      entry
        ? measureElement(element, entry, instance)
        : (batchHeights.get(element) ?? element.offsetHeight),
    // Apply row and composer measurements before paint. Deferring them to the
    // 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);
    },
    // Use the same end tolerance for append, resize, navigation, and snapshots.
    // A loose tolerance also mistakes optimistic row estimates for a pin.
    scrollEndThreshold: NEAR_BOTTOM_THRESHOLD,
    // The core reads scrollHeight for the end offset, forcing a layout whenever
    // rows just mounted (the initial scroll to latest, each reconcile frame,
    // every end check). The scroller holds only the sizer, max(viewport,
    // total), and writeScroll commits that before scrolling, so the
    // virtualizer's own sizes give the same extent without a layout.
    maxScrollOffset: (instance) =>
      Math.max(0, instance.getTotalSize() - (instance.scrollRect?.height ?? 0)),
    get paddingStart() {
      return insets().start;
    },
    get paddingEnd() {
      return insets().end;
    },
    get scrollPaddingStart() {
      return insets().start;
    },
    get scrollPaddingEnd() {
      return insets().end;
    },
    initialMeasurementsCache: snapshot?.measurements,
    initialOffset: () =>
      snapshot && !snapshot.isNearBottom
        ? snapshot.scrollOffset
        : initialPosition.type === 'latest' || (snapshot?.isNearBottom ?? false)
          ? props
              .keys()
              .reduce(
                (total, key) =>
                  total + (initialSizes.get(key) ?? BASE_ITEM_SIZE),
                insets().start + insets().end
              )
          : 0,
    get rangeExtractor() {
      historyPass();
      const index =
        props.targetId === undefined
          ? -1
          : props.keys().indexOf(props.targetId);
      return (range: Range) => {
        const indexes = withMeasuredHistory(range);
        if (index < 0 || index >= range.count || indexes.includes(index))
          return indexes;
        return [...indexes, index].sort((a, b) => a - b);
      };
    },
    scrollToFn: (offset, options, instance) => {
      // Each correction carries the absolute target, so a batch only needs its
      // last one. Writing every row's correction forces a layout per row.
      if (applyingBatch) {
        deferredScroll = [offset, options, instance];
        return;
      }
      writeScroll(offset, options, instance);
    },
    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 reportOffset = (offset: number, isScrolling: boolean) => {
        // An instant navigation/correction must not extend gesture compensation.
        const isOwnScroll =
          writingScroll ||
          (programmaticOffset !== undefined &&
            Math.abs(offset - programmaticOffset) < 1.5);
        programmaticOffset = undefined;
        if (isScrolling && !isOwnScroll) scrollIntent.observeScroll();
        const logicalOffset =
          scrollCompensation?.observeOffset(
            offset,
            isScrolling && !isOwnScroll
          ) ?? offset;
        callback(logicalOffset, isScrolling && !isOwnScroll);
      };
      const cleanup = observeElementOffset(instance, reportOffset);
      // A short list clamps the initial end scroll to zero without emitting a
      // scroll event. Read it back after the initial write so the virtual range
      // includes the first rows, before paint.
      let disposed = false;
      queueMicrotask(() => {
        if (!disposed && element?.isConnected)
          reportOffset(element.scrollTop, false);
      });
      return () => {
        disposed = true;
        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;
        const wasAtEnd =
          instance.getTotalSize() -
            previousHeight -
            (instance.scrollOffset ?? 0) <=
          NEAR_BOTTOM_THRESHOLD;
        callback(rect);
        setViewportSize(rect.height);
        scheduleScrollState();
        // 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: (instance) => {
      scheduleScrollState();
      if (
        resumeHistoryAfter !== undefined &&
        instance.itemSizeCache.size > resumeHistoryAfter
      ) {
        resumeHistoryAfter = undefined;
        queueMicrotask(() => setHistoryPass((pass) => pass + 1));
      }
    },
  });

  measured = { instance: virtualizer };

  function writeScroll(...[offset, options, instance]: Parameters<ScrollToFn>) {
    // 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.
    const deferred =
      lifecycle.isReady() &&
      !!scrollCompensation?.defer(offset + (options.adjustments ?? 0));
    // Size corrections happen before the Solid adapter publishes its new
    // total. Commit the sizer first so the browser cannot clamp the requested
    // scroll to the old range (especially with padding below a growing row).
    if (contentRef) {
      contentRef.style.height = `${sizerHeight(instance.getTotalSize())}px`;
    }
    if (deferred) return;
    writingScroll = true;
    try {
      elementScroll(offset, options, instance);
    } finally {
      writingScroll = false;
    }
    programmaticOffset =
      options.behavior === 'smooth'
        ? undefined
        : instance.scrollElement?.scrollTop;
  }

  // Rows mount together, so measure them together: read every height from
  // one layout, then apply the resizes and write the scroll once. Measuring
  // row by row interleaves reads with sizer and scroll writes, which forces a
  // full layout of the list per row.
  function flushRowMeasurements() {
    const rows = [...pendingRows].filter((row) => row.isConnected);
    pendingRows.clear();
    for (const row of rows) batchHeights.set(row, row.offsetHeight);
    applyingBatch = true;
    try {
      for (const row of rows) virtualizer.measureElement(row);
    } finally {
      applyingBatch = false;
      batchHeights.clear();
    }
    const scroll = deferredScroll;
    deferredScroll = undefined;
    if (scroll) writeScroll(...scroll);
  }

  // Markdown fills a row in child effects. Measuring the empty shell can
  // shrink the sizer and clamp scrollTop before paint, so wait a microtask.
  const queueRowMeasurement = (row: HTMLDivElement) => {
    pendingRows.add(row);
    if (pendingRows.size === 1) queueMicrotask(flushRowMeasurements);
  };

  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 = () =>
    props.shortListAlign === 'start'
      ? 0
      : Math.max(0, viewportSize() - virtualizer.getTotalSize());
  // The adapter mutates its store by index. Snapshot those values and let Key
  // own each row's accessor by message ID, including while a row is removed.
  // A lookup into a shared map can disappear before queued row effects run.
  const virtualItems = createMemo(() =>
    virtualizer.getVirtualItems().map((item) => ({ ...item }))
  );

  const scrollToMessage = (
    id: string,
    align: ScrollAlignment = 'center'
  ): boolean => {
    const index = props.keys().indexOf(id);
    if (index < 0) return false;
    scrollCompensation?.finish();
    virtualizer.scrollToIndex(index, { align });
    scheduleScrollState();
    return true;
  };

  const canNavigate = () =>
    lifecycle.isReady() &&
    scrollEl()?.isConnected &&
    (scrollEl()?.clientHeight ?? 0) > 0;

  const navigation: ThreadListNavigation = {
    requestLayoutUpdate: scheduleScrollState,
    scrollToLatest: (behavior) => {
      if (!canNavigate() || !props.keys().length) return false;
      lifecycle.send('navigate');
      scrollCompensation?.finish();
      virtualizer.scrollToEnd({ behavior });
      scheduleScrollState();
      return true;
    },
    scrollToMessage: (id, options) => {
      if (!canNavigate() || !props.keys().includes(id)) return false;
      lifecycle.send('navigate');
      if (options?.userIntent) scrollIntent.markUserIntent(options.userIntent);
      return scrollToMessage(id, options?.align);
    },
    scrollToElement: (targetElement) => {
      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();
      const scrollRect = el.getBoundingClientRect();
      const { start, end } = insets();
      const targetCenter =
        el.scrollTop + targetRect.top - scrollRect.top + targetRect.height / 2;
      virtualizer.scrollToOffset(
        clamp(
          targetCenter - (start + (el.clientHeight - start - end) / 2),
          0,
          Math.max(0, el.scrollHeight - el.clientHeight)
        )
      );
      scheduleScrollState();
      return true;
    },
  };

  function emitScrollState() {
    const el = scrollEl();
    if (!el) return;
    // This microtask runs after synchronous row measurements, before paint.
    lifecycle.send('layout');
    const scrollTop = el.scrollTop;
    const distanceFromTop = logicalScrollOffset(scrollTop);
    // The virtualizer's cached offset can trail scrollTop: this publish may run
    // in the microtask before its own scroll listener records the new position.
    // The sizer excludes the gesture adjustment, so compare native positions.
    const distanceFromBottom = Math.max(
      el.scrollHeight - el.clientHeight - scrollTop,
      0
    );
    // 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;
    if (delta !== 0) {
      explicitScrollDownDistance =
        hasUserIntent && delta > 0 && scrollIntent.lastDirection() === 'down'
          ? explicitScrollDownDistance + delta
          : 0;
    }
    previousScrollOffset = distanceFromTop;
    const visibleRows = virtualizer
      .getVirtualItems()
      .filter(
        (item) =>
          item.end + shortListOffset() > distanceFromTop + insets().start &&
          item.start + shortListOffset() <
            distanceFromTop + el.clientHeight - insets().end
      );
    const firstVisible = visibleRows.at(0);
    const lastVisible = visibleRows.at(-1);
    const state: ThreadListScrollState = {
      didInitialScroll: lifecycle.isReady(),
      isNearBottom: nearBottom,
      isScrollingDown:
        explicitScrollDownDistance >= EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE,
      distanceFromTop,
      distanceFromBottom,
      viewportSize: el.clientHeight,
      visibleRange:
        firstVisible && lastVisible
          ? { first: String(firstVisible.key), last: String(lastVisible.key) }
          : undefined,
    };
    // Capture both before invoking callers, which may synchronously navigate.
    const snapshot = state.didInitialScroll
      ? {
          scrollOffset: distanceFromTop,
          measurements: virtualizer.takeSnapshot(),
          isNearBottom: nearBottom,
        }
      : undefined;
    props.onScroll?.(state, snapshot);
    if (!lifecycle.isReady()) return;
    if (
      nearTop &&
      (hasUserIntent || scrollCompensation) &&
      nearTopKey !== props.keys()[0]
    ) {
      nearTopKey = props.keys()[0];
      props.onScrollNearTop?.();
    } else if (!nearTop) nearTopKey = undefined;
    if (nearBottom && !nearBottomFired && hasUserIntent) {
      nearBottomFired = true;
      props.onScrollNearBottom?.();
    } else if (!nearBottom) nearBottomFired = false;
  }

  // Floating chrome can resize without resizing the scroll viewport. Compare
  // against the old content extent before following the new inset to latest.
  createEffect(
    on(insets, (current, previous) => {
      if (!previous || !lifecycle.isReady()) return;
      const delta = current.start + current.end - previous.start - previous.end;
      const previousDistance =
        virtualizer.getTotalSize() -
        delta -
        viewportSize() -
        (virtualizer.scrollOffset ?? 0);
      if (delta !== 0 && previousDistance <= NEAR_BOTTOM_THRESHOLD) {
        scrollCompensation?.finish();
        virtualizer.scrollToEnd();
      }
      scheduleScrollState();
    })
  );

  onMount(() => {
    // Suspense can construct a channel in an inert template document and
    // insert it in a later task. Bind only after adoption into the live DOM.
    const attachmentObserver = new MutationObserver(connect);
    function connect() {
      if (!scrollRef?.isConnected) return;
      attachmentObserver.disconnect();
      setScrollEl(scrollRef);
      scheduleScrollState();
    }
    attachmentObserver.observe(document, { childList: true, subtree: true });
    connect();
    onCleanup(() => attachmentObserver.disconnect());
  });
  onCleanup(() => {
    scrollCompensation?.dispose();
    lifecycle.send('dispose');
    releaseNavigation?.();
  });

  return (
    <MessageReadVisibilityProvider root={scrollEl} insets={insets}>
      <div
        ref={scrollRef}
        data-channel-scroll
        class="scrollbar-hidden px-2"
        {...scrollIntent.handlers}
        onScroll={scheduleScrollState}
        style={{
          width: '100%',
          height: '100%',
          'overflow-y': 'auto',
          'overflow-anchor': 'none',
        }}
      >
        <div
          ref={contentRef}
          style={{
            position: 'relative',
            width: '100%',
            height: `${sizerHeight(virtualizer.getTotalSize())}px`,
          }}
        >
          <Key each={virtualItems()} by="key">
            {(item) => {
              const id = String(item().key);
              let row: HTMLDivElement | undefined;
              createEffect(
                on(
                  () => item().index,
                  () => {
                    if (row) queueRowMeasurement(row);
                  }
                )
              );
              return (
                <div
                  ref={row}
                  data-index={item().index}
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    transform: `translateY(calc(${item().start + shortListOffset()}px - var(--channel-scroll-adjustment, 0px)))`,
                    'overflow-anchor': 'none',
                  }}
                >
                  {props.children({ id })}
                </div>
              );
            }}
          </Key>
        </div>
      </div>
      <CustomScrollbar
        scrollContainer={scrollEl}
        watchContent
        onScrollIntent={(delta) => {
          scrollCompensation?.finish();
          scrollIntent.markUserIntent(delta > 0 ? 'down' : 'up');
        }}
      />
    </MessageReadVisibilityProvider>
  );
}