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(new-channels): ability to edit messages + better composition (#1907)

teo6085447063ba
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index 1bf841732c..f1b00c143f 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -45,6 +45,8 @@ import {
makeAttachmentTrackerPersistenceKey,
makeInputValuePersistenceKey,
} from '@channel/Input/utils/persistence';
+import { createMessageEditor } from './create-message-editor';
+import type { ChannelInputProps } from '@channel/Input/ChannelInput';
type ChannelProps = {
channelId: string;
@@ -78,6 +80,10 @@ export function Channel(props: ChannelProps) {
const threadManager = createThreadManager();
const threadPaginator = createThreadPaginator(messagesQuery);
+ const messageEditor = createMessageEditor({
+ channelId: () => props.channelId,
+ patchMessage: patchMessageMutation.mutate,
+ });
const threadListInitialScrollTarget: Accessor<ThreadListScrollTarget> = () =>
defaultThreadListTargetFromMessage(targetMessageId());
@@ -113,7 +119,6 @@ export function Channel(props: ChannelProps) {
const getMessageActions = createChannelMessageActions({
channelId: () => props.channelId,
userId,
- patchMessage: patchMessageMutation.mutate,
deleteMessage: deleteMessageMutation.mutate,
addReaction: addReactionMutation.mutate,
removeReaction: removeReactionMutation.mutate,
@@ -121,8 +126,23 @@ export function Channel(props: ChannelProps) {
const state = threadManager.getOrCreateThreadState(ctx.message.id);
state.setIsReplying(true);
},
+ onEdit: ({ message }) => {
+ messageEditor.start(message);
+ },
});
+ const onSend: ChannelInputProps['onSend'] = (snapshot) => {
+ const senderId = userId();
+ if (!senderId) return;
+
+ sendMessageMutation.mutate({
+ channelID: props.channelId,
+ senderId,
+ optimisticId: crypto.randomUUID(),
+ message: buildPostMessageRequest(snapshot),
+ });
+ };
+
return (
<Suspense>
<StaticMarkdownContext>
@@ -156,6 +176,7 @@ export function Channel(props: ChannelProps) {
replyInputState={state.replyInputState}
setReplyInputState={state.setReplyInputState}
listMeta={listMetaByMessageId()[item.id]}
+ messageEditor={messageEditor}
threadActions={{
onDismissNewMessages:
activityTracker.dismissNewMessages,
@@ -189,17 +210,7 @@ export function Channel(props: ChannelProps) {
onReady={(handle) => {
dragState.setAttachFilesToChannel(handle.attachFiles);
}}
- onSend={(snapshot) => {
- const senderId = userId();
- if (!senderId) return;
-
- sendMessageMutation.mutate({
- channelID: props.channelId,
- senderId,
- optimisticId: crypto.randomUUID(),
- message: buildPostMessageRequest(snapshot),
- });
- }}
+ onSend={onSend}
/>
</div>
</Suspense>
diff --git a/js/app/packages/channel/Channel/InlineMessageEditor.tsx b/js/app/packages/channel/Channel/InlineMessageEditor.tsx
new file mode 100644
index 0000000000..926f99e8a5
--- /dev/null
+++ b/js/app/packages/channel/Channel/InlineMessageEditor.tsx
@@ -0,0 +1,67 @@
+import TrashIcon from '@icon/regular/trash.svg';
+import FormatIcon from '@icon/regular/text-aa.svg';
+import {
+ ChannelInput,
+ createInputAttachmentTracker,
+ useInput,
+ useInputCommands,
+} from '../Input';
+import { renderIcon } from '../Input/utils/render-icon';
+import { InputActionButton } from '@channel/Input/PrimaryActions';
+import type { MessageEditor } from './create-message-editor';
+import { useMessage } from '../Message';
+
+function EditPrimaryActions() {
+ const commands = useInputCommands();
+ const input = useInput();
+
+ return (
+ <>
+ <InputActionButton
+ label="Format"
+ active={input().showFormatRibbon}
+ onClick={() => commands.toggleFormatRibbon()}
+ >
+ {renderIcon(FormatIcon, 'size-5')}
+ </InputActionButton>
+ <InputActionButton label="Discard Edit" onClick={() => commands.close()}>
+ {renderIcon(TrashIcon, 'size-5')}
+ </InputActionButton>
+ </>
+ );
+}
+
+type MessageEditorContentProps = {
+ channelId: string;
+ messageEditor: MessageEditor;
+};
+
+export function MessageEditorContent(props: MessageEditorContentProps) {
+ const message = useMessage();
+ const snapshot = () => props.messageEditor.state()?.snapshot;
+ const attachmentTracker = createInputAttachmentTracker({
+ initialAttachments: snapshot()?.attachments,
+ });
+
+ return (
+ <ChannelInput
+ input={{
+ mode: 'channel',
+ id: `edit-message-input-${message().id}`,
+ value: snapshot()?.value,
+ attachments: snapshot()?.attachments,
+ placeholder: 'Edit message',
+ }}
+ attachmentTracker={attachmentTracker}
+ markdownNamespace={`edit-message-${props.channelId}-${message().id}`}
+ onChange={(nextSnapshot) =>
+ props.messageEditor.update(message(), nextSnapshot)
+ }
+ onClose={() => props.messageEditor.cancel(message().id)}
+ onSend={(nextSnapshot) =>
+ props.messageEditor.save(message(), nextSnapshot)
+ }
+ primaryActions={<EditPrimaryActions />}
+ />
+ );
+}
diff --git a/js/app/packages/channel/Channel/create-channel-message-actions.ts b/js/app/packages/channel/Channel/create-channel-message-actions.ts
index ca650b540b..ed4622f36b 100644
--- a/js/app/packages/channel/Channel/create-channel-message-actions.ts
+++ b/js/app/packages/channel/Channel/create-channel-message-actions.ts
@@ -32,12 +32,6 @@ type RemoveReactionInput = {
currentReactions: MessageData['reactions'];
};
-type PatchMessageInput = {
- channelID: string;
- messageID: string;
- content: string;
-};
-
type DeleteMessageInput = {
channelID: string;
messageID: string;
@@ -47,20 +41,18 @@ type DeleteMessageInput = {
type ChannelMessageActionEffects = {
getLocationHref: () => string;
copyToClipboard: (text: string) => Promise<void>;
- promptForEdit: (content: string) => string | null;
notifyCopyLinkSuccess: () => void;
notifyCopyLinkFailure: (error: unknown) => void;
- notifyEmptyEdit: () => void;
};
export type CreateChannelMessageActionsOptions = {
channelId: Accessor<string>;
userId: Accessor<string | undefined>;
- patchMessage: (input: PatchMessageInput) => void;
deleteMessage: (input: DeleteMessageInput) => void;
addReaction: (input: AddReactionInput) => void;
removeReaction: (input: RemoveReactionInput) => void;
onReply?: MessageActionHandler;
+ onEdit?: MessageActionHandler;
effects?: Partial<ChannelMessageActionEffects>;
};
@@ -72,7 +64,6 @@ function createDefaultEffects(): ChannelMessageActionEffects {
window.location.search +
window.location.hash,
copyToClipboard: (text) => navigator.clipboard.writeText(text),
- promptForEdit: (content) => window.prompt('Edit message', content),
notifyCopyLinkSuccess: () => {
toast.success('Link copied to clipboard');
},
@@ -80,9 +71,6 @@ function createDefaultEffects(): ChannelMessageActionEffects {
console.error('failed to copy link', error);
toast.failure('Failed to copy link');
},
- notifyEmptyEdit: () => {
- toast.failure('Message cannot be empty');
- },
};
}
@@ -149,25 +137,7 @@ export function createChannelMessageActions(
effects.notifyCopyLinkFailure(error);
}
},
- onEdit: canEditDelete
- ? () => {
- const content = effects.promptForEdit(message.content);
- if (content == null) return;
-
- const nextContent = content.trim();
- if (nextContent.length === 0) {
- effects.notifyEmptyEdit();
- return;
- }
- if (nextContent === message.content) return;
-
- options.patchMessage({
- channelID: options.channelId(),
- messageID: message.id,
- content: nextContent,
- });
- }
- : undefined,
+ onEdit: canEditDelete ? options.onEdit : undefined,
onDelete: canEditDelete
? () => {
options.deleteMessage({
diff --git a/js/app/packages/channel/Channel/create-message-editor.ts b/js/app/packages/channel/Channel/create-message-editor.ts
new file mode 100644
index 0000000000..94838d4f50
--- /dev/null
+++ b/js/app/packages/channel/Channel/create-message-editor.ts
@@ -0,0 +1,90 @@
+import { toast } from '@core/component/Toast/Toast';
+import { createSignal, type Accessor } from 'solid-js';
+import type { InputSnapshot } from '@channel/Input';
+import type { MessageData } from '../Message';
+import type { MessageEditState } from '../Thread/types';
+import {
+ buildMessageEditSnapshot,
+ getAttachmentIdsToDelete,
+} from './message-editing';
+
+type PatchMessageInput = {
+ channelID: string;
+ messageID: string;
+ content: string;
+ attachmentIDsToDelete?: string[];
+};
+
+type CreateMessageEditorOptions = {
+ channelId: () => string;
+ patchMessage: (input: PatchMessageInput) => void;
+};
+
+export type MessageEditor = {
+ state: Accessor<MessageEditState | undefined>;
+ update: (message: MessageData, snapshot: InputSnapshot) => void;
+ cancel: (messageId: string) => void;
+ start: (message: MessageData) => void;
+ save: (message: MessageData, snapshot: InputSnapshot) => void;
+};
+
+export function createMessageEditor(
+ options: CreateMessageEditorOptions
+): MessageEditor {
+ const [editState, setEditState] = createSignal<MessageEditState>();
+
+ const start: MessageEditor['start'] = (message: MessageData) => {
+ setEditState({
+ messageId: message.id,
+ snapshot: buildMessageEditSnapshot(message),
+ });
+ };
+
+ const update: MessageEditor['update'] = (
+ _message: MessageData,
+ snapshot: InputSnapshot
+ ) => {
+ setEditState((current) => (current ? { ...current, snapshot } : current));
+ };
+
+ const cancel: MessageEditor['cancel'] = (messageId: string) => {
+ if (editState()?.messageId !== messageId) return;
+ setEditState(undefined);
+ };
+
+ const save: MessageEditor['save'] = (message, snapshot) => {
+ const nextContent = snapshot.value.trim();
+ if (nextContent.length === 0 && snapshot.attachments.length === 0) {
+ toast.failure('Message cannot be empty');
+ return;
+ }
+
+ const attachmentIDsToDelete = getAttachmentIdsToDelete({
+ currentAttachments: message.attachments,
+ nextSnapshot: snapshot,
+ });
+
+ const hasContentChanged = nextContent !== message.content;
+ const hasRemovedAttachments = attachmentIDsToDelete.length > 0;
+ if (!hasContentChanged && !hasRemovedAttachments) {
+ setEditState(undefined);
+ return;
+ }
+
+ options.patchMessage({
+ channelID: options.channelId(),
+ messageID: message.id,
+ content: nextContent,
+ attachmentIDsToDelete,
+ });
+ setEditState(undefined);
+ };
+
+ return {
+ state: editState,
+ save,
+ update,
+ cancel,
+ start,
+ };
+}
diff --git a/js/app/packages/channel/Channel/message-editing.ts b/js/app/packages/channel/Channel/message-editing.ts
new file mode 100644
index 0000000000..cd013bffdf
--- /dev/null
+++ b/js/app/packages/channel/Channel/message-editing.ts
@@ -0,0 +1,57 @@
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import {
+ isStaticAttachmentType,
+ STATIC_IMAGE,
+ STATIC_VIDEO,
+} from '@core/store/cacheChannelInput';
+import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
+import type { InputAttachmentData, InputSnapshot } from '../Input';
+import type { MessageData } from '../Message';
+
+function toInputAttachmentKind(
+ entityType: string
+): InputAttachmentData['kind'] | undefined {
+ if (entityType === STATIC_IMAGE) return 'image';
+ if (entityType === STATIC_VIDEO) return 'video';
+ if (!isStaticAttachmentType(entityType)) return 'document';
+}
+
+export function messageAttachmentToInputAttachment(
+ attachment: ApiMessageAttachment
+): InputAttachmentData | undefined {
+ const kind = toInputAttachmentKind(attachment.entity_type);
+ if (!kind) return;
+
+ return {
+ id: attachment.entity_id,
+ name: attachment.entity_id,
+ kind,
+ iconType:
+ kind === 'document'
+ ? fileTypeToBlockName(attachment.entity_type, true)
+ : undefined,
+ };
+}
+
+export function buildMessageEditSnapshot(message: MessageData): InputSnapshot {
+ return {
+ value: message.content,
+ mentions: [],
+ attachments: message.attachments
+ .map(messageAttachmentToInputAttachment)
+ .filter((attachment): attachment is InputAttachmentData => !!attachment),
+ };
+}
+
+export function getAttachmentIdsToDelete(args: {
+ currentAttachments: ApiMessageAttachment[];
+ nextSnapshot: InputSnapshot;
+}) {
+ const nextAttachmentIds = new Set(
+ args.nextSnapshot.attachments.map((attachment) => attachment.id)
+ );
+
+ return args.currentAttachments
+ .filter((attachment) => !nextAttachmentIds.has(attachment.entity_id))
+ .map((attachment) => attachment.id);
+}
diff --git a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
index f983a9041a..7cc4a2ad23 100644
--- a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
+++ b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
@@ -22,9 +22,9 @@ function buildHarness(input?: {
userId?: string | undefined;
channelId?: string;
onReply?: Parameters<typeof createChannelMessageActions>[0]['onReply'];
+ onEdit?: Parameters<typeof createChannelMessageActions>[0]['onEdit'];
effects?: Parameters<typeof createChannelMessageActions>[0]['effects'];
}) {
- const patchMessage = vi.fn();
const deleteMessage = vi.fn();
const addReaction = vi.fn();
const removeReaction = vi.fn();
@@ -32,16 +32,15 @@ function buildHarness(input?: {
const getMessageActions = createChannelMessageActions({
channelId: () => input?.channelId ?? 'channel-1',
userId: () => input?.userId,
- patchMessage,
deleteMessage,
addReaction,
removeReaction,
onReply: input?.onReply,
+ onEdit: input?.onEdit,
effects: input?.effects,
});
return {
- patchMessage,
deleteMessage,
addReaction,
removeReaction,
@@ -90,4 +89,16 @@ describe('createChannelMessageActions', () => {
currentReactions: [],
});
});
+
+ it('delegates edit handling to the provided callback', () => {
+ const onEdit = vi.fn();
+ const harness = buildHarness({ userId: 'user-1', onEdit });
+ const message = buildMessage();
+ const actions = harness.getMessageActions(message);
+
+ actions.onEdit?.({ message });
+
+ expect(onEdit).toHaveBeenCalledOnce();
+ expect(onEdit).toHaveBeenCalledWith({ message });
+ });
});
diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsx
index 4cc223792b..0bac6a1684 100644
--- a/js/app/packages/channel/Input/ChannelInput.tsx
+++ b/js/app/packages/channel/Input/ChannelInput.tsx
@@ -16,13 +16,16 @@ import type {
InputPersistenceKey,
} from './types';
import { applyInlineFormat, applyNodeFormat } from './utils/formatting';
+import type { JSX } from 'solid-js';
-type ChannelInputProps = InputCallbacks & {
+export type ChannelInputProps = InputCallbacks & {
input: InputData;
markdownNamespace?: string;
persistenceKey?: InputPersistenceKey;
attachmentTracker?: InputAttachmentTracker;
onReady?: (handle: InputHandle) => void;
+ primaryActions?: JSX.Element;
+ sendAction?: JSX.Element;
};
export function ChannelInput(props: ChannelInputProps) {
@@ -125,8 +128,8 @@ export function ChannelInput(props: ChannelInputProps) {
<Input.Attachments kind="media" />
<Input.Attachments kind="document" />
<Input.Footer>
- <Input.PrimaryActions />
- <Input.SendAction />
+ <Input.PrimaryActions>{props.primaryActions}</Input.PrimaryActions>
+ <Input.SendAction>{props.sendAction}</Input.SendAction>
</Input.Footer>
</Input.Layout>
</Input.DropZone>
diff --git a/js/app/packages/channel/Input/PrimaryActions.tsx b/js/app/packages/channel/Input/PrimaryActions.tsx
index 1794e53f42..6a19d05dd7 100644
--- a/js/app/packages/channel/Input/PrimaryActions.tsx
+++ b/js/app/packages/channel/Input/PrimaryActions.tsx
@@ -10,7 +10,7 @@ import { Button } from '@ui/components/Button';
import { LabelAndHotKey } from '@core/component/Tooltip';
import { CHANNEL_FILE_PICKER_ACCEPT } from './accepted-file-types';
-function InputActionButton(props: {
+export function InputActionButton(props: {
label: string;
onClick?: (event: MouseEvent) => void;
active?: boolean;
diff --git a/js/app/packages/channel/Message/ChannelMessage.tsx b/js/app/packages/channel/Message/ChannelMessage.tsx
index 4084537acc..37da724188 100644
--- a/js/app/packages/channel/Message/ChannelMessage.tsx
+++ b/js/app/packages/channel/Message/ChannelMessage.tsx
@@ -1,60 +1,149 @@
+import { Match, Show, Switch } from 'solid-js';
import type { MessageActions, MessageData } from './types';
import { Message } from './Message';
import type { ChannelMessageListMeta } from './list-meta';
-import { Show } from 'solid-js';
+import { useMessage } from './context';
+import type { MessageEditor } from '../Channel/create-message-editor';
+import { MessageEditorContent } from '../Channel/InlineMessageEditor';
type ChannelMessageProps = {
+ channelId: string;
message: MessageData;
actions?: MessageActions;
listMeta?: ChannelMessageListMeta;
+ messageEditor?: MessageEditor;
};
-function MessageFooter() {
+function isEditingMessage(
+ messageEditor: MessageEditor | undefined,
+ messageId: string
+) {
+ return messageEditor?.state()?.messageId === messageId;
+}
+
+function MessageContentSlot(props: {
+ channelId: string;
+ messageEditor?: MessageEditor;
+ class?: string;
+}) {
+ const message = useMessage();
+ const isEditing = () => isEditingMessage(props.messageEditor, message().id);
+
return (
- <>
+ <Switch>
+ <Match when={isEditing() && props.messageEditor}>
+ {(messageEditor) => (
+ <MessageEditorContent
+ channelId={props.channelId}
+ messageEditor={messageEditor()}
+ />
+ )}
+ </Match>
+ <Match when={true}>
+ <Message.Content class={props.class} />
+ </Match>
+ </Switch>
+ );
+}
+
+function MessageFooter(props: { messageEditor?: MessageEditor }) {
+ const message = useMessage();
+
+ return (
+ <Show when={!isEditingMessage(props.messageEditor, message().id)}>
<Message.Attachments />
<Message.Reactions />
- </>
+ </Show>
+ );
+}
+
+function MessageActionsSlot(props: { messageEditor?: MessageEditor }) {
+ const message = useMessage();
+
+ return (
+ <Show when={!isEditingMessage(props.messageEditor, message().id)}>
+ <Message.ActionMenu />
+ </Show>
+ );
+}
+
+function GroupedMeta(props: { messageEditor?: MessageEditor }) {
+ const message = useMessage();
+
+ return (
+ <Show when={!isEditingMessage(props.messageEditor, message().id)}>
+ <div class="flex items-center gap-2 shrink-0">
+ <Message.EditedIndicator />
+ <Message.Timestamp compact />
+ </div>
+ </Show>
);
}
-function NormalLayout() {
+function RegularMessageLayout(props: {
+ channelId: string;
+ messageEditor?: MessageEditor;
+}) {
return (
<Message.Layout>
- <div class="flex items-start gap-2">
+ <Message.Slot placement="icon">
<Message.SenderIcon />
- <div class="flex flex-col flex-1 min-w-0">
- <div class="flex items-center gap-2">
- <Message.SenderName />
- <Message.EditedIndicator />
- <Message.Timestamp class="ml-auto" />
- </div>
- <Message.Content />
- <MessageFooter />
- </div>
- </div>
- <Message.ActionMenu />
+ </Message.Slot>
+ <Message.Slot placement="header" class="flex items-center gap-2 min-w-0">
+ <Message.SenderName />
+ <Message.EditedIndicator />
+ <Message.Timestamp class="ml-auto" />
+ </Message.Slot>
+ <Message.Slot placement="content" class="mt-0.5">
+ <MessageContentSlot
+ channelId={props.channelId}
+ messageEditor={props.messageEditor}
+ />
+ </Message.Slot>
+ <Message.Slot placement="footer" class="flex flex-col min-w-0">
+ <MessageFooter messageEditor={props.messageEditor} />
+ </Message.Slot>
+ <Message.Slot placement="actions">
+ <MessageActionsSlot messageEditor={props.messageEditor} />
+ </Message.Slot>
</Message.Layout>
);
}
-function GroupedLayout() {
+function GroupedMessageLayout(props: {
+ channelId: string;
+ messageEditor?: MessageEditor;
+}) {
+ const message = useMessage();
+ const isEditing = () => isEditingMessage(props.messageEditor, message().id);
+
return (
<Message.Layout class="py-1">
- <div class="flex items-start gap-2">
+ <Message.Slot placement="icon">
<Message.SenderIcon hidden />
- <div class="flex flex-col flex-1 min-w-0">
- <div class="flex items-center gap-3 min-w-0">
- <Message.Content class="flex-1 min-w-0" />
- <div class="flex items-center gap-2 shrink-0">
- <Message.EditedIndicator />
- <Message.Timestamp compact />
- </div>
- </div>
- <MessageFooter />
+ </Message.Slot>
+ <Message.Slot placement="content" class="mt-0.5">
+ <div
+ class="flex gap-3 min-w-0"
+ classList={{
+ 'items-center': !isEditing(),
+ 'items-start': isEditing(),
+ }}
+ >
+ <MessageContentSlot
+ channelId={props.channelId}
+ messageEditor={props.messageEditor}
+ class="flex-1 min-w-0"
+ />
+ <GroupedMeta messageEditor={props.messageEditor} />
</div>
- </div>
- <Message.ActionMenu />
+ </Message.Slot>
+ <Message.Slot placement="footer" class="flex flex-col min-w-0">
+ <MessageFooter messageEditor={props.messageEditor} />
+ </Message.Slot>
+ <Message.Slot placement="actions">
+ <MessageActionsSlot messageEditor={props.messageEditor} />
+ </Message.Slot>
</Message.Layout>
);
}
@@ -64,9 +153,20 @@ export function ChannelMessage(props: ChannelMessageProps) {
return (
<Message.Root message={props.message} actions={props.actions}>
- <Show when={isGrouped()} fallback={<NormalLayout />}>
- <GroupedLayout />
- </Show>
+ <Switch>
+ <Match when={isGrouped()}>
+ <GroupedMessageLayout
+ channelId={props.channelId}
+ messageEditor={props.messageEditor}
+ />
+ </Match>
+ <Match when={true}>
+ <RegularMessageLayout
+ channelId={props.channelId}
+ messageEditor={props.messageEditor}
+ />
+ </Match>
+ </Switch>
</Message.Root>
);
}
diff --git a/js/app/packages/channel/Message/Layout.tsx b/js/app/packages/channel/Message/Layout.tsx
index 168020825f..e3b3c3c8f4 100644
--- a/js/app/packages/channel/Message/Layout.tsx
+++ b/js/app/packages/channel/Message/Layout.tsx
@@ -5,8 +5,17 @@ export function Layout(props: JSX.HTMLAttributes<HTMLDivElement>) {
const [local, rest] = splitProps(props, ['class', 'children']);
return (
- <div class={cn('flex flex-col w-full p-2', local.class)} {...rest}>
- {local.children}
+ <div class={cn('w-full p-2', local.class)} data-message-layout {...rest}>
+ <div
+ class="grid min-w-0 items-start gap-x-2"
+ style={{
+ 'grid-template-columns': 'var(--user-icon-width) minmax(0, 1fr) auto',
+ 'grid-template-areas':
+ '"icon header actions" "icon content actions" "icon footer actions"',
+ }}
+ >
+ <div class="contents">{local.children}</div>
+ </div>
</div>
);
}
diff --git a/js/app/packages/channel/Message/Message.ts b/js/app/packages/channel/Message/Message.ts
index 5d9d26742b..cf5449860e 100644
--- a/js/app/packages/channel/Message/Message.ts
+++ b/js/app/packages/channel/Message/Message.ts
@@ -1,5 +1,6 @@
import { Root } from './Root';
import { Layout } from './Layout';
+import { Slot } from './Slot';
import { SenderName } from './SenderName';
import { SenderIcon } from './SenderIcon';
import { Timestamp } from './Timestamp';
@@ -16,6 +17,7 @@ import { ActionMenu } from './ActionMenu';
export const Message = {
Root,
Layout,
+ Slot,
SenderName,
SenderIcon,
Timestamp,
diff --git a/js/app/packages/channel/Message/Slot.tsx b/js/app/packages/channel/Message/Slot.tsx
new file mode 100644
index 0000000000..0a8381f6e1
--- /dev/null
+++ b/js/app/packages/channel/Message/Slot.tsx
@@ -0,0 +1,69 @@
+import { cn } from '@ui/utils/classname';
+import {
+ type ComponentProps,
+ type JSX,
+ type ValidComponent,
+ splitProps,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+
+type SlotElement = 'div' | 'span' | 'button';
+
+export type MessageSlotPlacement =
+ | 'icon'
+ | 'header'
+ | 'content'
+ | 'footer'
+ | 'actions';
+
+type CommonProps = {
+ children?: JSX.Element;
+ placement: MessageSlotPlacement;
+ class?: string;
+ style?: JSX.CSSProperties | string;
+};
+
+type SlotProps<T extends ValidComponent = 'div'> = { as?: T } & CommonProps &
+ Omit<ComponentProps<T>, keyof CommonProps | 'component'>;
+
+function placementStyle(
+ placement: MessageSlotPlacement
+): Partial<JSX.CSSProperties> {
+ switch (placement) {
+ case 'icon':
+ return { 'grid-area': 'icon' };
+ case 'header':
+ return { 'grid-area': 'header' };
+ case 'content':
+ return { 'grid-area': 'content' };
+ case 'footer':
+ return { 'grid-area': 'footer' };
+ case 'actions':
+ return { 'grid-area': 'actions' };
+ }
+}
+
+export function Slot<T extends SlotElement = 'div'>(props: SlotProps<T>) {
+ const [local, rest] = splitProps(props, [
+ 'as',
+ 'class',
+ 'children',
+ 'placement',
+ 'style',
+ ]);
+
+ return (
+ <Dynamic
+ component={local.as ?? ('div' as SlotElement)}
+ class={cn('message-slot min-w-0', local.class)}
+ data-message-slot={local.placement}
+ style={{
+ ...placementStyle(local.placement),
+ ...(typeof local.style === 'object' ? local.style : {}),
+ }}
+ {...rest}
+ >
+ {local.children}
+ </Dynamic>
+ );
+}
diff --git a/js/app/packages/channel/Thread/ChannelThread.tsx b/js/app/packages/channel/Thread/ChannelThread.tsx
index 6875a752ce..8987833ace 100644
--- a/js/app/packages/channel/Thread/ChannelThread.tsx
+++ b/js/app/packages/channel/Thread/ChannelThread.tsx
@@ -77,9 +77,11 @@ export function ChannelThread(props: ThreadProps) {
channelId={props.channelId()}
>
<ChannelMessage
+ channelId={props.channelId()}
message={props.data()}
actions={props.getMessageActions?.(props.data())}
listMeta={props.listMeta}
+ messageEditor={props.messageEditor}
/>
</MarkMessaageNotifications>
<Show when={hasReplies() || props.isReplying()}>
@@ -91,19 +93,21 @@ export function ChannelThread(props: ThreadProps) {
when={!repliesQuery.isLoading && hasFetchedReplies()}
fallback={
<Thread.ReplyList
+ channelId={props.channelId()}
threadId={props.data().id}
replies={previewReplies()}
getMessageActions={props.getMessageActions}
- channelId={props.channelId()}
+ messageEditor={props.messageEditor}
/>
}
>
<Suspense>
<Thread.ReplyList
+ channelId={props.channelId()}
threadId={props.data().id}
replies={fetchedReplies()}
getMessageActions={props.getMessageActions}
- channelId={props.channelId()}
+ messageEditor={props.messageEditor}
/>
</Suspense>
</Show>
diff --git a/js/app/packages/channel/Thread/ThreadReplyList.tsx b/js/app/packages/channel/Thread/ThreadReplyList.tsx
index 28b14d92f4..23062460ec 100644
--- a/js/app/packages/channel/Thread/ThreadReplyList.tsx
+++ b/js/app/packages/channel/Thread/ThreadReplyList.tsx
@@ -7,12 +7,14 @@ import {
import type { ApiThreadReply } from '@service-comms/client';
import { MarkMessaageNotifications } from '@notifications/components/MarkMessageNotifications';
import { buildThreadReplyListMeta } from './reply-list-meta';
+import type { MessageEditor } from '../Channel/create-message-editor';
export function ThreadReplyList(props: {
+ channelId: string;
threadId: string;
replies: Array<ApiThreadReply>;
getMessageActions?: (message: MessageData) => MessageActions | undefined;
- channelId: string;
+ messageEditor?: MessageEditor;
}) {
const listMetaByReplyId = createMemo(() =>
buildThreadReplyListMeta(props.replies)
@@ -32,9 +34,11 @@ export function ThreadReplyList(props: {
channelId={props.channelId}
>
<ChannelMessage
+ channelId={props.channelId}
message={reply}
actions={props.getMessageActions?.(replyMessage())}
listMeta={listMetaByReplyId()[reply.id]}
+ messageEditor={props.messageEditor}
/>
</MarkMessaageNotifications>
);
diff --git a/js/app/packages/channel/Thread/types.ts b/js/app/packages/channel/Thread/types.ts
index c5ebf51c48..e0140cb5b0 100644
--- a/js/app/packages/channel/Thread/types.ts
+++ b/js/app/packages/channel/Thread/types.ts
@@ -6,6 +6,7 @@ import type {
} from '../Message';
import type { Accessor, Setter } from 'solid-js';
import type { InputSnapshot } from '@channel/Input';
+import type { MessageEditor } from '@channel/Channel/create-message-editor';
export type ThreadActions = {
onDismissNewMessages?: () => void;
@@ -20,10 +21,16 @@ export type ThreadState = {
setReplyInputState: Setter<InputSnapshot | undefined>;
};
+export type MessageEditState = {
+ messageId: string;
+ snapshot: InputSnapshot;
+};
+
export type ThreadProps = {
data: Accessor<ApiChannelMessage>;
channelId: Accessor<string>;
getMessageActions?: (message: MessageData) => MessageActions | undefined;
listMeta?: ChannelMessageListMeta;
threadActions?: ThreadActions;
+ messageEditor?: MessageEditor;
} & ThreadState;
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index a70d449e1b..8324adc865 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -5,10 +5,10 @@ import {
type ApiThreadReply,
type ChannelMessagesPage,
} from '@service-comms/client';
-import type { Attachment as ApiAttachment } from '@service-comms/generated/models';
import { type InfiniteData, useInfiniteQuery } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
import type { ApiCountedReaction } from '@service-storage/generated/schemas';
+import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
import { queryClient } from '../client';
import { channelKeys } from './keys';
import {
@@ -253,7 +253,7 @@ export function replaceTopLevelMessageReactionsInChannelMessages(
export function replaceTopLevelMessageAttachmentsInChannelMessages(
data: ChannelMessagesData | undefined,
messageId: string,
- attachments: ApiAttachment[]
+ attachments: ApiMessageAttachment[]
): ChannelMessagesData | undefined {
if (!data) return data;
@@ -262,6 +262,31 @@ export function replaceTopLevelMessageAttachmentsInChannelMessages(
);
}
+export function replaceTopLevelMessageStateInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ messageId: string,
+ nextState: {
+ content: string;
+ editedAt: string | null | undefined;
+ updatedAt: string;
+ attachments: ApiMessageAttachment[];
+ }
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) =>
+ message.id === messageId
+ ? {
+ ...message,
+ content: nextState.content,
+ edited_at: nextState.editedAt ?? undefined,
+ updated_at: nextState.updatedAt,
+ attachments: nextState.attachments,
+ }
+ : message
+ );
+}
+
export function getTopLevelMessageSnapshot(
data: ChannelMessagesData | undefined,
messageId: string
@@ -383,7 +408,7 @@ export function replaceThreadReplyAttachmentsInChannelMessages(
data: ChannelMessagesData | undefined,
threadId: string,
replyId: string,
- attachments: ApiAttachment[]
+ attachments: ApiMessageAttachment[]
): ChannelMessagesData | undefined {
if (!data) return data;
@@ -408,6 +433,46 @@ export function replaceThreadReplyAttachmentsInChannelMessages(
});
}
+export function replaceThreadReplyStateInChannelMessages(
+ data: ChannelMessagesData | undefined,
+ threadId: string,
+ replyId: string,
+ nextState: {
+ content: string;
+ editedAt: string | null | undefined;
+ updatedAt: string;
+ attachments: ApiMessageAttachment[];
+ }
+): ChannelMessagesData | undefined {
+ if (!data) return data;
+
+ return mapChannelMessagesItems(data, (message) => {
+ if (message.id !== threadId) return message;
+ let didChange = false;
+ const preview = message.thread.preview.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return {
+ ...reply,
+ content: nextState.content,
+ edited_at: nextState.editedAt ?? undefined,
+ updated_at: nextState.updatedAt,
+ attachments: nextState.attachments,
+ };
+ });
+
+ if (!didChange) return message;
+
+ return {
+ ...message,
+ thread: {
+ ...message.thread,
+ preview,
+ },
+ };
+ });
+}
+
export function getThreadPreviewReplySnapshot(
data: ChannelMessagesData | undefined,
threadId: string,
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index 4f93f445e6..845bfcc16b 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -24,8 +24,10 @@ import { channelKeys, ChannelNonceKeys } from './keys';
import { createMutationNonce, registerNonce } from '../nonce';
import {
captureDeleteSnapshotForTarget,
+ getTargetMessageState,
insertMessageIntoTargetCaches,
removeMessageFromTargetCaches,
+ replaceTargetMessageState,
restoreMessageInTargetCaches,
softInvalidateTargetCaches,
replaceTargetMessageId,
@@ -47,6 +49,12 @@ function registerMessageNonces(
}
}
+function normalizeDateValue(
+ value: DateValue | null | undefined
+): string | null | undefined {
+ return value instanceof Date ? value.toISOString() : value;
+}
+
type WithChannelId<T> = T & { channelId: string };
type WithOptimisticId<T> = T & { optimisticId: string };
type WithSenderId<T> = T & { senderId: string };
@@ -66,9 +74,11 @@ export type DeleteMessageContext = {
export type UpdateMessageContext = {
messageId: string;
+ target: ReturnType<typeof resolveMessageTarget>;
previousContent: string;
previousEditedAt: DateValue | null | undefined;
previousUpdatedAt: DateValue;
+ previousAttachments: Attachment[];
};
function makeOptimisticAttachments(
@@ -414,12 +424,37 @@ export function rollbackDeleteChannelMessage(
* Returns minimal context: only the previous content and timestamps.
*/
export function optimisticUpdateChannelMessage(
- vars: WithChannelId<Pick<ChannelMessage, 'message_id' | 'content'>>
+ vars: WithChannelId<
+ Pick<ChannelMessage, 'message_id' | 'content'> & {
+ attachment_ids_to_delete?: string[];
+ }
+ >
): UpdateMessageContext | undefined {
const queryKey = channelKeys.withID(vars.channelId).queryKey;
- queryClient.cancelQueries({ queryKey });
+ const target = resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.message_id,
+ });
let context: UpdateMessageContext | undefined;
+ const deletedAttachmentIDs = new Set(vars.attachment_ids_to_delete ?? []);
+ const now = new Date().toISOString();
+
+ const renderedState = getTargetMessageState(vars.channelId, target);
+ if (renderedState) {
+ context = {
+ messageId: vars.message_id,
+ target,
+ previousContent: renderedState.content,
+ previousEditedAt: renderedState.editedAt,
+ previousUpdatedAt: renderedState.updatedAt,
+ previousAttachments: renderedState.attachments.map((attachment) => ({
+ ...attachment,
+ channel_id: vars.channelId,
+ message_id: vars.message_id,
+ })),
+ };
+ }
queryClient.setQueriesData(
{ queryKey },
@@ -431,13 +466,15 @@ export function optimisticUpdateChannelMessage(
context = {
messageId: vars.message_id,
+ target,
previousContent: message.content,
previousEditedAt: message.edited_at,
previousUpdatedAt: message.updated_at,
+ previousAttachments: prev.attachments.filter(
+ (attachment) => attachment.message_id === vars.message_id
+ ),
};
- const now = new Date().toISOString();
-
return {
...prev,
messages: prev.messages.map((m) =>
@@ -445,10 +482,26 @@ export function optimisticUpdateChannelMessage(
? { ...m, content: vars.content, edited_at: now, updated_at: now }
: m
),
+ attachments: prev.attachments.filter(
+ (attachment) =>
+ attachment.message_id !== vars.message_id ||
+ !deletedAttachmentIDs.has(attachment.id)
+ ),
};
}
);
+ if (ENABLE_NEW_CHANNELS && context) {
+ replaceTargetMessageState(vars.channelId, target, {
+ content: vars.content,
+ editedAt: now,
+ updatedAt: now,
+ attachments: context.previousAttachments.filter(
+ (attachment) => !deletedAttachmentIDs.has(attachment.id)
+ ),
+ });
+ }
+
return context;
}
@@ -478,9 +531,24 @@ export function rollbackUpdateChannelMessage(
}
: m
),
+ attachments: [
+ ...prev.attachments.filter(
+ (attachment) => attachment.message_id !== context.messageId
+ ),
+ ...context.previousAttachments,
+ ],
};
}
);
+
+ if (ENABLE_NEW_CHANNELS) {
+ replaceTargetMessageState(channelId, context.target, {
+ content: context.previousContent,
+ editedAt: normalizeDateValue(context.previousEditedAt),
+ updatedAt: normalizeDateValue(context.previousUpdatedAt) ?? '',
+ attachments: context.previousAttachments,
+ });
+ }
}
const { track } = withAnalytics();
@@ -656,6 +724,7 @@ type PatchMessageParams = {
channelID: string;
messageID: string;
content: string;
+ attachmentIDsToDelete?: string[];
};
type PatchMutationContext = UpdateMessageContext | undefined;
@@ -685,6 +754,7 @@ export function usePatchMessageMutation(
channel_id: vars.channelID,
message_id: vars.messageID,
content: vars.content,
+ attachment_ids_to_delete: vars.attachmentIDsToDelete,
nonce: patchNonce.use(vars),
})
);
@@ -696,12 +766,16 @@ export function usePatchMessageMutation(
PatchMutationContext
>(
{
- onMutate: (vars) => {
+ onMutate: async (vars) => {
+ await queryClient.cancelQueries({
+ queryKey: channelKeys.withID(vars.channelID).queryKey,
+ });
patchNonce.prepare(vars);
return optimisticUpdateChannelMessage({
channelId: vars.channelID,
message_id: vars.messageID,
content: vars.content,
+ attachment_ids_to_delete: vars.attachmentIDsToDelete,
});
},
onError(error, vars, context) {
@@ -714,6 +788,15 @@ export function usePatchMessageMutation(
onSettled: (_data, _error, vars) => {
patchNonce.cleanup(vars);
softInvalidateChannelWithID(vars.channelID);
+ if (ENABLE_NEW_CHANNELS) {
+ softInvalidateTargetCaches(
+ vars.channelID,
+ resolveMessageTarget({
+ channelId: vars.channelID,
+ messageId: vars.messageID,
+ })
+ );
+ }
},
},
callbacks
diff --git a/js/app/packages/queries/channel/reconcile.ts b/js/app/packages/queries/channel/reconcile.ts
index 43152aaedd..8fc565423f 100644
--- a/js/app/packages/queries/channel/reconcile.ts
+++ b/js/app/packages/queries/channel/reconcile.ts
@@ -6,6 +6,8 @@ import {
insertTopLevelMessageIntoChannelMessages,
removeThreadReplyFromChannelMessages,
removeTopLevelMessageFromChannelMessages,
+ replaceThreadReplyStateInChannelMessages,
+ replaceTopLevelMessageStateInChannelMessages,
restoreThreadPreviewReplyInChannelMessages,
restoreTopLevelMessageInChannelMessages,
replaceThreadReplyIdInChannelMessages,
@@ -25,6 +27,7 @@ import {
getThreadReplySnapshot,
insertThreadReply,
removeThreadReply,
+ replaceThreadReplyState,
restoreThreadReply,
replaceThreadReplyId,
replaceThreadReplyReactions,
@@ -37,6 +40,7 @@ import type {
Attachment as ApiAttachment,
CountedReaction,
} from '@service-comms/generated/models';
+import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
import type { GetChannelResponse } from './types';
import { queryClient } from '../client';
import { channelKeys } from './keys';
@@ -63,6 +67,13 @@ export type DeleteTargetSnapshot =
preview?: ThreadPreviewReplySnapshot;
};
+export type TargetMessageState = {
+ content: string;
+ editedAt: string | null | undefined;
+ updatedAt: string;
+ attachments: ApiMessageAttachment[];
+};
+
export function makeMessageTarget(args: {
messageId: string;
threadId?: string;
@@ -340,6 +351,77 @@ export function replaceTargetAttachments(
);
}
+export function getTargetMessageState(
+ channelId: string,
+ target: MessageTarget
+): TargetMessageState | undefined {
+ if (target.kind === 'thread_reply') {
+ const reply =
+ queryClient
+ .getQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId)
+ )
+ ?.find((item) => item.id === target.messageId) ??
+ findThreadPreviewReplySnapshotInChannelMessages(
+ channelId,
+ target.threadId,
+ target.messageId
+ )?.reply;
+
+ if (!reply) return;
+
+ return {
+ content: reply.content,
+ editedAt: reply.edited_at,
+ updatedAt: reply.updated_at,
+ attachments: reply.attachments,
+ };
+ }
+
+ const message = findTopLevelMessageSnapshotInChannelMessages(
+ channelId,
+ target.messageId
+ )?.message;
+ if (!message) return;
+
+ return {
+ content: message.content,
+ editedAt: message.edited_at,
+ updatedAt: message.updated_at,
+ attachments: message.attachments,
+ };
+}
+
+export function replaceTargetMessageState(
+ channelId: string,
+ target: MessageTarget,
+ nextState: TargetMessageState
+) {
+ if (target.kind === 'thread_reply') {
+ queryClient.setQueryData<Array<ApiThreadReply>>(
+ getThreadRepliesQueryKey(channelId, target.threadId),
+ (prev) => replaceThreadReplyState(prev, target.messageId, nextState)
+ );
+ setChannelMessagesData(channelId, (prev) =>
+ replaceThreadReplyStateInChannelMessages(
+ prev,
+ target.threadId,
+ target.messageId,
+ nextState
+ )
+ );
+ return;
+ }
+
+ setChannelMessagesData(channelId, (prev) =>
+ replaceTopLevelMessageStateInChannelMessages(
+ prev,
+ target.messageId,
+ nextState
+ )
+ );
+}
+
/** Soft-invalidates the rendered caches touched by a target message. */
export function softInvalidateTargetCaches(
channelId: string,
diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
index 081e486ceb..f4b149fb83 100644
--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -42,7 +42,9 @@ import {
} from '../channel-messages';
import {
optimisticInsertChannelMessage,
+ optimisticUpdateChannelMessage,
rollbackInsertChannelMessage,
+ rollbackUpdateChannelMessage,
} from '../message';
import {
optimisticAddReaction,
@@ -308,6 +310,152 @@ describe('channel optimistic cache regressions', () => {
).toEqual([{ emoji: '👍', users: ['user-1'] }]);
});
+ it('rolls back optimistic top-level edits when only the paginated cache is warm', () => {
+ seedChannelMessagesCache(
+ 'channel-1',
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('message-1', '2024-01-03T00:00:00.000Z', {
+ content: 'Original body',
+ attachments: [
+ {
+ id: 'attachment-1',
+ entity_id: 'doc-1',
+ entity_type: 'document',
+ created_at: '2024-01-03T00:00:00.000Z',
+ },
+ ],
+ }),
+ ],
+ ])
+ );
+
+ const context = optimisticUpdateChannelMessage({
+ channelId: 'channel-1',
+ message_id: 'message-1',
+ content: 'Edited body',
+ attachment_ids_to_delete: ['attachment-1'],
+ });
+
+ expect(getChannelMessagesFromCache('channel-1')?.pages[0].items[0]).toEqual(
+ expect.objectContaining({
+ content: 'Edited body',
+ attachments: [],
+ })
+ );
+
+ if (context) {
+ rollbackUpdateChannelMessage('channel-1', context);
+ }
+
+ expect(getChannelMessagesFromCache('channel-1')?.pages[0].items[0]).toEqual(
+ expect.objectContaining({
+ content: 'Original body',
+ attachments: [
+ expect.objectContaining({
+ id: 'attachment-1',
+ entity_id: 'doc-1',
+ }),
+ ],
+ })
+ );
+ });
+
+ it('rolls back optimistic thread reply edits when only the thread caches are warm', () => {
+ seedChannelMessagesCache(
+ 'channel-1',
+ createChannelMessagesData([
+ [
+ createPaginatedMessage('parent-1', '2024-01-03T00:00:00.000Z', {
+ thread: {
+ preview: [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z', {
+ content: 'Original reply',
+ attachments: [
+ {
+ id: 'attachment-2',
+ entity_id: 'image-1',
+ entity_type: 'static_image',
+ created_at: '2024-01-03T01:00:00.000Z',
+ },
+ ],
+ }),
+ ],
+ reply_count: 1,
+ latest_reply_at: '2024-01-03T01:00:00.000Z',
+ },
+ }),
+ ],
+ ])
+ );
+ seedThreadRepliesCache('channel-1', 'parent-1', [
+ createThreadReply('reply-1', '2024-01-03T01:00:00.000Z', {
+ content: 'Original reply',
+ attachments: [
+ {
+ id: 'attachment-2',
+ entity_id: 'image-1',
+ entity_type: 'static_image',
+ created_at: '2024-01-03T01:00:00.000Z',
+ },
+ ],
+ }),
+ ]);
+
+ const context = optimisticUpdateChannelMessage({
+ channelId: 'channel-1',
+ message_id: 'reply-1',
+ content: 'Edited reply',
+ attachment_ids_to_delete: ['attachment-2'],
+ });
+
+ expect(getThreadRepliesFromCache('channel-1', 'parent-1')?.[0]).toEqual(
+ expect.objectContaining({
+ content: 'Edited reply',
+ attachments: [],
+ })
+ );
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread
+ .preview[0]
+ ).toEqual(
+ expect.objectContaining({
+ content: 'Edited reply',
+ attachments: [],
+ })
+ );
+
+ if (context) {
+ rollbackUpdateChannelMessage('channel-1', context);
+ }
+
+ expect(getThreadRepliesFromCache('channel-1', 'parent-1')?.[0]).toEqual(
+ expect.objectContaining({
+ content: 'Original reply',
+ attachments: [
+ expect.objectContaining({
+ id: 'attachment-2',
+ entity_id: 'image-1',
+ }),
+ ],
+ })
+ );
+ expect(
+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].thread
+ .preview[0]
+ ).toEqual(
+ expect.objectContaining({
+ content: 'Original reply',
+ attachments: [
+ expect.objectContaining({
+ id: 'attachment-2',
+ entity_id: 'image-1',
+ }),
+ ],
+ })
+ );
+ });
+
it('uses distinct query keys for target-message loads', () => {
expect(getChannelMessagesQueryKey('channel-1')).not.toEqual(
getChannelMessagesQueryKey('channel-1', 'message-42')
diff --git a/js/app/packages/queries/channel/thread-replies.ts b/js/app/packages/queries/channel/thread-replies.ts
index 3f054e4457..80174681f1 100644
--- a/js/app/packages/queries/channel/thread-replies.ts
+++ b/js/app/packages/queries/channel/thread-replies.ts
@@ -1,7 +1,7 @@
import { throwOnErr } from '@core/util/maybeResult';
import { type ApiThreadReply, commsServiceClient } from '@service-comms/client';
-import type { Attachment as ApiAttachment } from '@service-comms/generated/models';
import type { ApiCountedReaction } from '@service-storage/generated/schemas';
+import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -124,7 +124,7 @@ export function replaceThreadReplyReactions(
export function replaceThreadReplyAttachments(
data: Array<ApiThreadReply> | undefined,
replyId: string,
- attachments: ApiAttachment[]
+ attachments: ApiMessageAttachment[]
): Array<ApiThreadReply> | undefined {
if (!data) return data;
@@ -138,6 +138,34 @@ export function replaceThreadReplyAttachments(
return didChange ? nextReplies : data;
}
+export function replaceThreadReplyState(
+ data: Array<ApiThreadReply> | undefined,
+ replyId: string,
+ nextState: {
+ content: string;
+ editedAt: string | null | undefined;
+ updatedAt: string;
+ attachments: ApiMessageAttachment[];
+ }
+): Array<ApiThreadReply> | undefined {
+ if (!data) return data;
+
+ let didChange = false;
+ const nextReplies = data.map((reply) => {
+ if (reply.id !== replyId) return reply;
+ didChange = true;
+ return {
+ ...reply,
+ content: nextState.content,
+ edited_at: nextState.editedAt ?? undefined,
+ updated_at: nextState.updatedAt,
+ attachments: nextState.attachments,
+ };
+ });
+
+ return didChange ? nextReplies : data;
+}
+
export function getThreadReplySnapshot(
data: Array<ApiThreadReply> | undefined,
replyId: string