Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): move list focus to the row that replaces a removed one (#8228)
teo8ec5e4ab05d9
diff --git a/apps/web/src/components/list/create-list-controller.test.ts b/apps/web/src/components/list/create-list-controller.test.tsindex fa5350e4ac..6173d9df8f 100644--- a/apps/web/src/components/list/create-list-controller.test.ts+++ b/apps/web/src/components/list/create-list-controller.test.ts@@ -67,6 +67,78 @@ describe('createListController', () => {});});+ it("moves focus to the item that takes a removed item's place", () => {+ withRoot(() => {+ const [items, setItems] = createSignal<readonly Item[]>(+ ['a', 'b', 'c', 'd'].map((id) => item(id))+ );+ const list = createListController({+ items,+ getKey: (value: Item) => value.id,+ });++ list.focus.set('b');+ // b and c leave together (archived elsewhere); d takes their place.+ setItems([item('a'), item('d')]);+ expect(+ list.focus.restore(list.focus.requestedKey(), { fallback: 'successor' })+ ?.key+ ).toBe('d');++ list.focus.set('d');+ setItems([item('a')]);+ expect(+ list.focus.restore(list.focus.requestedKey(), { fallback: 'successor' })+ ?.key+ ).toBe('a');+ });+ });++ it('skips rows a successor cannot be, such as a load-more row', () => {+ withRoot(() => {+ const [items, setItems] = createSignal<readonly Item[]>(+ ['a', 'b', 'more'].map((id) => item(id))+ );+ const list = createListController({+ items,+ getKey: (value: Item) => value.id,+ });++ list.focus.set('b');+ // The last loaded email leaves; only the load-more row follows it.+ setItems([item('a'), item('more')]);+ expect(+ list.focus.restore(list.focus.requestedKey(), {+ fallback: 'successor',+ isNavigable: (value) => value.id !== 'more',+ })?.key+ ).toBe('a');+ });+ });++ it('keeps waiting for a removed item when none of its neighbours remain', () => {+ withRoot(() => {+ const [items, setItems] = createSignal<readonly Item[]>([+ item('a'),+ item('b'),+ ]);+ const list = createListController({+ items,+ getKey: (value: Item) => value.id,+ });++ list.focus.set('a');+ // A page reload briefly drops every row; focus must not move.+ setItems([]);+ expect(+ list.focus.restore('a', { fallback: 'successor' })+ ).toBeUndefined();+ expect(list.focus.requestedKey()).toBe('a');+ setItems([item('a'), item('b')]);+ expect(list.focus.key()).toBe('a');+ });+ });+it('skips structural rows and wraps only when requested', () => {withRoot(() => {const values = [item('header', 'Header', true), item('a'), item('b')];diff --git a/apps/web/src/components/list/create-list-controller.ts b/apps/web/src/components/list/create-list-controller.tsindex f9e1b3d6f1..08ba81e2da 100644--- a/apps/web/src/components/list/create-list-controller.ts+++ b/apps/web/src/components/list/create-list-controller.ts@@ -136,6 +136,19 @@ export function createListController<TItem, TMetadata = unknown>(return result && canNavigateTo(result, forcedFocus()) ? result : undefined;});+ // Where the focused item last sat: the list it sat in and its index. Only+ // the reference is kept, so lists pay nothing per change; neighbours are+ // read when a removed item needs a successor.+ const focusedPlace = createMemo<+ { key: ListKey; index: number; all: readonly TItem[] } | undefined+ >((previous) => {+ const focused = focusedResult();+ if (!focused) {+ return previous?.key === requestedFocusKey() ? previous : undefined;+ }+ return { key: focused.key, index: focused.index, all: snapshot().all };+ });+const commitFocus = (nextKey: ListKey | undefined,reason: NonNullable<ListFocusOptions['reason']>,@@ -280,7 +293,7 @@ export function createListController<TItem, TMetadata = unknown>(const restoreFocus = (key: ListKey | undefined,- restoreOptions: ListRestoreFocusOptions = {}+ restoreOptions: ListRestoreFocusOptions<TItem> = {}) => {const reason = restoreOptions.reason ?? 'restore';if (key !== undefined) {@@ -301,6 +314,22 @@ export function createListController<TItem, TMetadata = unknown>(restoreOptions.nearestIndex ?? focusedResult()?.index ?? 0,{ ...restoreOptions, reason });+ case 'successor': {+ const place = focusedPlace();+ if (key !== undefined && place?.key === key) {+ const { all, index } = place;+ const neighbours = [+ ...all.slice(index + 1),+ ...all.slice(0, index).reverse(),+ ];+ for (const neighbour of neighbours) {+ const result = itemResultFor(options.getKey(neighbour));+ if (!result || !matchesNavigation(result, restoreOptions)) continue;+ return focusResult(result, { ...restoreOptions, reason });+ }+ }+ return restoreFocus(key, { ...restoreOptions, fallback: 'none' });+ }case 'none':commitFocus(restoreOptions.retainUnavailable !== false &&diff --git a/apps/web/src/components/list/types.ts b/apps/web/src/components/list/types.tsindex 9d7f999928..6438579c08 100644--- a/apps/web/src/components/list/types.ts+++ b/apps/web/src/components/list/types.ts@@ -33,12 +33,24 @@ export type ListNavigationOptions<TItem> = ListFocusOptions & {wrap?: boolean;};-/** Fallback used when a requested restoration key is not currently present. */-export type ListFocusFallback = 'none' | 'first' | 'last' | 'nearest';+/**+ * Fallback used when a requested restoration key is not currently present.+ * `successor` moves to the item that took the key's place: its nearest+ * surviving neighbour from when it was last focused, later items first. With+ * no surviving neighbour the key is retained, as with `none`.+ */+export type ListFocusFallback =+ | 'none'+ | 'first'+ | 'last'+ | 'nearest'+ | 'successor';/** Options for restoring focus from persisted view state. */-export type ListRestoreFocusOptions = ListFocusOptions & {+export type ListRestoreFocusOptions<TItem = unknown> = ListFocusOptions & {fallback?: ListFocusFallback;+ /** Fallbacks skip items this rejects (a load-more row, a heading). */+ isNavigable?: (item: TItem, index: number) => boolean;/** Center point for a nearest fallback. */nearestIndex?: number;/** Keep an unavailable key as the restoration anchor. Defaults to true. */diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex 6233bb5011..9139e4c85c 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -1,6 +1,10 @@import { QueuedSendStatus } from '../../email-compose/queued-send-status';import '@entity/composed/ListEntity.css';-import { type ListActivation, useListInteractions } from '@app/components/list';+import {+ type ListActivation,+ type ListKey,+ useListInteractions,+} from '@app/components/list';import { CommandState } from '@app/features/command/state';import {resolveEntityActionViewContext,@@ -52,6 +56,7 @@ import {Suspense,Switch,} from 'solid-js';+import type { CacheSnapshot } from 'virtua';import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';import {persistSoupNavigationTouchHighlight,@@ -89,6 +94,22 @@ export type EmailListProps = {pane?: EmailListPane;};+/**+ * Each split's last measured list, so a list that remounts after a thread+ * closes lays its rows out as before and its saved offset lands on the same+ * rows. Bounded: one entry per recently used split.+ */+const savedLayouts = new Map<+ string,+ {+ scope: string;+ cache: CacheSnapshot;+ offset: number;+ focusKey: ListKey | undefined;+ }+>();+const MAX_SAVED_LAYOUTS = 20;+export function EmailList(props: EmailListProps) {const {state,@@ -174,6 +195,9 @@ export function EmailList(props: EmailListProps) {createScrollTopFade(viewport);const [topSpacer, setTopSpacer] = createSignal<HTMLDivElement>();const topSpacerSize = createElementSize(topSpacer);+ // The virtualizer's item offsets exclude this; its scroll offset includes it.+ const listStartMargin = () =>+ isTouchDevice() ? (topSpacerSize.height ?? 0) : 0;const [emptyViewport, setEmptyViewport] = createSignal<HTMLDivElement>();const [grid, setGrid] = createSignal<HTMLDivElement>();// Coming back from a thread, or toggling the reading pane, remounts the@@ -189,7 +213,10 @@ export function EmailList(props: EmailListProps) {DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES);+ // Kept as the user scrolls: the virtualizer drops its handle while it+ // unmounts, before this list's state is saved.let scrollOffset = DEFAULT_EMAIL_LIST_STATE.scrollOffset;+ let lastHandle: VirtualizerHandle | undefined;const readListState = (): EmailListStateSnapshot => ({focusKey: list.focus.requestedKey(),scrollOffset: virtualizer()?.scrollOffset ?? scrollOffset,@@ -419,12 +446,44 @@ export function EmailList(props: EmailListProps) {}let restoredScroll = false;+ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });function registerVirtualizer(handle?: VirtualizerHandle) {setVirtualizer(handle);+ if (handle) lastHandle = handle;if (!handle || restoredScroll) return;-- handle.scrollTo(scrollOffset);restoredScroll = true;+ // The virtualizer measures its viewport after this ref runs; a scroll+ // issued against a zero-height viewport lands in the wrong place.+ let frames = 0;+ const restore = () => {+ if (disposed) return;+ if (handle.viewportSize === 0 && frames++ < 30) {+ requestAnimationFrame(restore);+ return;+ }+ handle.scrollTo(scrollOffset);+ if (!resumed || list.focus.requestedKey() === resumed.focusKey) return;+ requestAnimationFrame(() => {+ if (!disposed) revealFocusedRow(handle);+ });+ };+ requestAnimationFrame(restore);+ }+ // j/k in the open thread moves list focus. Returning keeps the list where+ // it was and scrolls only when focus moved meanwhile to a row now off+ // screen; a row the user scrolled away from stays where it is.+ function revealFocusedRow(handle: VirtualizerHandle) {+ const focused = list.focus.index();+ if (focused < 0) return;+ const top = listStartMargin() + handle.getItemOffset(focused);+ const bottom = top + handle.getItemSize(focused);+ const viewTop = handle.scrollOffset;+ if (top < viewTop || bottom > viewTop + handle.viewportSize) {+ handle.scrollToIndex(focused, { align: 'nearest' });+ }}const hasEmailRows = () => rows().some((row) => row.kind === 'entity');@@ -456,6 +515,31 @@ export function EmailList(props: EmailListProps) {const listScope = () =>`${state.tab}|${state.inboxIds === undefined ? '*' : state.inboxIds.join(',')}|${state.aliasFilter?.emailAddress ?? ''}`;let activeScope = listScope();+ const layoutKey = panel.handle.id;+ const savedLayout = savedLayouts.get(layoutKey);+ // Closing a thread opens the list as a new history entry with no state of+ // its own; resume from this split's last layout. Back and Forward restore+ // their entry's own state instead.+ const traversed = panel.handle.lastNavigationCause().startsWith('history-');+ const resumed =+ !traversed && savedLayout?.scope === activeScope ? savedLayout : undefined;+ const initialCache = resumed?.cache;+ if (resumed) scrollOffset = resumed.offset;+ onCleanup(() => {+ const handle = lastHandle;+ if (!handle) return;+ savedLayouts.delete(layoutKey);+ savedLayouts.set(layoutKey, {+ scope: activeScope,+ cache: handle.cache,+ offset: scrollOffset,+ focusKey: list.focus.requestedKey(),+ });+ if (savedLayouts.size > MAX_SAVED_LAYOUTS) {+ const oldest = savedLayouts.keys().next().value;+ if (oldest !== undefined) savedLayouts.delete(oldest);+ }+ });createEffect(() => {const nextScope = listScope();if (nextScope === activeScope) return;@@ -473,10 +557,18 @@ export function EmailList(props: EmailListProps) {if (list.focus.result()) return;- const restored = list.focus.restore(list.focus.requestedKey(), {- retainUnavailable: false,+ // A row that left the list (archived from its open thread or on another+ // device) hands focus to the row that took its place, which sits where+ // the removed row was, so the list does not scroll for it.+ const requested = list.focus.requestedKey();+ const restored = list.focus.restore(requested, {+ fallback: 'successor',+ isNavigable: (row) => row.kind === 'entity',});if (restored) return;+ // Without a surviving neighbour the key waits only while rows are still+ // arriving; otherwise (search results, a stale saved key) take the first.+ if (requested !== undefined && !hasEmailRows()) return;if (isTouchDevice()) return;list.focus.first({@@ -623,11 +715,10 @@ export function EmailList(props: EmailListProps) {<Suspense><Virtualizerref={registerVirtualizer}+ cache={initialCache}data={rows()}scrollRef={viewport()}- startMargin={- isTouchDevice() ? (topSpacerSize.height ?? 0) : 0- }+ startMargin={listStartMargin()}bufferSize={500}itemSize={44}keepMounted={@@ -635,7 +726,8 @@ export function EmailList(props: EmailListProps) {? [list.focus.index()]: undefined}- onScroll={() => {+ onScroll={(offset) => {+ scrollOffset = offset;scrollAnchor.capture();checkNearEnd();}}diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 08dadc520c..bf96548cb5 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -410,7 +410,11 @@ where the list is already beside the thread). The subject, tags andparticipants stay put while only the messages scroll. Pressing `Escape` in the open threadwith focus outside any input does the same once there is nothing left to unwind(an open reply, an expanded body, or a focused message each take one `Escape`-first); the list keeps the row you came from focused. The `⋯` email title menu+first); the list keeps the row you came from focused and comes back at the same+scroll position, scrolling only if j/k in the thread moved focus off screen. If+the focused row leaves the list without a list `e` (a reply in Signal marks it+done, or another device archives it), focus moves to the row that took its+place, not the first row. The `⋯` email title menuright after the subject's last word, in place of Copy subject, holds **Ask AI**,**Create a Task**, and the other thread actions. On desktop, **Mark as unread**, **Mark done**,and reminders share one outlined group at the right of that header. Separate