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.

unified-list: replace virtua with tanstack virtual (#740)

Caleb Taylor354505c11cef
diff --git a/js/app/bun.lock b/js/app/bun.lock
index d185e676b6..a5f05e7754 100644
--- a/js/app/bun.lock
+++ b/js/app/bun.lock
@@ -1,5 +1,6 @@
{
"lockfileVersion": 1,
+ "configVersion": 0,
"workspaces": {
"": {
"name": "@coparse/monorepo",
@@ -55,6 +56,7 @@
"@tailwindcss/vite": "^4.1.14",
"@tanstack/solid-query": "^5.90.3",
"@tanstack/solid-query-devtools": "^5.90.3",
+ "@tanstack/solid-virtual": "^3.13.13",
"@tauri-apps/plugin-http": "~2",
"@tauri-apps/plugin-notification": "~2",
"@tauri-apps/plugin-os": "~2",
@@ -1132,6 +1134,10 @@
"@tanstack/solid-query-devtools": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-devtools": "5.90.1" }, "peerDependencies": { "@tanstack/solid-query": "^5.90.3", "solid-js": "^1.6.0" } }, "sha512-UWb2/tHgHrMetOHrQFCzpivCJyttG7vb6axav/aiih9CN5PArxb6um1/7eOuWTb43vSRaMt2LP2Dj3fhixtDZA=="],
+ "@tanstack/solid-virtual": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/virtual-core": "3.13.13" }, "peerDependencies": { "solid-js": "^1.3.0" } }, "sha512-ym4LhX2CygATku2gvs6StE16J6BwzB+5PoMXH5gUcNRwfTJLTB47ZBt3lAJru6uFjFoRdHN/8emfiQXm9Armuw=="],
+
+ "@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-uQFoSdKKf5S8k51W5t7b2qpfkyIbdHMzAn+AMQvHPxKUPeo1SsGaA4JRISQT87jm28b7z8OEqPcg1IOZagQHcA=="],
+
"@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw=="],
"@tauri-apps/plugin-http": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-x1mQKHSLDk4mS2S938OTeyk8L7QyLpCrKZCZcjkljGsvTvRMojCvI9SeJ1kaxc7t8xSilkC7WdId8xER9TIGLg=="],
diff --git a/js/app/package.json b/js/app/package.json
index 598239a0f7..6eb4adb5a3 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -94,6 +94,7 @@
"@tailwindcss/vite": "^4.1.14",
"@tanstack/solid-query": "^5.90.3",
"@tanstack/solid-query-devtools": "^5.90.3",
+ "@tanstack/solid-virtual": "^3.13.13",
"@tauri-apps/plugin-http": "~2",
"@tauri-apps/plugin-notification": "~2",
"@tauri-apps/plugin-os": "~2",
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index 39b5291f10..d347d88db5 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -47,7 +47,6 @@ import {
onCleanup,
type ParentComponent,
Show,
- Suspense,
Switch,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
@@ -81,6 +80,24 @@ const ViewTab: ParentComponent<{
);
};
+let runSuspenseWarningLog = false;
+const SuspenseUnifiedListFallback = () => {
+ const runWarningLog = () => {
+ if (!runSuspenseWarningLog) {
+ setTimeout(() => {
+ runSuspenseWarningLog = true;
+ });
+ return;
+ }
+
+ console.warn('UnifiedList Suspsense Triggered');
+ };
+
+ runWarningLog();
+
+ return null;
+};
+
const ViewWithSearch: Component<{
viewId: ViewId;
}> = (props) => {
@@ -90,17 +107,17 @@ const ViewWithSearch: Component<{
<Match
when={props.viewId === 'email' && DEFAULT_VIEWS.includes('email')}
>
- <Suspense>
+ <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
<EmailView />
- </Suspense>
+ </SuspenseContextComp>
</Match>
<Match when={props.viewId === 'all' && DEFAULT_VIEWS.includes('all')}>
- <Suspense>
+ <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
<AllView />
- </Suspense>
+ </SuspenseContextComp>
</Match>
<Match when={true}>
- <SuspenseContextComp fallback={''}>
+ <SuspenseContextComp fallback={<SuspenseUnifiedListFallback />}>
<UnifiedListView />
</SuspenseContextComp>
</Match>
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
index a28e4396b0..c1f409bf09 100644
--- a/js/app/packages/app/component/SoupContext.tsx
+++ b/js/app/packages/app/component/SoupContext.tsx
@@ -25,6 +25,7 @@ import {
import { storageServiceClient } from '@service-storage/client';
import { createLazyMemo } from '@solid-primitives/memo';
import { useQuery } from '@tanstack/solid-query';
+import type { Virtualizer } from '@tanstack/solid-virtual';
import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import {
type Accessor,
@@ -44,7 +45,6 @@ import {
type SetStoreFunction,
type Store,
} from 'solid-js/store';
-import type { VirtualizerHandle } from 'virtua/solid';
import { useUserId } from '../../macro-entity/src/queries/auth';
import { createBulkCopyDssEntityMutation } from '../../macro-entity/src/queries/dss';
import { playSound } from '../util/sound';
@@ -85,7 +85,7 @@ export type UnifiedListContext = {
setViewDataStore: SetStoreFunction<Partial<ViewDataMap>>;
selectedView: Accessor<ViewId>;
setSelectedView: Setter<ViewId>;
- virtualizerHandleSignal: Signal<VirtualizerHandle | undefined>;
+ virtualizerHandleSignal: Signal<Virtualizer<Element, Element> | undefined>;
entityListRefSignal: Signal<HTMLDivElement | undefined>;
entitiesSignal: Signal<EntityData[] | undefined>;
emailViewSignal: Signal<PreviewViewStandardLabel>;
@@ -128,7 +128,7 @@ export function createSoupContext(): UnifiedListContext {
const [viewsDataStore, setViewDataStore] = useAllViews({
selectedViewSignal: [selectedView, setSelectedView],
});
- const virtualizerHandleSignal = createSignal<VirtualizerHandle>();
+ const virtualizerHandleSignal = createSignal<Virtualizer<Element, Element>>();
const entityListRefSignal = createSignal<HTMLDivElement>();
const entitiesSignal = createSignal<EntityData[]>();
const emailViewSignal = createSignal<PreviewViewStandardLabel>('inbox');
@@ -333,6 +333,8 @@ export function createNavigationEntityListShortcut({
entity: EntityData | null | undefined,
clearSelection?: boolean
) => {
+ const virtualizer = virtualizerHandle();
+ const virtualItems = virtualizer?.getVirtualItems() || [];
if (clearSelection) {
setViewDataStore(selectedView(), 'multiSelectEntities', []);
}
@@ -340,9 +342,14 @@ export function createNavigationEntityListShortcut({
setSelectedEntity(entity);
const nextIndex = entities()?.findIndex(({ id }) => id === entity.id);
if (nextIndex !== undefined && nextIndex > -1) {
- virtualizerHandle()?.scrollToIndex(nextIndex, {
- align: 'nearest',
- });
+ const start = virtualItems[0]?.index;
+ const end = virtualItems.at(-1)?.index ?? 0;
+
+ if (nextIndex < start) {
+ virtualizer?.scrollToIndex(nextIndex, { align: 'start' });
+ } else if (nextIndex > end) {
+ virtualizer?.scrollToIndex(nextIndex, { align: 'end' });
+ }
waitForFrames(2).then(() => {
const elem = getEntityElAtIndex(nextIndex);
if (elem instanceof HTMLElement) {
@@ -352,9 +359,7 @@ export function createNavigationEntityListShortcut({
}
});
} else {
- const handle = virtualizerHandle();
- if (!handle) return;
- const firstIndex = handle.findItemIndex(handle.scrollOffset);
+ const firstIndex = virtualItems.at(0)?.index;
if (!firstIndex) return;
const elem = getEntityElAtIndex(firstIndex);
if (elem instanceof HTMLElement) elem.focus();
@@ -901,15 +906,17 @@ export function createNavigationEntityListShortcut({
const entityEl = entityListRef()?.querySelector('[data-entity]');
const scrollParent = getScrollParent(entityEl);
-
const getAdjecentEl = async () => {
- virtualizerHandle()?.scrollToIndex(index, {
- // align: mode === 'jump' && axis === 'end' ? 'end' : undefined,
- // align: align(),
- // align: index() < virtuaRef()!.findItemIndex(virtuaRef()!.scrollOffset) ? 'start' : 'end',
- align: 'nearest',
- // offset: 50,
- });
+ const virtualizer = virtualizerHandle();
+ const virtualItems = virtualizer?.getVirtualItems() || [];
+ const start = virtualItems[0]?.index;
+ const end = virtualItems.at(-1)?.index ?? 0;
+
+ if (index < start) {
+ virtualizer?.scrollToIndex(index, { align: 'start' });
+ } else if (index > end) {
+ virtualizer?.scrollToIndex(index, { align: 'end' });
+ }
if (mode === 'jump') {
await new Promise<true>((resolve) =>
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 8492b56424..1f57bfb667 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -216,8 +216,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
);
const splitContext = useSplitPanelOrThrow();
- const { isPanelActive, unifiedListContext, panelRef, previewState } =
- splitContext;
+ const { isPanelActive, unifiedListContext, previewState } = splitContext;
const [preview] = previewState;
const {
viewsDataStore: viewsData,
@@ -243,7 +242,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
const entityListResetScroll = () => {
setSelectedEntity(entities_()?.at(0));
- virtualizerHandle()?.scrollTo(0);
+ virtualizerHandle()?.scrollToOffset(0);
};
const rawSearchText = createMemo<string>(() => view()?.searchText ?? '');
@@ -257,17 +256,6 @@ export function UnifiedListView(props: UnifiedListViewProps) {
setEntityListRef(localEntityListRef);
if (view()?.hasUserInteractedEntity) {
- const selectedEntityId = selectedEntity()?.id;
- if (selectedEntityId) {
- if (localEntityListRef?.isConnected) {
- // focusing non-first entity causes issue where 100ms later, that focused entity loses focus and document.body is focused
- // forcing refocus on that entity works for now
- // read TODO inside function for more info
- tryFocusEntity(selectedEntityId, {
- forceRefocusOnce: true,
- });
- }
- }
return;
}
@@ -275,57 +263,6 @@ export function UnifiedListView(props: UnifiedListViewProps) {
if (!firstEntity) return;
setSelectedEntity(firstEntity);
-
- tryFocusEntity(firstEntity.id);
-
- function tryFocusEntity(
- entityId: string,
- { forceRefocusOnce }: { forceRefocusOnce: boolean } = {
- forceRefocusOnce: false,
- }
- ) {
- setTimeout(() => {
- const dontFocus = () => {
- if (!localEntityListRef) return true;
- // don't steal focus outside of entityList
- if (
- !(
- document.activeElement === document.body ||
- document.activeElement === panelRef() ||
- localEntityListRef.contains(document.activeElement)
- )
- ) {
- return true;
- }
- return false;
- };
-
- if (dontFocus()) return;
-
- const focusElement = localEntityListRef?.querySelector(
- `[data-entity-id="${entityId}"]`
- );
-
- if (focusElement instanceof HTMLElement) {
- focusElement.focus({ preventScroll: true });
-
- // TODO: figure out what's causing document.body to be focused
- // 100ms later or so, document.body is focused, despite focueElement still connected, and not shuffled
- // without this, createMenu on close doesn't refocus on entity
- if (forceRefocusOnce) {
- focusElement.addEventListener(
- 'blur',
- () => {
- if (dontFocus()) return;
-
- focusElement.focus({ preventScroll: true });
- },
- { once: true }
- );
- }
- }
- });
- }
}
)
);
diff --git a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
index dedf7471c8..f4c71e21ff 100644
--- a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
+++ b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
@@ -2,26 +2,27 @@ import { useSuspenseContext } from '@app/component/SuspenseContext';
import { EmptyState } from '@app/component/UnifiedListEmptyState';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import type { ViewId } from '@core/types/view';
-import Fragment from '@core/util/Fragment';
import { onElementConnect } from '@solid-primitives/lifecycle';
import { debounce } from '@solid-primitives/scheduled';
+import { createVirtualizer, type Virtualizer } from '@tanstack/solid-virtual';
import { StaticMarkdownContext } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';
import {
type Accessor,
+ createComputed,
createEffect,
createMemo,
createRenderEffect,
createSignal,
+ For,
Match,
on,
onCleanup,
type Setter,
+ Show,
Switch,
untrack,
} from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
-import { type VirtualizerHandle, VList } from 'virtua/solid';
-import { LIST_WRAPPER } from '../constants/classStrings';
import type {
EntityInfiniteQuery,
EntityList,
@@ -400,14 +401,38 @@ export function createUnifiedInfiniteList<T extends EntityData>({
const DEFAULT_HEIGHT = 600;
const [containerHeight, setContainerHeight] = createSignal(DEFAULT_HEIGHT);
+
const UnifiedInfiniteList = (props: {
children?: EntityRenderer<T>;
entityListRef?: (ref: HTMLDivElement | undefined) => void;
- virtualizerHandle?: Setter<VirtualizerHandle | undefined>;
+ virtualizerHandle?: Setter<Virtualizer<Element, Element> | undefined>;
hasRefinementsFromBase?: boolean;
viewId?: ViewId;
searchText?: string;
}) => {
+ const [scrollParentRef, setScrollParentRef] =
+ createSignal<HTMLDivElement>();
+
+ // Estimate items per viewport and derive overscan and page size
+ // Keep a conservative default item size for estimation; virtua will auto-measure precisely.
+ const ENTITY_HEIGHT = 40;
+ const viewportItemCount = createMemo(() =>
+ Math.max(1, Math.ceil(containerHeight() / ENTITY_HEIGHT))
+ );
+ const computedOverscan = createMemo(() =>
+ Math.max(6, Math.ceil(viewportItemCount() * 0.5))
+ );
+ const rowVirtualizer = createVirtualizer({
+ get count() {
+ return sortedEntitiesStore.length;
+ },
+ estimateSize: () => ENTITY_HEIGHT,
+ getScrollElement: () => scrollParentRef() as Element,
+ overscan: computedOverscan(),
+ });
+
+ props.virtualizerHandle?.(rowVirtualizer);
+
const [listRef, setListRef] = createSignal<HTMLDivElement>();
let containerSizeObserver: ResizeObserver | null = null;
@@ -433,16 +458,6 @@ export function createUnifiedInfiniteList<T extends EntityData>({
onCleanup(() => containerSizeObserver?.disconnect());
});
- // Estimate items per viewport and derive overscan and page size
- // Keep a conservative default item size for estimation; virtua will auto-measure precisely.
- const ENTITY_HEIGHT = 52;
- const viewportItemCount = createMemo(() =>
- Math.max(1, Math.ceil(containerHeight() / ENTITY_HEIGHT))
- );
- const computedOverscan = createMemo(() =>
- Math.max(6, Math.ceil(viewportItemCount() * 0.5))
- );
-
const loadingCount = () =>
entityQueries?.filter((query) => query.query.isLoading).length ??
0 + entityInfiniteQueries.filter((query) => query.query.isLoading).length;
@@ -464,37 +479,49 @@ export function createUnifiedInfiniteList<T extends EntityData>({
onCleanup(() => debouncedFetchMore.clear());
- const [virtualizerHandle, setVirtualizerHandle] =
- createSignal<VirtualizerHandle>();
// const cacheKey = createMemo(() => (id ? `list-cache-${id}` : null));
const cacheKey = `list-cache-${id}`;
+ // compose method to cache scroll position when called
+ const scrollToIndex = rowVirtualizer.scrollToIndex;
+ rowVirtualizer.scrollToIndex = (
+ index: number,
+ options?: ScrollToOptions | undefined
+ ) => {
+ // @ts-expect-error
+ scrollToIndex(index, options);
+ requestAnimationFrame(() => {
+ cacheVirtualizerHandle();
+ });
+ };
+
// Restore scroll position on mount
const restoreScrollPosition = () => {
- const handle = virtualizerHandle();
const { offset: cachedOffset } = cacheMap.get(cacheKey) || { offset: 0 };
- if (handle && cachedOffset) {
- handle.scrollTo(cachedOffset);
+ if (rowVirtualizer && cachedOffset != null) {
+ rowVirtualizer.scrollToOffset(cachedOffset);
+ }
+ };
+
+ const cacheVirtualizerHandle = () => {
+ const key = cacheKey;
+
+ const scrollOffset = rowVirtualizer.scrollOffset;
+ if (rowVirtualizer && key) {
+ cacheMap.set(key, { offset: scrollOffset ?? 0 });
}
};
+ let scrollMounted = false;
createEffect(
- on(virtualizerHandle, (virtualizerHandle, prev) => {
- if (virtualizerHandle && prev == null) {
+ on(scrollParentRef, (scrollParentRef, prev) => {
+ if (scrollParentRef && prev == null) {
+ scrollMounted = true;
restoreScrollPosition();
}
})
);
- const cacheVirtualizerHandle = () => {
- const handle = virtualizerHandle();
- const key = cacheKey;
-
- if (handle && key) {
- const { scrollOffset } = handle;
- cacheMap.set(key, { offset: scrollOffset });
- }
- };
const { isPending } = useSuspenseContext();
// Save scroll position and cache on cleanup
@@ -502,15 +529,20 @@ export function createUnifiedInfiniteList<T extends EntityData>({
cacheVirtualizerHandle();
});
- createEffect(
+ // Restore scroll after Suspense
+ createComputed(
on(
isPending,
(isPending, prevIsPending) => {
if (isPending) {
- cacheVirtualizerHandle();
+ if (scrollMounted) {
+ cacheVirtualizerHandle();
+ }
}
if (isPending === false && prevIsPending === true) {
- restoreScrollPosition();
+ queueMicrotask(() => {
+ restoreScrollPosition();
+ });
}
},
{ defer: true }
@@ -563,50 +595,81 @@ export function createUnifiedInfiniteList<T extends EntityData>({
<Match when={true}>
<div class="flex size-full relative" ref={setListRef}>
<StaticMarkdownContext>
- <Fragment
+ <div
+ class="size-full relative scrollbar-hidden"
+ data-unified-entity-list
ref={(el) => {
onElementConnect(el, () => {
- props.entityListRef?.(el as HTMLDivElement);
+ setScrollParentRef(el as HTMLDivElement);
});
}}
+ style={{
+ overflow: 'auto',
+ }}
>
- <VList
- ref={(ref) => {
- // runs before onCleanup
- // prevent ref from being set to null on cleanup otherwise the scroll position will be lost in onCleanup saving the cache
- if (ref) {
- setVirtualizerHandle(ref);
- }
- props.virtualizerHandle?.(ref);
+ <div
+ ref={(el) => {
+ onElementConnect(el, () => {
+ props.entityListRef?.(el as HTMLDivElement);
+ });
}}
- data={sortedEntitiesStore}
- class={`${LIST_WRAPPER} scrollbar-hidden`}
- data-unified-entity-list
- bufferSize={computedOverscan() * 50}
- >
- {(entity, index) => {
- if (
- untrack(index) >=
- Math.floor(untrack(sortedEntities).length * 0.9)
- ) {
- debouncedFetchMore();
- }
- return <EntityRenderer entity={entity} index={index()} />;
+ style={{
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative',
}}
- </VList>
- {/* <div class={LIST_WRAPPER}>
- <Key each={sortedEntities()} by={(item) => item.id}>
- {(entity, index) => {
- if (
- untrack(index) ===
- Math.floor(untrack(sortedEntities).length * 0.9)
- )
- debouncedFetchMore();
- return <EntityRenderer entity={entity()} index={index()} />;
- }}
- </Key>
- </div> */}
- </Fragment>
+ >
+ <div
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ transform: `translateY(${rowVirtualizer.getVirtualItems()?.[0]?.start}px)`,
+ }}
+ >
+ <For each={rowVirtualizer.getVirtualItems()}>
+ {(virtualItem) => {
+ if (
+ untrack(() => virtualItem.index) >=
+ Math.floor(untrack(sortedEntities).length * 0.9)
+ ) {
+ debouncedFetchMore();
+ }
+
+ return (
+ <Show
+ when={sortedEntitiesStore[virtualItem.index]?.id}
+ keyed
+ >
+ {(_) => {
+ const entity =
+ sortedEntitiesStore[virtualItem.index];
+ return (
+ <Show when={entity}>
+ <div
+ data-index={virtualItem.index}
+ ref={(el) =>
+ queueMicrotask(() =>
+ rowVirtualizer.measureElement(el)
+ )
+ }
+ >
+ <EntityRenderer
+ entity={entity}
+ index={virtualItem.index}
+ />
+ </div>
+ </Show>
+ );
+ }}
+ </Show>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ </div>
</StaticMarkdownContext>
<CustomScrollbar
scrollContainer={() => {