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
feat(new-channels): attachment tab in channels (#2279)
teoead00d89efde
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsxindex e035cc8205..2de4cc0ce7 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx@@ -9,6 +9,10 @@ import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-conteximport { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import { isListViewID, type ListView } from '@app/constants/list-views';import { useUserContext } from '@core/context/user';+import {+ SegmentedControl,+ type SegmentedControlItem,+} from '@core/component/SegmentedControl';import {batch,createEffect,@@ -18,18 +22,14 @@ import {Match,on,onMount,- type ParentComponent,Switch,} from 'solid-js';-import {- SegmentedControl as KSegmentedControl,- type SegmentedControlRootProps,-} from '@kobalte/core/segmented-control';import { DropdownMenu } from '@kobalte/core/dropdown-menu';import ChevronDownIcon from '@icon/regular/caret-down.svg';import { impactFeedback } from '@tauri-apps/plugin-haptics';import { cn } from '@ui/utils/classname';-type TabItem = { value: string; label: string };++type TabItem = SegmentedControlItem;/** Views that have tab definitions. Shared between VIEW_TAB_LISTS and VIEW_TAB_PRESETS. */export type TabbedListView = Extract<@@ -338,50 +338,3 @@ const MobileViewTabs = (props: { view: TabbedListView }) => {</div>);};--export const SegmentedControl: ParentComponent<- {- list: { value: string; label: string }[];- value?: string;- defaultValue?: string;- } & Omit<SegmentedControlRootProps, 'defaultValue'>-> = (props) => {- const onChange = (newValue: string) => {- props.onChange?.(newValue);- };-- return (- <KSegmentedControl- class="h-full text-sm rounded-xs border border-edge-muted relative overflow-hidden"- value={props.value}- defaultValue={props.defaultValue ?? props.list[0]?.value}- onChange={onChange}- disabled={props.disabled}- >- <div class="relative" role="presentation">- <div class="flex" role="presentation">- <For each={props.list}>- {(item) => {- const itemValue = () =>- typeof item === 'object' ? item.value : item;- const itemLabel = () =>- typeof item === 'object' ? item.label : item;- return (- <KSegmentedControl.Item- value={itemValue()}- disabled={props.disabled}- class="border-r border-edge-muted last:border-r-0"- >- <KSegmentedControl.ItemInput class="absolute inset-0 pointer-events-none" />- <KSegmentedControl.ItemLabel class="relative text-ink-muted/70 size-full mobile:min-h-11 flex items-center justify-center px-2.5 py-1 text-xs font-medium data-[checked]:text-ink data-[checked]:bg-edge/50 hover:text-ink hover:bg-ink/6 data-[checked]:hover:bg-edge/60 transition-colors duration-150">- {itemLabel()}- </KSegmentedControl.ItemLabel>- </KSegmentedControl.Item>- );- }}- </For>- </div>- </div>- </KSegmentedControl>- );-};diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsxindex 862240eb04..d63bc045cf 100644--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx@@ -4,7 +4,7 @@ import {} from '@channel/Channel/Channel';import { useBlockId } from '@core/block';import { EntityPermissionsGate } from '@core/component/EntityPermissionsGate';-import { Suspense } from 'solid-js';+import { createSignal, Match, Suspense, Switch } from 'solid-js';import { blockHandleSignal } from '@core/signal/load';import { createMethodRegistration } from '@core/orchestrator';import { URL_PARAMS } from '@block-channel/constants';@@ -12,8 +12,18 @@ import { useBlockEntityCommands } from '@app/component/next-soup/actions';import { ChannelTopLeft } from './Top';import { useChannelName, useChannelType } from '@core/context/channels';import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';+import {+ CHANNEL_TABS,+ DEFAULT_CHANNEL_TAB,+ type ChannelTabId,+} from '@channel/Channel/channel-tabs';+import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';-function NewTop(props: { channelId: string }) {+function NewTop(props: {+ channelId: string;+ activeTab: ChannelTabId;+ onTabChange: (value: ChannelTabId) => void;+}) {const channelName = useChannelName(props.channelId);const channelType = useChannelType(props.channelId);const participantsQuery = useChannelParticipantsQuery(() => props.channelId);@@ -27,6 +37,9 @@ function NewTop(props: { channelId: string }) {channelType={channelType()!}participants={participants() ?? []}channelName={channelName() ?? 'New Channel'}+ tabs={CHANNEL_TABS}+ activeTab={props.activeTab}+ onTabChange={props.onTabChange}/></Suspense>);@@ -36,6 +49,8 @@ export function NewChannelBlockAdapter() {useBlockEntityCommands();const channelId = useBlockId();const blockHandle = blockHandleSignal.get;+ const [activeTab, setActiveTab] =+ createSignal<ChannelTabId>(DEFAULT_CHANNEL_TAB);const onChannelReady = (handle: ChannelHandle) => {createMethodRegistration(blockHandle, {@@ -50,6 +65,7 @@ export function NewChannelBlockAdapter() {const messageReplyId = threadId ? messageId : threadId;if (topLevelMessageId && handle) {+ setActiveTab(DEFAULT_CHANNEL_TAB);handle.goToMessage(topLevelMessageId, messageReplyId);}},@@ -58,8 +74,21 @@ export function NewChannelBlockAdapter() {return (<EntityPermissionsGate entityType="channel" entityId={channelId}>- <NewChannel channelId={channelId} onHandleReady={onChannelReady} />- <NewTop channelId={channelId} />+ <div class="relative h-full flex flex-col">+ <Switch>+ <Match when={activeTab() === 'messages'}>+ <NewChannel channelId={channelId} onHandleReady={onChannelReady} />+ </Match>+ <Match when={activeTab() === 'attachments'}>+ <ChannelAttachmentsTab channelId={channelId} />+ </Match>+ </Switch>+ <NewTop+ channelId={channelId}+ activeTab={activeTab()}+ onTabChange={setActiveTab}+ />+ </div></EntityPermissionsGate>);}diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsxindex 4faa227680..81f2b8c2e5 100644--- a/js/app/packages/block-channel/component/Top.tsx+++ b/js/app/packages/block-channel/component/Top.tsx@@ -33,6 +33,11 @@ import { isChannelAdminOrOwner } from '@queries/channel/derived';import { useChannelModals } from './ModalsProvider';import { ParticipantManagerButton } from './ParticipantManager';import { useAnalytics } from '@app/component/analytics-context';+import {+ SegmentedControl,+ type SegmentedControlItem,+} from '@core/component/SegmentedControl';+import type { ChannelTabId } from '@channel/Channel/channel-tabs';type TopIconProps = {channelType: ChannelType;@@ -68,6 +73,9 @@ type TopProps = {type ChannelTopLeftProps = TopProps & {lockRename?: boolean;+ tabs?: readonly SegmentedControlItem[];+ activeTab?: ChannelTabId;+ onTabChange?: (value: ChannelTabId) => void;};export function ChannelTopLeft(props: ChannelTopLeftProps) {@@ -79,8 +87,8 @@ export function ChannelTopLeft(props: ChannelTopLeftProps) {return (<SplitHeaderLeft>- <div class="h-full my-auto flex gap-2 justify-start items-center">- <div class="ph-no-capture z-3 relative flex items-center gap-2 max-w-full h-full shrink">+ <div class="h-full my-auto flex gap-3 justify-start items-center min-w-0">+ <div class="ph-no-capture z-3 relative flex items-center gap-2 max-w-full h-full shrink min-w-0"><TopIconchannelType={props.channelType}participants={props.participants}@@ -92,6 +100,15 @@ export function ChannelTopLeft(props: ChannelTopLeftProps) {lockRename={props.lockRename}/></div>+ <Show when={props.tabs && props.activeTab && props.onTabChange}>+ <div class="ph-no-capture min-w-0 shrink-0">+ <SegmentedControl+ list={[...(props.tabs ?? [])]}+ value={props.activeTab}+ onChange={(value) => props.onTabChange?.(value as ChannelTabId)}+ />+ </div>+ </Show></div></SplitHeaderLeft>);diff --git a/js/app/packages/channel/Attachments/AttachmentEntityList.tsx b/js/app/packages/channel/Attachments/AttachmentEntityList.tsxnew file mode 100644index 0000000000..c22ed75b62--- /dev/null+++ b/js/app/packages/channel/Attachments/AttachmentEntityList.tsx@@ -0,0 +1,53 @@+import { For, Show } from 'solid-js';+import type { EntityData } from '@entity';+import type { DateValue } from '@core/util/date';+import { SectionHeader, LoadMoreButton } from './SectionHeader';+import { AttachmentEntityRow } from './AttachmentEntityRow';++export type AttachmentEntityListRow = {+ entity: EntityData;+ timestamp?: DateValue | null;+ senderId?: string;+ onClick?: () => void;+};++export function AttachmentEntityList(props: {+ rows: AttachmentEntityListRow[];+ hasNextPage: boolean;+ isFetchingNextPage: boolean;+ onLoadMore: () => void;+}) {+ const hasDocuments = () => props.rows.length > 0;++ return (+ <div class="flex flex-col">+ <SectionHeader label="Documents" />++ <Show when={!hasDocuments()}>+ <div class="text-sm text-ink-faint px-2 py-3">+ No documents in this channel yet.+ </div>+ </Show>++ <Show when={hasDocuments()}>+ <For each={props.rows}>+ {(row) => (+ <AttachmentEntityRow+ entity={row.entity}+ timestamp={row.timestamp}+ senderId={row.senderId}+ onClick={row.onClick}+ />+ )}+ </For>+ </Show>++ <Show when={hasDocuments() && props.hasNextPage}>+ <LoadMoreButton+ onLoadMore={props.onLoadMore}+ isFetching={() => props.isFetchingNextPage}+ />+ </Show>+ </div>+ );+}diff --git a/js/app/packages/channel/Attachments/AttachmentEntityRow.tsx b/js/app/packages/channel/Attachments/AttachmentEntityRow.tsxnew file mode 100644index 0000000000..7b3abadff3--- /dev/null+++ b/js/app/packages/channel/Attachments/AttachmentEntityRow.tsx@@ -0,0 +1,39 @@+import { Show } from 'solid-js';+import { type EntityData, Entity } from '@entity';+import { UserIcon } from '@core/component/UserIcon';+import type { DateValue } from '@core/util/date';++export function AttachmentEntityRow(props: {+ entity: EntityData;+ timestamp?: DateValue | null;+ senderId?: string;+ onClick?: () => void;+}) {+ return (+ <Entity.Root+ entity={props.entity}+ onClick={() => props.onClick?.()}+ class="flex items-center gap-2 min-h-10 px-2 text-sm hover:bg-hover/30 cursor-pointer w-full"+ >+ <div class="size-4 shrink-0">+ <Entity.Icon entity={props.entity} />+ </div>+ <span class="ph-no-capture font-semibold truncate flex-1">+ <Entity.Title entity={props.entity} />+ </span>+ <Show when={props.senderId}>+ {(id) => (+ <div class="shrink-0">+ <UserIcon id={id()} size="xs" suppressClick showTooltip />+ </div>+ )}+ </Show>+ <span class="text-xs font-mono text-ink-extra-muted uppercase font-light shrink-0">+ <Entity.Timestamp+ entity={props.entity}+ overrideTimeStamp={props.timestamp ?? undefined}+ />+ </span>+ </Entity.Root>+ );+}diff --git a/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx b/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsxnew file mode 100644index 0000000000..b2884ca377--- /dev/null+++ b/js/app/packages/channel/Attachments/ChannelAttachmentEntitySection.tsx@@ -0,0 +1,82 @@+import { createMemo } from 'solid-js';+import { useSplitLayout } from '@app/component/split-layout/layout';+import type { EntityData } from '@entity';+import type { ApiChannelAttachment } from '@service-comms/client';+import { useSoupItemsQuery } from '@queries/soup/items';+import {+ flattenAttachments,+ useChannelAttachmentsQuery,+ type ChannelAttachmentsData,+} from '@queries/channel/channel-attachments';+import { partitionAttachments } from '@channel/Media/media-items';+import {+ buildAttachmentEntityFilters,+ getEntityClickContent,+} from './attachment-utils';+import {+ AttachmentEntityList,+ type AttachmentEntityListRow,+} from './AttachmentEntityList';++export function ChannelAttachmentEntitySection(props: { channelId: string }) {+ const attachmentsQuery = useChannelAttachmentsQuery(() => props.channelId);++ const allAttachments = createMemo(() =>+ flattenAttachments(+ attachmentsQuery.data as ChannelAttachmentsData | undefined+ )+ );+ const documentAttachments = createMemo(+ () => partitionAttachments(allAttachments()).documentAttachments+ );++ const soupQuery = useSoupItemsQuery(+ () => ({+ params: { limit: 500 },+ body: buildAttachmentEntityFilters(documentAttachments()),+ }),+ () => ({ enabled: documentAttachments().length > 0 })+ );++ const attachmentByEntityId = createMemo(() => {+ const map = new Map<string, ApiChannelAttachment>();+ for (const attachment of documentAttachments()) {+ map.set(attachment.entity_id, attachment);+ }+ return map;+ });++ const { replaceOrInsertSplit } = useSplitLayout();+ const handleEntityClick = (entity: EntityData) =>+ replaceOrInsertSplit(getEntityClickContent(entity));++ const rows = createMemo<AttachmentEntityListRow[]>(() => {+ const entities = soupQuery.data ?? [];+ const lookup = attachmentByEntityId();++ return [...entities]+ .sort((a, b) => {+ const aTime = lookup.get(a.id)?.created_at ?? '';+ const bTime = lookup.get(b.id)?.created_at ?? '';+ return bTime.localeCompare(aTime);+ })+ .map((entity) => {+ const attachment = lookup.get(entity.id);+ return {+ entity,+ timestamp: attachment?.created_at,+ senderId: attachment?.sender_id,+ onClick: () => handleEntityClick(entity),+ };+ });+ });++ return (+ <AttachmentEntityList+ rows={rows()}+ hasNextPage={!!attachmentsQuery.hasNextPage}+ isFetchingNextPage={attachmentsQuery.isFetchingNextPage}+ onLoadMore={() => attachmentsQuery.fetchNextPage()}+ />+ );+}diff --git a/js/app/packages/channel/Attachments/ChannelAttachmentMediaSection.tsx b/js/app/packages/channel/Attachments/ChannelAttachmentMediaSection.tsxnew file mode 100644index 0000000000..b08f52f29d--- /dev/null+++ b/js/app/packages/channel/Attachments/ChannelAttachmentMediaSection.tsx@@ -0,0 +1,30 @@+import { createMemo } from 'solid-js';+import {+ flattenAttachments,+ useChannelAttachmentsQuery,+ type ChannelAttachmentsData,+} from '@queries/channel/channel-attachments';+import { type MediaItem, mapMediaItems } from '@channel/Media/media-items';+import { MediaGallery } from './MediaGallery';++export function ChannelAttachmentMediaSection(props: { channelId: string }) {+ const attachmentsQuery = useChannelAttachmentsQuery(() => props.channelId);++ const items = createMemo<MediaItem[]>((previous = []) =>+ mapMediaItems(+ flattenAttachments(+ attachmentsQuery.data as ChannelAttachmentsData | undefined+ ),+ previous+ )+ );++ return (+ <MediaGallery+ items={items()}+ hasNextPage={!!attachmentsQuery.hasNextPage}+ isFetchingNextPage={attachmentsQuery.isFetchingNextPage}+ onLoadMore={() => attachmentsQuery.fetchNextPage()}+ />+ );+}diff --git a/js/app/packages/channel/Attachments/ChannelAttachmentsTab.tsx b/js/app/packages/channel/Attachments/ChannelAttachmentsTab.tsxnew file mode 100644index 0000000000..5b50640d39--- /dev/null+++ b/js/app/packages/channel/Attachments/ChannelAttachmentsTab.tsx@@ -0,0 +1,22 @@+import { Suspense } from 'solid-js';+import {+ AttachmentEntityListSkeleton,+ MediaGallerySkeleton,+} from './Skeletons';+import { ChannelAttachmentMediaSection } from './ChannelAttachmentMediaSection';+import { ChannelAttachmentEntitySection } from './ChannelAttachmentEntitySection';++export function ChannelAttachmentsTab(props: { channelId: string }) {+ return (+ <div class="relative flex-1 min-h-0 overflow-y-auto">+ <div class="macro-message-width macro-message-padding mx-auto w-full py-4 flex flex-col gap-6">+ <Suspense fallback={<MediaGallerySkeleton />}>+ <ChannelAttachmentMediaSection channelId={props.channelId} />+ </Suspense>+ <Suspense fallback={<AttachmentEntityListSkeleton />}>+ <ChannelAttachmentEntitySection channelId={props.channelId} />+ </Suspense>+ </div>+ </div>+ );+}diff --git a/js/app/packages/channel/Attachments/MediaGallery.tsx b/js/app/packages/channel/Attachments/MediaGallery.tsxnew file mode 100644index 0000000000..38695a0674--- /dev/null+++ b/js/app/packages/channel/Attachments/MediaGallery.tsx@@ -0,0 +1,99 @@+import { createSignal, onCleanup, Show } from 'solid-js';+import ChevronDownIcon from '@icon/regular/caret-down.svg';+import { MediaGrid } from '@channel/Media/MediaGrid';+import { MediaViewerDialog } from '@channel/Media/MediaViewerDialog';+import type { MediaItem } from '@channel/Media/media-items';+import { THUMB_SIZE, itemsPerRow } from './attachment-utils';+import { SectionHeader, LoadMoreButton } from './SectionHeader';++export function MediaGallery(props: {+ items: MediaItem[];+ hasNextPage: boolean;+ isFetchingNextPage: boolean;+ onLoadMore: () => void;+}) {+ const [expanded, setExpanded] = createSignal(false);+ const [containerWidth, setContainerWidth] = createSignal(0);+ const [lightboxIndex, setLightboxIndex] = createSignal(0);+ const [viewerOpen, setViewerOpen] = createSignal(false);++ const observeGrid = (el: HTMLDivElement) => {+ const observer = new ResizeObserver((entries) => {+ const entry = entries[0];+ if (entry) setContainerWidth(entry.contentRect.width);+ });+ observer.observe(el);+ onCleanup(() => observer.disconnect());+ };++ const rowLimit = () => itemsPerRow(containerWidth());+ const hasMedia = () => props.items.length > 0;+ const hiddenCount = () => Math.max(0, props.items.length - rowLimit());+ const collapsedMaxHeight = () => THUMB_SIZE;++ return (+ <div class="flex flex-col">+ <SectionHeader+ label="Photos and videos"+ action={+ <Show when={hiddenCount() > 0}>+ <button+ type="button"+ class="flex items-center gap-1 text-xs font-medium text-ink-muted/70 hover:text-ink-muted transition-colors"+ onClick={() => setExpanded((prev) => !prev)}+ >+ {expanded() ? 'Show less' : 'See all'}+ <ChevronDownIcon+ class="w-3 h-3 transition-transform"+ classList={{ 'rotate-180': expanded() }}+ />+ </button>+ </Show>+ }+ />++ <Show when={!hasMedia()}>+ <div class="text-sm text-ink-faint px-2 py-3">+ No photos or videos in this channel yet.+ </div>+ </Show>++ <Show when={hasMedia()}>+ <div>+ <div+ class="flex flex-row flex-wrap gap-1.5 pt-3 overflow-hidden transition-[max-height] duration-200"+ style={{+ 'max-height': expanded()+ ? 'none'+ : `${collapsedMaxHeight() + 12}px`,+ }}+ ref={observeGrid}+ >+ <MediaGrid+ items={props.items}+ variant="attachments"+ onOpen={(index) => {+ setLightboxIndex(index);+ setViewerOpen(true);+ }}+ />+ </div>+ <MediaViewerDialog+ items={() => props.items}+ open={viewerOpen()}+ onOpenChange={setViewerOpen}+ currentIndex={lightboxIndex}+ onCurrentIndexChange={setLightboxIndex}+ />+ </div>+ </Show>++ <Show when={expanded() && props.hasNextPage}>+ <LoadMoreButton+ onLoadMore={props.onLoadMore}+ isFetching={() => props.isFetchingNextPage}+ />+ </Show>+ </div>+ );+}diff --git a/js/app/packages/channel/Attachments/SectionHeader.tsx b/js/app/packages/channel/Attachments/SectionHeader.tsxnew file mode 100644index 0000000000..9a75cedf76--- /dev/null+++ b/js/app/packages/channel/Attachments/SectionHeader.tsx@@ -0,0 +1,42 @@+import { type Accessor, Show, type JSX } from 'solid-js';+import { Button } from '@ui/components/Button';+import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';++export function SectionHeader(props: { label: string; action?: JSX.Element }) {+ return (+ <>+ <div class="flex items-center justify-between px-2 py-1.5">+ <h3 class="text-xs font-medium text-ink-muted/70">{props.label}</h3>+ {props.action}+ </div>+ <div class="border-b border-edge-muted/50" />+ </>+ );+}++export function LoadMoreButton(props: {+ onLoadMore: () => void;+ isFetching: Accessor<boolean>;+}) {+ return (+ <Button+ variant="ghost"+ size="sm"+ class="w-full"+ onClick={() => props.onLoadMore()}+ disabled={props.isFetching()}+ >+ <Show+ when={!props.isFetching()}+ fallback={+ <>+ <Spinner class="w-3.5 h-3.5 animate-spin" />+ Loading...+ </>+ }+ >+ Load more+ </Show>+ </Button>+ );+}diff --git a/js/app/packages/channel/Attachments/Skeletons.tsx b/js/app/packages/channel/Attachments/Skeletons.tsxnew file mode 100644index 0000000000..ff7ca522da--- /dev/null+++ b/js/app/packages/channel/Attachments/Skeletons.tsx@@ -0,0 +1,47 @@+import { For } from 'solid-js';+import { SectionHeader } from './SectionHeader';++export function ThumbnailSkeleton() {+ return (+ <div class="size-23 rounded-2xl border border-edge bg-edge/50 animate-pulse" />+ );+}++export function DocumentRowSkeleton() {+ return (+ <div class="flex items-center gap-2 min-h-10 px-2">+ <div class="size-4 rounded bg-edge/50 animate-pulse shrink-0" />+ <div class="h-3.5 rounded bg-edge/50 animate-pulse w-48" />+ <div class="flex-1" />+ <div class="h-3 w-16 rounded bg-edge/50 animate-pulse shrink-0" />+ <div class="h-3 w-12 rounded bg-edge/50 animate-pulse shrink-0" />+ </div>+ );+}++const MEDIA_SKELETON_COUNT = 6;+const DOCUMENT_SKELETON_COUNT = 6;++export function MediaGallerySkeleton() {+ return (+ <div class="flex flex-col">+ <SectionHeader label="Photos and videos" />+ <div class="flex flex-row flex-wrap gap-1.5 pt-3">+ <For each={Array.from({ length: MEDIA_SKELETON_COUNT })}>+ {() => <ThumbnailSkeleton />}+ </For>+ </div>+ </div>+ );+}++export function AttachmentEntityListSkeleton() {+ return (+ <div class="flex flex-col">+ <SectionHeader label="Documents" />+ <For each={Array.from({ length: DOCUMENT_SKELETON_COUNT })}>+ {() => <DocumentRowSkeleton />}+ </For>+ </div>+ );+}diff --git a/js/app/packages/channel/Attachments/attachment-utils.ts b/js/app/packages/channel/Attachments/attachment-utils.tsnew file mode 100644index 0000000000..8f0c4a1a37--- /dev/null+++ b/js/app/packages/channel/Attachments/attachment-utils.ts@@ -0,0 +1,90 @@+import type { ApiChannelAttachment } from '@service-comms/client';+import { stringToItemType } from '@service-storage/client';+import type { EntityData } from '@entity';+import { match } from 'ts-pattern';+import { fileTypeToBlockName } from '@core/constant/allBlocks';++/** size-23 = 92px */+export const THUMB_SIZE = 92;+const THUMB_GAP = 6;++const NIL_ID = '00000000-0000-0000-0000-000000000000';++export function itemsPerRow(containerWidth: number): number {+ if (containerWidth <= 0) return 1;+ return Math.max(+ 1,+ Math.floor((containerWidth + THUMB_GAP) / (THUMB_SIZE + THUMB_GAP))+ );+}++/**+ * 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[] = [];++ 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;+ }+ }++ 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],+ },+ };+}++export function getEntityClickContent(entity: EntityData) {+ return match(entity)+ .with({ type: 'document' }, (e) => ({+ type: fileTypeToBlockName(e.subType?.type ?? e.fileType),+ id: e.id,+ }))+ .with({ type: 'chat' }, (e) => ({ type: 'chat' as const, id: e.id }))+ .with({ type: 'email' }, (e) => ({ type: 'email' as const, id: e.id }))+ .with({ type: 'channel' }, (e) => ({+ type: 'channel' as const,+ id: e.id,+ }))+ .with({ type: 'project' }, (e) => ({+ type: 'project' as const,+ id: e.id,+ }))+ .exhaustive();+}diff --git a/js/app/packages/channel/Channel/ChannelTabPlaceholder.tsx b/js/app/packages/channel/Channel/ChannelTabPlaceholder.tsxnew file mode 100644index 0000000000..c219410818--- /dev/null+++ b/js/app/packages/channel/Channel/ChannelTabPlaceholder.tsx@@ -0,0 +1,9 @@+export function ChannelTabPlaceholder(props: { label: string }) {+ return (+ <div class="flex min-h-0 flex-1 justify-center px-3 pb-3 pt-2">+ <div class="flex min-h-0 w-full max-w-channel-message flex-1 items-center justify-center rounded-md border border-dashed border-edge-muted bg-surface-1 px-4 py-8 text-sm text-ink-muted">+ {props.label} view is not implemented yet.+ </div>+ </div>+ );+}diff --git a/js/app/packages/channel/Channel/channel-tabs.ts b/js/app/packages/channel/Channel/channel-tabs.tsnew file mode 100644index 0000000000..1412552e27--- /dev/null+++ b/js/app/packages/channel/Channel/channel-tabs.ts@@ -0,0 +1,8 @@+export const CHANNEL_TABS = [+ { value: 'messages', label: 'Messages' },+ { value: 'attachments', label: 'Attachments' },+] as const;++export type ChannelTabId = (typeof CHANNEL_TABS)[number]['value'];++export const DEFAULT_CHANNEL_TAB: ChannelTabId = 'messages';diff --git a/js/app/packages/channel/Input/Attachments.tsx b/js/app/packages/channel/Input/Attachments.tsxindex dc6c9cf820..292bcf550c 100644--- a/js/app/packages/channel/Input/Attachments.tsx+++ b/js/app/packages/channel/Input/Attachments.tsx@@ -1,3 +1,10 @@+import { staticFileIdEndpoint } from '@core/constant/servers';+import { EntityIcon } from '@core/component/EntityIcon';+import SpinnerIcon from '@icon/bold/spinner-gap-bold.svg';+import XIcon from '@icon/regular/x.svg';+import { MediaImage } from '@channel/Media/MediaImage';+import { MediaVideo } from '@channel/Media/MediaVideo';+import { cn } from '@ui/utils/classname';import {children,For,@@ -7,14 +14,8 @@ import {Switch,type JSX,} from 'solid-js';-import { EntityIcon } from '@core/component/EntityIcon';-import { ImagePreview } from '@core/component/ImagePreview';-import { VideoPreview } from '@core/component/VideoPreview';-import { cn } from '@ui/utils/classname';import { useInput, useInputCommands } from './context';import type { InputAttachmentData, InputAttachmentKind } from './types';-import XIcon from '@icon/regular/x.svg';-import SpinnerIcon from '@icon/bold/spinner-gap-bold.svg';type AttachmentsProps = JSX.HTMLAttributes<HTMLDivElement> & {kind?: InputAttachmentKind | 'media';@@ -47,13 +48,10 @@ function MediaAttachmentItem(props: {attachment: InputAttachmentData;onRemove: (attachment: InputAttachmentData) => void;}) {+ const mediaSrc = () => staticFileIdEndpoint(props.attachment.id);+return (<div class="ph-no-capture relative group">- <RemoveButton- attachment={props.attachment}- onRemove={props.onRemove}- class="absolute -top-2 -right-2 z-[10] rounded-full bg-menu border border-edge-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100"- /><Showwhen={!props.attachment.pending && props.attachment.kind === 'image'}fallback={@@ -67,11 +65,36 @@ function MediaAttachmentItem(props: {</div>}>- <VideoPreview id={props.attachment.id} variant="small" />+ <MediaVideo.Root class="size-23 group overflow-hidden border border-edge bg-menu">+ <MediaVideo.Preview+ src={mediaSrc()}+ class="size-full object-cover"+ />+ <MediaVideo.PlayOverlay />+ <RemoveButton+ attachment={props.attachment}+ onRemove={props.onRemove}+ class="absolute -top-2 -right-2 z-[10] rounded-full bg-menu border border-edge-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ />+ </MediaVideo.Root></Show>}>- <ImagePreview image={{ id: props.attachment.id }} variant="small" />+ <MediaImage.Root>+ <MediaImage.Image+ src={mediaSrc()}+ class="size-23 select-none rounded-2xl border border-edge object-cover"+ width={92}+ height={92}+ loading="lazy"+ fallback={<MediaImage.Fallback square />}+ />+ <RemoveButton+ attachment={props.attachment}+ onRemove={props.onRemove}+ class="absolute -top-2 -right-2 z-[10] rounded-full bg-menu border border-edge-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ />+ </MediaImage.Root></Show></div>);diff --git a/js/app/packages/channel/Media/MediaGrid.tsx b/js/app/packages/channel/Media/MediaGrid.tsxnew file mode 100644index 0000000000..4b557034ba--- /dev/null+++ b/js/app/packages/channel/Media/MediaGrid.tsx@@ -0,0 +1,206 @@+import ExpandIcon from '@icon/regular/arrows-out-simple.svg';+import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';+import { constrainImageDimensions } from '@lexical-core/utils/media';+import { For, Match, Show, Switch, createMemo, createSignal } from 'solid-js';+import { cn } from '@ui/utils/classname';+import { MediaImage } from './MediaImage';+import { MediaVideo } from './MediaVideo';+import type { MediaItem } from './media-items';++const ATTACHMENT_TILE_SIZE = 92;+const SINGLE_IMAGE_MAX_WIDTH = 400;+const MESSAGE_GALLERY_IMAGE_MAX_WIDTH = 200;+const MESSAGE_GALLERY_IMAGE_MAX_HEIGHT = 200;++function MessageImageTile(props: {+ item: MediaItem;+ large: boolean;+ onOpen: () => void;+}) {+ const dimensions = () =>+ constrainImageDimensions(+ props.item.width ?? undefined,+ props.item.height ?? undefined,+ props.large ? SINGLE_IMAGE_MAX_WIDTH : MESSAGE_GALLERY_IMAGE_MAX_WIDTH,+ props.large ? undefined : MESSAGE_GALLERY_IMAGE_MAX_HEIGHT+ );++ return (+ <button+ type="button"+ class="relative flex rounded-2xl"+ onClick={props.onOpen}+ aria-label="Open image viewer"+ >+ <MediaImage.Image+ src={props.item.src}+ class="max-h-[80vh] w-full select-none rounded-2xl border border-edge object-contain"+ width={dimensions()?.width ?? props.item.width ?? undefined}+ height={dimensions()?.height ?? props.item.height ?? undefined}+ fallback={<MediaImage.Fallback dims={dimensions()} />}+ style={{+ ...(dimensions()+ ? {+ 'aspect-ratio': `${dimensions()!.width} / ${dimensions()!.height}`,+ 'max-width': `${dimensions()!.width}px`,+ }+ : {+ 'max-width': `${props.large ? SINGLE_IMAGE_MAX_WIDTH : MESSAGE_GALLERY_IMAGE_MAX_WIDTH}px`,+ }),+ }}+ />+ </button>+ );+}++function AttachmentImageTile(props: { item: MediaItem; onOpen?: () => void }) {+ return (+ <MediaImage.Root>+ <MediaImage.Image+ src={props.item.src}+ class={cn(+ 'size-23 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 />}+ />+ </MediaImage.Root>+ );+}++function MessageVideoTile(props: { item: MediaItem; onOpen: () => void }) {+ const [isInlinePlaying, setIsInlinePlaying] = createSignal(false);+ const src = () => props.item.src;+ const videoWidth = () => props.item.width ?? undefined;+ const videoHeight = () => props.item.height ?? undefined;++ return (+ <div class="group relative flex min-h-20 max-h-[480px] max-w-[480px] min-w-0 overflow-hidden rounded-2xl border border-edge bg-menu">+ <Show+ when={isInlinePlaying()}+ fallback={+ <>+ <button+ type="button"+ class="block max-w-full cursor-pointer"+ onClick={props.onOpen}+ aria-label="Open video viewer"+ >+ <MediaVideo.Preview+ src={props.item.src}+ class="block max-h-[480px] max-w-full"+ width={videoWidth()}+ height={videoHeight()}+ />+ <MediaVideo.PlayOverlay class="[&_svg]:size-6" />+ </button>+ <button+ type="button"+ class="absolute bottom-2 left-2 rounded-md bg-dialog/90 px-2 py-1 text-xs font-medium text-ink shadow-sm"+ onClick={(event) => {+ event.stopPropagation();+ setIsInlinePlaying(true);+ }}+ >+ Play inline+ </button>+ </>+ }+ >+ <video+ class="block max-h-[480px] max-w-full"+ controls+ autoplay+ playsinline+ src={src()}+ width={videoWidth()}+ height={videoHeight()}+ />+ </Show>+ <div class="absolute right-2 top-2 z-10">+ <DeprecatedIconButton+ icon={ExpandIcon}+ theme="clear"+ onClick={(event) => {+ event.stopPropagation();+ props.onOpen();+ }}+ tooltip={{ label: 'Open video viewer' }}+ />+ </div>+ </div>+ );+}++function AttachmentVideoTile(props: { item: MediaItem; onOpen?: () => void }) {+ return (+ <MediaVideo.Root class="size-23 group overflow-hidden border border-edge bg-menu">+ <MediaVideo.Preview+ src={props.item.src}+ class="size-full object-cover"+ onOpen={props.onOpen}+ />+ <MediaVideo.PlayOverlay onOpen={props.onOpen} />+ </MediaVideo.Root>+ );+}++export function MediaGrid(props: {+ items: MediaItem[];+ variant: 'message' | 'attachments';+ onOpen: (index: number) => void;+ class?: string;+}) {+ const hasSingleLargeImage = createMemo(+ () => props.items.length === 1 && props.items[0]?.kind === 'image'+ );++ return (+ <div+ class={cn(+ props.variant === 'attachments'+ ? 'flex flex-row flex-wrap gap-1.5'+ : 'flex flex-row flex-wrap gap-2',+ props.class+ )}+ >+ <For each={props.items}>+ {(item, index) => (+ <Switch>+ <Match when={item.kind === 'image' && props.variant === 'message'}>+ <MessageImageTile+ item={item}+ large={hasSingleLargeImage()}+ onOpen={() => props.onOpen(index())}+ />+ </Match>+ <Match+ when={item.kind === 'image' && props.variant === 'attachments'}+ >+ <AttachmentImageTile+ item={item}+ onOpen={() => props.onOpen(index())}+ />+ </Match>+ <Match when={item.kind === 'video' && props.variant === 'message'}>+ <MessageVideoTile+ item={item}+ onOpen={() => props.onOpen(index())}+ />+ </Match>+ <Match when={true}>+ <AttachmentVideoTile+ item={item}+ onOpen={() => props.onOpen(index())}+ />+ </Match>+ </Switch>+ )}+ </For>+ </div>+ );+}diff --git a/js/app/packages/channel/Media/MediaImage.tsx b/js/app/packages/channel/Media/MediaImage.tsxnew file mode 100644index 0000000000..13fe3feb5e--- /dev/null+++ b/js/app/packages/channel/Media/MediaImage.tsx@@ -0,0 +1,85 @@+import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';+import { cn } from '@ui/utils/classname';+import { type ParentProps, type JSX, Show, createSignal } from 'solid-js';+const ATTACHMENT_TILE_SIZE = 92;++function ImagePlaceholder(props: {+ dims?: { width: number; height: number };+ square?: boolean;+}) {+ return (+ <div+ class="flex items-center justify-center rounded-2xl border border-edge bg-menu"+ style={+ props.square+ ? {+ 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="h-4 w-4 animate-spin" />+ </div>+ );+}++function Root(props: ParentProps<{ class?: string }>) {+ return (+ <div class={cn('relative flex rounded-2xl', props.class)}>+ {props.children}+ </div>+ );+}++function Fallback(props: {+ dims?: { width: number; height: number };+ square?: boolean;+}) {+ return <ImagePlaceholder dims={props.dims} square={props.square} />;+}++function Image(props: {+ src: string;+ onOpen?: () => void;+ class?: string;+ width?: number;+ height?: number;+ style?: JSX.CSSProperties;+ loading?: 'eager' | 'lazy';+ fallback?: JSX.Element;+}) {+ const [loaded, setLoaded] = createSignal(false);++ return (+ <>+ <Show when={!loaded()}>{props.fallback}</Show>+ <img+ class={cn(props.class, props.onOpen && 'cursor-pointer')}+ classList={{ invisible: !loaded(), absolute: !loaded() }}+ src={props.src}+ alt="preview"+ width={props.width}+ height={props.height}+ style={props.style}+ loading={props.loading}+ onClick={() => props.onOpen?.()}+ onLoad={() => setLoaded(true)}+ />+ </>+ );+}++export const MediaImage = {+ Root,+ Fallback,+ Image,+};diff --git a/js/app/packages/channel/Media/MediaVideo.tsx b/js/app/packages/channel/Media/MediaVideo.tsxnew file mode 100644index 0000000000..339bb9903d--- /dev/null+++ b/js/app/packages/channel/Media/MediaVideo.tsx@@ -0,0 +1,54 @@+import PlayIcon from '@icon/fill/play-fill.svg';+import { cn } from '@ui/utils/classname';+import type { ParentProps } from 'solid-js';++function Root(props: ParentProps<{ class?: string }>) {+ return (+ <div class={cn('relative flex rounded-2xl', props.class)}>+ {props.children}+ </div>+ );+}++function Preview(props: {+ src: string;+ class?: string;+ onOpen?: () => void;+ width?: number;+ height?: number;+}) {+ return (+ <video+ class={props.class}+ preload="metadata"+ playsinline+ muted+ src={props.src}+ width={props.width}+ height={props.height}+ onClick={() => props.onOpen?.()}+ />+ );+}++function PlayOverlay(props: { onOpen?: () => void; class?: string }) {+ return (+ <div+ class={cn(+ 'absolute inset-0 flex items-center justify-center bg-ink/20',+ props.onOpen &&+ 'cursor-pointer transition-colors group-hover:bg-ink/30',+ props.class+ )}+ onClick={() => props.onOpen?.()}+ >+ <PlayIcon class="size-5 text-page drop-shadow" />+ </div>+ );+}++export const MediaVideo = {+ Root,+ Preview,+ PlayOverlay,+};diff --git a/js/app/packages/channel/Media/MediaViewerDialog.tsx b/js/app/packages/channel/Media/MediaViewerDialog.tsxnew file mode 100644index 0000000000..d9504afe57--- /dev/null+++ b/js/app/packages/channel/Media/MediaViewerDialog.tsx@@ -0,0 +1,144 @@+import * as stackingContext from '@core/constant/stackingContext';+import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';+import { Lightbox, LightboxToolbar } from '@core/component/Lightbox';+import ChevronLeftIcon from '@icon/regular/caret-left.svg';+import ChevronRightIcon from '@icon/regular/caret-right.svg';+import XIcon from '@icon/regular/x.svg';+import { Dialog } from '@kobalte/core/dialog';+import { Show, type Accessor, createMemo } from 'solid-js';+import { cn } from '@ui/utils/classname';+import type { MediaItem } from './media-items';++type MediaViewerDialogProps = {+ items: Accessor<MediaItem[]>;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ currentIndex: Accessor<number>;+ onCurrentIndexChange: (index: number) => void;+};++function VideoViewerContent(props: {+ item: Accessor<MediaItem>;+ onPrevious?: () => void;+ onNext?: () => void;+ indexLabel?: Accessor<string>;+}) {+ const navButtonClass =+ 'absolute top-1/2 -translate-y-1/2 bg-dialog backdrop-blur-sm rounded-lg border border-edge p-2 shadow-md hover:bg-button transition-colors';++ return (+ <div+ class="fixed inset-0 z-modal flex items-center justify-center"+ style={{+ 'padding-top': 'max(var(--safe-top), 0.5rem)',+ 'padding-bottom': 'max(var(--safe-bottom), 1.5rem)',+ 'padding-left': 'max(var(--safe-left), 0.5rem)',+ 'padding-right': 'max(var(--safe-right), 0.5rem)',+ }}+ >+ <Dialog.Content class="relative flex h-full w-full items-center justify-center bg-panel">+ <LightboxToolbar isVisible={true}>+ <Dialog.CloseButton>+ <DeprecatedIconButton+ icon={XIcon}+ theme="clear"+ tooltip={{ label: 'Close' }}+ />+ </Dialog.CloseButton>+ </LightboxToolbar>++ <Show when={props.indexLabel}>+ <div+ class="absolute top-4 left-4 rounded-lg border border-edge bg-dialog px-3 py-1.5 shadow-md"+ style={{ 'z-index': stackingContext.zModal + 1 }}+ >+ <span class="text-sm font-medium text-ink">+ {props.indexLabel?.()}+ </span>+ </div>+ </Show>++ <Show when={props.onPrevious}>+ <button+ class={cn(navButtonClass, 'left-4')}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ onClick={props.onPrevious}+ aria-label="Previous media"+ >+ <ChevronLeftIcon class="h-5 w-5 text-ink" />+ </button>+ </Show>+ <Show when={props.onNext}>+ <button+ class={cn(navButtonClass, 'right-4')}+ style={{ 'z-index': stackingContext.zModal + 1 }}+ onClick={props.onNext}+ aria-label="Next media"+ >+ <ChevronRightIcon class="h-5 w-5 text-ink" />+ </button>+ </Show>++ <div class="flex h-full w-full items-center justify-center">+ <video+ class="max-h-[80vh] max-w-[90vw] rounded-2xl bg-black"+ controls+ autoplay+ playsinline+ src={props.item().src}+ />+ </div>+ </Dialog.Content>+ </div>+ );+}++export function MediaViewerDialog(props: MediaViewerDialogProps) {+ const currentItem = createMemo(() => props.items()[props.currentIndex()]);+ const hasPrevious = () => props.currentIndex() > 0;+ const hasNext = () => props.currentIndex() < props.items().length - 1;+ const hasMultipleItems = () => props.items().length > 1;+ const indexLabel = () =>+ `${props.currentIndex() + 1}/${props.items().length}`;++ const navigatePrevious = () => {+ if (!hasPrevious()) return;+ props.onCurrentIndexChange(props.currentIndex() - 1);+ };++ const navigateNext = () => {+ if (!hasNext()) return;+ props.onCurrentIndexChange(props.currentIndex() + 1);+ };++ return (+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay class="fixed inset-0 z-modal bg-modal-overlay pattern-edge-muted pattern-diagonal-4" />+ <Show when={currentItem()}>+ {(item) => (+ <Show+ when={item().kind === 'image'}+ fallback={+ <VideoViewerContent+ item={item}+ onPrevious={hasPrevious() ? navigatePrevious : undefined}+ onNext={hasNext() ? navigateNext : undefined}+ indexLabel={hasMultipleItems() ? indexLabel : undefined}+ />+ }+ >+ <Lightbox+ src={() => item().src}+ imageId={() => item().id}+ onPrevious={hasPrevious() ? navigatePrevious : undefined}+ onNext={hasNext() ? navigateNext : undefined}+ indexLabel={hasMultipleItems() ? indexLabel : undefined}+ />+ </Show>+ )}+ </Show>+ </Dialog.Portal>+ </Dialog>+ );+}diff --git a/js/app/packages/channel/Media/media-items.ts b/js/app/packages/channel/Media/media-items.tsnew file mode 100644index 0000000000..02c2dc2504--- /dev/null+++ b/js/app/packages/channel/Media/media-items.ts@@ -0,0 +1,104 @@+import { staticFileIdEndpoint } from '@core/constant/servers';+import {+ isStaticAttachmentType,+ STATIC_IMAGE,+ STATIC_VIDEO,+} from '@core/store/cacheChannelInput';++export type MediaItem = {+ id: string;+ src: string;+ kind: 'image' | 'video';+ width?: number | null;+ height?: number | null;+};++type AttachmentWithMediaFields = {+ id: string;+ entity_id: string;+ entity_type: string;+ width?: number | null;+ height?: number | null;+};++function getMediaKind(entityType: string): MediaItem['kind'] | undefined {+ if (entityType === STATIC_IMAGE) return 'image';+ if (entityType === STATIC_VIDEO) return 'video';+ return undefined;+}++function isMediaAttachmentType(entityType: string): boolean {+ return entityType === STATIC_IMAGE || entityType === STATIC_VIDEO;+}++export function partitionAttachments<T extends { entity_type: string }>(+ attachments: T[]+) {+ const mediaAttachments: T[] = [];+ const documentAttachments: T[] = [];++ for (const attachment of attachments) {+ if (isMediaAttachmentType(attachment.entity_type)) {+ mediaAttachments.push(attachment);+ continue;+ }++ if (!isStaticAttachmentType(attachment.entity_type)) {+ documentAttachments.push(attachment);+ }+ }++ return { mediaAttachments, documentAttachments };+}++function mapAttachmentToMediaItem(+ attachment: AttachmentWithMediaFields+): MediaItem | undefined {+ const kind = getMediaKind(attachment.entity_type);+ if (!kind) return;++ return {+ id: attachment.entity_id,+ src: staticFileIdEndpoint(attachment.entity_id),+ kind,+ width: attachment.width ?? undefined,+ height: attachment.height ?? undefined,+ };+}++function mapAttachmentsToMediaItems<T extends AttachmentWithMediaFields>(+ attachments: T[],+ previousItems: MediaItem[] = []+): MediaItem[] {+ const previousByAttachmentId = new Map(+ attachments.map((attachment, index) => [+ attachment.id,+ previousItems[index],+ ])+ );++ return attachments.flatMap((attachment) => {+ const item = mapAttachmentToMediaItem(attachment);+ if (!item) return [];++ const previousItem = previousByAttachmentId.get(attachment.id);+ if (+ previousItem &&+ previousItem.src === item.src &&+ previousItem.kind === item.kind &&+ previousItem.width === item.width &&+ previousItem.height === item.height+ ) {+ return [previousItem];+ }++ return [item];+ });+}++export function mapMediaItems<T extends AttachmentWithMediaFields>(+ attachments: T[],+ previousItems?: MediaItem[]+): MediaItem[] {+ return mapAttachmentsToMediaItems(attachments, previousItems);+}diff --git a/js/app/packages/channel/Message/Attachments.tsx b/js/app/packages/channel/Message/Attachments.tsxindex 32e730dc1c..a3c4038efc 100644--- a/js/app/packages/channel/Message/Attachments.tsx+++ b/js/app/packages/channel/Message/Attachments.tsx@@ -1,13 +1,12 @@import { ItemPreview } from '@core/component/ItemPreview';-import {- isStaticAttachmentType,- STATIC_IMAGE,- STATIC_VIDEO,-} from '@core/store/cacheChannelInput';import { stringToItemType } from '@service-storage/client';-import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';import { cn } from '@ui/utils/classname';-import { createMemo, For, Match, Show, Switch } from 'solid-js';+import { createMemo, For, Show } from 'solid-js';+import {+ type MediaItem,+ mapMediaItems,+ partitionAttachments,+} from '@channel/Media/media-items';import { useMessage } from './context';import { MediaPreview } from './MediaPreview';@@ -15,61 +14,17 @@ type AttachmentsProps = {class?: string;};-type MessageAttachmentBuckets = {- imageAttachments: ApiMessageAttachment[];- videoAttachments: ApiMessageAttachment[];- documentAttachments: ApiMessageAttachment[];-};--export function partitionMessageAttachments(- attachments: ApiMessageAttachment[]-): MessageAttachmentBuckets {- const imageAttachments: ApiMessageAttachment[] = [];- const videoAttachments: ApiMessageAttachment[] = [];- const documentAttachments: ApiMessageAttachment[] = [];-- for (const attachment of attachments) {- if (attachment.entity_type === STATIC_IMAGE) {- imageAttachments.push(attachment);- continue;- }-- if (attachment.entity_type === STATIC_VIDEO) {- videoAttachments.push(attachment);- continue;- }-- if (!isStaticAttachmentType(attachment.entity_type)) {- documentAttachments.push(attachment);- }- }-- return {- imageAttachments,- videoAttachments,- documentAttachments,- };-}-export function Attachments(props: AttachmentsProps) {const message = useMessage();const buckets = createMemo(() =>- partitionMessageAttachments(message().attachments ?? [])+ partitionAttachments(message().attachments ?? []));- const imagePreviewData = createMemo(() =>- buckets().imageAttachments.map((attachment) => ({- id: attachment.entity_id,- width: attachment.width ?? undefined,- height: attachment.height ?? undefined,- }))- );- const imageAttachmentIds = createMemo(() =>- buckets().imageAttachments.map((attachment) => attachment.id)+ const mediaItems = createMemo<MediaItem[]>((previous = []) =>+ mapMediaItems(buckets().mediaAttachments, previous));const hasAttachments = createMemo(() =>- buckets().imageAttachments.length > 0 ||- buckets().videoAttachments.length > 0 ||+ buckets().mediaAttachments.length > 0 ||buckets().documentAttachments.length > 0);const shouldRender = createMemo(@@ -82,37 +37,8 @@ export function Attachments(props: AttachmentsProps) {class={cn('allow-css-brackets mb-2', props.class)}data-message-attachments>- <Show when={buckets().videoAttachments.length > 0}>- <For each={buckets().videoAttachments}>- {(attachment) => (- <MediaPreview- kind="video"- id={attachment.entity_id}- width={attachment.width ?? undefined}- height={attachment.height ?? undefined}- />- )}- </For>- </Show>-- <Show when={buckets().imageAttachments.length > 0}>- <div class="flex not-first:mt-2">- <Switch>- <Match when={buckets().imageAttachments.length === 1}>- <MediaPreview- kind="single-image"- image={imagePreviewData()[0]!}- />- </Match>- <Match when={buckets().imageAttachments.length > 1}>- <MediaPreview- kind="image-gallery"- images={imagePreviewData()}- attachmentIds={imageAttachmentIds()}- />- </Match>- </Switch>- </div>+ <Show when={mediaItems().length > 0}>+ <MediaPreview items={mediaItems()} /></Show><Show when={buckets().documentAttachments.length > 0}>diff --git a/js/app/packages/channel/Message/MediaPreview.tsx b/js/app/packages/channel/Message/MediaPreview.tsxindex 3c700b74e9..e7b500c3b8 100644--- a/js/app/packages/channel/Message/MediaPreview.tsx+++ b/js/app/packages/channel/Message/MediaPreview.tsx@@ -1,120 +1,35 @@-import { ImageGalleryPreview } from '@core/component/ImageGalleryPreview';-import { ImagePreview } from '@core/component/ImagePreview';-import { VideoPreview } from '@core/component/VideoPreview';-import { matches } from '@core/util/match';-import { cn } from '@ui/utils/classname';-import { Match, Switch } from 'solid-js';+import { createSignal } from 'solid-js';+import { MediaGrid } from '@channel/Media/MediaGrid';+import { MediaViewerDialog } from '@channel/Media/MediaViewerDialog';+import type { MediaItem } from '@channel/Media/media-items';-type ImageAttachment = {- id: string;- width?: number | undefined;- height?: number | undefined;-};--type SingleImageMediaPreviewProps = {- kind: 'single-image';- image: ImageAttachment;- class?: string;-};--type ImageGalleryMediaPreviewProps = {- kind: 'image-gallery';- images: ImageAttachment[];- attachmentIds: string[];- class?: string;-};--type VideoMediaPreviewProps = {- kind: 'video';- id: string;- width?: number | undefined;- height?: number | undefined;+type MediaPreviewProps = {+ items: MediaItem[];class?: string;};-export type MediaPreviewProps =- | SingleImageMediaPreviewProps- | ImageGalleryMediaPreviewProps- | VideoMediaPreviewProps;--function isSingleImageMediaPreview(- props: MediaPreviewProps-): props is SingleImageMediaPreviewProps {- return props.kind === 'single-image';-}--function isImageGalleryMediaPreview(- props: MediaPreviewProps-): props is ImageGalleryMediaPreviewProps {- return props.kind === 'image-gallery';-}--function isVideoMediaPreview(- props: MediaPreviewProps-): props is VideoMediaPreviewProps {- return props.kind === 'video';-}--function SingleImagePreview(props: SingleImageMediaPreviewProps) {- return (- <div- class={cn('w-full max-w-[400px] min-w-0', props.class)}- data-message-media-preview="single-image"- >- <ImagePreview image={props.image} variant="dynamic" />- </div>- );-}+export function MediaPreview(props: MediaPreviewProps) {+ const [selectedIndex, setSelectedIndex] = createSignal(0);+ const [viewerOpen, setViewerOpen] = createSignal(false);-function ImageGalleryMediaPreview(props: ImageGalleryMediaPreviewProps) {return (- <div- class={cn('w-full max-w-[412px] min-w-0', props.class)}- data-message-media-preview="image-gallery"- >- <ImageGalleryPreview- images={props.images}- attachmentIds={props.attachmentIds}- variant="dynamic"- wrapperClass="flex flex-row flex-wrap gap-2"+ <>+ <MediaGrid+ items={props.items}+ variant="message"+ class={props.class}+ onOpen={(index) => {+ setSelectedIndex(index);+ setViewerOpen(true);+ }}/>- </div>- );-}--function VideoMediaPreview(props: VideoMediaPreviewProps) {- return (- <div- class={cn(- 'w-full max-w-[400px] min-w-0 [&>div]:max-w-full [&_video]:block [&_video]:max-w-full [&_video]:max-h-[500px]',- props.class- )}- data-message-media-preview="video"- >- <VideoPreview- id={props.id}- variant="dynamic"- width={props.width}- height={props.height}+ <MediaViewerDialog+ items={() => props.items}+ open={viewerOpen()}+ onOpenChange={setViewerOpen}+ currentIndex={selectedIndex}+ onCurrentIndexChange={setSelectedIndex}/>- </div>- );-}--export function MediaPreview(props: MediaPreviewProps) {- return (- <Switch>- <Match when={matches(props, isSingleImageMediaPreview)}>- {(singleImageProps) => <SingleImagePreview {...singleImageProps()} />}- </Match>- <Match when={matches(props, isImageGalleryMediaPreview)}>- {(imageGalleryProps) => (- <ImageGalleryMediaPreview {...imageGalleryProps()} />- )}- </Match>- <Match when={matches(props, isVideoMediaPreview)}>- {(videoProps) => <VideoMediaPreview {...videoProps()} />}- </Match>- </Switch>+ </>);}diff --git a/js/app/packages/channel/Message/index.ts b/js/app/packages/channel/Message/index.tsindex 75636e719d..a3d8546371 100644--- a/js/app/packages/channel/Message/index.ts+++ b/js/app/packages/channel/Message/index.ts@@ -9,7 +9,7 @@ import {export { Message } from './Message';export { ChannelMessage } from './ChannelMessage';-export { Attachments, partitionMessageAttachments } from './Attachments';+export { Attachments } from './Attachments';export { MediaPreview } from './MediaPreview';export { DateDivider } from './DateDivider';export { NewDivider } from './NewDivider';diff --git a/js/app/packages/core/component/ImageGalleryPreview.tsx b/js/app/packages/core/component/ImageGalleryPreview.tsxindex 0c3ff3e646..0bd0a4eabd 100644--- a/js/app/packages/core/component/ImageGalleryPreview.tsx+++ b/js/app/packages/core/component/ImageGalleryPreview.tsx@@ -22,6 +22,10 @@ type ImageData = {height?: string | number | undefined;};+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export type ImageGalleryPreviewProps = {images: ImageData[];initialIndex?: number;@@ -67,6 +71,10 @@ function GalleryImagePlaceholder(props: {);}+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (props) => {diff --git a/js/app/packages/core/component/ImagePreview.tsx b/js/app/packages/core/component/ImagePreview.tsxindex beeb9133e9..1e9392872f 100644--- a/js/app/packages/core/component/ImagePreview.tsx+++ b/js/app/packages/core/component/ImagePreview.tsx@@ -28,6 +28,10 @@ type ImageData = {height?: string | number | undefined;};+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export type ImagePreviewProps = {image: ImageData;variant: 'small' | 'dynamic';@@ -84,6 +88,10 @@ function ImagePlaceholder(props: {);}+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export function ImagePreview(props: ImagePreviewProps) {const [imageBlob, setImageBlob] = createSignal<Blob>();const [objectUrl, setObjectUrl] = createSignal<string>();diff --git a/js/app/packages/core/component/SegmentedControl.tsx b/js/app/packages/core/component/SegmentedControl.tsxnew file mode 100644index 0000000000..f0c087f3bc--- /dev/null+++ b/js/app/packages/core/component/SegmentedControl.tsx@@ -0,0 +1,51 @@+import {+ SegmentedControl as KSegmentedControl,+ type SegmentedControlRootProps,+} from '@kobalte/core/segmented-control';+import { For, type ParentComponent } from 'solid-js';++export type SegmentedControlItem = {+ value: string;+ label: string;+};++export const SegmentedControl: ParentComponent<+ {+ list: SegmentedControlItem[];+ value?: string;+ defaultValue?: string;+ } & Omit<SegmentedControlRootProps, 'defaultValue'>+> = (props) => {+ const onChange = (newValue: string) => {+ props.onChange?.(newValue);+ };++ return (+ <KSegmentedControl+ class="h-full text-sm rounded-xs border border-edge-muted relative overflow-hidden"+ value={props.value}+ defaultValue={props.defaultValue ?? props.list[0]?.value}+ onChange={onChange}+ disabled={props.disabled}+ >+ <div class="relative" role="presentation">+ <div class="flex" role="presentation">+ <For each={props.list}>+ {(item) => (+ <KSegmentedControl.Item+ value={item.value}+ disabled={props.disabled}+ class="border-r border-edge-muted last:border-r-0"+ >+ <KSegmentedControl.ItemInput class="absolute inset-0 pointer-events-none" />+ <KSegmentedControl.ItemLabel class="relative text-ink-muted/70 size-full mobile:min-h-11 flex items-center justify-center px-2.5 py-1 text-xs font-medium data-[checked]:text-ink data-[checked]:bg-edge/50 hover:text-ink hover:bg-ink/6 data-[checked]:hover:bg-edge/60 transition-colors duration-150">+ {item.label}+ </KSegmentedControl.ItemLabel>+ </KSegmentedControl.Item>+ )}+ </For>+ </div>+ </div>+ </KSegmentedControl>+ );+};diff --git a/js/app/packages/core/component/VideoPreview.tsx b/js/app/packages/core/component/VideoPreview.tsxindex fa24491c52..a05f32a28d 100644--- a/js/app/packages/core/component/VideoPreview.tsx+++ b/js/app/packages/core/component/VideoPreview.tsx@@ -1,5 +1,9 @@import { staticFileIdEndpoint } from '@core/constant/servers';+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export type VideoPreviewProps = {id: string;variant: 'small' | 'dynamic';@@ -18,6 +22,10 @@ const VIDEO_THEMES = {dynamic: '',};+/**+ * @deprecated Prefer the composable media primitives in `@channel/Media`.+ * Keep this only for legacy callers until they are migrated.+ */export function VideoPreview(props: VideoPreviewProps) {return (<div class={CONTAINER_THEMES[props.variant]}>diff --git a/js/app/packages/queries/channel/channel-attachments.ts b/js/app/packages/queries/channel/channel-attachments.tsindex 6b2b080315..840e9cbd70 100644--- a/js/app/packages/queries/channel/channel-attachments.ts+++ b/js/app/packages/queries/channel/channel-attachments.ts@@ -29,7 +29,7 @@ export function channelAttachmentsQueryOptions(channelId: string) {},initialPageParam: null as string | null,getNextPageParam: (lastPage: ChannelAttachmentsPage) =>- lastPage.next_cursor ?? null,+ lastPage.next_cursor ?? undefined,staleTime: Infinity,};}