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.

feat(email): polish thread layout and keyboard UX (#6038)

Cameron Pak45b0fdf6a35b
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 5178a5aad1..ad1084d95c 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -16,6 +16,7 @@
### SolidJs
- Avoid createEffect. Legitimate uses: syncing with external/imperative systems (DOM APIs, third-party libs). If you're using it to derive state or trigger updates, use a derived signal or wrap the setter instead.
+- Prefer wrapping the setter over `createEffect(() => { if (signal()) sideEffect() })`. When setting focus/selection should also clear another stop, blur a control, or scroll, put that work in the setter (or a named helper the setter calls) so the action is explicit at the call site — not a distant effect watching the signal.
- Use createMemo only when you need referential stability or the derivation is expensive. Cheap derivations (() => a() + b()) don't need it regardless of subscriber count.
- Before rolling your own reactive utility, check solid-primitives first.
@@ -28,6 +29,7 @@
## Styling
- Use semantic color tokens, not raw Tailwind color classes.
- Do not add cursor-pointer to clickable elements.
+- Prefer styling in the component (Tailwind classes on the markup) so styling lives next to structure. Reserve `@utility` in `index.css` for styles that are widely shared across many components — not one-off or two-component layouts.
## TS
- For exhaustive switch statements use `match` from `ts-pattern`.
diff --git a/apps/web/src/features/block-email/component/CollapsedMessage.tsx b/apps/web/src/features/block-email/component/CollapsedMessage.tsx
index 31bf93947e..9a4b8bb933 100644
--- a/apps/web/src/features/block-email/component/CollapsedMessage.tsx
+++ b/apps/web/src/features/block-email/component/CollapsedMessage.tsx
@@ -1,19 +1,17 @@
import { UserIcon, type UserIconProps } from '@core/component/UserIcon';
import { useEmail } from '@core/context/user';
import type { ApiMessage } from '@service-email/generated/schemas';
-import { cn } from '@ui/utils/classname';
+import { Tooltip } from '@ui';
import { createMemo, Show } from 'solid-js';
import { getSenderDisplayName, getSenderMacroId } from '../util/emailUser';
-import { formatShortDate } from './EmailMessageTopBar';
+import { formatFullDate, formatShortDate } from '../util/formatEmailDate';
import { EmailUserTooltip } from './EmailUserTooltip';
interface CollapsedMessageProps {
message: ApiMessage;
- isFocused: boolean;
- onClick: () => void;
- onFocus?: () => void;
}
+/** Collapsed thread row: sender, snippet, date. The chrome is MessageCard's. */
export function CollapsedMessage(props: CollapsedMessageProps) {
const currentUserEmail = useEmail();
@@ -21,10 +19,6 @@ export function CollapsedMessage(props: CollapsedMessageProps) {
getSenderDisplayName(props.message, currentUserEmail())
);
const senderMacroId = createMemo(() => getSenderMacroId(props.message));
- const _allRecipients = createMemo(() => [
- ...props.message.to,
- ...props.message.cc,
- ]);
const senderIconProps = createMemo<UserIconProps>(() => {
const senderId = senderMacroId();
const photoUrl = props.message.from?.photo_url ?? undefined;
@@ -47,56 +41,38 @@ export function CollapsedMessage(props: CollapsedMessageProps) {
return '';
});
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- e.stopPropagation();
- props.onClick();
- }
- };
-
return (
- <div class="shrink-0 flex justify-center w-full">
- <div class="macro-message-width macro-message-padding w-full">
- <div
- class={cn(
- 'relative flex flex-col gap-2 p-4 rounded-lg min-w-0 border',
- props.isFocused
- ? 'bg-active border-edge'
- : 'bg-hover hover:bg-active hover:border-edge border-transparent'
- )}
- style={{
- '--user-icon-width': '1rem',
- }}
- data-message-body-id={props.message.db_id}
- tabIndex={0}
- onClick={props.onClick}
- onFocus={props.onFocus}
- onKeyDown={handleKeyDown}
- >
- <div class="flex items-center gap-2 min-w-0 text-xs">
- <div class="shrink-0 flex justify-center items-center size-6">
- <UserIcon
- {...senderIconProps()}
- isDeleted={false}
- size="fill"
- suppressClick={true}
- />
- </div>
- <EmailUserTooltip recipient={props.message.from}>
- <span class="text-ink truncate cursor-default shrink-0 max-w-32">
- {senderDisplay()}
- </span>
- </EmailUserTooltip>
- <Show when={props.message.internal_date_ts}>
- <span class="shrink-0 text-ink-extra-muted/60 tabular-nums">
- {formatShortDate(props.message.internal_date_ts!)}
- </span>
- </Show>
- </div>
- <div class="min-w-0 text-sm text-ink-muted truncate">{snippet()}</div>
+ <div class="min-w-0 grid grid-cols-[7rem_minmax(0,1fr)_4.5rem] items-center gap-x-2 @max-[480px]/message:grid-cols-[minmax(0,1fr)_auto] @max-[480px]/message:gap-y-2">
+ <div class="flex items-center min-h-6 gap-2 min-w-0 text-sm @max-[480px]/message:col-start-1 @max-[480px]/message:row-start-1">
+ <div class="shrink-0 flex justify-center items-center size-6">
+ <UserIcon
+ {...senderIconProps()}
+ isDeleted={false}
+ size="fill"
+ suppressClick={true}
+ />
</div>
+ <div class="min-w-0">
+ <EmailUserTooltip recipient={props.message.from}>
+ <span class="text-ink line-clamp-1">{senderDisplay()}</span>
+ </EmailUserTooltip>
+ </div>
+ </div>
+ <div class="min-w-0 text-sm text-ink-extra-muted overflow-hidden text-ellipsis whitespace-nowrap @max-[480px]/message:col-span-full @max-[480px]/message:row-start-2 @max-[480px]/message:whitespace-normal @max-[480px]/message:line-clamp-2">
+ {snippet()}
</div>
+ <Show when={props.message.internal_date_ts}>
+ <span class="flex items-center min-h-6 justify-self-end @max-[480px]/message:col-start-2 @max-[480px]/message:row-start-1">
+ <Tooltip
+ as="span"
+ label={formatFullDate(props.message.internal_date_ts!)}
+ >
+ <span class="text-sm text-ink-extra-muted/60 tabular-nums">
+ {formatShortDate(props.message.internal_date_ts!)}
+ </span>
+ </Tooltip>
+ </span>
+ </Show>
</div>
);
}
diff --git a/apps/web/src/features/block-email/component/Email.tsx b/apps/web/src/features/block-email/component/Email.tsx
index 75aa607910..567c3ab446 100644
--- a/apps/web/src/features/block-email/component/Email.tsx
+++ b/apps/web/src/features/block-email/component/Email.tsx
@@ -30,20 +30,44 @@ import {
createMemo,
createSignal,
Match,
+ on,
+ onCleanup,
onMount,
Show,
Switch,
untrack,
} from 'solid-js';
+import { match } from 'ts-pattern';
import { isScrollingToMessage } from '../signal/scrollState';
import { registerEmailHotkeys } from '../util/emailHotkeys';
import { isPersonalMessage } from '../util/isPersonalMessage';
import type { ReplyType } from '../util/replyType';
-import { scrollToMessage } from '../util/scrollToMessage';
+import {
+ hiddenMessagesControl,
+ isTruncatedMiddleMessage,
+ isUnreadMessage,
+ keyboardRevealDelta,
+ leadingThrottle,
+ listScrollBehavior,
+ messageElement,
+ nearestDelta,
+ pageThenAdvanceDelta,
+ revealMessageAfterLayout,
+ type ScrollAlign,
+ scrollToListEndDelta,
+ scrollToListStartDelta,
+ scrollToMessage,
+ threadMessageIsExpanded,
+} from '../util/scrollToMessage';
+import {
+ adjacentStop,
+ nextThreadStop,
+ shownStops,
+ type ThreadStop,
+ threadStopFromHover,
+} from '../util/threadStops';
import { BottomReplyButtons } from './BottomReplyButtons';
import { EmailFormContextProvider } from './EmailFormContext';
-import { EmailParticipants } from './EmailParticipants';
-import { EmailThreadTitle } from './EmailThreadTitle';
import { openEmailReplyComposerForMessage } from './emailReplyActions';
import { MessageList } from './MessageList';
import { MobileEmailComposeDrawer } from './MobileEmailComposeDrawer';
@@ -52,10 +76,9 @@ import { EmailSidePanelSections } from './sidepanel/EmailSidePanelSections';
import { TopBar } from './TopBar';
const TARGET_MESSAGE_HIGHLIGHT_MS = 800;
-const SCROLL_ANIMATION_MS = 1000;
-const SCROLL_AFTER_SEND_DELAY_MS = 100;
-const SCROLL_SETTLE_STABLE_FRAMES = 15;
-const SCROLL_SETTLE_MAX_MS = 2000;
+/** List navigation — keep within the 300ms UI motion budget (improve-animations). */
+const SCROLL_ANIMATION_MS = 250;
+const KEYBOARD_SCROLL_MS = 250;
type EmailViewProps = {
title: string;
@@ -89,12 +112,6 @@ function EmailContent(props: EmailViewProps) {
const { isLoading: isUserLoading } = useUserContext();
const userEmail = useEmail();
- const [isScrolled, setIsScrolled] = createSignal(false);
-
- const handleScrollPositionChange = (scrollFromTop: number) => {
- setIsScrolled(scrollFromTop > 1);
- };
-
const openTaskCompose = () => {
const threadId = context.thread()?.db_id;
if (!threadId) return;
@@ -154,13 +171,50 @@ function EmailContent(props: EmailViewProps) {
}
};
- /**
- * Loads the next page only when there is more data to load and
- * it's not already fetching
- */
- const fetchNextPage = () => {
+ const fetchNextPage = async () => {
if (context.query.hasMore() && !context.query.isFetching()) {
context.query.fetchNextPage();
+ await waitForQueryLoad();
+ }
+ };
+
+ const canRunInitialEmailScroll = () =>
+ !isTouchDevice() || splitPanel?.isPanelActive() !== false;
+
+ const [keyboardSelecting, setKeyboardSelecting] = createSignal(false);
+ const [listAnchor, setListAnchor] = createSignal<'title' | 'composer'>();
+ let lastPointer = { x: Number.NaN, y: Number.NaN };
+ let armedPointer: { x: number; y: number } | undefined;
+
+ // Hand list navigation back to the pointer: arrow keys resume from whatever
+ // the mouse is over. The selection itself survives, so a message reached with
+ // the keyboard stays selected once the mouse moves.
+ const releaseKeyboardPointer = () => {
+ armedPointer = undefined;
+ setKeyboardSelecting(false);
+ setListAnchor(undefined);
+ leaveHiddenChip();
+ };
+
+ /** Escape drops the selection too, not just the keyboard's claim on it. */
+ const clearSelection = () => {
+ releaseKeyboardPointer();
+ context.messages.setFocused(undefined);
+ };
+
+ const armKeyboardPointer = () => {
+ if (isTouchDevice()) return;
+ setKeyboardSelecting(true);
+ armedPointer = { x: lastPointer.x, y: lastPointer.y };
+ };
+
+ const leaveHiddenChip = () => {
+ context.messages.setHiddenChipFocused(false);
+ const list = untrack(context.messagesListRef);
+ const button = list ? hiddenMessagesControl(list) : undefined;
+ if (button && document.activeElement === button) {
+ button.blur();
+ blockElement()?.focus({ preventScroll: true });
}
};
@@ -169,26 +223,26 @@ function EmailContent(props: EmailViewProps) {
*/
const performScrollToMessage = (
messageId: string,
- opts: { behavior?: ScrollBehavior; focus?: boolean } = {
+ opts: {
+ behavior?: ScrollBehavior;
+ focus?: boolean;
+ align?: ScrollAlign;
+ } = {
behavior: 'smooth',
focus: true,
}
) => {
- opts = { focus: true, behavior: 'smooth', ...opts };
+ opts = { focus: true, behavior: 'smooth', align: 'nearest', ...opts };
const messages = untrack(context.messages.list);
const container = untrack(context.messagesListRef);
if (!messages || !container) return false;
- if (opts.focus) {
- context.messages.setFocused(messageId);
- }
-
setIsScrollingToMessage(true);
const success = scrollToMessage(messageId, messages, container, {
behavior: opts.behavior,
- reversed: true,
+ align: opts.align,
});
if (!success) {
@@ -196,254 +250,240 @@ function EmailContent(props: EmailViewProps) {
return false;
}
+ if (opts.focus) {
+ leaveHiddenChip();
+ context.messages.setFocused(messageId);
+ }
+
if (context.messages.targetMessageID() === messageId) {
setTimeout(() => {
context.messages.setTargetMessageID(undefined);
}, TARGET_MESSAGE_HIGHLIGHT_MS);
}
- // Clear scrolling flag after animation
setTimeout(() => setIsScrollingToMessage(false), SCROLL_ANIMATION_MS);
return true;
};
- // Message bodies keep resizing briefly after render (images load, inline
- // cid: images fail and collapse), so a scroll computed against that
- // transient layout gets displaced — browser scroll anchoring can clamp it
- // to the very top of the thread. Re-assert the initial scroll whenever the
- // content height changes until layout settles or the user scrolls.
- let cancelActiveScrollPin: (() => void) | undefined;
- const pinInitialScroll = (messageId: string) => {
- cancelActiveScrollPin?.();
- const list = untrack(context.messagesListRef);
- if (!list) return;
-
- let cancelled = false;
- let stableFrames = 0;
- let lastHeight = list.scrollHeight;
- const startedAt = performance.now();
-
- const cancel = () => {
- cancelled = true;
- list.removeEventListener('wheel', cancel);
- list.removeEventListener('touchstart', cancel);
- list.removeEventListener('pointerdown', cancel);
- };
- cancelActiveScrollPin = cancel;
- list.addEventListener('wheel', cancel, { passive: true });
- list.addEventListener('touchstart', cancel, { passive: true });
- list.addEventListener('pointerdown', cancel, { passive: true });
-
- const tick = () => {
- if (cancelled || !list.isConnected) return cancel();
- if (list.scrollHeight !== lastHeight) {
- lastHeight = list.scrollHeight;
- stableFrames = 0;
- performScrollToMessage(messageId, {
- behavior: 'instant',
- focus: false,
- });
- } else {
- stableFrames++;
- }
- if (
- stableFrames >= SCROLL_SETTLE_STABLE_FRAMES ||
- performance.now() - startedAt > SCROLL_SETTLE_MAX_MS
- ) {
- return cancel();
- }
- requestAnimationFrame(tick);
- };
- requestAnimationFrame(tick);
- };
-
- const scrollToLastMessage = (
- behavior: ScrollBehavior = 'instant',
- focus = false
- ) => {
- const messages = context.messages.list();
- if (!messages?.length) return;
-
- const lastMessage = messages[messages.length - 1];
-
- if (!lastMessage.db_id) return;
-
- performScrollToMessage(lastMessage.db_id, { behavior, focus });
- };
-
- const firstUnreadMessageId = createMemo(() => {
- const messages = context.messages.list().toSorted((a, b) => {
- if (a.internal_date_ts && b.internal_date_ts) {
- return (
- new Date(a.internal_date_ts).getTime() -
- new Date(b.internal_date_ts).getTime()
- );
- } else if (a.sent_at && b.sent_at) {
- return new Date(a.sent_at).getTime() - new Date(b.sent_at).getTime();
- }
- return 0;
- });
- return messages?.find((m) =>
- m.labels.some((l) => l.provider_label_id === 'UNREAD')
- )?.db_id;
- });
-
- const canRunInitialEmailScroll = () =>
- !isTouchDevice() || splitPanel?.isPanelActive() !== false;
-
- // ============================================
- // PHASE 2: HANDLE TARGET MESSAGE SCROLLING
- // ============================================
- // This effect handles scrolling to a specific message (if provided via URL) or scrolling to the last message by default
- // This effect should only run once.
context.onInitialDataLoad(() => {
- // Initial scroll positioning visibly shifts the email panel if it runs
- // while the split is swiping in on touch devices.
if (!canRunInitialEmailScroll()) return false;
+ if (!untrack(context.messagesListRef)) return false;
- // Check for target message
const targetMessageId_ = context.messages.targetMessageID();
-
if (targetMessageId_ && typeof targetMessageId_ !== 'string') return true;
-
- if (targetMessageId_) {
- handleTargetMessage(targetMessageId_);
- } else {
- const lastUnreadMessageId_ = untrack(firstUnreadMessageId);
- // Check if there is an unread message
- if (lastUnreadMessageId_) {
- setTimeout(() => {
- performScrollToMessage(lastUnreadMessageId_!, {
- behavior: 'instant',
- });
- pinInitialScroll(lastUnreadMessageId_!);
- });
- context.messages.setFocused(lastUnreadMessageId_!);
- } else {
- scrollToLastMessage('instant', false);
- const lastMessageId = untrack(context.messages.list).at(-1)?.db_id;
- if (lastMessageId) pinInitialScroll(lastMessageId);
- }
+ if (typeof targetMessageId_ === 'string') {
+ void revealTargetMessage(targetMessageId_);
}
return true;
});
- /**
- * Handles scrolling to a specific message ID from URL
- */
- async function handleTargetMessage(messageId: string) {
+ async function revealTargetMessage(messageId: string) {
+ context.messages.setExpandedBodyId(messageId, true);
const messages = untrack(context.messages.list);
if (!messages) return;
- // Expand the target so the navigated-to hit isn't a collapsed row
- context.messages.setExpandedBodyId(messageId, true);
- const targetIndex = messages.findIndex((m) => m.db_id === messageId);
- // Case 1: Message not in current loaded batch - need to load more
- if (targetIndex < 0) {
+ const initialIndex = messages.findIndex(
+ (message) => message.db_id === messageId
+ );
+
+ if (initialIndex < 0) {
try {
const found = await loadMessagesUntilFound(messageId);
- if (found) {
- // Load one more batch for scroll context
- fetchNextPage();
- await waitForQueryLoad();
- // Scroll to the message after DOM updates
- setTimeout(() => {
- performScrollToMessage(messageId, { behavior: 'instant' });
- pinInitialScroll(messageId);
- });
- } else {
- // Message not found, fallback to last message
- setTimeout(() => scrollToLastMessage('instant', true));
- }
+ if (!found) return;
+ await fetchNextPage();
} catch (error) {
console.error('Error loading target message:', error);
- setTimeout(() => scrollToLastMessage('instant', true));
+ return;
}
+ } else if (initialIndex === 0) {
+ await fetchNextPage();
}
- // Case 2: Message is first in current batch - load more for context
- else if (targetIndex === 0) {
- fetchNextPage();
- await waitForQueryLoad();
- setTimeout(() => {
- performScrollToMessage(messageId, { behavior: 'instant' });
- pinInitialScroll(messageId);
- });
- }
- // Case 3: Message is in current batch with sufficient context
- else {
- setTimeout(() => {
- performScrollToMessage(messageId, { behavior: 'instant' });
- pinInitialScroll(messageId);
+
+ requestAnimationFrame(() => {
+ performScrollToMessage(messageId, {
+ behavior: 'instant',
+ focus: true,
+ align: 'start',
});
- }
+ });
}
- // If there is a focused message id, but it does not currently exist in the message list, it is because the user has just sent a message. When it does come into existence, we want to scroll to the bottom.
- createEffect((prev: boolean | undefined) => {
- const currentFocusedId = context.messages.focusedID();
+ const [userOpenedMiddle, setUserOpenedMiddle] = createSignal(false);
+ createEffect(
+ on(
+ () => context.thread()?.db_id,
+ () => {
+ setUserOpenedMiddle(false);
+ leaveHiddenChip();
+ }
+ )
+ );
+
+ const showMiddleMessages = createMemo(() => {
+ if (userOpenedMiddle()) return true;
const messages = context.messages.list();
+ const focus = context.messages.focusedID();
+ const target = context.messages.targetMessageID();
+ for (let i = 0; i < messages.length; i++) {
+ if (!isTruncatedMiddleMessage(i, messages.length)) continue;
+ const id = messages[i]?.db_id;
+ if (id && (id === focus || id === target)) return true;
+ if (isUnreadMessage(messages[i])) return true;
+ if (!isTouchDevice() && id && context.drafts.getDraftForMessage(id))
+ return true;
+ }
+ return false;
+ });
- if (!currentFocusedId || !messages) return true;
+ let markdownDomRef!: HTMLDivElement;
+ const tryKeyboardListScroll = leadingThrottle(KEYBOARD_SCROLL_MS);
- const currentIndex = messages.findIndex(
- (m) => m.db_id === currentFocusedId
- );
- if (currentIndex < 0) return false;
+ const scrollListBy = (
+ list: HTMLElement,
+ top: number,
+ animationMs = SCROLL_ANIMATION_MS
+ ) => {
+ if (top === 0) return false;
+ setIsScrollingToMessage(true);
+ setTimeout(() => setIsScrollingToMessage(false), animationMs);
+ list.scrollBy({ top, behavior: listScrollBehavior() });
+ return true;
+ };
- if (prev === false) {
- setTimeout(() => {
- scrollToLastMessage('smooth');
- }, SCROLL_AFTER_SEND_DELAY_MS);
- }
+ const keyboardScrollListBy = (list: HTMLElement, top: number) => {
+ if (top === 0) return false;
+ if (!tryKeyboardListScroll()) return true;
+ setIsScrollingToMessage(true);
+ setTimeout(() => setIsScrollingToMessage(false), KEYBOARD_SCROLL_MS);
+ list.scrollBy({ top, behavior: listScrollBehavior() });
return true;
- });
+ };
+
+ const focusHiddenMessages = () => {
+ const list = untrack(context.messagesListRef);
+ if (!list) return false;
+ const button = hiddenMessagesControl(list);
+ if (!button) return false;
+ context.messages.setFocused(undefined);
+ context.messages.setHiddenChipFocused(true);
+ scrollListBy(list, nearestDelta(list, button));
+ return true;
+ };
+
+ const applyStop = (
+ stop: ThreadStop | undefined,
+ messages: ApiMessage[],
+ list: HTMLElement
+ ) => {
+ if (!stop) return true;
+ return match(stop)
+ .with({ kind: 'title' }, () => {
+ armKeyboardPointer();
+ setListAnchor('title');
+ context.messages.setFocused(undefined);
+ const startDelta = scrollToListStartDelta(list);
+ if (startDelta !== 0) return scrollListBy(list, startDelta);
+ return true;
+ })
+ .with({ kind: 'hidden-chip' }, () => {
+ armKeyboardPointer();
+ setListAnchor(undefined);
+ return focusHiddenMessages();
+ })
+ .with({ kind: 'message' }, ({ index }) => {
+ const id = messages[index]?.db_id;
+ if (!id) return false;
+ armKeyboardPointer();
+ setListAnchor(undefined);
+ return performScrollToMessage(id, {
+ behavior: 'smooth',
+ focus: true,
+ });
+ })
+ .with({ kind: 'composer' }, () => {
+ armKeyboardPointer();
+ setListAnchor('composer');
+ leaveHiddenChip();
+ context.messages.setFocused(undefined);
+ markdownDomRef.focus();
+ return true;
+ })
+ .exhaustive();
+ };
const navigateMessage = createCallback((dir: 'prev' | 'next') => {
const messages = context.messages.list();
const list = context.messagesListRef();
if (!messages?.length || !list) return false;
- const currentFocusedId = context.messages.focusedID();
-
- if (!currentFocusedId) {
- const target =
- dir === 'prev' ? messages[messages.length - 1] : messages[0];
- if (!target?.db_id) return false;
- performScrollToMessage(target.db_id, {
- behavior: 'smooth',
- focus: true,
- });
- return true;
- }
-
- const currentIndex = messages.findIndex(
- (m) => m.db_id === currentFocusedId
- );
- if (currentIndex < 0) return false;
+ const stops = shownStops({
+ length: messages.length,
+ showMiddle: showMiddleMessages(),
+ hasComposer: Boolean(markdownDomRef),
+ });
- const delta = dir === 'prev' ? -1 : 1;
- const targetIndex = currentIndex + delta;
+ const keyboard = (() => {
+ if (!keyboardSelecting()) return undefined;
+ if (context.messages.hiddenChipFocused())
+ return { kind: 'hidden-chip' } as const;
+ const anchor = listAnchor();
+ if (anchor === 'title' || anchor === 'composer') {
+ return { kind: anchor } as const;
+ }
+ const focusedId = context.messages.focusedID();
+ if (!focusedId) return undefined;
+ const index = messages.findIndex(
+ (message) => message.db_id === focusedId
+ );
+ return index >= 0 ? ({ kind: 'message', index } as const) : undefined;
+ })();
+
+ if (keyboard?.kind === 'message') {
+ const focusedId = messages[keyboard.index]?.db_id;
+ const focusedEl = focusedId
+ ? messageElement(list, messages, focusedId)
+ : undefined;
+ if (focusedEl) {
+ const revealDelta = keyboardRevealDelta(list, focusedEl, dir);
+ if (revealDelta !== 0) return keyboardScrollListBy(list, revealDelta);
+
+ const pageDelta = pageThenAdvanceDelta(list, focusedEl, dir);
+ if (pageDelta !== 0) return keyboardScrollListBy(list, pageDelta);
+ }
- if (targetIndex < 0 || targetIndex >= messages.length) {
- if (dir === 'next' && markdownDomRef) {
- context.messages.setFocused(undefined);
- markdownDomRef.focus();
- return true;
+ if (
+ dir === 'next' &&
+ keyboard.index === messages.length - 1 &&
+ keyboardSelecting()
+ ) {
+ const nextStop = adjacentStop(stops, keyboard, 'next');
+ if (!nextStop || nextStop.kind === 'composer') {
+ const endDelta = scrollToListEndDelta(list);
+ if (endDelta !== 0) return keyboardScrollListBy(list, endDelta);
+ return true;
+ }
}
- return false;
}
- const targetMsg = messages[targetIndex];
- if (!targetMsg?.db_id) return false;
-
- performScrollToMessage(targetMsg.db_id, {
- behavior: 'smooth',
- focus: true,
- });
-
- return true;
+ const messageIds = messages.map((message) => message.db_id);
+ const hover = threadStopFromHover(context.messages.hovered(), messageIds);
+ // The pointer leads while it is over the list. With the pointer elsewhere,
+ // arrows step off the selected card rather than re-entering at the end.
+ const selectedId = context.messages.focusedID();
+ const selectedIndex = selectedId ? messageIds.indexOf(selectedId) : -1;
+ const cursor =
+ hover ??
+ (selectedIndex >= 0
+ ? ({ kind: 'message', index: selectedIndex } as const)
+ : undefined);
+
+ return applyStop(
+ nextThreadStop({ stops, keyboard, hover: cursor, dir }),
+ messages,
+ list
+ );
});
const navigateToPreviousMessage = () => navigateMessage('prev');
@@ -461,8 +501,6 @@ function EmailContent(props: EmailViewProps) {
hasRun = true;
});
- let markdownDomRef!: HTMLDivElement;
-
const getHotkeyTarget = () => {
const messages = context.messages.list();
if (messages.length === 0) return;
@@ -486,15 +524,20 @@ function EmailContent(props: EmailViewProps) {
const messageId = target.message.db_id;
if (!messageId) return false;
- const isNewMessage = target.message.labels.some(
- (label) => label.provider_label_id === 'UNREAD'
- );
-
- return (
- context.messages.isBodyExpanded(messageId) ||
- target.isLastMessage ||
- isNewMessage
+ const list = context.messages.list();
+ const chronologicalIndex = list.findIndex(
+ (message) => message.db_id === messageId
);
+ if (chronologicalIndex < 0) return false;
+
+ return threadMessageIsExpanded({
+ chronologicalIndex,
+ listLength: list.length,
+ expansionOverride: context.messages.expandedBodyIds[messageId],
+ isUnread: isUnreadMessage(target.message),
+ hasDraft:
+ !isTouchDevice() && !!context.drafts.getDraftForMessage(messageId),
+ });
};
const openHotkeyTarget = (replyType: ReplyType) => {
@@ -510,6 +553,18 @@ function EmailContent(props: EmailViewProps) {
};
onMount(() => {
+ if (!isTouchDevice()) {
+ const onMove = (event: PointerEvent) => {
+ lastPointer = { x: event.clientX, y: event.clientY };
+ const armed = armedPointer;
+ if (!armed) return;
+ if (event.clientX === armed.x && event.clientY === armed.y) return;
+ releaseKeyboardPointer();
+ };
+ window.addEventListener('pointermove', onMove);
+ onCleanup(() => window.removeEventListener('pointermove', onMove));
+ }
+
registerEmailHotkeys(scopeId(), {
replyToFocusedMessage: () => openHotkeyTarget('reply-all'),
forwardFocusedMessage: () => openHotkeyTarget('forward'),
@@ -532,12 +587,40 @@ function EmailContent(props: EmailViewProps) {
hotkey: 'enter',
description: 'Reply to message',
keyDownHandler: () => {
+ if (context.messages.hiddenChipFocused()) {
+ const messages = untrack(context.messages.list);
+ const next = adjacentStop(
+ shownStops({ length: messages.length, showMiddle: true }),
+ { kind: 'message', index: 0 },
+ 'next'
+ );
+ const nextId =
+ next?.kind === 'message' ? messages[next.index]?.db_id : undefined;
+ setUserOpenedMiddle(true);
+ if (!nextId) {
+ leaveHiddenChip();
+ return true;
+ }
+ context.messages.setFocused(nextId);
+ revealMessageAfterLayout(
+ nextId,
+ messages,
+ untrack(context.messagesListRef)
+ );
+ return true;
+ }
+
const focusedId = context.messages.focusedID();
const target = getHotkeyTarget();
if (focusedId && target?.message.db_id === focusedId) {
if (!isMessageRenderedExpanded(target)) {
context.messages.setExpandedBodyId(focusedId, true);
+ revealMessageAfterLayout(
+ focusedId,
+ untrack(context.messages.list),
+ untrack(context.messagesListRef)
+ );
return true;
}
@@ -558,7 +641,7 @@ function EmailContent(props: EmailViewProps) {
registerScopeSignalHotkey(scopeId, {
hotkey: 'escape',
- description: 'Collapse message',
+ description: 'Collapse or unselect message',
keyDownHandler: () => {
// Skip if focus is in an editable area (compose input handles its own Escape)
const activeEl = document.activeElement;
@@ -570,8 +653,24 @@ function EmailContent(props: EmailViewProps) {
return false;
}
+ if (context.messages.hiddenChipFocused()) {
+ clearSelection();
+ return true;
+ }
+
+ if (keyboardSelecting() && listAnchor()) {
+ clearSelection();
+ return true;
+ }
+
const focusedId = context.messages.focusedID();
- if (!focusedId) return false;
+ if (!focusedId) {
+ if (keyboardSelecting()) {
+ clearSelection();
+ return true;
+ }
+ return false;
+ }
// If there's an active reply, just clear it (don't collapse the message)
if (context.messages.replyingToMessageId() === focusedId) {
@@ -579,16 +678,20 @@ function EmailContent(props: EmailViewProps) {
return true;
}
- // If message is expanded and not the last message, collapse it
- if (context.messages.isBodyExpanded(focusedId)) {
- const messages = context.messages.list();
- const lastMessage = messages[messages.length - 1];
- if (lastMessage?.db_id !== focusedId) {
- context.messages.setExpandedBodyId(focusedId, false);
- return true;
- }
+ const target = getHotkeyTarget();
+ if (target && isMessageRenderedExpanded(target)) {
+ context.messages.setExpandedBodyId(focusedId, false);
+ return true;
}
- return false;
+
+ clearSelection();
+ if (
+ activeEl instanceof HTMLElement &&
+ activeEl.closest(`[data-message-body-id="${CSS.escape(focusedId)}"]`)
+ ) {
+ activeEl.blur();
+ }
+ return true;
},
hotkeyToken: TOKENS.email.cancelReply,
hide: true,
@@ -743,40 +846,27 @@ function EmailContent(props: EmailViewProps) {
class="w-full flex-1 flex flex-col items-center overflow-hidden"
ref={context.registerMessagesContainer}
>
- <Show when={!isTouchDevice()}>
- <div class="shrink-0 w-full flex justify-center">
- <div
- class="macro-message-width macro-message-padding w-full border-b"
- classList={{
- 'border-edge-muted/50': isScrolled(),
- 'border-transparent': !isScrolled(),
- }}
- >
- <div class="h-12" />
- <EmailThreadTitle
- title={props.title}
- copyReveal="hover"
- class="text-2xl pb-1.5"
- />
- <div class="pb-2.5">
- <EmailParticipants />
- </div>
- </div>
- </div>
- </Show>
<MessageList
initialLoadComplete={context.initialLoadComplete()}
markdownDomRef={(el) => {
markdownDomRef = el;
}}
- onScrollPositionChange={handleScrollPositionChange}
title={props.title}
underScrollsBottom={!replyInputInFlow()}
+ showMiddleMessages={showMiddleMessages()}
+ hiddenChipFocused={context.messages.hiddenChipFocused()}
+ allowRowHover={!keyboardSelecting()}
+ onHiddenChipFocus={() => {
+ armKeyboardPointer();
+ context.messages.setFocused(undefined);
+ context.messages.setHiddenChipFocused(true);
+ }}
+ onOpenMiddle={() => {
+ leaveHiddenChip();
+ setUserOpenedMiddle(true);
+ }}
/>
- <CustomScrollbar
- reverse
- scrollContainer={context.messagesListRef}
- />
+ <CustomScrollbar scrollContainer={context.messagesListRef} />
</div>
<Show when={isTouchDevice() && mobileBottomReplyMessage()}>
{(lastMessage) => (
diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsx
index 34e98e9a9d..a15c948d40 100644
--- a/apps/web/src/features/block-email/component/EmailContext.tsx
+++ b/apps/web/src/features/block-email/component/EmailContext.tsx
@@ -16,6 +16,7 @@ import {
import { toast } from '@core/component/Toast/Toast';
import { useEmail, useUserId } from '@core/context/user';
import { createMethodRegistration } from '@core/orchestrator';
+import { blockElementSignal } from '@core/signal/blockElement';
import { blockHandleSignal } from '@core/signal/load';
import {
recipientEntityMapper,
@@ -73,6 +74,8 @@ import {
} from 'solid-js';
import { createStore } from 'solid-js/store';
import type { ReplyType } from '../util/replyType';
+import { hiddenMessagesControl } from '../util/scrollToMessage';
+import type { HoveredThreadStop } from '../util/threadStops';
/**
* Tracks thread IDs that had a draft saved since the last query fetch.
@@ -115,6 +118,10 @@ type EmailContextValues = {
setTargetMessageID: (id: string | undefined) => void;
focusedID: Accessor<string | undefined>;
setFocused: (messageID: string | undefined) => void;
+ hiddenChipFocused: Accessor<boolean>;
+ setHiddenChipFocused: (focused: boolean) => void;
+ hovered: Accessor<HoveredThreadStop | undefined>;
+ setHovered: (stop: HoveredThreadStop | undefined) => void;
expandedBodyIds: Record<string, boolean>;
setExpandedBodyId: (id: string, expanded: boolean) => void;
isBodyExpanded: (id: string) => boolean;
@@ -245,6 +252,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
);
const [focusedMessageId, setFocusedMessageId] = createSignal<string>();
+ const [hiddenChipFocused, setHiddenChipFocused] = createSignal(false);
+ const [hoveredStop, setHoveredStop] = createSignal<HoveredThreadStop>();
const [replyingToMessageId, setReplyingToMessageId] = createSignal<string>();
const [bottomReplyOpen, setBottomReplyOpen] = createSignal(false);
const [mobileReplyComposerOpen, setMobileReplyComposerOpen] =
@@ -270,6 +279,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
const [targetMessageId, setTargetMessageId] = createSignal<
string | undefined
>(searchParamsMessageId());
+ // Deep links (`?messageId=`) scroll to and expand a specific message after load.
const [hasHandledTarget, setHasHandledTarget] = createSignal(false);
@@ -817,40 +827,35 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
HTMLDivElement | undefined
>(undefined);
- let containerFilled = false;
+ /** Selecting a message clears the hidden-chip stop explicitly (no createEffect). */
+ const setFocused = (messageID: string | undefined) => {
+ if (messageID) {
+ setHiddenChipFocused(false);
+ const list = messagesListRef();
+ const button = list ? hiddenMessagesControl(list) : undefined;
+ if (button && document.activeElement === button) {
+ button.blur();
+ blockElementSignal.get()?.focus({ preventScroll: true });
+ }
+ }
+ setFocusedMessageId(messageID);
+ };
+
const isContainerFilled = () => {
const messageList = messagesListRef();
const containerRef = messagesContainerRef();
- // Skip if dependencies not ready
if (
!messageList ||
!containerRef ||
- !untrack(() => threadQuery.data)?.db_id
+ !untrack(() => threadQuery.data)?.db_id ||
+ threadQuery.isFetching
) {
- containerFilled = false;
return false;
}
- // Skip if still loading or already filled
- if (threadQuery.isFetching || containerFilled) {
- return containerFilled;
- }
-
- const messageListHeight = messageList.getBoundingClientRect().height;
- const containerHeight = containerRef.getBoundingClientRect().height;
-
- // Load more if container isn't filled
- if (
- messageListHeight < containerHeight &&
- threadQuery.hasNextPage &&
- !threadQuery.isFetching
- ) {
- threadQuery.fetchNextPage();
- containerFilled = false;
- return false;
- }
- containerFilled = true;
+ // Older-page prefetch when the first batch does not overflow moved to
+ // MessageList (`listNeedsOlderPage` + `fetchOlderMessages`).
return true;
};
@@ -876,31 +881,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
};
const onExpandMessageBody = (messageID: string, expanded: boolean) => {
- const listContainer = messagesListRef();
-
- const lastScrollPosition = listContainer?.scrollTop;
- const lastScrollHeight = listContainer?.scrollHeight;
-
setExpandedMessageBodyIds(messageID, expanded);
-
- if (
- !listContainer ||
- lastScrollPosition == null ||
- lastScrollHeight == null
- )
- return;
-
- // Maintain the scroll position when expansion changes
- queueMicrotask(() => {
- const lastPos = lastScrollHeight + lastScrollPosition;
- const currentPos = listContainer.scrollHeight + listContainer.scrollTop;
-
- // List is reversed, we need a negative value to maintain scroll
- // position
- const diff = lastPos - currentPos;
-
- messagesListRef()?.scrollBy({ top: diff });
- });
};
// When the provider unmounts (user navigates away), clear the thread query
@@ -960,7 +941,11 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
},
messages: {
focusedID: focusedMessageId,
- setFocused: setFocusedMessageId,
+ setFocused,
+ hiddenChipFocused,
+ setHiddenChipFocused,
+ hovered: hoveredStop,
+ setHovered: setHoveredStop,
targetMessageID: targetMessageId,
setTargetMessageID: setTargetMessageId,
list: createMemo(() => threadQuery.data?.filtered ?? []),
diff --git a/apps/web/src/features/block-email/component/EmailInput.tsx b/apps/web/src/features/block-email/component/EmailInput.tsx
index 30be3bef1c..c2b2436018 100644
--- a/apps/web/src/features/block-email/component/EmailInput.tsx
+++ b/apps/web/src/features/block-email/component/EmailInput.tsx
@@ -1,4 +1,5 @@
import { useEmailContext } from '@block-email/component/EmailContext';
+import { revealMessageAfterLayout } from '@block-email/util/scrollToMessage';
import type {
ApiDraftOutputDbId,
ApiMessage,
@@ -57,15 +58,19 @@ export function EmailInput(props: EmailInputProps) {
return decodedHtml;
});
- function afterSend(newMessageId: ApiDraftOutputDbId | null) {
- // Refresh to get the new message
- ctx.query.refetch();
-
- // Set focus to new message if provided
- if (newMessageId) ctx.messages.setFocused(newMessageId);
-
+ async function afterSend(newMessageId: ApiDraftOutputDbId | null) {
// Collapse the input after sending (Gmail-style).
props.setShowReply?.(false);
+
+ if (!newMessageId) return;
+
+ ctx.messages.setFocused(newMessageId);
+ await ctx.query.refetch();
+ revealMessageAfterLayout(
+ newMessageId,
+ ctx.messages.list(),
+ ctx.messagesListRef()
+ );
}
return (
diff --git a/apps/web/src/features/block-email/component/EmailMessageBody.tsx b/apps/web/src/features/block-email/component/EmailMessageBody.tsx
index 50b1da5324..fecde97d9a 100644
--- a/apps/web/src/features/block-email/component/EmailMessageBody.tsx
+++ b/apps/web/src/features/block-email/component/EmailMessageBody.tsx
@@ -328,7 +328,7 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {
return (
<div
- class="ph-no-capture flex flex-col pt-1"
+ class="ph-no-capture flex flex-col [&_.md-p:first-child]:mt-0 [&_.md-p:last-child]:mb-0"
onPointerDown={() => {
if (!props.isBodyExpanded() && props.message.db_id) {
props.setExpandedMessageBody(props.message.db_id);
diff --git a/apps/web/src/features/block-email/component/EmailMessageTopBar.tsx b/apps/web/src/features/block-email/component/EmailMessageTopBar.tsx
index c3f9febab0..95e698bdfc 100644
--- a/apps/web/src/features/block-email/component/EmailMessageTopBar.tsx
+++ b/apps/web/src/features/block-email/component/EmailMessageTopBar.tsx
@@ -1,5 +1,5 @@
import { useEmail } from '@core/context/user';
-import type { DateValue } from '@core/util/date';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import CaretRight from '@phosphor/caret-right.svg';
import type { ApiMessage } from '@service-email/generated/schemas';
import { Button, cn, Tooltip } from '@ui';
@@ -16,7 +16,8 @@ import {
getRecipientDisplayName,
getSenderDisplayName,
} from '../util/emailUser';
-import { useEmailContext } from './EmailContext';
+import { formatFullDate, formatShortDate } from '../util/formatEmailDate';
+
import { EmailUserTooltip } from './EmailUserTooltip';
import { type EmailMessageAction, MessageActions } from './MessageActions';
@@ -39,35 +40,6 @@ interface Recipient {
email?: string | null;
}
-function formatFullDate(date: DateValue): string {
- return new Date(date)
- .toLocaleString('en-US', {
- weekday: 'long',
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit',
- timeZoneName: 'short',
- })
- .replace(',', '');
-}
-
-export function formatShortDate(date: DateValue): string {
- const d = new Date(date);
- if (d.getFullYear() !== new Date().getFullYear()) {
- return d.toLocaleDateString('en-US', {
- month: 'numeric',
- day: 'numeric',
- year: '2-digit',
- });
- }
- return d.toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- });
-}
-
function RecipientChip(props: { recipient: Recipient }): JSX.Element {
return (
<EmailUserTooltip recipient={props.recipient}>
@@ -160,7 +132,7 @@ function CollapsedRecipientList(props: {
function HeaderTopRow(props: {
senderName: string;
- isHovering: boolean;
+ showHeaderToggle: boolean;
isExpanded: boolean;
onToggle: () => void;
message: ApiMessage;
@@ -176,12 +148,10 @@ function HeaderTopRow(props: {
]);
return (
- <div class="flex flex-row w-full items-center justify-between gap-2 text-xs min-w-0">
- <div class="flex flex-row items-center gap-1.5 min-w-0">
+ <div class="flex flex-row w-full min-w-0 flex-1 items-center gap-2 text-sm">
+ <div class="flex flex-row items-center gap-1.5 min-w-0 flex-1">
<EmailUserTooltip recipient={props.message.from}>
- <span class="text-ink font-medium cursor-default">
- {props.senderName}
- </span>
+ <span class="text-ink font-medium">{props.senderName}</span>
</EmailUserTooltip>
<span class="text-ink-extra-muted/60 truncate">
to{' '}
@@ -190,17 +160,10 @@ function HeaderTopRow(props: {
currentUserEmail={props.currentUserEmail}
/>
</span>
- <Show when={props.message.internal_date_ts}>
- <Tooltip label={formatFullDate(props.message.internal_date_ts!)}>
- <span class="text-xs text-ink-extra-muted/60 tabular-nums cursor-default shrink-0">
- {formatShortDate(props.message.internal_date_ts!)}
- </span>
- </Tooltip>
- </Show>
<div
classList={{
- 'opacity-0': !props.isHovering && !props.isExpanded,
- 'opacity-100': props.isHovering || props.isExpanded,
+ 'opacity-0': !props.showHeaderToggle,
+ 'opacity-100': props.showHeaderToggle,
}}
>
<Tooltip
@@ -213,6 +176,7 @@ function HeaderTopRow(props: {
<Button
variant="ghost"
size="icon-sm"
+ noTouchResize
onClick={(e) => {
e.stopPropagation();
props.onToggle();
@@ -220,7 +184,7 @@ function HeaderTopRow(props: {
>
<CaretRight
class={cn(
- 'size-3! text-ink-muted/30 transition-transform',
+ 'size-3! text-ink-muted transition-transform duration-150 ease-out',
props.isExpanded && 'rotate-90'
)}
/>
@@ -237,6 +201,16 @@ function HeaderTopRow(props: {
hiddenActions={props.hiddenActions}
/>
</div>
+ <Show when={props.message.internal_date_ts}>
+ <Tooltip
+ as="span"
+ label={formatFullDate(props.message.internal_date_ts!)}
+ >
+ <span class="text-ink-extra-muted/60 tabular-nums shrink-0">
+ {formatShortDate(props.message.internal_date_ts!)}
+ </span>
+ </Tooltip>
+ </Show>
</div>
);
}
@@ -244,61 +218,44 @@ function HeaderTopRow(props: {
export function EmailMessageTopBar(props: EmailMessageTopBarProps) {
const [isHovering, setIsHovering] = createSignal(false);
const userEmail = useEmail();
- const context = useEmailContext();
-
- // Wraps setExpandedHeader with scroll compensation.
- // The message list uses flex-col-reverse, so expanding the header
- // shifts content above upward. This adjusts scrollTop to keep the
- // visual position stable.
- const toggleExpandedHeader = (expanded: boolean) => {
- const scrollContainer = context.messagesListRef();
- if (!scrollContainer) {
- props.setExpandedHeader(expanded);
- return;
- }
- const prevScrollHeight = scrollContainer.scrollHeight;
- const prevScrollTop = scrollContainer.scrollTop;
- props.setExpandedHeader(expanded);
- requestAnimationFrame(() => {
- const delta = scrollContainer.scrollHeight - prevScrollHeight;
- scrollContainer.scrollTop = prevScrollTop - delta;
- });
- };
- const senderName = createMemo(() =>
- getSenderDisplayName(props.message, userEmail())
- );
+ const senderName = () => getSenderDisplayName(props.message, userEmail());
- const shouldIgnoreClick = (target: Element) =>
- target.localName === 'button' ||
- target.localName === 'svg' ||
- target.localName === 'path' ||
- target.tagName === 'SPAN' ||
- target.closest('[role="tooltip"]');
+ const showHeaderToggle = () =>
+ isHovering() ||
+ props.expandedHeader() ||
+ (isTouchDevice() && props.isBodyExpanded());
- const handleClick = (e: MouseEvent) => {
+ const handleHeaderClick = (e: MouseEvent) => {
const id = props.message.db_id;
if (id) props.setFocusedMessageId(id);
- if (shouldIgnoreClick(e.target as Element)) return;
- if (id) props.setExpandedBodyId(id, !props.isBodyExpanded());
+ const target = e.target;
+ if (target instanceof Element && target.closest('[data-button]')) {
+ return;
+ }
+ if (id) props.setExpandedBodyId(id, false);
+ // The header consumed the click. Without this the card sees an
+ // already-collapsed row on the way up and expands it straight back.
+ e.stopPropagation();
};
return (
<div
class="ph-no-capture flex flex-col w-full"
- style={{ 'min-height': 'var(--user-icon-width)' }}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
- onClick={handleClick}
>
<Show when={props.isBodyExpanded()}>
- <div class="flex items-center gap-2">
+ <div
+ class="flex items-center min-h-6 gap-2"
+ onClick={handleHeaderClick}
+ >
{props.avatar}
<HeaderTopRow
senderName={senderName()}
- isHovering={isHovering()}
+ showHeaderToggle={showHeaderToggle()}
isExpanded={props.expandedHeader()}
- onToggle={() => toggleExpandedHeader(!props.expandedHeader())}
+ onToggle={() => props.setExpandedHeader(!props.expandedHeader())}
message={props.message}
focused={props.focused}
setShowReply={props.setShowReply}
diff --git a/apps/web/src/features/block-email/component/EmailThreadTitle.tsx b/apps/web/src/features/block-email/component/EmailThreadTitle.tsx
index 6929bcf233..e6ce8f13b1 100644
--- a/apps/web/src/features/block-email/component/EmailThreadTitle.tsx
+++ b/apps/web/src/features/block-email/component/EmailThreadTitle.tsx
@@ -32,7 +32,7 @@ export function EmailThreadTitle(props: {
<CopySubjectButton
subject={props.title}
class={cn(
- 'ml-1.5 select-none text-inherit transition-opacity',
+ 'ml-1.5 select-none text-inherit transition-opacity duration-150 ease',
copyHidden() ? 'opacity-0' : 'opacity-100'
)}
/>
diff --git a/apps/web/src/features/block-email/component/MessageActions.tsx b/apps/web/src/features/block-email/component/MessageActions.tsx
index c21c940ef8..173812fe9f 100644
--- a/apps/web/src/features/block-email/component/MessageActions.tsx
+++ b/apps/web/src/features/block-email/component/MessageActions.tsx
@@ -53,6 +53,7 @@ export function MessageActions(props: {
<Show when={!props.hiddenActions?.includes('reply')}>
<Button
class="size-6 p-0 border-0 bg-transparent rounded text-ink-muted hover:text-ink hover:bg-ink-muted/8"
+ noTouchResize
onClick={onChangeReplyType('reply-all')}
tooltip="Reply"
>
@@ -62,6 +63,7 @@ export function MessageActions(props: {
<Show when={!props.hiddenActions?.includes('forward')}>
<Button
class="size-6 p-0 border-0 bg-transparent rounded text-ink-muted hover:text-ink hover:bg-ink-muted/8"
+ noTouchResize
onClick={onChangeReplyType('forward')}
tooltip="Forward"
>
diff --git a/apps/web/src/features/block-email/component/MessageCard.tsx b/apps/web/src/features/block-email/component/MessageCard.tsx
new file mode 100644
index 0000000000..d6a7a19ef9
--- /dev/null
+++ b/apps/web/src/features/block-email/component/MessageCard.tsx
@@ -0,0 +1,97 @@
+import { useEmailContext } from '@block-email/component/EmailContext';
+import { scrollFocusedCardIntoView } from '@block-email/util/scrollToMessage';
+import { cn } from '@ui';
+import type { JSX } from 'solid-js';
+
+interface MessageCardProps {
+ messageId: string | null | undefined;
+ isSelected: boolean;
+ allowHover: boolean;
+ /**
+ * Click or Enter on the row. Clicks landing on a control inside the card are
+ * excluded so row activation never fights an inner button.
+ */
+ onActivate?: () => void;
+ children: JSX.Element;
+}
+
+/**
+ * The card every thread message sits in, collapsed or expanded. It owns the
+ * chrome and the row-level interactions — selection, hover, focus scrolling —
+ * so both content shapes read identically and a single DOM node carries
+ * `data-message-body-id` across an expand.
+ *
+ * Selection (one message at a time) reads as depth rather than an accent ring:
+ * a drop shadow in light mode, an accent-tinted border in dark mode where a
+ * shadow would be invisible. The border is present in every state so moving the
+ * selection never reflows the list. Hover is the `hover` tint painted *over*
+ * the card background (see the `overlay-*` utility) rather than replacing it,
+ * so the card keeps its lift; the selected card skips the tint so selection
+ * always reads as one settled state.
+ *
+ * There is no focus ring: focusing the card selects it, so the selected styling
+ * is already the focus indicator. A ring would also linger after a collapse,
+ * since this node keeps DOM focus while its content swaps.
+ */
+export function MessageCard(props: MessageCardProps) {
+ const context = useEmailContext();
+
+ const select = () => {
+ if (!props.messageId) return;
+ context.messages.setFocused(props.messageId);
+ };
+
+ const hoverThisRow = () => {
+ if (!props.messageId) return;
+ context.messages.setHovered({ kind: 'message', id: props.messageId });
+ };
+
+ const unhoverThisRow = () => {
+ const hovered = context.messages.hovered();
+ if (hovered?.kind === 'message' && hovered.id === props.messageId) {
+ context.messages.setHovered(undefined);
+ }
+ };
+
+ return (
+ <div class="shrink-0 flex justify-center w-full">
+ <div class="@container/message macro-message-width macro-message-padding w-full">
+ <div
+ class={cn(
+ 'relative p-4 rounded-lg bg-message border border-edge-muted outline-none',
+ props.isSelected
+ ? 'z-1 light-mode:shadow-lg light-mode:shadow-drop-shadow dark-mode:ring-1 dark-mode:ring-accent/40'
+ : props.allowHover && 'hover:overlay-hover'
+ )}
+ style={{ '--user-icon-width': '1rem' }}
+ data-message-body-id={props.messageId}
+ tabIndex={0}
+ onPointerEnter={hoverThisRow}
+ onPointerLeave={unhoverThisRow}
+ onClick={(e) => {
+ // Selection is unconditional: a click that lands on a link or a
+ // button inside the card focuses that child, not the card.
+ select();
+ const target = e.target;
+ if (target instanceof Element && target.closest('[data-button]')) {
+ return;
+ }
+ props.onActivate?.();
+ }}
+ onKeyDown={(e) => {
+ if (e.key !== 'Enter' || !props.onActivate) return;
+ e.preventDefault();
+ e.stopPropagation();
+ props.onActivate();
+ }}
+ onFocus={(e) => {
+ scrollFocusedCardIntoView(e.currentTarget);
+ select();
+ }}
+ >
+ {props.children}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-email/component/MessageContainer.tsx b/apps/web/src/features/block-email/component/MessageContainer.tsx
index 7458cd23d0..acaa07738e 100644
--- a/apps/web/src/features/block-email/component/MessageContainer.tsx
+++ b/apps/web/src/features/block-email/component/MessageContainer.tsx
@@ -4,7 +4,9 @@ import { useEmailContext } from '@block-email/component/EmailContext';
import { EmailInput } from '@block-email/component/EmailInput';
import { EmailMessageBody } from '@block-email/component/EmailMessageBody';
import { EmailMessageTopBar } from '@block-email/component/EmailMessageTopBar';
+import { MessageCard } from '@block-email/component/MessageCard';
import { getSenderMacroId } from '@block-email/util/emailUser';
+import { revealMessageAfterLayout } from '@block-email/util/scrollToMessage';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { FloatingInputLoader } from '@core/component/FloatingInputLoader';
import { ImageGalleryPreview } from '@core/component/ImageGalleryPreview';
@@ -26,8 +28,8 @@ interface MessageContainerProps {
message: ApiMessage;
isFirstMessage: boolean;
isLastMessage: boolean;
- isFocused: boolean;
- isTarget: boolean;
+ isSelected: boolean;
+ allowHover: boolean;
isExpanded: boolean;
markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
}
@@ -198,189 +200,169 @@ export function MessageContainer(props: MessageContainerProps) {
);
};
+ // The card selects itself; expanding is the collapsed row's extra behaviour.
const handleExpand = () => {
- if (props.message.db_id) {
- context.messages.setExpandedBodyId(props.message.db_id, true);
- context.messages.setFocused(props.message.db_id);
- }
+ const messageId = props.message.db_id;
+ if (!messageId) return;
+ context.messages.setExpandedBodyId(messageId, true);
+ revealMessageAfterLayout(
+ messageId,
+ context.messages.list(),
+ context.messagesListRef()
+ );
};
return (
- <Show
- when={isBodyExpanded()}
- fallback={
- <CollapsedMessage
- message={props.message}
- isFocused={props.isFocused}
- onClick={handleExpand}
- onFocus={() => {
- if (props.message.db_id) {
- context.messages.setFocused(props.message.db_id);
- }
- }}
- />
- }
+ <MessageCard
+ messageId={props.message.db_id}
+ isSelected={props.isSelected}
+ allowHover={props.allowHover}
+ onActivate={isBodyExpanded() ? undefined : handleExpand}
>
- {/* Expanded message view */}
- <div class="shrink-0 flex justify-center w-full">
- <div class="macro-message-width macro-message-padding w-full">
- <div
- class="relative rounded-lg overflow-hidden p-4 border"
- style={{ '--user-icon-width': '1rem' }}
- classList={{
- 'bg-accent border-transparent': props.isTarget,
- 'bg-active border-edge': !props.isTarget && props.isFocused,
- 'bg-ink-muted/4 border-transparent':
- !props.isTarget && !props.isFocused,
- }}
- data-message-body-id={props.message.db_id}
- tabIndex={0}
- >
- <div class="flex flex-col min-w-0 gap-2">
- <EmailMessageTopBar
- message={props.message}
- focused={props.isFocused}
- setExpandedBodyId={context.messages.setExpandedBodyId}
- isBodyExpanded={isBodyExpanded}
- expandedHeader={expandedHeader}
- setExpandedHeader={setExpandedHeader}
- setFocusedMessageId={context.messages.setFocused}
- setShowReply={setShowReply}
- isLastMessage={props.isLastMessage}
- hiddenActions={
- !context.permissions().isOwner
- ? ['reply', 'reply-all', 'forward']
- : undefined
- }
- avatar={
- <div class="shrink-0 flex justify-center items-center size-6">
- <UserIcon
- {...senderIconProps()}
- isDeleted={false}
- size="fill"
- suppressClick={true}
- />
- </div>
- }
- />
- <div class="ph-no-capture text-sm text-ink pr-4">
- <EmailMessageBody
- message={props.message}
- personalSenders={context.messages.personalSenders}
- isBodyExpanded={isBodyExpanded}
- setExpandedMessageBody={(id) =>
- context.messages.setExpandedBodyId(id, true)
- }
- setFocusedMessageId={context.messages.setFocused}
- isFirstMessageInThread={props.isFirstMessage}
- isFocused={props.isFocused}
+ <Show
+ when={isBodyExpanded()}
+ fallback={<CollapsedMessage message={props.message} />}
+ >
+ <div class="flex flex-col min-w-0 gap-2 overflow-hidden">
+ <EmailMessageTopBar
+ message={props.message}
+ focused={props.isSelected}
+ setExpandedBodyId={context.messages.setExpandedBodyId}
+ isBodyExpanded={isBodyExpanded}
+ expandedHeader={expandedHeader}
+ setExpandedHeader={setExpandedHeader}
+ setFocusedMessageId={context.messages.setFocused}
+ setShowReply={setShowReply}
+ isLastMessage={props.isLastMessage}
+ hiddenActions={
+ !context.permissions().isOwner
+ ? ['reply', 'reply-all', 'forward']
+ : undefined
+ }
+ avatar={
+ <div class="shrink-0 flex justify-center items-center size-6">
+ <UserIcon
+ {...senderIconProps()}
+ isDeleted={false}
+ size="fill"
+ suppressClick={true}
/>
</div>
- {/* Image attachments */}
- <Show when={imageAttachmentsWithSfs().length > 0}>
- <div class="flex flex-wrap gap-2 mt-2">
- <ImageGalleryPreview
- images={imageAttachmentsWithSfs().map((a) => ({
- id: a.sfs_id!,
- }))}
- variant="small"
- attachmentIds={imageAttachmentsWithSfs().map(
- (a) => a.db_id!
- )}
- />
- </div>
- </Show>
-
- {/* Video attachments */}
- <Show when={videoAttachmentsWithSfs().length > 0}>
- <For each={videoAttachmentsWithSfs()}>
- {(attachment) => (
- <VideoPreview id={attachment.sfs_id!} variant="dynamic" />
- )}
- </For>
- </Show>
+ }
+ />
+ <div class="ph-no-capture text-sm text-ink pr-4">
+ <EmailMessageBody
+ message={props.message}
+ personalSenders={context.messages.personalSenders}
+ isBodyExpanded={isBodyExpanded}
+ setExpandedMessageBody={(id) =>
+ context.messages.setExpandedBodyId(id, true)
+ }
+ setFocusedMessageId={context.messages.setFocused}
+ isFirstMessageInThread={props.isFirstMessage}
+ isFocused={props.isSelected}
+ />
+ </div>
+ {/* Image attachments */}
+ <Show when={imageAttachmentsWithSfs().length > 0}>
+ <div class="flex flex-wrap gap-2 mt-2">
+ <ImageGalleryPreview
+ images={imageAttachmentsWithSfs().map((a) => ({
+ id: a.sfs_id!,
+ }))}
+ variant="small"
+ attachmentIds={imageAttachmentsWithSfs().map((a) => a.db_id!)}
+ />
+ </div>
+ </Show>
- {/* Other attachments (non-media or without sfs_id) */}
- <Show when={otherAttachments().length > 0}>
- <div class="flex flex-row overflow-x-scroll mt-2 gap-2">
- <For each={otherAttachments()}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment.filename ?? '',
- mimeType: attachment.mime_type ?? undefined,
- }}
- onClick={(fileType) =>
- onClickAttachment(attachment, fileType)
- }
- />
- )}
- </For>
- </div>
- </Show>
+ {/* Video attachments */}
+ <Show when={videoAttachmentsWithSfs().length > 0}>
+ <For each={videoAttachmentsWithSfs()}>
+ {(attachment) => (
+ <VideoPreview id={attachment.sfs_id!} variant="dynamic" />
+ )}
+ </For>
+ </Show>
- {/* Draft attachments */}
- <Show
- when={
- draftAttachments().length > 0 ||
- forwardedAttachments().length > 0
- }
- >
- <div class="flex flex-row overflow-x-scroll mt-2 gap-2">
- <For each={draftAttachments()}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment.file_name,
- mimeType: attachment.content_type,
- }}
- />
- )}
- </For>
- <For each={forwardedAttachments()}>
- {(attachment) => (
- <EmailAttachmentPill
- attachment={{
- fileName: attachment.filename ?? '',
- mimeType: attachment.mime_type ?? undefined,
- }}
- />
- )}
- </For>
- </div>
- </Show>
+ {/* Other attachments (non-media or without sfs_id) */}
+ <Show when={otherAttachments().length > 0}>
+ <div class="flex flex-row overflow-x-scroll mt-2 gap-2">
+ <For each={otherAttachments()}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment.filename ?? '',
+ mimeType: attachment.mime_type ?? undefined,
+ }}
+ onClick={(fileType) =>
+ onClickAttachment(attachment, fileType)
+ }
+ />
+ )}
+ </For>
</div>
- <Show when={showInlineReplyArea()}>
- <div class="relative -mx-4 mb-0 border-t border-ink/20 mt-4">
- <Show when={props.isLastMessage && !isTouchDevice()}>
- <FloatingInputLoader
- isLoading={context.query.isFetching}
- loadingText="Loading messages"
+ </Show>
+
+ {/* Draft attachments */}
+ <Show
+ when={
+ draftAttachments().length > 0 || forwardedAttachments().length > 0
+ }
+ >
+ <div class="flex flex-row overflow-x-scroll mt-2 gap-2">
+ <For each={draftAttachments()}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment.file_name,
+ mimeType: attachment.content_type,
+ }}
/>
- </Show>
- <div class="px-4">
- <Switch>
- <Match when={showInlineReplyInput()}>
- <EmailInput
- replyingTo={() => props.message}
- setShowReply={setShowReply}
- draft={draftChild()}
- markdownDomRef={
- props.isLastMessage ? props.markdownDomRef : undefined
- }
- unframed
- />
- </Match>
- <Match when={props.isLastMessage && !isTouchDevice()}>
- <BottomReplyButtons lastMessage={props.message} />
- </Match>
- </Switch>
- </div>
- </div>
+ )}
+ </For>
+ <For each={forwardedAttachments()}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment.filename ?? '',
+ mimeType: attachment.mime_type ?? undefined,
+ }}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ <Show when={showInlineReplyArea()}>
+ <div class="relative -mx-4 mb-0 border-t border-ink/20 mt-4">
+ <Show when={props.isLastMessage && !isTouchDevice()}>
+ <FloatingInputLoader
+ isLoading={context.query.isFetching}
+ loadingText="Loading messages"
+ />
</Show>
+ <div class="px-4">
+ <Switch>
+ <Match when={showInlineReplyInput()}>
+ <EmailInput
+ replyingTo={() => props.message}
+ setShowReply={setShowReply}
+ draft={draftChild()}
+ markdownDomRef={
+ props.isLastMessage ? props.markdownDomRef : undefined
+ }
+ unframed
+ />
+ </Match>
+ <Match when={props.isLastMessage && !isTouchDevice()}>
+ <BottomReplyButtons lastMessage={props.message} />
+ </Match>
+ </Switch>
+ </div>
</div>
- </div>
- </div>
- </Show>
+ </Show>
+ </Show>
+ </MessageCard>
);
}
diff --git a/apps/web/src/features/block-email/component/MessageList.tsx b/apps/web/src/features/block-email/component/MessageList.tsx
index 9e28bfb803..b2dbb5d130 100644
--- a/apps/web/src/features/block-email/component/MessageList.tsx
+++ b/apps/web/src/features/block-email/component/MessageList.tsx
@@ -2,26 +2,30 @@ import { useEmailContext } from '@block-email/component/EmailContext';
import { isScrollingToMessage } from '@block-email/signal/scrollState';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { cn } from '@ui';
+import { Key } from '@solid-primitives/keyed';
+import { Button, cn, Layer } from '@ui';
import {
createEffect,
createMemo,
createSelector,
- Index,
onCleanup,
Show,
} from 'solid-js';
+import {
+ fetchOlderMessages,
+ isTruncatedMiddleMessage,
+ isUnreadMessage,
+ listNeedsOlderPage,
+ threadMessageIsExpanded,
+ truncatedMiddleCount,
+} from '../util/scrollToMessage';
+import { EmailParticipants } from './EmailParticipants';
import { EmailThreadTitle } from './EmailThreadTitle';
import { MessageContainer } from './MessageContainer';
-// Fraction of the list height reserved below the newest message so it rests
-// toward the middle of the view instead of pinned to the bottom edge.
-const LAST_MESSAGE_REST_FRACTION = 0.4;
-
interface MessageListProps {
initialLoadComplete: boolean;
markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
- onScrollPositionChange?: (scrollFromTop: number) => void;
title?: string;
/**
* Full-frame mobile: when nothing is in flow below the list (the collapsed
@@ -29,35 +33,54 @@ interface MessageListProps {
* inset in-scroll so the last message rests above the floating chrome.
*/
underScrollsBottom?: boolean;
+ showMiddleMessages: boolean;
+ hiddenChipFocused: boolean;
+ allowRowHover: boolean;
+ onHiddenChipFocus: () => void;
+ onOpenMiddle: () => void;
}
export function MessageList(props: MessageListProps) {
const getIsScrollingToMessage = isScrollingToMessage.get;
const context = useEmailContext();
- const isFocusedSelector = createSelector(
+ // One selected message at a time, whether it was reached by click, tab, or
+ // arrow keys — they all write the same focused id.
+ const isSelectedSelector = createSelector(
context.messages.focusedID,
(a, b) => !!a && !!b && a === b
);
- const isTargetSelector = createSelector(
- context.messages.targetMessageID,
- (a, b) => a === b
+ const hiddenCount = createMemo(() =>
+ truncatedMiddleCount(context.messages.list().length)
);
-
- // Since the list is bottom-anchored (col-reverse), extra bottom padding is
- // the only way to let the newest message rest above the bottom edge. A
- // thread that fills the screen gets its oldest messages pushed above the
- // fold (still one scroll away) — the newest message resting at a
- // consistent height wins over keeping the whole thread in view.
createEffect(() => {
const list = context.messagesListRef();
- if (!list || isTouchDevice()) return;
- const observer = new ResizeObserver(() => {
- list.style.setProperty(
- '--thread-bottom-pad',
- `${Math.round(list.clientHeight * LAST_MESSAGE_REST_FRACTION)}px`
- );
- // Lets the inline composer cap its height to the visible thread area
+ if (!list) return;
+
+ const applyHeight = () => {
list.style.setProperty('--thread-height', `${list.clientHeight}px`);
+ };
+
+ const maybeFetchOlder = () => {
+ if (
+ !listNeedsOlderPage({
+ initialLoadComplete: props.initialLoadComplete,
+ isScrollingToMessage: getIsScrollingToMessage(),
+ isFetching: context.query.isFetching(),
+ hasMore: context.query.hasMore(),
+ scrollHeight: list.scrollHeight,
+ clientHeight: list.clientHeight,
+ })
+ ) {
+ return;
+ }
+ void fetchOlderMessages(list, context.query.fetchNextPage);
+ };
+
+ applyHeight();
+ maybeFetchOlder();
+ const observer = new ResizeObserver(() => {
+ applyHeight();
+ maybeFetchOlder();
});
observer.observe(list);
onCleanup(() => observer.disconnect());
@@ -66,126 +89,179 @@ export function MessageList(props: MessageListProps) {
return (
<div
class={cn(
- 'pt-1 pb-[calc(1.5rem+var(--thread-bottom-pad,0px))] w-full flex flex-col-reverse items-center overflow-y-scroll overflow-x-hidden scrollbar-hidden text-sm gap-1.5',
- // In-scroll top inset: messages rest below the floating split chrome
- // but under-scroll it.
+ 'pt-1 pb-6 w-full flex flex-col items-center gap-2 overflow-y-scroll overflow-x-hidden [overflow-anchor:none] scrollbar-hidden text-sm scroll-pt-4 scroll-pb-4 scroll-smooth motion-reduce:scroll-auto',
'touch:pt-[calc(var(--mobile-content-inset-top,0)+0.5rem)]',
props.underScrollsBottom &&
'touch:pb-[calc(var(--mobile-content-inset-bottom,0)+1.5rem)]'
)}
ref={context.registerMessagesList}
onscroll={(e) => {
- // Since the list is reversed, calculate scroll from visual top
- const scrollFromTop =
- e.currentTarget.scrollHeight +
- e.currentTarget.scrollTop -
- e.currentTarget.clientHeight;
+ const list = e.currentTarget;
+ const scrollFromTop = list.scrollTop;
- props.onScrollPositionChange?.(scrollFromTop);
-
- // Don't load more if we're programmatically scrolling to a message
if (getIsScrollingToMessage() || !props.initialLoadComplete) return;
- const threshold = 300;
- const isNearBeginning = scrollFromTop <= threshold;
+ const isNearBeginning = scrollFromTop <= 300;
if (
isNearBeginning &&
!context.query.isFetching() &&
context.query.hasMore()
) {
- context.query.fetchNextPage();
+ void fetchOlderMessages(list, context.query.fetchNextPage);
}
}}
>
- <StaticMarkdownContext>
- {/* We use Index because the index of the messages should always be stable and
- only the value changes. This also helps prevent nested inputs from rerendering
- */}
- <Index each={context.messages.list().toReversed()}>
- {(message, index) => {
- // We need the index as if the list was not reversed
- const normalizedIndex = createMemo(() => {
- const listLength = context.messages.list().length;
-
- const normalized = listLength - 1 - index;
-
- // The element at the 0th index isn't actually the first message
- // if there is more data to load so we return -1 so that `isFirstMessage`
- // evaluates to false. This fixes an issue with the "first" message' full
- // html to show in `EmailMessageBody`
- if (normalized === 0 && context.query.hasMore()) {
- return -1;
- }
-
- return normalized;
- });
-
- const isLastMessage = createMemo(() => {
- return (
- normalizedIndex() === (context.messages.list().length ?? 0) - 1
+ <Show when={props.title}>
+ <div class="shrink-0 w-full flex justify-center">
+ <div
+ class={cn(
+ 'macro-message-width macro-message-padding w-full',
+ isTouchDevice() ? 'pt-6 pb-3' : 'pt-12 pb-2.5'
+ )}
+ >
+ <EmailThreadTitle
+ title={props.title ?? ''}
+ copyReveal={isTouchDevice() ? 'always' : 'hover'}
+ class={isTouchDevice() ? 'text-xl pt-1 pb-0' : 'text-2xl pb-1.5'}
+ />
+ <Show when={!isTouchDevice()}>
+ <EmailParticipants />
+ </Show>
+ </div>
+ </div>
+ </Show>
+ <Layer depth={1}>
+ <StaticMarkdownContext>
+ {/* Key by db_id so prepends and refetches keep per-row state. */}
+ <Key each={context.messages.list()} by="db_id">
+ {(message) => {
+ const chronologicalIndex = createMemo(() =>
+ context.messages
+ .list()
+ .findIndex((item) => item.db_id === message().db_id)
);
- });
+ const normalizedIndex = createMemo(() => {
+ // The element at the 0th index isn't actually the first message
+ // if there is more data to load so we return -1 so that `isFirstMessage`
+ // evaluates to false. This fixes an issue with the "first" message' full
+ // html to show in `EmailMessageBody`
+ if (chronologicalIndex() === 0 && context.query.hasMore()) {
+ return -1;
+ }
- const isNewMessage = createMemo(() => {
- return (
- message().labels.find(
- (l) => l.provider_label_id === 'UNREAD'
- ) !== undefined
- );
- });
+ return chronologicalIndex();
+ });
- // A message with an in-progress draft reply stays expanded so the
- // draft remains visible even after newer messages arrive (matches
- // Gmail/Superhuman). Desktop only: mobile edits drafts in a drawer.
- const hasDraft = createMemo(() => {
- const messageID = message().db_id;
- if (!messageID || isTouchDevice()) return false;
- return !!context.drafts.getDraftForMessage(messageID);
- });
+ const isLastMessage = createMemo(() => {
+ return (
+ chronologicalIndex() ===
+ (context.messages.list().length ?? 0) - 1
+ );
+ });
+ const hideMiddle = createMemo(() => {
+ return (
+ !props.showMiddleMessages &&
+ isTruncatedMiddleMessage(
+ chronologicalIndex(),
+ context.messages.list().length
+ )
+ );
+ });
- const isExpanded = createMemo(() => {
- const messageID = message().db_id;
+ // A message with an in-progress draft reply stays expanded so the
+ // draft remains visible even after newer messages arrive (matches
+ // Gmail/Superhuman). Desktop only: mobile edits drafts in a drawer.
+ const hasDraft = createMemo(() => {
+ const messageID = message().db_id;
+ if (!messageID || isTouchDevice()) return false;
+ return !!context.drafts.getDraftForMessage(messageID);
+ });
- if (!messageID) return false;
- const manuallyExpanded =
- context.messages.isBodyExpanded(messageID);
+ const isExpanded = createMemo(() => {
+ const messageID = message().db_id;
+ if (!messageID) return false;
+ return threadMessageIsExpanded({
+ chronologicalIndex: chronologicalIndex(),
+ listLength: context.messages.list().length,
+ expansionOverride:
+ context.messages.expandedBodyIds[messageID],
+ isUnread: isUnreadMessage(message()),
+ hasDraft: hasDraft(),
+ });
+ });
return (
- manuallyExpanded ||
- isLastMessage() ||
- isNewMessage() ||
- hasDraft()
+ <>
+ <Show when={!hideMiddle()}>
+ <MessageContainer
+ isFirstMessage={normalizedIndex() === 0}
+ isLastMessage={isLastMessage()}
+ isSelected={isSelectedSelector(
+ message().db_id ?? undefined
+ )}
+ allowHover={props.allowRowHover}
+ message={message()}
+ isExpanded={isExpanded()}
+ markdownDomRef={
+ isLastMessage() ? props.markdownDomRef : undefined
+ }
+ />
+ </Show>
+ <Show
+ when={
+ chronologicalIndex() === 0 &&
+ !props.showMiddleMessages &&
+ hiddenCount() > 0
+ }
+ >
+ <div class="shrink-0 w-full flex justify-center">
+ <div class="macro-message-width macro-message-padding w-full">
+ <div class="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2">
+ <span
+ aria-hidden="true"
+ class="border-t border-edge-muted"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ class={cn(
+ props.hiddenChipFocused && 'bg-active text-ink'
+ )}
+ data-hidden-messages
+ onPointerEnter={() =>
+ context.messages.setHovered({
+ kind: 'hidden-chip',
+ })
+ }
+ onPointerLeave={() => {
+ if (
+ context.messages.hovered()?.kind ===
+ 'hidden-chip'
+ ) {
+ context.messages.setHovered(undefined);
+ }
+ }}
+ onFocus={() => props.onHiddenChipFocus()}
+ onClick={() => props.onOpenMiddle()}
+ >
+ Show {hiddenCount()} hidden{' '}
+ {hiddenCount() === 1 ? 'message' : 'messages'}
+ </Button>
+ <span
+ aria-hidden="true"
+ class="border-t border-edge-muted"
+ />
+ </div>
+ </div>
+ </div>
+ </Show>
+ </>
);
- });
-
- return (
- <MessageContainer
- isFirstMessage={normalizedIndex() === 0}
- isLastMessage={isLastMessage()}
- isFocused={isFocusedSelector(message().db_id ?? undefined)}
- isTarget={isTargetSelector(message().db_id ?? undefined)}
- message={message()}
- isExpanded={isExpanded()}
- markdownDomRef={
- isLastMessage() ? props.markdownDomRef : undefined
- }
- />
- );
- }}
- </Index>
- </StaticMarkdownContext>
- <Show when={isTouchDevice() && props.title}>
- <div class="shrink-0 w-full flex justify-center pb-3">
- <div class="macro-message-width macro-message-padding w-full">
- <EmailThreadTitle
- title={props.title ?? ''}
- copyReveal="always"
- class="text-xl pt-1 pb-0"
- />
- </div>
- </div>
- </Show>
+ }}
+ </Key>
+ </StaticMarkdownContext>
+ </Layer>
</div>
);
}
diff --git a/apps/web/src/features/block-email/util/formatEmailDate.ts b/apps/web/src/features/block-email/util/formatEmailDate.ts
new file mode 100644
index 0000000000..bac6a5d193
--- /dev/null
+++ b/apps/web/src/features/block-email/util/formatEmailDate.ts
@@ -0,0 +1,30 @@
+import type { DateValue } from '@core/util/date';
+
+export function formatFullDate(date: DateValue): string {
+ return new Date(date)
+ .toLocaleString('en-US', {
+ weekday: 'long',
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZoneName: 'short',
+ })
+ .replace(',', '');
+}
+
+export function formatShortDate(date: DateValue): string {
+ const d = new Date(date);
+ if (d.getFullYear() !== new Date().getFullYear()) {
+ return d.toLocaleDateString('en-US', {
+ month: 'numeric',
+ day: 'numeric',
+ year: '2-digit',
+ });
+ }
+ return d.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ });
+}
diff --git a/apps/web/src/features/block-email/util/scrollToMessage.test.ts b/apps/web/src/features/block-email/util/scrollToMessage.test.ts
new file mode 100644
index 0000000000..92d2317c4d
--- /dev/null
+++ b/apps/web/src/features/block-email/util/scrollToMessage.test.ts
@@ -0,0 +1,435 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from 'vitest';
+import {
+ adjustScrollAfterPrepend,
+ alignmentDelta,
+ fetchOlderMessages,
+ hiddenMessagesControl,
+ isTruncatedMiddleMessage,
+ keyboardRevealDelta,
+ leadingThrottle,
+ listNeedsOlderPage,
+ listScrollBehavior,
+ nearestDelta,
+ pageThenAdvanceDelta,
+ revealDelta,
+ scrollToListEndDelta,
+ scrollToListStartDelta,
+ threadMessageIsExpanded,
+ truncatedMiddleCount,
+} from './scrollToMessage';
+
+function box(element: HTMLElement, top: number, bottom: number): void {
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
+ top,
+ bottom,
+ left: 0,
+ right: 0,
+ width: 0,
+ height: bottom - top,
+ x: 0,
+ y: top,
+ toJSON() {
+ return {};
+ },
+ });
+}
+
+describe('isTruncatedMiddleMessage', () => {
+ it('hides only the middle when there are more than three messages', () => {
+ expect(truncatedMiddleCount(3)).toBe(0);
+ expect(truncatedMiddleCount(6)).toBe(3);
+ expect(isTruncatedMiddleMessage(0, 6)).toBe(false);
+ expect(isTruncatedMiddleMessage(1, 6)).toBe(true);
+ expect(isTruncatedMiddleMessage(3, 6)).toBe(true);
+ expect(isTruncatedMiddleMessage(4, 6)).toBe(false);
+ expect(isTruncatedMiddleMessage(5, 6)).toBe(false);
+ });
+});
+
+describe('hiddenMessagesControl', () => {
+ it('finds the expand control in the list', () => {
+ const list = document.createElement('div');
+ const button = document.createElement('button');
+ button.setAttribute('data-hidden-messages', '');
+ list.append(button);
+ expect(hiddenMessagesControl(list)).toBe(button);
+ });
+});
+
+describe('threadMessageIsExpanded', () => {
+ it('opens the newest message and unread, draft, or manual cards', () => {
+ expect(
+ threadMessageIsExpanded({
+ chronologicalIndex: 2,
+ listLength: 3,
+ isUnread: false,
+ hasDraft: false,
+ })
+ ).toBe(true);
+ expect(
+ threadMessageIsExpanded({
+ chronologicalIndex: 0,
+ listLength: 3,
+ isUnread: true,
+ hasDraft: false,
+ })
+ ).toBe(true);
+ expect(
+ threadMessageIsExpanded({
+ chronologicalIndex: 1,
+ listLength: 3,
+ isUnread: false,
+ hasDraft: false,
+ })
+ ).toBe(false);
+ });
+
+ it('lets an explicit collapse win over newest or unread', () => {
+ expect(
+ threadMessageIsExpanded({
+ chronologicalIndex: 2,
+ listLength: 3,
+ expansionOverride: false,
+ isUnread: false,
+ hasDraft: false,
+ })
+ ).toBe(false);
+ expect(
+ threadMessageIsExpanded({
+ chronologicalIndex: 0,
+ listLength: 3,
+ expansionOverride: false,
+ isUnread: true,
+ hasDraft: false,
+ })
+ ).toBe(false);
+ });
+});
+
+describe('alignmentDelta', () => {
+ it('start-aligns the card to the list top', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 175, 800);
+ box(element, 175, 400);
+ expect(alignmentDelta(container, element, 'start')).toBe(0);
+ box(element, 200, 400);
+ expect(alignmentDelta(container, element, 'start')).toBe(25);
+ });
+
+ it('respects scroll-padding on the list container', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ container.style.scrollPaddingTop = '8px';
+ box(container, 0, 800);
+ box(element, 0, 200);
+ expect(alignmentDelta(container, element, 'start')).toBe(-8);
+ });
+
+ it('end-aligns the card to the list bottom', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 600, 800);
+ expect(alignmentDelta(container, element, 'end')).toBe(0);
+ });
+});
+
+describe('revealDelta', () => {
+ it('does nothing when the card already fits', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 200, 400);
+ expect(revealDelta(container, element)).toBe(0);
+ });
+
+ it('scrolls down when the card grows past the bottom', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 600, 950);
+ expect(revealDelta(container, element)).toBe(150);
+ });
+
+ it('start-aligns a card taller than the list', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 200, 1200);
+ expect(revealDelta(container, element)).toBe(200);
+ });
+});
+
+describe('nearestDelta', () => {
+ it('does nothing when the card sits inside the scrollport', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 200, 400);
+ expect(nearestDelta(container, element)).toBe(0);
+ });
+
+ it('start-aligns when the card top sits above the scroll-padding inset', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ container.style.scrollPaddingTop = '8px';
+ box(container, 0, 800);
+ box(element, 4, 200);
+ expect(nearestDelta(container, element)).toBe(-4);
+ });
+
+ it('start-aligns when the card sits entirely above the list', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, -200, -50);
+ expect(nearestDelta(container, element)).toBe(-200);
+ });
+
+ it('end-aligns a card that sits entirely below the list', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 900, 1100);
+ expect(nearestDelta(container, element)).toBe(300);
+ });
+});
+
+describe('listScrollBehavior', () => {
+ it('returns auto when reduced motion is preferred', () => {
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
+ matches: true,
+ } as MediaQueryList);
+ expect(listScrollBehavior()).toBe('auto');
+ });
+
+ it('returns smooth otherwise', () => {
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
+ matches: false,
+ } as MediaQueryList);
+ expect(listScrollBehavior()).toBe('smooth');
+ });
+});
+
+describe('leadingThrottle', () => {
+ it('allows the first call and blocks calls inside the interval', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ const throttle = leadingThrottle(300);
+ expect(throttle()).toBe(true);
+ vi.setSystemTime(100);
+ expect(throttle()).toBe(false);
+ vi.setSystemTime(300);
+ expect(throttle()).toBe(true);
+ vi.useRealTimers();
+ });
+});
+
+describe('keyboardRevealDelta', () => {
+ it('end-aligns a short card whose bottom is clipped when moving down', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 720, 820);
+ expect(keyboardRevealDelta(container, element, 'next')).toBe(20);
+ });
+
+ it('start-aligns a short card whose top is clipped when moving up', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, -20, 80);
+ expect(keyboardRevealDelta(container, element, 'prev')).toBe(-20);
+ });
+
+ it('does nothing when the card already fits in the scrollport', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 200, 400);
+ expect(keyboardRevealDelta(container, element, 'next')).toBe(0);
+ expect(keyboardRevealDelta(container, element, 'prev')).toBe(0);
+ });
+
+ it('does nothing for a tall card at the bottom so the next message can load', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, -800, 800);
+ expect(keyboardRevealDelta(container, element, 'next')).toBe(0);
+ expect(pageThenAdvanceDelta(container, element, 'next')).toBe(0);
+ });
+});
+
+describe('pageThenAdvanceDelta', () => {
+ it('advances when the card already fits', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 200, 400);
+ expect(pageThenAdvanceDelta(container, element, 'next')).toBe(0);
+ expect(pageThenAdvanceDelta(container, element, 'prev')).toBe(0);
+ });
+
+ it('pages down by the remaining overflow when it is less than a viewport', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 100, 950);
+ expect(pageThenAdvanceDelta(container, element, 'next')).toBe(150);
+ });
+
+ it('pages down by one viewport when overflow is larger', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, 0, 2400);
+ expect(pageThenAdvanceDelta(container, element, 'next')).toBe(800);
+ });
+
+ it('pages up when the card top is above the list', () => {
+ const container = document.createElement('div');
+ const element = document.createElement('div');
+ box(container, 0, 800);
+ box(element, -400, 600);
+ expect(pageThenAdvanceDelta(container, element, 'prev')).toBe(-400);
+ });
+});
+
+describe('scrollToListStartDelta', () => {
+ it('scrolls the leftover distance to the title', () => {
+ const container = document.createElement('div');
+ container.scrollTop = 80;
+ expect(scrollToListStartDelta(container)).toBe(-80);
+ });
+
+ it('is zero when the list is already at the top', () => {
+ const container = document.createElement('div');
+ container.scrollTop = 0;
+ expect(scrollToListStartDelta(container)).toBe(0);
+ });
+});
+
+describe('scrollToListEndDelta', () => {
+ it('scrolls the leftover distance to the bottom', () => {
+ const container = document.createElement('div');
+ Object.defineProperty(container, 'scrollHeight', {
+ value: 1200,
+ writable: true,
+ });
+ Object.defineProperty(container, 'clientHeight', {
+ value: 800,
+ writable: true,
+ });
+ container.scrollTop = 200;
+ expect(scrollToListEndDelta(container)).toBe(200);
+ });
+
+ it('is zero when the list is already at the bottom', () => {
+ const container = document.createElement('div');
+ Object.defineProperty(container, 'scrollHeight', {
+ value: 1200,
+ writable: true,
+ });
+ Object.defineProperty(container, 'clientHeight', {
+ value: 800,
+ writable: true,
+ });
+ container.scrollTop = 400;
+ expect(scrollToListEndDelta(container)).toBe(0);
+ });
+});
+
+describe('adjustScrollAfterPrepend', () => {
+ it('keeps the same card on screen when height grows above', () => {
+ const container = document.createElement('div');
+ let scrollHeight = 200;
+ Object.defineProperty(container, 'scrollHeight', {
+ get: () => scrollHeight,
+ });
+ Object.defineProperty(container, 'clientHeight', { get: () => 150 });
+ container.scrollTop = 50;
+ scrollHeight = 400;
+ adjustScrollAfterPrepend(container, 200, 50);
+ expect(container.scrollTop).toBe(250);
+ });
+
+ it('leaves the title pinned when you were already at the top', () => {
+ const container = document.createElement('div');
+ Object.defineProperty(container, 'scrollHeight', { get: () => 400 });
+ Object.defineProperty(container, 'clientHeight', { get: () => 150 });
+ container.scrollTop = 0;
+ adjustScrollAfterPrepend(container, 200, 0);
+ expect(container.scrollTop).toBe(0);
+ });
+
+ it('leaves the title pinned when the first page did not overflow', () => {
+ const container = document.createElement('div');
+ let scrollHeight = 200;
+ Object.defineProperty(container, 'scrollHeight', {
+ get: () => scrollHeight,
+ });
+ Object.defineProperty(container, 'clientHeight', { get: () => 400 });
+ container.scrollTop = 0;
+ scrollHeight = 500;
+ adjustScrollAfterPrepend(container, 200, 0);
+ expect(container.scrollTop).toBe(0);
+ });
+});
+
+describe('listNeedsOlderPage', () => {
+ const ready = {
+ initialLoadComplete: true,
+ isScrollingToMessage: false,
+ isFetching: false,
+ hasMore: true,
+ scrollHeight: 200,
+ clientHeight: 400,
+ };
+
+ it('fetches when the first page does not overflow', () => {
+ expect(listNeedsOlderPage(ready)).toBe(true);
+ });
+
+ it('waits for overflow scroll once the list is taller than the view', () => {
+ expect(
+ listNeedsOlderPage({ ...ready, scrollHeight: 800, clientHeight: 400 })
+ ).toBe(false);
+ });
+
+ it('does not fetch while loading, scrolling, or finished', () => {
+ expect(listNeedsOlderPage({ ...ready, initialLoadComplete: false })).toBe(
+ false
+ );
+ expect(listNeedsOlderPage({ ...ready, isScrollingToMessage: true })).toBe(
+ false
+ );
+ expect(listNeedsOlderPage({ ...ready, isFetching: true })).toBe(false);
+ expect(listNeedsOlderPage({ ...ready, hasMore: false })).toBe(false);
+ });
+});
+
+describe('fetchOlderMessages', () => {
+ it('uses live scrollTop after the fetch completes', async () => {
+ vi.useFakeTimers();
+ const list = document.createElement('div');
+ let scrollHeight = 200;
+ Object.defineProperty(list, 'scrollHeight', { get: () => scrollHeight });
+ Object.defineProperty(list, 'clientHeight', { get: () => 150 });
+ list.scrollTop = 10;
+
+ const fetchNextPage = vi.fn(async () => {
+ list.scrollTop = 40;
+ scrollHeight = 400;
+ });
+
+ const pending = fetchOlderMessages(list, fetchNextPage);
+ await vi.runAllTimersAsync();
+ await pending;
+
+ expect(list.scrollTop).toBe(240);
+ vi.useRealTimers();
+ });
+});
diff --git a/apps/web/src/features/block-email/util/scrollToMessage.ts b/apps/web/src/features/block-email/util/scrollToMessage.ts
index 14d9c6e17b..676a4b1a4d 100644
--- a/apps/web/src/features/block-email/util/scrollToMessage.ts
+++ b/apps/web/src/features/block-email/util/scrollToMessage.ts
@@ -1,72 +1,357 @@
-import type { ApiMessage } from '@service-email/generated/schemas';
+import { match } from 'ts-pattern';
-/**
- * Scrolls to a message by its ID within a messages container
- * @param messageId - The db_id of the message to scroll to
- * @param messages - Array of messages in the current thread
- * @param messagesContainer - The DOM container holding the message elements
- * @param behavior - Scroll behavior ('smooth' | 'instant' | 'auto')
- * @returns true if message was found and scrolled to, false otherwise
- */
-export function scrollToMessage(
- messageId: string,
- messages: ApiMessage[],
- messagesContainer: HTMLElement,
- {
- behavior = 'smooth',
- reversed = false,
- }: { behavior?: ScrollBehavior; reversed?: boolean }
+export type ScrollAlign = 'start' | 'end' | 'nearest';
+export type NavDirection = 'prev' | 'next';
+
+export type OpenTargetMessage = {
+ db_id?: string | null;
+ labels: Array<{ provider_label_id?: string | null }>;
+};
+
+export function isUnreadMessage(message: OpenTargetMessage): boolean {
+ return message.labels.some((label) => label.provider_label_id === 'UNREAD');
+}
+
+/** Oldest, penultimate, and newest stay visible. Hide the rest when length > 3. */
+export function isTruncatedMiddleMessage(
+ chronologicalIndex: number,
+ length: number
): boolean {
- let messageIndex = messages.findIndex((m) => m.db_id === messageId);
+ return (
+ length > 3 && chronologicalIndex > 0 && chronologicalIndex < length - 2
+ );
+}
+
+export function truncatedMiddleCount(length: number): number {
+ return length > 3 ? length - 3 : 0;
+}
+
+export function hiddenMessagesControl(
+ container: HTMLElement
+): HTMLButtonElement | undefined {
+ const el = container.querySelector('[data-hidden-messages]');
+ return el instanceof HTMLButtonElement ? el : undefined;
+}
+
+export function threadMessageIsExpanded(args: {
+ chronologicalIndex: number;
+ listLength: number;
+ expansionOverride?: boolean;
+ isUnread: boolean;
+ hasDraft: boolean;
+}): boolean {
+ if (args.expansionOverride === false) return false;
+ if (args.expansionOverride === true) return true;
+ return (
+ args.chronologicalIndex === args.listLength - 1 ||
+ args.isUnread ||
+ args.hasDraft
+ );
+}
+
+function scrollportRect(container: HTMLElement) {
+ const rect = container.getBoundingClientRect();
+ const height = container.clientHeight || rect.height;
+ const width = container.clientWidth || rect.width;
+ const top = rect.top + container.clientTop;
+ const left = rect.left + container.clientLeft;
+ return {
+ top,
+ bottom: top + height,
+ left,
+ right: left + width,
+ height,
+ width,
+ };
+}
+
+function scrollPaddingInset(
+ container: HTMLElement,
+ edge: 'top' | 'bottom'
+): number {
+ const style = getComputedStyle(container);
+ return (
+ parseFloat(
+ edge === 'top' ? style.scrollPaddingTop : style.scrollPaddingBottom
+ ) || 0
+ );
+}
+
+/** Respect system motion settings for programmatic list scroll. */
+export function listScrollBehavior(): ScrollBehavior {
+ if (typeof window === 'undefined') return 'auto';
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ? 'auto'
+ : 'smooth';
+}
+
+export function alignmentDelta(
+ container: HTMLElement,
+ element: HTMLElement,
+ align: ScrollAlign
+): number {
+ const port = scrollportRect(container);
+ const elementBox = element.getBoundingClientRect();
+ return match(align)
+ .with('end', () => {
+ const inset = scrollPaddingInset(container, 'bottom');
+ return elementBox.bottom - port.bottom + inset;
+ })
+ .with('start', () => {
+ const inset = scrollPaddingInset(container, 'top');
+ return elementBox.top - port.top - inset;
+ })
+ .with('nearest', () => nearestDelta(container, element))
+ .exhaustive();
+}
+
+/** Native scroll-into-view so the list scroll-padding keeps focus rings in view. */
+export function scrollFocusedCardIntoView(element: HTMLElement): void {
+ element.scrollIntoView({
+ block: 'nearest',
+ inline: 'nearest',
+ behavior: listScrollBehavior(),
+ });
+}
- if (reversed) {
- messageIndex = messages.length - 1 - messageIndex;
+export function messageElement(
+ container: HTMLElement,
+ messages: Array<{ db_id?: string | null }>,
+ messageId: string
+): HTMLElement | undefined {
+ if (!messages.some((message) => message.db_id === messageId))
+ return undefined;
+ const el = container.querySelector(
+ `[data-message-body-id="${CSS.escape(messageId)}"]`
+ );
+ return el instanceof HTMLElement ? el : undefined;
+}
+
+export function alignElementInContainer(
+ container: HTMLElement,
+ element: HTMLElement,
+ align: ScrollAlign,
+ behavior: ScrollBehavior = listScrollBehavior()
+): void {
+ const nativeBehavior: ScrollBehavior =
+ behavior === 'instant' ? 'auto' : behavior;
+ container.scrollBy({
+ top: alignmentDelta(container, element, align),
+ behavior: nativeBehavior,
+ });
+}
+
+/** Scroll only if the card does not intersect the viewport. */
+export function nearestDelta(
+ container: HTMLElement,
+ element: HTMLElement
+): number {
+ const port = scrollportRect(container);
+ const elementBox = element.getBoundingClientRect();
+ const topInset = scrollPaddingInset(container, 'top');
+ const bottomInset = scrollPaddingInset(container, 'bottom');
+ if (elementBox.top < port.top + topInset - 1) {
+ return alignmentDelta(container, element, 'start');
+ }
+ if (elementBox.bottom <= port.top + topInset + 1) {
+ return alignmentDelta(container, element, 'start');
}
+ if (elementBox.top >= port.bottom - bottomInset - 1) {
+ return alignmentDelta(container, element, 'end');
+ }
+ return 0;
+}
- if (messageIndex < 0) {
- return false;
+/** Keep a card in view after it grows. Prefer scrolling down. */
+export function revealDelta(
+ container: HTMLElement,
+ element: HTMLElement
+): number {
+ const port = scrollportRect(container);
+ const elementBox = element.getBoundingClientRect();
+ if (elementBox.height >= port.height) {
+ return alignmentDelta(container, element, 'start');
}
+ if (elementBox.top < port.top) {
+ return alignmentDelta(container, element, 'start');
+ }
+ if (elementBox.bottom > port.bottom) {
+ return alignmentDelta(container, element, 'end');
+ }
+ return 0;
+}
- const targetElement = messagesContainer.children[messageIndex];
+/** Scroll a partially visible short card into view before paging or advancing. */
+export function keyboardRevealDelta(
+ container: HTMLElement,
+ element: HTMLElement,
+ dir: NavDirection
+): number {
+ const port = scrollportRect(container);
+ const elementBox = element.getBoundingClientRect();
+ const topInset = scrollPaddingInset(container, 'top');
+ const bottomInset = scrollPaddingInset(container, 'bottom');
+ const fitsInPort = elementBox.height <= port.height;
- if (!targetElement) {
- return false;
+ // Tall cards page in place; snapping them would fight keyboard paging.
+ if (!fitsInPort) return 0;
+
+ if (dir === 'next') {
+ if (elementBox.top < port.top + topInset - 1) {
+ return alignmentDelta(container, element, 'start');
+ }
+ if (elementBox.bottom > port.bottom - bottomInset + 1) {
+ return alignmentDelta(container, element, 'end');
+ }
+ return 0;
}
- targetElement.scrollIntoView({
- behavior,
- block: 'start',
- });
+ if (elementBox.bottom > port.bottom - bottomInset + 1) {
+ return alignmentDelta(container, element, 'end');
+ }
+ if (elementBox.top < port.top + topInset - 1) {
+ return alignmentDelta(container, element, 'start');
+ }
+ return 0;
+}
- return true;
+/** Page the focused card if it still overflows. 0 means advance to the next card. */
+export function pageThenAdvanceDelta(
+ container: HTMLElement,
+ element: HTMLElement,
+ dir: NavDirection
+): number {
+ const port = scrollportRect(container);
+ const elementBox = element.getBoundingClientRect();
+ const page = port.height;
+ return match(dir)
+ .with('next', () => {
+ const overflow = elementBox.bottom - port.bottom;
+ if (overflow <= 1) return 0;
+ return Math.min(overflow, page);
+ })
+ .with('prev', () => {
+ const topInset = scrollPaddingInset(container, 'top');
+ const overflow = port.top + topInset - elementBox.top;
+ if (overflow <= 1) return 0;
+ return -Math.min(overflow, page);
+ })
+ .exhaustive();
}
-/**
- * Scrolls to the last message in the thread
- * @param messagesContainer - The DOM container holding the message elements
- * @param behavior - Scroll behavior ('smooth' | 'instant' | 'auto')
- */
-function _scrollToLastMessage(
- messagesContainer: HTMLDivElement,
- behavior: ScrollBehavior | 'instant' = 'instant'
+/** Remaining scroll to the thread title. 0 means the list is already at the top. */
+export function scrollToListStartDelta(container: HTMLElement): number {
+ return container.scrollTop > 1 ? -container.scrollTop : 0;
+}
+
+/** Remaining scroll to the list bottom. 0 means the list is already at the end. */
+export function scrollToListEndDelta(container: HTMLElement): number {
+ const maxScroll = container.scrollHeight - container.clientHeight;
+ const remaining = maxScroll - container.scrollTop;
+ return remaining > 1 ? remaining : 0;
+}
+
+/** Leading-edge throttle for repeated keyboard scroll steps. */
+export function leadingThrottle(intervalMs: number): () => boolean {
+ let lastAt = -Infinity;
+ return () => {
+ const now = Date.now();
+ if (now - lastAt < intervalMs) return false;
+ lastAt = now;
+ return true;
+ };
+}
+
+export function revealMessageInView(
+ messageId: string,
+ messages: Array<{ db_id?: string | null }>,
+ container: HTMLElement,
+ behavior: ScrollBehavior = 'smooth'
): void {
+ const element = messageElement(container, messages, messageId);
+ if (!element) return;
+ const top = revealDelta(container, element);
+ if (top === 0) return;
const nativeBehavior: ScrollBehavior =
behavior === 'instant' ? 'auto' : behavior;
- const lastChild = messagesContainer.children[
- messagesContainer.children.length - 1
- ] as HTMLElement | undefined;
+ container.scrollBy({ top, behavior: nativeBehavior });
+}
- if (!lastChild) return;
- // Align the last child to the bottom of the nearest scrolling container
- lastChild.scrollIntoView({ behavior: nativeBehavior, block: 'start' });
+/** Older pages insert above. Keep the card you were reading on screen. */
+export function adjustScrollAfterPrepend(
+ container: HTMLElement,
+ previousScrollHeight: number,
+ previousScrollTop: number
+): void {
+ const delta = container.scrollHeight - previousScrollHeight;
+ if (delta <= 0) return;
+ if (previousScrollTop <= 0) return;
+ container.scrollTop = previousScrollTop + delta;
+}
+
+export function listNeedsOlderPage(args: {
+ initialLoadComplete: boolean;
+ isScrollingToMessage: boolean;
+ isFetching: boolean;
+ hasMore: boolean;
+ scrollHeight: number;
+ clientHeight: number;
+}): boolean {
+ if (!args.initialLoadComplete || args.isScrollingToMessage) return false;
+ if (args.isFetching || !args.hasMore) return false;
+ return args.scrollHeight <= args.clientHeight;
+}
+
+export async function fetchOlderMessages(
+ list: HTMLElement,
+ fetchNextPage: () => unknown
+): Promise<void> {
+ const previousScrollHeight = list.scrollHeight;
+ try {
+ await fetchNextPage();
+ requestAnimationFrame(() => {
+ adjustScrollAfterPrepend(list, previousScrollHeight, list.scrollTop);
+ });
+ } catch {
+ return;
+ }
+}
+
+export function revealMessageAfterLayout(
+ messageId: string,
+ messages: Array<{ db_id?: string | null }>,
+ container: HTMLElement | undefined | null,
+ behavior: ScrollBehavior = 'smooth'
+): void {
+ if (!container) return;
+ requestAnimationFrame(() => {
+ revealMessageInView(messageId, messages, container, behavior);
+ });
}
/**
- * Gets the last message ID from a thread
+ * Scrolls to a message by its ID within a messages container
+ * @param messageId - The db_id of the message to scroll to
* @param messages - Array of messages in the current thread
- * @returns The db_id of the last message, or undefined if no messages
+ * @param messagesContainer - The DOM container holding the message elements
+ * @param behavior - Scroll behavior ('smooth' | 'instant' | 'auto')
+ * @returns true if message was found and scrolled to, false otherwise
*/
-function _getLastMessageId(messages: ApiMessage[]): string | undefined {
- const lastMessage = messages[messages.length - 1];
- return lastMessage?.db_id?.toString();
+export function scrollToMessage(
+ messageId: string,
+ messages: Array<{ db_id?: string | null }>,
+ messagesContainer: HTMLElement,
+ {
+ behavior = 'smooth',
+ align = 'start',
+ }: {
+ behavior?: ScrollBehavior;
+ align?: ScrollAlign;
+ } = {}
+): boolean {
+ const targetElement = messageElement(messagesContainer, messages, messageId);
+ if (!targetElement) return false;
+
+ alignElementInContainer(messagesContainer, targetElement, align, behavior);
+ return true;
}
diff --git a/apps/web/src/features/block-email/util/threadStops.test.ts b/apps/web/src/features/block-email/util/threadStops.test.ts
new file mode 100644
index 0000000000..5d51628997
--- /dev/null
+++ b/apps/web/src/features/block-email/util/threadStops.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import {
+ adjacentStop,
+ enterListStop,
+ nextThreadStop,
+ shownStops,
+ type ThreadStop,
+ threadStopFromHover,
+} from './threadStops';
+
+const message = (index: number): ThreadStop => ({ kind: 'message', index });
+
+describe('shownStops', () => {
+ it('inserts the chip after the first card when the middle is collapsed', () => {
+ expect(
+ shownStops({ length: 6, showMiddle: false, hasComposer: true })
+ ).toEqual([
+ { kind: 'title' },
+ message(0),
+ { kind: 'hidden-chip' },
+ message(4),
+ message(5),
+ { kind: 'composer' },
+ ]);
+ });
+
+ it('lists every card once the middle is open', () => {
+ expect(shownStops({ length: 6, showMiddle: true })).toEqual([
+ { kind: 'title' },
+ message(0),
+ message(1),
+ message(2),
+ message(3),
+ message(4),
+ message(5),
+ ]);
+ });
+});
+
+describe('adjacentStop', () => {
+ const collapsed = shownStops({
+ length: 6,
+ showMiddle: false,
+ hasComposer: true,
+ });
+
+ it('treats the chip as the stop after the first card', () => {
+ expect(adjacentStop(collapsed, message(0), 'next')).toEqual({
+ kind: 'hidden-chip',
+ });
+ expect(adjacentStop(collapsed, { kind: 'hidden-chip' }, 'prev')).toEqual(
+ message(0)
+ );
+ });
+
+ it('treats the chip as the stop before the penultimate card', () => {
+ expect(adjacentStop(collapsed, message(4), 'prev')).toEqual({
+ kind: 'hidden-chip',
+ });
+ expect(adjacentStop(collapsed, { kind: 'hidden-chip' }, 'next')).toEqual(
+ message(4)
+ );
+ });
+
+ it('walks the last shown cards and the composer', () => {
+ expect(adjacentStop(collapsed, message(4), 'next')).toEqual(message(5));
+ expect(adjacentStop(collapsed, message(5), 'next')).toEqual({
+ kind: 'composer',
+ });
+ expect(adjacentStop(collapsed, message(0), 'prev')).toEqual({
+ kind: 'title',
+ });
+ });
+
+ it('steps into the first revealed middle card once open', () => {
+ const opened = shownStops({ length: 6, showMiddle: true });
+ expect(adjacentStop(opened, message(0), 'next')).toEqual(message(1));
+ expect(adjacentStop(opened, message(1), 'prev')).toEqual(message(0));
+ expect(adjacentStop(opened, message(5), 'prev')).toEqual(message(4));
+ });
+});
+
+describe('enterListStop', () => {
+ it('enters at the oldest or newest shown card', () => {
+ const collapsed = shownStops({ length: 6, showMiddle: false });
+ expect(enterListStop(collapsed, 'next')).toEqual(message(0));
+ expect(enterListStop(collapsed, 'prev')).toEqual(message(5));
+ });
+});
+
+describe('threadStopFromHover', () => {
+ const ids = ['a', 'b', 'c'];
+
+ it('maps a hovered card id to its index', () => {
+ expect(threadStopFromHover({ kind: 'message', id: 'b' }, ids)).toEqual(
+ message(1)
+ );
+ });
+
+ it('maps the hidden chip and ignores unknown ids', () => {
+ expect(threadStopFromHover({ kind: 'hidden-chip' }, ids)).toEqual({
+ kind: 'hidden-chip',
+ });
+ expect(threadStopFromHover({ kind: 'message', id: 'missing' }, ids)).toBe(
+ undefined
+ );
+ expect(threadStopFromHover(undefined, ids)).toBe(undefined);
+ });
+});
+
+describe('nextThreadStop', () => {
+ const stops = shownStops({
+ length: 6,
+ showMiddle: false,
+ hasComposer: true,
+ });
+
+ it('steps off the hovered card when nothing is keyboard-selected', () => {
+ expect(
+ nextThreadStop({
+ stops,
+ keyboard: undefined,
+ hover: message(0),
+ dir: 'next',
+ })
+ ).toEqual({ kind: 'hidden-chip' });
+ expect(
+ nextThreadStop({
+ stops,
+ keyboard: undefined,
+ hover: message(0),
+ dir: 'prev',
+ })
+ ).toEqual({ kind: 'title' });
+ });
+
+ it('prefers the keyboard cursor over hover', () => {
+ expect(
+ nextThreadStop({
+ stops,
+ keyboard: message(5),
+ hover: message(0),
+ dir: 'prev',
+ })
+ ).toEqual(message(4));
+ });
+
+ it('enters from the ends when there is no cursor and no hover', () => {
+ expect(
+ nextThreadStop({
+ stops,
+ keyboard: undefined,
+ hover: undefined,
+ dir: 'next',
+ })
+ ).toEqual(message(0));
+ expect(
+ nextThreadStop({
+ stops,
+ keyboard: undefined,
+ hover: undefined,
+ dir: 'prev',
+ })
+ ).toEqual(message(5));
+ });
+});
diff --git a/apps/web/src/features/block-email/util/threadStops.ts b/apps/web/src/features/block-email/util/threadStops.ts
new file mode 100644
index 0000000000..cf741c6a79
--- /dev/null
+++ b/apps/web/src/features/block-email/util/threadStops.ts
@@ -0,0 +1,82 @@
+import {
+ isTruncatedMiddleMessage,
+ type NavDirection,
+ truncatedMiddleCount,
+} from './scrollToMessage';
+
+export type ThreadStop =
+ | { kind: 'title' }
+ | { kind: 'message'; index: number }
+ | { kind: 'hidden-chip' }
+ | { kind: 'composer' };
+
+export type HoveredThreadStop =
+ | { kind: 'message'; id: string }
+ | { kind: 'hidden-chip' };
+
+function sameStop(left: ThreadStop, right: ThreadStop): boolean {
+ if (left.kind !== right.kind) return false;
+ if (left.kind === 'message' && right.kind === 'message') {
+ return left.index === right.index;
+ }
+ return true;
+}
+
+/** Visible reading order: title, shown cards, optional chip, optional composer. */
+export function shownStops(args: {
+ length: number;
+ showMiddle: boolean;
+ hasComposer?: boolean;
+}): ThreadStop[] {
+ const stops: ThreadStop[] = [{ kind: 'title' }];
+ const hideMiddle = !args.showMiddle && truncatedMiddleCount(args.length) > 0;
+ for (let i = 0; i < args.length; i++) {
+ if (hideMiddle && isTruncatedMiddleMessage(i, args.length)) continue;
+ stops.push({ kind: 'message', index: i });
+ if (hideMiddle && i === 0) stops.push({ kind: 'hidden-chip' });
+ }
+ if (args.hasComposer) stops.push({ kind: 'composer' });
+ return stops;
+}
+
+export function adjacentStop(
+ stops: ThreadStop[],
+ current: ThreadStop,
+ dir: NavDirection
+): ThreadStop | undefined {
+ const index = stops.findIndex((stop) => sameStop(stop, current));
+ if (index < 0) return undefined;
+ return dir === 'next' ? stops[index + 1] : stops[index - 1];
+}
+
+/** First Arrow with no cursor: next lands on the oldest card, prev on the newest. */
+export function enterListStop(
+ stops: ThreadStop[],
+ dir: NavDirection
+): ThreadStop | undefined {
+ const messages = stops.filter((stop) => stop.kind === 'message');
+ return dir === 'prev' ? messages.at(-1) : messages[0];
+}
+
+export function threadStopFromHover(
+ hover: HoveredThreadStop | undefined,
+ messageIds: Array<string | undefined>
+): ThreadStop | undefined {
+ if (!hover) return undefined;
+ if (hover.kind === 'hidden-chip') return { kind: 'hidden-chip' };
+ const index = messageIds.indexOf(hover.id);
+ if (index < 0) return undefined;
+ return { kind: 'message', index };
+}
+
+/** Keyboard cursor wins. Otherwise the first arrow steps off the hovered stop. */
+export function nextThreadStop(args: {
+ stops: ThreadStop[];
+ keyboard: ThreadStop | undefined;
+ hover: ThreadStop | undefined;
+ dir: NavDirection;
+}): ThreadStop | undefined {
+ const from = args.keyboard ?? args.hover;
+ if (from) return adjacentStop(args.stops, from, args.dir);
+ return enterListStop(args.stops, args.dir);
+}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index b2d5ee4eaf..5f957594d9 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -156,6 +156,7 @@ body.tauri-ios {
--color-surface: var(--theme-surface, var(--layer-surface));
--color-inset: var(--theme-inset, var(--layer-inset));
--color-lift: var(--theme-lift, var(--layer-lift));
+ --color-message: var(--color-lift);
}
[data-layer][data-depth='0'] {
@@ -936,7 +937,6 @@ a {
@utility macro-message-padding {
@container (width < 936px) { padding-inline: calc(var(--spacing) * 4); }
- @container (width < 640px) { padding-inline: calc(var(--spacing) * 2); }
}
@utility macro-message-margin {
diff --git a/apps/web/src/lib/core/mobile/isTouchDevice.ts b/apps/web/src/lib/core/mobile/isTouchDevice.ts
index eff6b83536..4392fdab6a 100644
--- a/apps/web/src/lib/core/mobile/isTouchDevice.ts
+++ b/apps/web/src/lib/core/mobile/isTouchDevice.ts
@@ -1,23 +1,34 @@
import { createSignal } from 'solid-js';
+// This is a media query that checks if use is using a
+// pointing device, such as a finger on a touch screen.
const coarsePointerQuery =
typeof window !== 'undefined' && typeof window.matchMedia === 'function'
? window.matchMedia('(pointer: coarse)')
: null;
-const [isCoarsePointer, setIsCoarsePointer] = createSignal(
+const [touchFirst, setTouchFirst] = createSignal(
coarsePointerQuery?.matches ?? false
);
-// Tracks the media query live (rather than caching the first answer) so
-// devtools touch emulation toggled after load is picked up reactively.
-coarsePointerQuery?.addEventListener('change', (event) =>
- setIsCoarsePointer(event.matches)
-);
+// Latch ON only. Transient flips to fine are ignored, because the most
+// common cause is DevTools' element picker borrowing the pointer.
+coarsePointerQuery?.addEventListener('change', (event) => {
+ if (event.matches) setTouchFirst(true);
+});
+
+// A real viewport change (device emulation toggled off, rotation, window
+// resize) is a legitimate "the world changed" signal: re-read absolutely.
+// The picker never resizes the viewport, so it can never land here.
+if (coarsePointerQuery) {
+ addEventListener('resize', () => {
+ setTouchFirst(coarsePointerQuery.matches);
+ });
+}
/**
* This function returns true if the device is PRIMARILY touch device, E.g. this should return false for touchscreen laptops. However, the user might still be using a keyboard, e.g. if they have a physical keyboard attached to their iPad. In that case, you may want to use isModality('touch') instead.
*/
export function isTouchDevice(): boolean {
- return isCoarsePointer();
+ return touchFirst();
}
diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md
index f9ec191e8c..6953abc709 100644
--- a/docs/STYLE_GUIDE.md
+++ b/docs/STYLE_GUIDE.md
@@ -184,7 +184,9 @@ TypeScript · `[ui]` UI / UX conventions
(#3898)
- **FE-10** `[solid]` `createEffect` is for external/imperative systems only (DOM APIs,
third-party libs, navigation events) — never for deriving state; use `on()` to make
- dependencies explicit when an effect is warranted. (#3750, #3898 · also: AGENTS.md)
+ dependencies explicit when an effect is warranted. Prefer wrapping the setter over
+ `createEffect(() => { if (signal()) sideEffect() })` when setting a value should also
+ clear related UI, blur a control, or scroll. (#3750, #3898, #6038 · also: AGENTS.md)
- **FE-11** `[solid]` Check `solid-primitives` before writing a custom reactive utility.
(also: AGENTS.md)
- **FE-12** `[async]` `async`/`await` with `try`/`catch`, not `.then()`/`.catch()`
@@ -246,3 +248,6 @@ TypeScript · `[ui]` UI / UX conventions
from `@service-storage/client`, the one owner of entity-type spellings (email
threads alone are stored as `email`, `thread`, and `email_thread`). (#6043 ·
enforced: ast-grep `ts-no-item-type-cast` + `tsx-no-item-type-cast`, CI error)
+- **FE-32** `[ui]` Prefer styling in the component (Tailwind on the markup). Reserve
+ `@utility` in `apps/web/src/index.css` for styles widely shared across many
+ components — not one-off or two-callsite layouts. (#6038 · also: apps/web/AGENTS.md)