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.

fix(channels): virtualize media gallery and refactor attachment entity resolution (#4170)

teo84c7229a6a39
diff --git a/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx b/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx
index 09bdc6c651..5814524de5 100644
--- a/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx
+++ b/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx
@@ -1,3 +1,9 @@
+import {
+ compileToAst,
+ defineQueryFilters,
+ type Query,
+ queryStateFrom,
+} from '@app/component/next-soup/filters/filter-store';
import { useSplitLayout } from '@app/component/split-layout/layout';
import type { EntityData } from '@entity';
import {
@@ -5,17 +11,62 @@ import {
flattenAttachments,
useChannelDocumentAttachmentsQuery,
} from '@queries/channel/channel-attachments';
-import { useSoupItemsQuery } from '@queries/soup/items';
+import { useSoupAstItemsQuery } from '@queries/soup/items';
+import { stringToItemType } from '@service-storage/client';
import type { ApiChannelAttachment } from '@service-storage/generated/schemas/apiChannelAttachment';
import { createMemo } from 'solid-js';
import {
AttachmentEntityList,
type AttachmentEntityListRow,
} from './AttachmentEntityList';
-import {
- buildAttachmentEntityFilters,
- getEntityClickContent,
-} from './attachment-utils';
+import { getEntityClickContent } from './attachment-utils';
+
+/**
+ * Scope a soup query to exactly the attachment entities. `defineQueryFilters`
+ * NIL-fills every entity type we don't reference, so soup never fans out to
+ * crm companies or foreign entities (which it would otherwise fetch unfiltered).
+ */
+function attachmentSoupAst(attachments: ApiChannelAttachment[]) {
+ const documentId: string[] = [];
+ const threadId: string[] = [];
+ const chatId: string[] = [];
+ const channelId: string[] = [];
+ const folderId: string[] = [];
+ const callId: string[] = [];
+
+ for (const a of attachments) {
+ switch (stringToItemType(a.entity_type)) {
+ case 'document':
+ documentId.push(a.entity_id);
+ break;
+ case 'email':
+ threadId.push(a.entity_id);
+ break;
+ case 'chat':
+ chatId.push(a.entity_id);
+ break;
+ case 'channel':
+ channelId.push(a.entity_id);
+ break;
+ case 'project':
+ folderId.push(a.entity_id);
+ break;
+ case 'call':
+ callId.push(a.entity_id);
+ break;
+ }
+ }
+
+ const include: NonNullable<Query['include']> = {};
+ if (documentId.length) include.documentId = documentId;
+ if (threadId.length) include.threadId = threadId;
+ if (chatId.length) include.chatId = chatId;
+ if (channelId.length) include.channelId = channelId;
+ if (folderId.length) include.folderId = folderId;
+ if (callId.length) include.callId = callId;
+
+ return compileToAst(queryStateFrom(defineQueryFilters({ include })));
+}
export function ChannelAttachmentEntitySection(props: { channelId: string }) {
const attachmentsQuery = useChannelDocumentAttachmentsQuery(
@@ -28,10 +79,10 @@ export function ChannelAttachmentEntitySection(props: { channelId: string }) {
)
);
- const soupQuery = useSoupItemsQuery(
+ const soupQuery = useSoupAstItemsQuery(
() => ({
params: { limit: 500 },
- body: buildAttachmentEntityFilters(documentAttachments()),
+ body: attachmentSoupAst(documentAttachments()),
}),
() => ({ enabled: documentAttachments().length > 0 })
);
@@ -49,7 +100,7 @@ export function ChannelAttachmentEntitySection(props: { channelId: string }) {
replaceOrInsertSplit(getEntityClickContent(entity));
const rows = createMemo<AttachmentEntityListRow[]>(() => {
- const entities = soupQuery.data ?? [];
+ const entities = soupQuery.data?.entities ?? [];
const lookup = attachmentByEntityId();
return [...entities]
diff --git a/js/app/packages/channel/Attachments/MediaGallery.tsx b/js/app/packages/channel/Attachments/MediaGallery.tsx
index d1cd35e770..43d5a21eae 100644
--- a/js/app/packages/channel/Attachments/MediaGallery.tsx
+++ b/js/app/packages/channel/Attachments/MediaGallery.tsx
@@ -1,8 +1,14 @@
import { MediaGrid } from '@channel/Media/MediaGrid';
import { MediaViewerDialog } from '@channel/Media/MediaViewerDialog';
import type { MediaItem } from '@channel/Media/media-items';
-import { createSignal, Show } from 'solid-js';
-import { AttachmentSection, LoadMoreButton } from './SectionHeader';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { createEffect, createMemo, createSignal, Show } from 'solid-js';
+import { type VirtualizerHandle, VList } from 'virtua/solid';
+import { itemsPerRow, THUMB_GAP, THUMB_SIZE } from './attachment-utils';
+import { AttachmentSection } from './SectionHeader';
+
+// Initial row-height estimate; virtua measures the real size after mount.
+const ROW_SIZE = THUMB_SIZE + THUMB_GAP;
export function MediaGallery(props: {
items: MediaItem[];
@@ -13,47 +19,88 @@ export function MediaGallery(props: {
const [lightboxIndex, setLightboxIndex] = createSignal(0);
const [viewerOpen, setViewerOpen] = createSignal(false);
+ const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();
+ const containerSize = createElementSize(containerRef);
+ const [handle, setHandle] = createSignal<VirtualizerHandle>();
+
const hasMedia = () => props.items.length > 0;
+ const columns = createMemo(() => itemsPerRow(containerSize.width ?? 0));
+
+ // Chunk into rows so the virtualizer renders (and downloads) only on-screen tiles.
+ const rows = createMemo(() => {
+ const cols = columns();
+ const out: MediaItem[][] = [];
+ for (let i = 0; i < props.items.length; i += cols) {
+ out.push(props.items.slice(i, i + cols));
+ }
+ return out;
+ });
+
+ const maybeLoadMore = () => {
+ const h = handle();
+ if (!h || !props.hasNextPage || props.isFetchingNextPage) return;
+ const distanceFromBottom = h.scrollSize - h.viewportSize - h.scrollOffset;
+ if (distanceFromBottom <= ROW_SIZE * 4) props.onLoadMore();
+ };
+
+ // A short first page may not fill the viewport (e.g. wide layouts); keep
+ // pulling pages until it does. maybeLoadMore no-ops while a fetch is in
+ // flight or once there's no next page, so the loop terminates.
+ createEffect(() => {
+ rows();
+ if (handle()) requestAnimationFrame(maybeLoadMore);
+ });
+
+ const openAt = (index: number) => {
+ setLightboxIndex(index);
+ setViewerOpen(true);
+ };
return (
- <AttachmentSection label="Photos and Videos">
- <div class="grid py-2 px-6">
- <Show when={!hasMedia()}>
- <div class="py-3 text-sm text-ink-faint">
+ <AttachmentSection label="Photos and Videos" fillBody>
+ <Show
+ when={hasMedia()}
+ fallback={
+ <div class="px-6 py-3 text-sm text-ink-faint">
No photos or videos in this channel yet.
</div>
- </Show>
-
- <Show when={hasMedia()}>
- <div>
- <div aria-label="Photos and videos gallery">
- <MediaGrid
- items={props.items}
- variant="attachments"
- class="justify-center"
- onOpen={(index) => {
- setLightboxIndex(index);
- setViewerOpen(true);
- }}
- />
- </div>
- <MediaViewerDialog
- items={() => props.items}
- open={viewerOpen()}
- onOpenChange={setViewerOpen}
- currentIndex={lightboxIndex}
- onCurrentIndexChange={setLightboxIndex}
- />
+ }
+ >
+ <div class="flex min-h-0 flex-1 flex-col px-6 py-2">
+ <div
+ ref={setContainerRef}
+ aria-label="Photos and videos gallery"
+ class="min-h-0 flex-1"
+ >
+ <VList
+ ref={(h) => setHandle(h)}
+ data={rows()}
+ itemSize={ROW_SIZE}
+ class="size-full overscroll-none"
+ onScroll={maybeLoadMore}
+ >
+ {(row, rowIndex) => (
+ <MediaGrid
+ items={row}
+ variant="attachments"
+ class="justify-center pb-1.5"
+ onOpen={(localIndex) =>
+ openAt(rowIndex() * columns() + localIndex)
+ }
+ />
+ )}
+ </VList>
</div>
- </Show>
-
- <Show when={props.hasNextPage}>
- <LoadMoreButton
- onLoadMore={props.onLoadMore}
- isFetching={() => props.isFetchingNextPage}
- />
- </Show>
- </div>
+ </div>
+ </Show>
+
+ <MediaViewerDialog
+ items={() => props.items}
+ open={viewerOpen()}
+ onOpenChange={setViewerOpen}
+ currentIndex={lightboxIndex}
+ onCurrentIndexChange={setLightboxIndex}
+ />
</AttachmentSection>
);
}
diff --git a/js/app/packages/channel/Attachments/SectionHeader.tsx b/js/app/packages/channel/Attachments/SectionHeader.tsx
index f387670c1a..8c3fbfaa35 100644
--- a/js/app/packages/channel/Attachments/SectionHeader.tsx
+++ b/js/app/packages/channel/Attachments/SectionHeader.tsx
@@ -8,6 +8,9 @@ export function AttachmentSection(props: {
action?: JSX.Element;
class?: string;
label: string;
+ /** Fill the panel height without scrolling, so a child (e.g. a virtualized
+ * list) owns the scroll container instead of `Panel.Body`. */
+ fillBody?: boolean;
}) {
return (
<Panel depth={2} class={cn('h-auto', props.class)}>
@@ -15,9 +18,18 @@ export function AttachmentSection(props: {
<h3 class="text-sm font-medium text-ink">{props.label}</h3>
<div class="shrink-0">{props.action}</div>
</Panel.Header>
- <Panel.Body scroll class={props.contentClass}>
- {props.children}
- </Panel.Body>
+ <Show
+ when={props.fillBody}
+ fallback={
+ <Panel.Body scroll class={props.contentClass}>
+ {props.children}
+ </Panel.Body>
+ }
+ >
+ <Panel.Body class={cn('flex flex-col', props.contentClass)}>
+ {props.children}
+ </Panel.Body>
+ </Show>
</Panel>
);
}
diff --git a/js/app/packages/channel/Attachments/attachment-utils.ts b/js/app/packages/channel/Attachments/attachment-utils.ts
index 03eb53bc7a..a75cdd6def 100644
--- a/js/app/packages/channel/Attachments/attachment-utils.ts
+++ b/js/app/packages/channel/Attachments/attachment-utils.ts
@@ -2,16 +2,14 @@ import type { SplitContent } from '@app/component/split-layout/layoutManager';
import { getChannelParams } from '@channel/Channel/link';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import type { EntityData } from '@entity';
-import { stringToItemType } from '@service-storage/client';
-import type { ApiChannelAttachment } from '@service-storage/generated/schemas/apiChannelAttachment';
import { match } from 'ts-pattern';
-/** size-23 = 92px */
-export const THUMB_SIZE = 92;
-const THUMB_GAP = 6;
-
-const NIL_ID = '00000000-0000-0000-0000-000000000000';
+/** size-25.5 = 102px, matching the tile size in MediaGrid. */
+export const THUMB_SIZE = 102;
+/** gap-1.5 = 6px between tiles. */
+export const THUMB_GAP = 6;
+/** Number of square thumbnails that fit in a row of the given content width. */
export function itemsPerRow(containerWidth: number): number {
if (containerWidth <= 0) return 1;
return Math.max(
@@ -20,67 +18,6 @@ export function itemsPerRow(containerWidth: number): number {
);
}
-/**
- * Build soup query filters that fetch only the given entity IDs,
- * grouped by type. Unused entity types are zeroed out with NIL_ID
- * so they return nothing instead of everything.
- */
-export function buildAttachmentEntityFilters(
- attachments: ApiChannelAttachment[]
-) {
- const documentIds: string[] = [];
- const emailIds: string[] = [];
- const chatIds: string[] = [];
- const channelIds: string[] = [];
- const projectIds: string[] = [];
- const callIds: string[] = [];
-
- for (const a of attachments) {
- const itemType = stringToItemType(a.entity_type);
- switch (itemType) {
- case 'document':
- documentIds.push(a.entity_id);
- break;
- case 'email':
- emailIds.push(a.entity_id);
- break;
- case 'chat':
- chatIds.push(a.entity_id);
- break;
- case 'channel':
- channelIds.push(a.entity_id);
- break;
- case 'project':
- projectIds.push(a.entity_id);
- break;
- case 'call':
- callIds.push(a.entity_id);
- break;
- }
- }
-
- return {
- document_filters: {
- document_ids: documentIds.length > 0 ? documentIds : [NIL_ID],
- },
- email_filters: {
- email_thread_ids: emailIds.length > 0 ? emailIds : [NIL_ID],
- },
- chat_filters: { chat_ids: chatIds.length > 0 ? chatIds : [NIL_ID] },
- channel_filters: {
- channel_ids: channelIds.length > 0 ? channelIds : [NIL_ID],
- },
- project_filters: {
- project_ids: projectIds.length > 0 ? projectIds : [NIL_ID],
- },
- call_filters: {
- call_ids: callIds.length > 0 ? callIds : [NIL_ID],
- },
- // Attachments are never crm companies; exclude them.
- crm_company_filters: { company_ids: [NIL_ID] },
- };
-}
-
export function getEntityClickContent(entity: EntityData): SplitContent {
return match(entity)
.with({ type: 'document' }, (e) => ({
diff --git a/js/app/packages/channel/Media/MediaGrid.tsx b/js/app/packages/channel/Media/MediaGrid.tsx
index 665e9de9dc..10593ce1f8 100644
--- a/js/app/packages/channel/Media/MediaGrid.tsx
+++ b/js/app/packages/channel/Media/MediaGrid.tsx
@@ -6,7 +6,8 @@ import { MediaImage } from './MediaImage';
import { MediaVideo } from './MediaVideo';
import type { MediaItem } from './media-items';
-const ATTACHMENT_TILE_SIZE = 106;
+// Square tile size in px; keep in sync with the `size-25.5` class and THUMB_SIZE.
+const ATTACHMENT_TILE_SIZE = 102;
const SINGLE_IMAGE_MAX_WIDTH = 400;
const SINGLE_IMAGE_MAX_HEIGHT = 400;
const MESSAGE_GALLERY_IMAGE_MAX_WIDTH = 200;
@@ -56,19 +57,21 @@ function MessageImageTile(props: {
function AttachmentImageTile(props: { item: MediaItem; onOpen?: () => void }) {
return (
- <MediaImage.Root>
+ // Root holds the fixed square; image and fallback both fill it (no reflow).
+ <MediaImage.Root class="size-25.5">
<MediaImage.Image
- src={props.item.src}
+ // Small thumbnail for these ~100px boxes; src is the fallback.
+ src={props.item.thumbSrc ?? props.item.src}
previewSrc={props.item.previewSrc}
class={cn(
- 'size-25.5 select-none rounded-2xl border border-edge object-cover',
+ 'size-full select-none rounded-2xl border border-edge object-cover',
props.onOpen && 'hover:opacity-80'
)}
onOpen={props.onOpen}
width={ATTACHMENT_TILE_SIZE}
height={ATTACHMENT_TILE_SIZE}
loading="lazy"
- fallback={<MediaImage.Fallback square />}
+ fallback={<MediaImage.Fallback fill />}
/>
</MediaImage.Root>
);
diff --git a/js/app/packages/channel/Media/MediaImage.tsx b/js/app/packages/channel/Media/MediaImage.tsx
index c6e266291d..53fee3dd19 100644
--- a/js/app/packages/channel/Media/MediaImage.tsx
+++ b/js/app/packages/channel/Media/MediaImage.tsx
@@ -16,25 +16,32 @@ const ATTACHMENT_TILE_SIZE = 92;
function ImagePlaceholder(props: {
dims?: { width: number; height: number };
square?: boolean;
+ /** Fill the parent's fixed box, so the placeholder matches the loaded image. */
+ fill?: boolean;
}) {
return (
<div
- class="flex items-center justify-center rounded-2xl border border-edge bg-surface"
+ class={cn(
+ 'flex items-center justify-center rounded-2xl border border-edge bg-surface',
+ props.fill && 'size-full'
+ )}
style={
- props.square
- ? {
- width: `${ATTACHMENT_TILE_SIZE}px`,
- height: `${ATTACHMENT_TILE_SIZE}px`,
- }
- : props.dims
+ props.fill
+ ? undefined
+ : props.square
? {
- width: `${props.dims.width}px`,
- height: `${props.dims.height}px`,
- }
- : {
- width: '60px',
- height: '60px',
+ width: `${ATTACHMENT_TILE_SIZE}px`,
+ height: `${ATTACHMENT_TILE_SIZE}px`,
}
+ : props.dims
+ ? {
+ width: `${props.dims.width}px`,
+ height: `${props.dims.height}px`,
+ }
+ : {
+ width: '60px',
+ height: '60px',
+ }
}
>
<Spinner class="size-4 animate-spin" />
@@ -53,8 +60,15 @@ function Root(props: ParentProps<{ class?: string }>) {
function Fallback(props: {
dims?: { width: number; height: number };
square?: boolean;
+ fill?: boolean;
}) {
- return <ImagePlaceholder dims={props.dims} square={props.square} />;
+ return (
+ <ImagePlaceholder
+ dims={props.dims}
+ square={props.square}
+ fill={props.fill}
+ />
+ );
}
function Image(props: {
diff --git a/js/app/packages/channel/Media/media-items.ts b/js/app/packages/channel/Media/media-items.ts
index 1e1d6d798c..eb7b4d9a94 100644
--- a/js/app/packages/channel/Media/media-items.ts
+++ b/js/app/packages/channel/Media/media-items.ts
@@ -12,6 +12,8 @@ export type MediaItem = {
id: string;
/** Sized variant for previews (1080/ for images, original for videos) */
src: string;
+ /** Small (320px) variant for the tiny grid thumbnails; images only. */
+ thumbSrc?: string;
/** Full-resolution original — used when expanding */
fullSrc: string;
/** Local preview for optimistic media we just uploaded/sent. */
@@ -73,6 +75,10 @@ function mapAttachmentToMediaItem(
kind === 'image'
? staticFileSizedEndpoint(attachment.entity_id, 'medium')
: fullSrc,
+ thumbSrc:
+ kind === 'image'
+ ? staticFileSizedEndpoint(attachment.entity_id, 'small')
+ : undefined,
fullSrc,
previewSrc: attachment.previewSrc,
kind,
@@ -110,6 +116,7 @@ function mapAttachmentsToMediaItems<T extends AttachmentWithMediaFields>(
if (
previousItem &&
previousItem.src === nextItem.src &&
+ previousItem.thumbSrc === nextItem.thumbSrc &&
previousItem.fullSrc === nextItem.fullSrc &&
previousItem.previewSrc === nextItem.previewSrc &&
previousItem.kind === nextItem.kind &&
diff --git a/js/app/packages/queries/channel/channel-attachments.ts b/js/app/packages/queries/channel/channel-attachments.ts
index d548cd4abd..7ec28faf87 100644
--- a/js/app/packages/queries/channel/channel-attachments.ts
+++ b/js/app/packages/queries/channel/channel-attachments.ts
@@ -19,9 +19,15 @@ type ChannelAttachmentsQueryKey = ReturnType<
typeof channelKeys.attachments
>['queryKey'];
+// Media grid is virtualized and pages in on scroll, so the page size only needs
+// to fill the first viewport.
+const MEDIA_PAGE_SIZE = 50;
+const DOCUMENT_PAGE_SIZE = 50;
+
export function channelAttachmentsQueryOptions(
channelId: string,
- attachmentType?: ChannelAttachmentType
+ attachmentType?: ChannelAttachmentType,
+ limit = 100
) {
return {
queryKey: channelKeys.attachments(channelId, attachmentType).queryKey,
@@ -36,7 +42,7 @@ export function channelAttachmentsQueryOptions(
async () =>
await storageServiceClient.getChannelAttachments({
channel_id: channelId,
- limit: 100,
+ limit,
cursor: pageParam,
attachment_type: attachmentType,
signal,
@@ -52,21 +58,22 @@ export function channelAttachmentsQueryOptions(
function useChannelAttachmentsQuery(
channelId: Accessor<string>,
- attachmentType?: Accessor<ChannelAttachmentType | undefined>
+ attachmentType?: Accessor<ChannelAttachmentType | undefined>,
+ limit?: number
) {
return useInfiniteQuery(() =>
- channelAttachmentsQueryOptions(channelId(), attachmentType?.())
+ channelAttachmentsQueryOptions(channelId(), attachmentType?.(), limit)
);
}
export function useChannelMediaAttachmentsQuery(channelId: Accessor<string>) {
- return useChannelAttachmentsQuery(channelId, () => 'static');
+ return useChannelAttachmentsQuery(channelId, () => 'static', MEDIA_PAGE_SIZE);
}
export function useChannelDocumentAttachmentsQuery(
channelId: Accessor<string>
) {
- return useChannelAttachmentsQuery(channelId, () => 'dss');
+ return useChannelAttachmentsQuery(channelId, () => 'dss', DOCUMENT_PAGE_SIZE);
}
function _useChannelAttachmentsWithIndex(channelId: Accessor<string>) {
diff --git a/js/app/packages/queries/channel/tests/channel-attachments.test.ts b/js/app/packages/queries/channel/tests/channel-attachments.test.ts
index 0b69778c7d..91ff1ed6f6 100644
--- a/js/app/packages/queries/channel/tests/channel-attachments.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-attachments.test.ts
@@ -40,7 +40,7 @@ describe('channel attachment queries', () => {
const signal = new AbortController().signal;
await expect(
- channelAttachmentsQueryOptions('channel-1', 'static').queryFn({
+ channelAttachmentsQueryOptions('channel-1', 'static', 50).queryFn({
pageParam: 'cursor-1',
signal,
})
@@ -48,7 +48,7 @@ describe('channel attachment queries', () => {
expect(storageServiceClient.getChannelAttachments).toHaveBeenCalledWith({
channel_id: 'channel-1',
- limit: 100,
+ limit: 50,
cursor: 'cursor-1',
attachment_type: 'static',
signal,