Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(channel): Send static attachment dimensions and use dimensions for displaying attachments (#653)

dev-rbe0b5fbfa1060
diff --git a/js/app/packages/block-channel/component/Attachment.tsx b/js/app/packages/block-channel/component/Attachment.tsx
index 54e6e2d725..29a61530ae 100644
--- a/js/app/packages/block-channel/component/Attachment.tsx
+++ b/js/app/packages/block-channel/component/Attachment.tsx
@@ -71,7 +71,12 @@ export function Attachment(props: AttachmentProps) {
</div>
</Match>
<Match when={props.attachment.blockName === STATIC_IMAGE}>
- <ImagePreview id={props.attachment.id} variant="small" />
+ <ImagePreview
+ image={{
+ id: props.attachment.id,
+ }}
+ variant="small"
+ />
</Match>
<Match when={props.attachment.blockName === STATIC_VIDEO}>
<VideoPreview id={props.attachment.id} variant="small" />
diff --git a/js/app/packages/block-channel/component/Message/DynamicImageList.tsx b/js/app/packages/block-channel/component/Message/DynamicImageList.tsx
index 26981ef4f5..87636edcea 100644
--- a/js/app/packages/block-channel/component/Message/DynamicImageList.tsx
+++ b/js/app/packages/block-channel/component/Message/DynamicImageList.tsx
@@ -3,8 +3,14 @@ import { ImagePreview } from '@core/component/ImagePreview';
import { commsServiceClient } from '@service-comms/client';
import { Match, Switch } from 'solid-js';
+type ImageData = {
+ id: string;
+ width?: string | number | undefined;
+ height?: string | number | undefined;
+};
+
type DynamicImageListProps = {
- ids: string[];
+ images: ImageData[];
attachmentIds: string[];
isCurrentUser: boolean;
channelId?: string;
@@ -27,10 +33,10 @@ export function DynamicImageList(props: DynamicImageListProps) {
return (
<Switch>
- <Match when={props.ids.length === 1}>
+ <Match when={props.images.length === 1}>
<div class="max-w-[400px] w-fit mt-0.5">
<ImagePreview
- id={props.ids[0]}
+ image={props.images[0]}
variant="dynamic"
onDelete={
props.isCurrentUser
@@ -42,10 +48,10 @@ export function DynamicImageList(props: DynamicImageListProps) {
</div>
</Match>
- <Match when={props.ids.length > 1}>
+ <Match when={props.images.length > 1}>
<div class={`flex flex-wrap gap-2 mt-0.5`}>
<ImageGalleryPreview
- ids={props.ids}
+ images={props.images}
variant="dynamic"
attachmentIds={props.attachmentIds}
onDelete={props.isCurrentUser ? handleDelete : undefined}
diff --git a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx b/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
index 2a8a692226..97f788b7aa 100644
--- a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
+++ b/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
@@ -22,14 +22,25 @@ export function MessageAttachments(props: MessageAttachmentsProps) {
{/* Video attachments */}
<Show when={props.videoAttachments()?.length > 0 && !props.isDeleted()}>
<For each={props.videoAttachments()}>
- {(item) => <VideoPreview id={item.entity_id} variant="dynamic" />}
+ {(item) => (
+ <VideoPreview
+ id={item.entity_id}
+ variant="dynamic"
+ width={item.width}
+ height={item.height}
+ />
+ )}
</For>
</Show>
{/* Image attachments */}
<Show when={props.imageAttachments()?.length > 0 && !props.isDeleted()}>
<div class="flex not-first:mt-2">
<DynamicImageList
- ids={props.imageAttachments()?.map((a) => a.entity_id)}
+ images={props.imageAttachments()?.map((a) => ({
+ id: a.entity_id,
+ width: a.width ?? undefined,
+ height: a.height ?? undefined,
+ }))}
attachmentIds={props.imageAttachments()?.map((a) => a.id)}
isCurrentUser={props.isCurrentUser()}
channelId={props.channelId}
diff --git a/js/app/packages/block-channel/signal/channel.ts b/js/app/packages/block-channel/signal/channel.ts
index 5badd04d5f..c0ef753472 100644
--- a/js/app/packages/block-channel/signal/channel.ts
+++ b/js/app/packages/block-channel/signal/channel.ts
@@ -1,15 +1,17 @@
import type { ChannelData } from '@block-channel/definition';
import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
-import { type BlockName, createBlockMemo, createBlockStore } from '@core/block';
+import { createBlockMemo, createBlockStore } from '@core/block';
import { useChannelsContext } from '@core/component/ChannelsProvider';
import {
type InputAttachment,
isStaticAttachmentType,
} from '@core/store/cacheChannelInput';
import { isErr } from '@core/util/maybeResult';
+import { getImageDimensions, getVideoDimensions } from '@core/util/media';
import { useSendMessageMutation } from '@queries/channel/message';
import { commsServiceClient } from '@service-comms/client';
+import type { NewAttachment } from '@service-comms/generated/models';
import type { Attachment } from '@service-comms/generated/models/attachment';
import type { Channel } from '@service-comms/generated/models/channel';
import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';
@@ -236,22 +238,48 @@ export function useSendChannelMessageAction() {
const channelId = channelStore.get.id;
if (!channelId) return;
- const attachmentsToSend = attachments
- .map((a) => ({
- entity_id: a.id,
- entity_type: isStaticAttachmentType(a.blockName)
+ const attachmentsToSend = await Promise.allSettled(
+ attachments.map(async (a) => {
+ const attachmentType = isStaticAttachmentType(a.blockName)
? a.blockName
- : blockNameToItemType(a.blockName as BlockName),
- }))
- .filter((a) => a.entity_type !== undefined) as {
- entity_id: string;
- entity_type: string;
- }[];
+ : blockNameToItemType(a.blockName);
+
+ if (!attachmentType) return;
+
+ let attachment: NewAttachment = {
+ entity_id: a.id,
+ entity_type: attachmentType,
+ };
+
+ if (!a.file) return attachment;
+
+ if (
+ attachmentType !== 'static/image' &&
+ attachmentType !== 'static/video'
+ ) {
+ return attachment;
+ }
+
+ const dimensions =
+ attachmentType === 'static/image'
+ ? await getImageDimensions(a.file)
+ : await getVideoDimensions(a.file);
+
+ attachment.width = dimensions.width;
+ attachment.height = dimensions.height;
+
+ return attachment;
+ })
+ );
+
+ const filteredAttachements = attachmentsToSend
+ .map((r) => (r.status === 'fulfilled' ? r.value : undefined))
+ .filter((r) => r !== undefined);
const data = await mutation.mutateAsync({
channelID: channelId,
message: {
- attachments: attachmentsToSend,
+ attachments: filteredAttachements,
content: content ?? '',
thread_id: threadId,
mentions: mentions ?? [],
diff --git a/js/app/packages/block-channel/utils/inputAttachments.ts b/js/app/packages/block-channel/utils/inputAttachments.ts
index 881f468dfe..5fbff40d3e 100644
--- a/js/app/packages/block-channel/utils/inputAttachments.ts
+++ b/js/app/packages/block-channel/utils/inputAttachments.ts
@@ -71,6 +71,7 @@ export async function handleFileUpload(
name: file.name,
blockName: initialAttachmentType || 'unknown',
pending: true,
+ file,
};
const existingAttachments = inputAttachmentsStore.store[key] ?? [];
@@ -93,6 +94,7 @@ export async function handleFileUpload(
name: file.name,
blockName: initialAttachmentType || 'unknown',
pending: false,
+ file,
};
} else if (result.destination === 'dss' && result.type === 'document') {
finalAttachment = {
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 0646817030..4b0f95ad8c 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -225,7 +225,9 @@ export function MessageContainer(props: MessageContainerProps) {
<Match when={imageAttachmentsWithSfs().length === 1}>
<div class="max-w-[400px] w-fit mt-2">
<ImagePreview
- id={imageAttachmentsWithSfs()[0].sfs_id!}
+ image={{
+ id: imageAttachmentsWithSfs()[0].sfs_id!,
+ }}
variant="dynamic"
/>
</div>
@@ -233,7 +235,9 @@ export function MessageContainer(props: MessageContainerProps) {
<Match when={imageAttachmentsWithSfs().length > 1}>
<div class="flex flex-wrap gap-2 mt-2">
<ImageGalleryPreview
- ids={imageAttachmentsWithSfs().map((a) => a.sfs_id!)}
+ images={imageAttachmentsWithSfs().map((a) => ({
+ id: a.sfs_id!,
+ }))}
variant="dynamic"
attachmentIds={imageAttachmentsWithSfs().map(
(a) => a.db_id!
diff --git a/js/app/packages/core/component/AI/component/input/Attachment.tsx b/js/app/packages/core/component/AI/component/input/Attachment.tsx
index 1737d4657f..71b9589d75 100644
--- a/js/app/packages/core/component/AI/component/input/Attachment.tsx
+++ b/js/app/packages/core/component/AI/component/input/Attachment.tsx
@@ -85,7 +85,7 @@ function ImageAttachment(props: {
/>
</Show>
<ImagePreview
- id={props.attachment.attachmentId}
+ image={{ id: props.attachment.attachmentId }}
variant="small"
isDss={isDssImage(props.attachment)}
onError={(e) => {
diff --git a/js/app/packages/core/component/AI/component/message/UserMessage.tsx b/js/app/packages/core/component/AI/component/message/UserMessage.tsx
index c9095324e2..9d2f0c104d 100644
--- a/js/app/packages/core/component/AI/component/message/UserMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/UserMessage.tsx
@@ -90,7 +90,7 @@ export function UserMessage(props: {
<For each={imageAttachments()}>
{(attachment) => (
<ImagePreview
- id={attachment.attachmentId}
+ image={{ id: attachment.attachmentId }}
variant="small"
isDss={isDssImage(attachment)}
/>
diff --git a/js/app/packages/core/component/ImageGalleryPreview.tsx b/js/app/packages/core/component/ImageGalleryPreview.tsx
index 954c95757f..e32642db02 100644
--- a/js/app/packages/core/component/ImageGalleryPreview.tsx
+++ b/js/app/packages/core/component/ImageGalleryPreview.tsx
@@ -26,8 +26,14 @@ import { IconButton } from './IconButton';
import { DropdownMenuContent, MenuItem, MenuSeparator } from './Menu';
import { toast } from './Toast/Toast';
+type ImageData = {
+ id: string;
+ width?: string | number | undefined;
+ height?: string | number | undefined;
+};
+
export type ImageGalleryPreviewProps = {
- ids: string[];
+ images: ImageData[];
initialIndex?: number;
variant: 'small' | 'dynamic';
square?: boolean;
@@ -63,8 +69,11 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
const [touchEndX, setTouchEndX] = createSignal(0);
const [isSwiping, setIsSwiping] = createSignal(false);
- const currentImageUrl = (): string => {
- const id = props.ids[currentIndex()];
+ const currentImageUrl = () => {
+ const id = props.images[currentIndex()]?.id;
+
+ if (!id) return;
+
return `${SERVER_HOSTS['static-file']}/file/${id}`;
};
@@ -72,7 +81,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
return `${SERVER_HOSTS['static-file']}/file/${id}`;
};
- const hasNext = () => currentIndex() < props.ids.length - 1;
+ const hasNext = () => currentIndex() < props.images.length - 1;
const hasPrevious = () => currentIndex() > 0;
const navigateNext = () => {
@@ -123,13 +132,15 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
};
const downloadImage = async () => {
+ const imageUrl = currentImageUrl();
+ if (!imageUrl) return;
try {
- const response = await platformFetch(currentImageUrl());
+ const response = await platformFetch(imageUrl);
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
- a.download = `image-${props.ids[currentIndex()]}.png`;
+ a.download = `image-${props.images[currentIndex()]?.id}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -175,11 +186,11 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
};
const copyToClipboard = async () => {
+ const imageUrl = currentImageUrl();
+ if (!imageUrl) return;
if (isTouchDevice) {
try {
- const blob = await platformFetch(currentImageUrl()).then((res) =>
- res.blob()
- );
+ const blob = await platformFetch(imageUrl).then((res) => res.blob());
const file = new File([blob], 'image.png', { type: blob.type });
if (navigator.share) {
@@ -198,14 +209,14 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
]);
toast.success('Copied to clipboard');
} else {
- await navigator.clipboard.writeText(currentImageUrl());
+ await navigator.clipboard.writeText(imageUrl);
toast.success('Copied image URL to clipboard');
}
}
} catch (err) {
console.error('Share/clipboard operation failed:', err);
try {
- await navigator.clipboard.writeText(currentImageUrl());
+ await navigator.clipboard.writeText(imageUrl);
toast.success('Copied image URL to clipboard');
} catch {
toast.failure('Failed to copy image');
@@ -213,7 +224,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
}
} else {
try {
- const response = await platformFetch(currentImageUrl());
+ const response = await platformFetch(imageUrl);
const blob = await response.blob();
const isSupported = ClipboardItem.supports(blob.type);
@@ -226,13 +237,13 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
]);
toast.success('Copied to clipboard');
} else {
- await navigator.clipboard.writeText(currentImageUrl());
+ await navigator.clipboard.writeText(imageUrl);
toast.success('Copied image URL to clipboard');
}
} catch (err) {
console.error('Clipboard operation failed:', err);
try {
- await navigator.clipboard.writeText(currentImageUrl());
+ await navigator.clipboard.writeText(imageUrl);
toast.success('Copied image URL to clipboard');
} catch {
toast.failure('Failed to copy image');
@@ -432,8 +443,8 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
}}
>
<div class={props.wrapperClass ?? 'flex flex-row flex-wrap gap-2'}>
- <For each={props.ids}>
- {(id, index) => (
+ <For each={props.images}>
+ {(image, index) => (
<div
class={props.variant === 'dynamic' ? 'max-w-[200px] w-fit' : ''}
>
@@ -456,12 +467,12 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
<MenuItem
text="Copy image"
icon={ClipboardIcon}
- onClick={() => copyToClipboardById(id)}
+ onClick={() => copyToClipboardById(image.id)}
/>
<MenuItem
text="Download image"
icon={DownloadIcon}
- onClick={() => downloadImageById(id)}
+ onClick={() => downloadImageById(image.id)}
/>
<Show when={props.onDelete}>
<MenuSeparator />
@@ -485,7 +496,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
>
<img
class={`${THEMES[props.variant]} select-none`}
- src={getImageUrl(id)}
+ src={getImageUrl(image.id)}
alt="preview"
style={{
'-webkit-touch-callout': 'none',
@@ -545,7 +556,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
{/* Navigation arrows */}
<Show when={!isMobileWidth() || !isTouchDevice}>
- <Show when={props.ids.length > 1 && hasPrevious()}>
+ <Show when={props.images.length > 1 && hasPrevious()}>
<button
class="absolute left-4 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-opacity duration-300"
classList={{
@@ -562,7 +573,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
</button>
</Show>
- <Show when={props.ids.length > 1 && hasNext()}>
+ <Show when={props.images.length > 1 && hasNext()}>
<button
class="absolute right-4 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-opacity duration-300"
classList={{
@@ -581,7 +592,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
</Show>
{/* Navigation indicator */}
- <Show when={props.ids.length > 1}>
+ <Show when={props.images.length > 1}>
<div
class="absolute top-4 left-4 bg-dialog backdrop-blur-sm rounded-lg border border-edge px-3 py-1.5 shadow-md transition-opacity duration-300"
classList={{
@@ -593,7 +604,7 @@ export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
style={{ 'z-index': stackingContext.zModal + 1 }}
>
<span class="text-sm text-ink font-medium">
- {currentIndex() + 1}/{props.ids.length}
+ {currentIndex() + 1}/{props.images.length}
</span>
</div>
</Show>
diff --git a/js/app/packages/core/component/ImagePreview.tsx b/js/app/packages/core/component/ImagePreview.tsx
index 872bfedfba..a73c65cb4f 100644
--- a/js/app/packages/core/component/ImagePreview.tsx
+++ b/js/app/packages/core/component/ImagePreview.tsx
@@ -21,8 +21,14 @@ import { IconButton } from './IconButton';
import { DropdownMenuContent, MenuItem, MenuSeparator } from './Menu';
import { toast } from './Toast/Toast';
-export type ImagePreviewProps = {
+type ImageData = {
id: string;
+ width?: string | number | undefined;
+ height?: string | number | undefined;
+};
+
+export type ImagePreviewProps = {
+ image: ImageData;
variant: 'small' | 'dynamic';
square?: boolean;
onDelete?: () => void;
@@ -66,7 +72,7 @@ export function ImagePreview(props: ImagePreviewProps) {
console.error('do not access sfs image url for dss images');
return '';
}
- return `${SERVER_HOSTS['static-file']}/file/${props.id}`;
+ return `${SERVER_HOSTS['static-file']}/file/${props.image.id}`;
};
const imageSrc = () => {
@@ -80,7 +86,7 @@ export function ImagePreview(props: ImagePreviewProps) {
createEffect(() => {
if (!props.isDss) return;
- getDssImageBlob(props.id)
+ getDssImageBlob(props.image.id)
.then((blob) => {
if (!blob) {
throw new Error('Failed to download DSS image');
@@ -116,7 +122,7 @@ export function ImagePreview(props: ImagePreviewProps) {
if (!url) throw new Error('No blob url');
const a = document.createElement('a');
a.href = url;
- a.download = `image-${props.id}.png`;
+ a.download = `image-${props.image.id}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -302,6 +308,8 @@ export function ImagePreview(props: ImagePreviewProps) {
class={`${THEMES[props.variant]} select-none`}
src={imageSrc()}
alt="preview"
+ width={props.image.width}
+ height={props.image.height}
// Prevent long press on image ios behavior
style={{
'-webkit-touch-callout': 'none',
@@ -370,6 +378,8 @@ export function ImagePreview(props: ImagePreviewProps) {
class={THEMES['expanded']}
src={imageSrc()}
alt="preview"
+ width={props.image.width}
+ height={props.image.height}
/>
</Show>
</div>
diff --git a/js/app/packages/core/component/VideoPreview.tsx b/js/app/packages/core/component/VideoPreview.tsx
index 4e08502e53..791db5239e 100644
--- a/js/app/packages/core/component/VideoPreview.tsx
+++ b/js/app/packages/core/component/VideoPreview.tsx
@@ -3,6 +3,8 @@ import { staticFileIdEndpoint } from '@core/constant/servers';
export type VideoPreviewProps = {
id: string;
variant: 'small' | 'dynamic';
+ width?: string | number | undefined | null;
+ height?: string | number | undefined | null;
};
const THEMES = {
@@ -13,7 +15,12 @@ const THEMES = {
export function VideoPreview(props: VideoPreviewProps) {
return (
<div class={THEMES[props.variant]}>
- <video controls src={staticFileIdEndpoint(props.id)} />
+ <video
+ controls
+ src={staticFileIdEndpoint(props.id)}
+ width={props.width ?? undefined}
+ height={props.height ?? undefined}
+ />
</div>
);
}
diff --git a/js/app/packages/core/store/cacheChannelInput.ts b/js/app/packages/core/store/cacheChannelInput.ts
index 6c26ea3640..939485ee7e 100644
--- a/js/app/packages/core/store/cacheChannelInput.ts
+++ b/js/app/packages/core/store/cacheChannelInput.ts
@@ -23,6 +23,7 @@ export type InputAttachment = {
name: string;
blockName: AttachmentType;
pending?: boolean;
+ file?: File;
};
export interface DraftMessage {
diff --git a/js/app/packages/core/util/media.ts b/js/app/packages/core/util/media.ts
new file mode 100644
index 0000000000..e881057a31
--- /dev/null
+++ b/js/app/packages/core/util/media.ts
@@ -0,0 +1,79 @@
+type Dimensions = { width: number; height: number };
+
+export async function getVideoDimensions(src: string | File) {
+ return new Promise<Dimensions>((resolve) => {
+ const video = document.createElement('video');
+
+ function onMetadataLoaded(event: Event) {
+ const target = event.currentTarget;
+ if (target instanceof HTMLVideoElement) {
+ resolve({ width: target.videoWidth, height: target.videoHeight });
+ return;
+ }
+
+ resolve({ width: 0, height: 0 });
+ }
+
+ video.addEventListener('loadedmetadata', onMetadataLoaded, {
+ capture: false,
+ once: true,
+ });
+
+ video.addEventListener(
+ 'error',
+ () => {
+ video.removeEventListener('loadedmetadata', onMetadataLoaded);
+ resolve({ width: 0, height: 0 });
+ },
+ { capture: false, once: true }
+ );
+
+ let url;
+ if (src instanceof File) {
+ url = URL.createObjectURL(src);
+ } else {
+ url = src;
+ }
+
+ video.src = url;
+ });
+}
+
+export async function getImageDimensions(src: string | File) {
+ return new Promise<Dimensions>((resolve) => {
+ const image = new Image();
+
+ function onMetadataLoaded(event: Event) {
+ const target = event.currentTarget;
+ if (target instanceof HTMLImageElement) {
+ resolve({ width: target.naturalWidth, height: target.naturalHeight });
+ return;
+ }
+
+ resolve({ width: 0, height: 0 });
+ }
+
+ image.addEventListener('load', onMetadataLoaded, {
+ capture: false,
+ once: true,
+ });
+
+ image.addEventListener(
+ 'error',
+ () => {
+ image.removeEventListener('load', onMetadataLoaded);
+ resolve({ width: 0, height: 0 });
+ },
+ { capture: false, once: true }
+ );
+
+ let url;
+ if (src instanceof File) {
+ url = URL.createObjectURL(src);
+ } else {
+ url = src;
+ }
+
+ image.src = url;
+ });
+}