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: add soup and channel scroll state to split history (#4317)

Peter Chinman9bac34dbd73e
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index dfbffebc21..1c639df333 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -351,15 +351,13 @@ const useSoupNotificationInvalidators = () => {
);
};
-const listStateCache = new Map<
- string,
- {
- focus: string | undefined;
- searchText: string;
- virtualCache?: CacheSnapshot;
- scrollOffset?: number;
- }
->();
+const SOUP_LIST_STATE_ENTRY_KEY = 'soup.listState';
+
+type SoupListEntryState = {
+ focus: string | undefined;
+ virtualCache?: CacheSnapshot;
+ scrollOffset?: number;
+};
interface SoupViewProps {
viewName: string;
@@ -719,7 +717,6 @@ export const SoupViewList = (props: SoupViewListProps) => {
source,
rows,
searchText,
- setSearchText,
featuredIds,
isSearchServiceLoading,
isLocalSearchSettling,
@@ -1012,7 +1009,10 @@ export const SoupViewList = (props: SoupViewListProps) => {
const isProjectList = panel.handle.content().type === 'project';
const contentId = panel.handle.content().id;
- const cacheKey = `soup-view-${panel.handle.id}-${contentId}${previewPanel ? '-preview' : ''}`;
+ const readListEntryState = () =>
+ panel.handle.currentEntryState()?.[SOUP_LIST_STATE_ENTRY_KEY] as
+ | SoupListEntryState
+ | undefined;
// Preview-pane open state is transient per history entry: captured into
// per-entry state on nav-away and restored on back/forward. Read
@@ -1046,32 +1046,42 @@ export const SoupViewList = (props: SoupViewListProps) => {
);
onCleanup(groupByCaptorTeardown);
- onCleanup(() => {
- if (isProjectList) return;
- const virtualHandle = virtualizerHandle();
- listStateCache.set(cacheKey, {
- searchText: searchText(),
- focus: soup.focus.id(),
- virtualCache: virtualHandle?.cache,
- scrollOffset: virtualHandle?.scrollOffset,
- });
- });
+ if (!isProjectList) {
+ const listStateCaptorTeardown = panel.handle.registerEntryStateCaptor(
+ SOUP_LIST_STATE_ENTRY_KEY,
+ (): SoupListEntryState => {
+ const virtualHandle = virtualizerHandle();
+ return {
+ focus: soup.focus.id(),
+ virtualCache: virtualHandle?.cache,
+ scrollOffset: virtualHandle?.scrollOffset,
+ };
+ }
+ );
+ onCleanup(listStateCaptorTeardown);
+ }
// Handles restoring scroll + focus.
let restored = false;
- const restoreListState = () => {
- if (restored || isProjectList) return;
- restored = true;
+ const restoreListState = (force = false) => {
+ if (isProjectList) return;
+ if (restored && !force) return;
- const cached = listStateCache.get(cacheKey);
+ const cached = readListEntryState();
if (cached) {
- setSearchText(cached.searchText);
soup.focus.set(cached.focus);
- virtualizerHandle()?.scrollTo(cached.scrollOffset ?? 0);
+ const handle = virtualizerHandle();
+ if (!handle) return;
+
+ handle.scrollTo(cached.scrollOffset ?? 0);
+ restored = true;
registerFocusEffects(false);
return;
}
+ if (force) return;
+
+ restored = true;
registerFocusEffects();
};
@@ -1080,7 +1090,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
) => {
setVirtualizerHandle(handle);
- restoreListState();
+ if (handle) restoreListState();
};
const featuredCount = createMemo(() => featuredIds().length);
@@ -1204,7 +1214,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
setCollapseEntity={soup.collapseEntity.set}
>
<SoupList
- cache={listStateCache.get(cacheKey)?.virtualCache}
+ cache={readListEntryState()?.virtualCache}
ref={(el) => {
setLocalEntityListRef(el);
soupNavigationTouchHighlight(el);
diff --git a/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx b/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
index c4a2da9eb5..2347768336 100644
--- a/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
+++ b/js/app/packages/app/component/split-layout/components/PopoverSplitRenderer.tsx
@@ -88,6 +88,7 @@ function PopoverSplitModal(props: {
referredFrom: () => null,
lastNavigationCause: () => 'fresh',
registerEntryStateCaptor: () => () => {},
+ captureEntryState: () => {},
currentEntryState: () => undefined,
};
diff --git a/js/app/packages/app/component/split-layout/layoutManager.ts b/js/app/packages/app/component/split-layout/layoutManager.ts
index 49a9622f14..20b6dfa13b 100644
--- a/js/app/packages/app/component/split-layout/layoutManager.ts
+++ b/js/app/packages/app/component/split-layout/layoutManager.ts
@@ -422,6 +422,12 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {
* keyed by `key`. Returns a teardown.
*/
registerEntryStateCaptor: (key: string, getter: () => unknown) => () => void;
+ /**
+ * Immediately capture registered entry-state slices into the split's current
+ * history entry. This is usually done implicitly on navigation, but here we offer
+ * an explicit handle to trigger it manually, e.g. for mobile to manage it's split.
+ */
+ captureEntryState: () => void;
/**
* Read the `state` blob attached to this split's *current* history entry.
* Returns `undefined` if no state has been captured.
@@ -560,7 +566,7 @@ export function createSplitLayout(
if (idx < 0 || idx >= items.length) return;
const currentItem = items[idx];
- const state: EntryState = {};
+ const state: EntryState = { ...(currentItem.state ?? {}) };
for (const [key, getter] of captors) {
try {
state[key] = getter();
@@ -1014,6 +1020,11 @@ export function createSplitLayout(
if (map.size === 0) entryStateCaptors.delete(currentSplit.id);
};
},
+ captureEntryState: () => {
+ const live = s();
+ if (!live) return;
+ captureCurrentEntryState(live);
+ },
currentEntryState: () => {
const live = s();
if (!live) return undefined;
diff --git a/js/app/packages/app/component/split-layout/mobile/createMobileSplitMotion.ts b/js/app/packages/app/component/split-layout/mobile/createMobileSplitMotion.ts
index 3fa0292bae..f3a2f186d2 100644
--- a/js/app/packages/app/component/split-layout/mobile/createMobileSplitMotion.ts
+++ b/js/app/packages/app/component/split-layout/mobile/createMobileSplitMotion.ts
@@ -46,7 +46,6 @@ export function createMobileSplitMotion(options: MobileSplitMotionOptions) {
const forwardPhase = forwardAnimation.phase;
const forwardIsActive = () => forwardPhase() !== 'idle';
- const forwardIsAnimating = () => forwardPhase() === 'animating';
function styleForSlot(isForeground: boolean) {
if (forwardIsActive()) {
@@ -60,9 +59,7 @@ export function createMobileSplitMotion(options: MobileSplitMotionOptions) {
'absolute inset-0',
{
'z-10': isForeground && !forwardIsActive(),
- 'z-0 pointer-events-none':
- (!isForeground && !forwardIsActive()) ||
- (isForeground && forwardIsAnimating()),
+ 'z-0 pointer-events-none': !isForeground && !forwardIsActive(),
'z-user-highlight pointer-events-none':
!isForeground && forwardIsActive(),
},
@@ -70,7 +67,7 @@ export function createMobileSplitMotion(options: MobileSplitMotionOptions) {
!swipeBackGesture.isDragging() &&
!swipeBackGesture.isAnimatingOut() &&
!forwardIsActive() &&
- 'hidden'
+ 'invisible'
);
}
diff --git a/js/app/packages/app/component/split-layout/mobile/createMobileSwipeLayout.ts b/js/app/packages/app/component/split-layout/mobile/createMobileSwipeLayout.ts
index 29ecbb17ae..356ec05b82 100644
--- a/js/app/packages/app/component/split-layout/mobile/createMobileSwipeLayout.ts
+++ b/js/app/packages/app/component/split-layout/mobile/createMobileSwipeLayout.ts
@@ -102,6 +102,8 @@ export function createMobileSwipeLayout(
? splitManager.getSplit(currentBgId)
: undefined;
+ fgHandle?.captureEntryState();
+
// If the target is already mounted in BG, promote it instead of recreating it.
if (bgHandle && sameContent(bgHandle.content(), content)) {
if (forwardNavigationTrigger) {
diff --git a/js/app/packages/app/component/split-layout/tests/layoutManager.test.ts b/js/app/packages/app/component/split-layout/tests/layoutManager.test.ts
index 6c5e4954f0..f773301031 100644
--- a/js/app/packages/app/component/split-layout/tests/layoutManager.test.ts
+++ b/js/app/packages/app/component/split-layout/tests/layoutManager.test.ts
@@ -3,7 +3,7 @@ import { createRoot } from 'solid-js';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { createSplitLayout, type SplitContent } from '../layoutManager';
-vi.mock('../componentRegistry.tsx', () => ({
+vi.mock('../componentRegistry', () => ({
resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({
type: 'mock-component',
id,
@@ -11,7 +11,10 @@ vi.mock('../componentRegistry.tsx', () => ({
})),
}));
-vi.mock('zod', () => ({ z: undefined }));
+vi.mock('@core/constant/allBlocks', () => ({
+ isBlockAlias: vi.fn(() => false),
+ resolveBlockAlias: vi.fn((type: string) => type),
+}));
beforeAll(() => {
// Mock window.matchMedia for tests
@@ -118,4 +121,37 @@ describe('layoutManager', () => {
});
});
});
+
+ describe('entry state', () => {
+ it('captures registered entry state and merges with existing state', () => {
+ createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ {
+ type: 'component',
+ id: 'unified-list',
+ state: { existing: true },
+ },
+ ]);
+
+ const split = manager.getSplit(manager.splits()[0].id)!;
+ split.registerEntryStateCaptor('soup.listState', () => ({
+ scrollOffset: 120,
+ focus: 'entity-1',
+ }));
+
+ split.captureEntryState();
+
+ expect(split.currentEntryState()).toEqual({
+ existing: true,
+ 'soup.listState': {
+ scrollOffset: 120,
+ focus: 'entity-1',
+ },
+ });
+ expect(split.history()[0].state).toEqual(split.currentEntryState());
+
+ dispose();
+ });
+ });
+ });
});
diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
index 6032978143..964aea01be 100644
--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
@@ -2,6 +2,7 @@ import { useBlockEntityCommands } from '@app/component/next-soup/actions';
import { useMaybePreviewPanel } from '@app/component/PreviewPanel';
import { HeaderIsland } from '@app/component/split-layout/components/HeaderIsland';
import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHeader';
+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';
import { globalSplitManager } from '@app/signal/splitLayout';
import { URL_PARAMS } from '@block-channel/constants';
@@ -18,6 +19,7 @@ import {
} from '@channel/Call';
import {
type ChannelHandle,
+ type ChannelMessagesStateSnapshot,
type ChannelProps,
Channel as NewChannel,
} from '@channel/Channel/Channel';
@@ -59,6 +61,8 @@ import {
} from 'solid-js';
import { ChannelTopLeft } from './Top';
+const CHANNEL_STATE_ENTRY_KEY = 'channel.state';
+
type ChannelTargetMessageParams = {
[URL_PARAMS.message]?: string;
[URL_PARAMS.thread]?: string;
@@ -68,6 +72,11 @@ type ChannelTargetMessageParams = {
export type BlockChannelProps = ChannelTargetMessageParams;
+type ChannelEntryStateSnapshot = {
+ activeTab?: ChannelTabId;
+ messages?: ChannelMessagesStateSnapshot;
+};
+
type ChannelPropsTargetMessage = Pick<
ChannelProps,
'targetMessageId' | 'targetMessageReplyId'
@@ -95,11 +104,12 @@ const normalizeChannelTab = (tab: ChannelTabId) => {
const initialChannelTab = (options: {
wantsJoinCall: boolean;
hasActiveCallHere: boolean;
+ persistedTab?: ChannelTabId;
}) => {
return normalizeChannelTab(
options.wantsJoinCall || options.hasActiveCallHere
? 'call'
- : DEFAULT_CHANNEL_TAB
+ : (options.persistedTab ?? DEFAULT_CHANNEL_TAB)
);
};
@@ -171,6 +181,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
useBlockEntityCommands();
const isPreview = !!useMaybePreviewPanel();
+ const splitPanel = useSplitPanelOrThrow();
const { navigatedFromJK } = useNavigatedFromJK();
const channelId = useBlockId();
const blockHandle = blockHandleSignal.get;
@@ -189,9 +200,43 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
const hasActiveCallHere = !!(
callCtx?.isInCall() && callCtx.activeChannelId() === channelId
);
+ const persistedChannelState = (
+ isPreview
+ ? undefined
+ : splitPanel.handle.currentEntryState()?.[CHANNEL_STATE_ENTRY_KEY]
+ ) as ChannelEntryStateSnapshot | undefined;
+
+ const hasInitialTargetRequest = () => {
+ const hasPropsTarget =
+ props[URL_PARAMS.message] !== undefined ||
+ props[URL_PARAMS.thread] !== undefined;
+ if (hasPropsTarget) return true;
+
+ const isSingleSplit = globalSplitManager()?.splits().length === 1;
+ if (!isSingleSplit) return false;
+
+ return (
+ searchParams[URL_PARAMS.message] !== undefined ||
+ searchParams[URL_PARAMS.thread] !== undefined
+ );
+ };
+
+ const shouldHydratePersistedChannelState =
+ !isPreview &&
+ !wantsJoinCall &&
+ !hasActiveCallHere &&
+ !isOpenCallTabRequested(props[CHANNEL_URL_PARAMS.openCallTab]) &&
+ !isOpenCallTabRequested(searchParams[CHANNEL_URL_PARAMS.openCallTab]) &&
+ !hasInitialTargetRequest();
const [activeTab, setActiveTabInternal] = createSignal<ChannelTabId>(
- initialChannelTab({ wantsJoinCall, hasActiveCallHere })
+ initialChannelTab({
+ wantsJoinCall,
+ hasActiveCallHere,
+ persistedTab: shouldHydratePersistedChannelState
+ ? persistedChannelState?.activeTab
+ : undefined,
+ })
);
const [pendingJoinCall, setPendingJoinCall] = createSignal(wantsJoinCall);
@@ -199,6 +244,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
// A signal so goToLocationFromParams can await it via the orchestrator's
// availability primitive when the tab hasn't mounted yet.
const [messagesHandle, setMessagesHandle] = createSignal<ChannelHandle>();
+ let lastMessagesStateSnapshot = persistedChannelState?.messages;
const setActiveTab = (tab: ChannelTabId) => {
tab = normalizeChannelTab(tab);
@@ -312,6 +358,30 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
setMessagesHandle(() => handle);
};
+ if (!isPreview) {
+ const disposeChannelStateCaptor =
+ splitPanel.handle.registerEntryStateCaptor(
+ CHANNEL_STATE_ENTRY_KEY,
+ (): ChannelEntryStateSnapshot => {
+ const handle = messagesHandle();
+ const messages = handle
+ ? handle.getMessagesStateSnapshot()
+ : lastMessagesStateSnapshot;
+ lastMessagesStateSnapshot = messages;
+ return {
+ activeTab: activeTab(),
+ messages,
+ };
+ }
+ );
+ onCleanup(disposeChannelStateCaptor);
+ }
+
+ const initialMessagesStateSnapshot = () =>
+ shouldHydratePersistedChannelState
+ ? persistedChannelState?.messages
+ : undefined;
+
return (
<EntityPermissionsGate entityType="channel" entityId={channelId}>
<CallEventSync />
@@ -337,6 +407,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
channelId={channelId}
onHandleReady={onChannelReady}
autofocus={!isPreview && !navigatedFromJK()}
+ initialMessagesStateSnapshot={initialMessagesStateSnapshot()}
{...convertTargetMessage(initialTargetMessageParams())}
/>
</Match>
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index 2877bc72c1..7f4678ed31 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -91,10 +91,14 @@ import {
defaultThreadListTargetFromMessage,
ThreadList,
type ThreadListNavigation,
+ type ThreadListScrollSnapshot,
type ThreadListScrollState,
type ThreadListScrollTarget,
} from './ThreadList';
-import { createThreadManager } from './thread-manager';
+import {
+ createThreadManager,
+ type ThreadManagerSnapshot,
+} from './thread-manager';
import { createThreadPaginator } from './thread-paginator';
export type ChannelProps = {
@@ -102,13 +106,20 @@ export type ChannelProps = {
targetMessageId?: string | undefined;
targetMessageReplyId?: string | undefined;
lastViewedAt?: DateValue | null;
+ initialMessagesStateSnapshot?: ChannelMessagesStateSnapshot;
onHandleReady?: (handle: ChannelHandle) => void;
/** Whether to auto-focus the channel input on mount. Defaults to `!isMobile()`. */
autofocus?: boolean;
};
+export type ChannelMessagesStateSnapshot = {
+ scroll?: ThreadListScrollSnapshot;
+ threads?: ThreadManagerSnapshot;
+};
+
export type ChannelHandle = {
goToMessage: TargetMessageController['goToMessage'];
+ getMessagesStateSnapshot: () => ChannelMessagesStateSnapshot | undefined;
};
export function Channel(props: ChannelProps) {
@@ -219,7 +230,9 @@ export function Channel(props: ChannelProps) {
markAsViewed();
});
- const threadManager = createThreadManager();
+ const threadManager = createThreadManager(
+ props.initialMessagesStateSnapshot?.threads
+ );
const [isChannelInputHidden, setIsChannelInputHidden] = createSignal(false);
const [channelInputEl, setChannelInputEl] = createSignal<HTMLDivElement>();
const threadPaginator = createThreadPaginator(messagesQuery);
@@ -370,6 +383,21 @@ export function Channel(props: ChannelProps) {
targetMessageController.goToMessage(messageId, replyId);
};
+ const [threadListScrollSnapshot, setThreadListScrollSnapshot] = createSignal<
+ ThreadListScrollSnapshot | undefined
+ >(props.initialMessagesStateSnapshot?.scroll);
+
+ const getMessagesStateSnapshot: ChannelHandle['getMessagesStateSnapshot'] =
+ () => {
+ const scroll = threadListScrollSnapshot();
+ const threads = threadManager.getSnapshot();
+ if (!scroll && !threads) return undefined;
+ return {
+ ...(scroll ? { scroll } : {}),
+ ...(threads ? { threads } : {}),
+ };
+ };
+
const findBar = createChannelFindBar({
channelId: () => props.channelId,
goToMessage,
@@ -457,6 +485,7 @@ export function Channel(props: ChannelProps) {
if (props.onHandleReady)
props.onHandleReady({
goToMessage,
+ getMessagesStateSnapshot,
});
})
);
@@ -495,6 +524,12 @@ export function Channel(props: ChannelProps) {
onScrollNearBottom={threadPaginator.prependPaginate}
onNavigationReady={setThreadListNavigation}
onScrollStateChange={setThreadListScrollState}
+ initialScrollSnapshot={
+ props.targetMessageId
+ ? undefined
+ : props.initialMessagesStateSnapshot?.scroll
+ }
+ onScrollSnapshotChange={setThreadListScrollSnapshot}
>
{(item) => {
const message = () => messageById().get(item.id);
diff --git a/js/app/packages/channel/Channel/ThreadList.tsx b/js/app/packages/channel/Channel/ThreadList.tsx
index 770ca77e23..136793efb3 100644
--- a/js/app/packages/channel/Channel/ThreadList.tsx
+++ b/js/app/packages/channel/Channel/ThreadList.tsx
@@ -5,7 +5,7 @@ import {
} from '@core/util/scroll-intent';
import { type Accessor, createSignal, type JSX } from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
-import type { ScrollToIndexOpts } from 'virtua/unstable_core';
+import type { CacheSnapshot, ScrollToIndexOpts } from 'virtua/unstable_core';
import { NEAR_BOTTOM_THRESHOLD } from './constants';
const BASE_ITEM_SIZE: number = 64;
@@ -19,6 +19,10 @@ export type ThreadListScrollTarget =
| { tag: 'index'; index: number; align?: ScrollAlignment }
| { tag: 'id'; id: string; align?: ScrollAlignment };
+type InitialScrollTarget =
+ | ThreadListScrollTarget
+ | { tag: 'offset'; scrollOffset: number };
+
export function defaultThreadListTargetFromMessage(
targetMessageId: string | undefined
): ThreadListScrollTarget {
@@ -59,6 +63,12 @@ export type ThreadListScrollState = {
viewportSize: number;
};
+export type ThreadListScrollSnapshot = {
+ scrollOffset: number;
+ virtualCache?: CacheSnapshot;
+ isNearBottom: boolean;
+};
+
export type FullFrameThreadListScrollInsets = {
/** Space reserved before the first message (e.g. status bar + floating header). */
start: number;
@@ -74,6 +84,8 @@ type ThreadListProps = {
onScrollNearBottom?: () => void;
onNavigationReady?: (navigation: ThreadListNavigation) => void;
onScrollStateChange?: (state: ThreadListScrollState) => void;
+ initialScrollSnapshot?: ThreadListScrollSnapshot;
+ onScrollSnapshotChange?: (snapshot: ThreadListScrollSnapshot) => void;
shift?: Accessor<boolean>;
prepend?: Accessor<boolean>;
/**
@@ -150,8 +162,7 @@ export function ThreadList(props: ThreadListProps) {
let initialScrollStarted = false;
let initialScrollRetried = false;
- let initialScrollTarget: ThreadListScrollTarget =
- DEFAULT_INITIAL_SCROLL_TARGET;
+ let initialScrollTarget: InitialScrollTarget = DEFAULT_INITIAL_SCROLL_TARGET;
const resetInitialScroll = () => {
initialScrollStarted = false;
@@ -189,6 +200,16 @@ export function ThreadList(props: ThreadListProps) {
return true;
};
+ const scrollToInitialTarget = (
+ handle: VirtualizerHandle,
+ target: InitialScrollTarget
+ ): boolean => {
+ if (target.tag !== 'offset') return scrollToTarget(handle, target);
+
+ handle.scrollTo(target.scrollOffset);
+ return true;
+ };
+
// DOM-based so the scroll insets are accounted for — virtua's scrollSize
// only covers its own items, not the inset padding around them.
const getDistanceFromBottom = (handle: VirtualizerHandle): number => {
@@ -203,9 +224,11 @@ export function ThreadList(props: ThreadListProps) {
const isScrollPositionCorrect = (
handle: VirtualizerHandle,
- target: ThreadListScrollTarget
+ target: InitialScrollTarget
): boolean => {
switch (target.tag) {
+ case 'offset':
+ return Math.abs(handle.scrollOffset - target.scrollOffset) <= 1;
case 'bottom':
return getDistanceFromBottom(handle) <= NEAR_BOTTOM_THRESHOLD;
case 'top':
@@ -255,6 +278,15 @@ export function ThreadList(props: ThreadListProps) {
const completeInitialScroll = (handle: VirtualizerHandle) => {
setDidInitialScroll(true);
emitScrollState(handle, false);
+ emitScrollSnapshot(handle);
+ };
+
+ const emitScrollSnapshot = (handle: VirtualizerHandle) => {
+ props.onScrollSnapshotChange?.({
+ scrollOffset: handle.scrollOffset,
+ virtualCache: handle.cache,
+ isNearBottom: getDistanceFromBottom(handle) <= NEAR_BOTTOM_THRESHOLD,
+ });
};
const createNavigation = (
@@ -301,11 +333,10 @@ export function ThreadList(props: ThreadListProps) {
markUserIntent: scrollIntent.markUserIntent,
});
- function scrollOnMount(handle: VirtualizerHandle) {
- if (initialScrollStarted) return;
- initialScrollStarted = true;
-
- const target = props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;
+ function beginInitialTargetScroll(
+ handle: VirtualizerHandle,
+ target: InitialScrollTarget
+ ) {
initialScrollTarget = target;
console.debug('ThreadList: scrollOnMount', {
@@ -316,7 +347,7 @@ export function ThreadList(props: ThreadListProps) {
viewportSize: handle.viewportSize,
});
- const didScroll = scrollToTarget(handle, target);
+ const didScroll = scrollToInitialTarget(handle, target);
if (!didScroll) {
// Empty list or target not found — nothing to verify.
@@ -341,6 +372,28 @@ export function ThreadList(props: ThreadListProps) {
});
}
+ function scrollOnMount(handle: VirtualizerHandle) {
+ if (initialScrollStarted) return;
+ initialScrollStarted = true;
+
+ const snapshot = props.initialScrollSnapshot;
+ if (snapshot) {
+ if (snapshot.isNearBottom) {
+ beginInitialTargetScroll(handle, DEFAULT_INITIAL_SCROLL_TARGET);
+ } else {
+ beginInitialTargetScroll(handle, {
+ tag: 'offset',
+ scrollOffset: snapshot.scrollOffset,
+ });
+ }
+
+ return;
+ }
+
+ const target = props.initialScrollTarget ?? DEFAULT_INITIAL_SCROLL_TARGET;
+ beginInitialTargetScroll(handle, target);
+ }
+
const handleScrollEnd = () => {
if (didInitialScroll()) return;
@@ -366,7 +419,10 @@ export function ThreadList(props: ThreadListProps) {
distanceFromBottom: getDistanceFromBottom(handle),
});
requestAnimationFrame(() => {
- const retryScrolled = scrollToTarget(handle, initialScrollTarget);
+ const retryScrolled = scrollToInitialTarget(
+ handle,
+ initialScrollTarget
+ );
if (!retryScrolled) {
// Target disappeared between mount and retry — finalize now since
// no scroll events will fire to trigger another onScrollEnd.
@@ -424,6 +480,7 @@ export function ThreadList(props: ThreadListProps) {
}
previousScrollOffset = handle.scrollOffset;
emitScrollState(handle, nextIsScrollingDown);
+ emitScrollSnapshot(handle);
if (!didInitialScroll()) return;
@@ -474,6 +531,7 @@ export function ThreadList(props: ThreadListProps) {
/>
<div style="flex-grow: 1" />
<Virtualizer
+ cache={props.initialScrollSnapshot?.virtualCache}
ref={(ref) => {
if (!ref) return;
setVirtualHandle(ref);
diff --git a/js/app/packages/channel/Channel/tests/thread-manager.test.ts b/js/app/packages/channel/Channel/tests/thread-manager.test.ts
new file mode 100644
index 0000000000..4325325cb4
--- /dev/null
+++ b/js/app/packages/channel/Channel/tests/thread-manager.test.ts
@@ -0,0 +1,72 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { createThreadManager } from '../thread-manager';
+
+describe('createThreadManager', () => {
+ it('hydrates thread state from a snapshot', () => {
+ createRoot((dispose) => {
+ const manager = createThreadManager({
+ expanded: { isExpanded: true },
+ replying: {
+ isReplying: true,
+ },
+ });
+
+ const expanded = manager.getOrCreateThreadState('expanded');
+ const replying = manager.getOrCreateThreadState('replying');
+
+ expect(expanded.isExpanded()).toBe(true);
+ expect(expanded.isReplying()).toBe(false);
+ expect(replying.isExpanded()).toBe(true);
+ expect(replying.isReplying()).toBe(true);
+
+ dispose();
+ });
+ });
+
+ it('serializes only non-default thread state', () => {
+ createRoot((dispose) => {
+ const replyInputState = {
+ value: 'draft reply',
+ mentions: [],
+ attachments: [],
+ };
+ const manager = createThreadManager({
+ replying: {
+ isReplying: true,
+ },
+ });
+
+ manager.getOrCreateThreadState('default');
+ manager.getOrCreateThreadState('expanded').setIsExpanded(true);
+ manager
+ .getOrCreateThreadState('draft')
+ .setReplyInputState(replyInputState);
+
+ expect(manager.getSnapshot()).toEqual({
+ replying: {
+ isReplying: true,
+ },
+ expanded: {
+ isExpanded: true,
+ },
+ });
+
+ dispose();
+ });
+ });
+
+ it('clears restored thread state after a materialized thread returns to defaults', () => {
+ createRoot((dispose) => {
+ const manager = createThreadManager({
+ expanded: { isExpanded: true },
+ });
+
+ manager.getOrCreateThreadState('expanded').setIsExpanded(false);
+
+ expect(manager.getSnapshot()).toBeUndefined();
+
+ dispose();
+ });
+ });
+});
diff --git a/js/app/packages/channel/Channel/thread-manager.ts b/js/app/packages/channel/Channel/thread-manager.ts
index de217be412..11b7800ba9 100644
--- a/js/app/packages/channel/Channel/thread-manager.ts
+++ b/js/app/packages/channel/Channel/thread-manager.ts
@@ -5,12 +5,25 @@ import type { ThreadState } from '../Thread';
import { createFocusRequest } from '../Thread/focus-request';
type ThreadStore = Record<string, ThreadState>;
-export function createThreadManager() {
+
+export type ThreadStateSnapshot = {
+ isExpanded?: boolean;
+ isReplying?: boolean;
+};
+
+export type ThreadManagerSnapshot = Record<string, ThreadStateSnapshot>;
+
+export function createThreadManager(initialSnapshot?: ThreadManagerSnapshot) {
const [threadStore, setThreadStore] = createStore<ThreadStore>({});
function initThreadState(threadId: string): ThreadState {
- const [isExpanded, setIsExpanded] = createSignal<boolean>(false);
- const [isReplying, setIsReplyingRaw] = createSignal<boolean>(false);
+ const snapshot = initialSnapshot?.[threadId];
+ const initialIsReplying = snapshot?.isReplying ?? false;
+ const [isExpanded, setIsExpanded] = createSignal<boolean>(
+ snapshot?.isExpanded || initialIsReplying
+ );
+ const [isReplying, setIsReplyingRaw] =
+ createSignal<boolean>(initialIsReplying);
const [replyInputState, setReplyInputState] = createSignal<
InputSnapshot | undefined
>();
@@ -64,7 +77,29 @@ export function createThreadManager() {
return initThreadState(threadId);
}
+ // Passed up via messagesHandle to get called by split history captor on navigation, so that we can restore thread state on history navigation
+ function getSnapshot(): ThreadManagerSnapshot | undefined {
+ const snapshot: ThreadManagerSnapshot = { ...(initialSnapshot ?? {}) };
+
+ for (const [threadId, state] of Object.entries(threadStore)) {
+ const isExpanded = state.isExpanded();
+ const isReplying = state.isReplying();
+ if (!isExpanded && !isReplying) {
+ delete snapshot[threadId];
+ continue;
+ }
+
+ snapshot[threadId] = {
+ ...(isExpanded ? { isExpanded } : {}),
+ ...(isReplying ? { isReplying } : {}),
+ };
+ }
+
+ return Object.keys(snapshot).length > 0 ? snapshot : undefined;
+ }
+
return {
getOrCreateThreadState,
+ getSnapshot,
};
}