Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(channel): Sending, editing, and deleting a message not updating view (#721)

dev-rb2d4a6107c01b
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/BaseInput.tsx
index e6f58d858d..515b0ea419 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/BaseInput.tsx
@@ -2,7 +2,7 @@ import {
isDraggingOverChannelSignal,
isValidChannelDragSignal,
} from '@block-channel/signal/attachment';
-import type { sendMessage } from '@block-channel/signal/channel';
+import type { SendMessageArgs } from '@block-channel/signal/channel';
import { handleFileUpload } from '@block-channel/utils/inputAttachments';
import { isInBlock } from '@core/block';
import { BrightJoins } from '@core/component/BrightJoins';
@@ -66,7 +66,7 @@ type InputAttachmentsStore = {
type BaseInputProps = {
/** callback to be executed when the user clicks the send button
* or presses enter */
- onSend: (args: Parameters<typeof sendMessage>[0]) => Promise<void>;
+ onSend: (args: SendMessageArgs) => Promise<void>;
/** callback to be executed when the user changes the input */
onChange: (content: string) => void;
/** initial value of the input */
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
index 2ad770d36c..86706c7d57 100644
--- a/js/app/packages/block-channel/component/Block.tsx
+++ b/js/app/packages/block-channel/component/Block.tsx
@@ -27,7 +27,12 @@ export type BlockChannelProps = {
export default function BlockChannel(props: BlockChannelProps) {
const channelId = useBlockId();
- const channel = useChannelQuery(() => channelId);
+ const channel = useChannelQuery(
+ () => channelId,
+ () => ({
+ placeholderData: (p) => p,
+ })
+ );
const userId = useUserId();
const [error] = createSignal<string>();
diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsx
index 7e2ba49a62..1d3c4ad36d 100644
--- a/js/app/packages/block-channel/component/Channel.tsx
+++ b/js/app/packages/block-channel/component/Channel.tsx
@@ -370,15 +370,17 @@ export function Channel(props: {
<div class="shrink-0 w-full px-4 pb-2">
{/* seamus: note this element is below the scroll so we translate it back to account for the scroll above */}
<div class="mx-auto -translate-x-1 w-full macro-message-width">
- <ChannelInput
- channelName={channel.data?.channel?.name ?? ''}
- inputAttachmentsStore={channelInputAttachmentsStore}
- setInputAttachmentsStore={setChannelInputAttachmentsStore}
- inputAttachmentsKey={channelId}
- onFocusLeaveStart={onChannelInputFocusLeaveStart}
- autoFocusOnMount={autoFocusOnMount()}
- domRef={setChannelInputRef}
- />
+ <Suspense>
+ <ChannelInput
+ channelName={channel.data?.channel?.name ?? ''}
+ inputAttachmentsStore={channelInputAttachmentsStore}
+ setInputAttachmentsStore={setChannelInputAttachmentsStore}
+ inputAttachmentsKey={channelId}
+ onFocusLeaveStart={onChannelInputFocusLeaveStart}
+ autoFocusOnMount={autoFocusOnMount()}
+ domRef={setChannelInputRef}
+ />
+ </Suspense>
</div>
</div>
</div>
diff --git a/js/app/packages/block-channel/component/ChannelInput.tsx b/js/app/packages/block-channel/component/ChannelInput.tsx
index 3cc0d0183c..d89f5be68f 100644
--- a/js/app/packages/block-channel/component/ChannelInput.tsx
+++ b/js/app/packages/block-channel/component/ChannelInput.tsx
@@ -1,4 +1,7 @@
-import { channelStore, sendMessage } from '@block-channel/signal/channel';
+import {
+ channelStore,
+ useSendChannelMessageAction,
+} from '@block-channel/signal/channel';
import { postTypingUpdate } from '@block-channel/signal/typing';
import {
clearDraftMessage,
@@ -30,11 +33,8 @@ export type ChannelInputProps = {
export function ChannelInput(props: ChannelInputProps) {
const channelId = useBlockId();
- const sendMessage_ = createCallback(
- (args: Parameters<typeof sendMessage>[0]) => {
- return sendMessage(args);
- }
- );
+ const sendMessage = useSendChannelMessageAction();
+
const postTypingUpdate_ = createCallback(postTypingUpdate);
const channel = channelStore.get;
@@ -72,7 +72,7 @@ export function ChannelInput(props: ChannelInputProps) {
placeholder={`Message ${props.channelName} — @mention to share`}
onStartTyping={() => postTypingUpdate_('start')}
onStopTyping={() => postTypingUpdate_('stop')}
- onSend={sendMessage_}
+ onSend={sendMessage}
afterSend={() => clearDraftMessage(channelId)}
onChange={handleChange}
initialValue={() => draftMessage()?.content ?? ''}
diff --git a/js/app/packages/block-channel/component/Message/MessageContainer.tsx b/js/app/packages/block-channel/component/Message/MessageContainer.tsx
index 936d2ef686..e5df75cfb3 100644
--- a/js/app/packages/block-channel/component/Message/MessageContainer.tsx
+++ b/js/app/packages/block-channel/component/Message/MessageContainer.tsx
@@ -1,6 +1,5 @@
import { COLLAPSED_THREAD_INDEX_CUTOFF } from '@block-channel/constants';
import { messageAttachmentsStore } from '@block-channel/signal/attachment';
-import { editMessage } from '@block-channel/signal/channel';
import { reactToMessage } from '@block-channel/signal/reactions';
import type { ThreadViewData } from '@block-channel/type/threadView';
import type { MessageListContext } from '@block-channel/utils/listContext';
@@ -26,6 +25,7 @@ import {
import { useDisplayName } from '@core/user';
import { formatRelativeDate, isSameDay } from '@core/util/time';
import { ContextMenu } from '@kobalte/core/context-menu';
+import { usePatchMessageMutation } from '@queries/channel/message';
import type { Message as MessageType } from '@service-comms/generated/models/message';
import { useUserId } from '@service-gql/client';
import { createCallback } from '@solid-primitives/rootless';
@@ -143,7 +143,17 @@ export function MessageContainer(props: MessageProps) {
}
return undefined;
}) satisfies typeof setMessageBodyRefInner;
- const editMessage_ = createCallback(editMessage);
+
+ const editMessageMutation = usePatchMessageMutation();
+
+ const editMessage = (content: string) => {
+ if (content.trim().length === 0) return;
+ editMessageMutation.mutate({
+ channelID: message.channel_id,
+ messageID: message.id,
+ content,
+ });
+ };
const userId = useUserId();
const [currentUserName] = useDisplayName(userId());
@@ -339,6 +349,7 @@ export function MessageContainer(props: MessageProps) {
};
const actions = createMessageActions({
+ channelId: message.channel_id,
messageId: message.id,
messageContent: message.content ?? '',
threadId: message.thread_id ?? undefined,
@@ -610,9 +621,7 @@ export function MessageContainer(props: MessageProps) {
<EditMessageInput
content={props.message?.content ?? ''}
setEditing={setEditing}
- save={(input) =>
- editMessage_(props.message?.id ?? '', input)
- }
+ save={editMessage}
/>
}
>
diff --git a/js/app/packages/block-channel/component/Message/actions.ts b/js/app/packages/block-channel/component/Message/actions.ts
index 6aaae32e80..3d316cfa54 100644
--- a/js/app/packages/block-channel/component/Message/actions.ts
+++ b/js/app/packages/block-channel/component/Message/actions.ts
@@ -1,4 +1,3 @@
-import { deleteMessage } from '@block-channel/signal/channel';
import { getUrlToMessage } from '@block-channel/state/link';
import { useBlockId } from '@core/block';
import { logger } from '@observability';
@@ -7,8 +6,8 @@ import CopyIcon from '@phosphor-icons/core/regular/copy.svg?component-solid';
import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';
import Pencil from '@phosphor-icons/core/regular/pencil.svg?component-solid';
import Trash from '@phosphor-icons/core/regular/trash.svg?component-solid';
+import { useDeleteMessageMutation } from '@queries/channel/message';
import { useUserId } from '@service-gql/client';
-import { createCallback } from '@solid-primitives/rootless';
import { toast } from 'core/component/Toast/Toast';
import type { Accessor, Component } from 'solid-js';
import { createMemo } from 'solid-js';
@@ -22,6 +21,7 @@ export type MessageAction = {
};
export function createMessageActions(params: {
+ channelId: string;
messageId: string;
messageContent: string;
threadId?: string;
@@ -32,7 +32,14 @@ export function createMessageActions(params: {
const blockId = useBlockId();
const userId = useUserId();
- const deleteMessage_ = createCallback(() => deleteMessage(params.messageId));
+ const deleteMessageMutation = useDeleteMessageMutation();
+
+ const deleteMessage = () => {
+ deleteMessageMutation.mutate({
+ channelID: params.channelId,
+ messageID: params.messageId,
+ });
+ };
function copyLinkToMessage() {
const normalizedThreadId =
@@ -85,7 +92,7 @@ export function createMessageActions(params: {
},
{
text: 'Delete Message',
- onClick: deleteMessage_,
+ onClick: deleteMessage,
enabled: userId() === params.senderId,
icon: Trash,
},
diff --git a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
index 21bc01c420..b08a1e9a5b 100644
--- a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
+++ b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
@@ -1,4 +1,8 @@
-import { channelStore, sendMessage } from '@block-channel/signal/channel';
+import {
+ channelStore,
+ type SendMessageArgs,
+ useSendChannelMessageAction,
+} from '@block-channel/signal/channel';
import type { ThreadStoreData } from '@block-channel/signal/threads';
import { postTypingUpdate } from '@block-channel/signal/typing';
import type { ThreadViewData } from '@block-channel/type/threadView';
@@ -40,8 +44,9 @@ export type ReplyInputsPortalerProps = {
};
export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
+ const sendMessage = useSendChannelMessageAction();
+
const postTypingUpdate_ = createCallback(postTypingUpdate);
- const sendMessage_ = createCallback(sendMessage);
const blockRef = blockElementSignal.get;
const channel = channelStore.get;
@@ -53,36 +58,33 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
const [focusedReplyInputThreadId, setFocusedReplyInputThreadId] =
createSignal<string>();
- const onSend =
- (threadId: string) => async (args: Parameters<typeof sendMessage>[0]) => {
- clearDraftMessage(props.channelId, threadId);
- await sendMessage_({ ...args, threadId });
- // After sending, focus the message immediately after the current one in the
- // flattened list.
- // Use a timeout to ensure the new message mounts in the DOM first.
- setTimeout(() => {
- const list = props.orderedMessages() ?? [];
- const lastMessageInThreadId = props.threads[threadId]?.at(-1)?.id;
- const currentIdx = list.findIndex(
- (m) => m.id === lastMessageInThreadId
- );
- const targetIndex = currentIdx >= 0 ? currentIdx + 1 : -1;
- if (targetIndex < 0 || targetIndex >= list.length) return;
- const targetMessageId = list[targetIndex]?.id;
- if (!targetMessageId) return;
+ const onSend = (threadId: string) => async (args: SendMessageArgs) => {
+ clearDraftMessage(props.channelId, threadId);
+ await sendMessage({ ...args, threadId });
+ // After sending, focus the message immediately after the current one in the
+ // flattened list.
+ // Use a timeout to ensure the new message mounts in the DOM first.
+ setTimeout(() => {
+ const list = props.orderedMessages() ?? [];
+ const lastMessageInThreadId = props.threads[threadId]?.at(-1)?.id;
+ const currentIdx = list.findIndex((m) => m.id === lastMessageInThreadId);
+ const targetIndex = currentIdx >= 0 ? currentIdx + 1 : -1;
+ if (targetIndex < 0 || targetIndex >= list.length) return;
+ const targetMessageId = list[targetIndex]?.id;
+ if (!targetMessageId) return;
- // Ensure it's scrolled into view in the virtual list
- props.virtualHandle()?.scrollToIndex(targetIndex, { align: 'nearest' });
+ // Ensure it's scrolled into view in the virtual list
+ props.virtualHandle()?.scrollToIndex(targetIndex, { align: 'nearest' });
- // Then focus the element once mounted
- setTimeout(() => {
- const el = document.querySelector(
- `[data-message-body-id="${targetMessageId}"]`
- ) as HTMLElement | null;
- el?.focus();
- }, 0);
- }, 100);
- };
+ // Then focus the element once mounted
+ setTimeout(() => {
+ const el = document.querySelector(
+ `[data-message-body-id="${targetMessageId}"]`
+ ) as HTMLElement | null;
+ el?.focus();
+ }, 0);
+ }, 100);
+ };
const onAfterSend = (threadId: string) => () => {
props.setThreadViewStore(threadId, (prev) =>
diff --git a/js/app/packages/block-channel/signal/channel.ts b/js/app/packages/block-channel/signal/channel.ts
index 9037dfd73e..5badd04d5f 100644
--- a/js/app/packages/block-channel/signal/channel.ts
+++ b/js/app/packages/block-channel/signal/channel.ts
@@ -8,7 +8,7 @@ import {
isStaticAttachmentType,
} from '@core/store/cacheChannelInput';
import { isErr } from '@core/util/maybeResult';
-import { invalidateChannelWithID } from '@queries/channel/channel';
+import { useSendMessageMutation } from '@queries/channel/message';
import { commsServiceClient } from '@service-comms/client';
import type { Attachment } from '@service-comms/generated/models/attachment';
import type { Channel } from '@service-comms/generated/models/channel';
@@ -191,36 +191,6 @@ function optimisticChannelMessage({
}
}
-export async function deleteMessage(messageId: string) {
- const channelId = channelStore.get.id;
- if (!channelId) return;
-
- try {
- await commsServiceClient.deleteMessage({
- channel_id: channelId,
- message_id: messageId,
- });
- } catch (e) {
- console.error(e);
- }
-}
-
-export async function editMessage(messageId: string, content: string) {
- const channelId = channelStore.get.id;
- if (content.trim().length === 0) return;
- if (!channelId) return;
-
- try {
- await commsServiceClient.patchMessage({
- message_id: messageId,
- channel_id: channelId,
- content,
- });
- } catch (e) {
- console.error(e);
- }
-}
-
function isMessageSendable(
content: string | undefined,
attachments: InputAttachment[]
@@ -228,72 +198,74 @@ function isMessageSendable(
return (content && content.trim().length > 0) || attachments.length > 0;
}
-export async function sendMessage({
- content,
- attachments,
- threadId,
- mentions,
-}: {
+export type SendMessageArgs = {
content: string | undefined;
attachments: InputAttachment[];
threadId?: string;
mentions?: SimpleMention[];
-}) {
+};
+
+export function useSendChannelMessageAction() {
const optimisticSend = createCallback(optimisticChannelMessage);
const channelsContext = useChannelsContext();
const userId = useUserId();
- if (!userId) return;
- if (!isMessageSendable(content, attachments)) return;
- const channelId = channelStore.get.id;
- if (!channelId) return;
- let attachmentsToSend = attachments
- .map((a) => ({
- entity_id: a.id,
- entity_type: isStaticAttachmentType(a.blockName)
- ? a.blockName
- : blockNameToItemType(a.blockName as BlockName),
- }))
- .filter((a) => a.entity_type !== undefined) as {
- entity_id: string;
- entity_type: string;
- }[];
-
- let result = await commsServiceClient.postMessage({
- channel_id: channelId,
- message: {
- attachments: attachmentsToSend,
- content: content ?? '',
- thread_id: threadId,
- mentions: mentions ?? [],
+ const mutation = useSendMessageMutation({
+ onSettled() {
+ channelsContext.refetchChannels();
+ },
+ onSuccess(_, variables) {
+ const message = variables.message;
+ track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
+ channelId: variables.channelID,
+ contentLength: message.content?.length ?? 0,
+ attachmentsLength: message.attachments.length,
+ inThread: message.thread_id !== undefined,
+ });
},
});
- channelsContext.refetchChannels();
- invalidateChannelWithID(channelId);
-
- if (isErr(result)) {
- console.error('failed to send message', result[0]);
- toast.failure('Failed to send message');
- return Promise.reject(result[0] ?? new Error('Failed to send message'));
- }
-
- const { id } = result[1]!;
-
- track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
- channelId,
- contentLength: content?.length ?? 0,
- attachmentsLength: attachmentsToSend.length,
- inThread: threadId !== undefined,
- });
-
- optimisticSend({
- channelId,
- messageId: id,
- content: content ?? '',
+ return async ({
+ content,
+ attachments,
threadId,
- senderId: userId()!,
- });
+ mentions,
+ }: SendMessageArgs) => {
+ if (!userId) return;
+ if (!isMessageSendable(content, attachments)) return;
+ const channelId = channelStore.get.id;
+ if (!channelId) return;
+
+ const attachmentsToSend = attachments
+ .map((a) => ({
+ entity_id: a.id,
+ entity_type: isStaticAttachmentType(a.blockName)
+ ? a.blockName
+ : blockNameToItemType(a.blockName as BlockName),
+ }))
+ .filter((a) => a.entity_type !== undefined) as {
+ entity_id: string;
+ entity_type: string;
+ }[];
+
+ const data = await mutation.mutateAsync({
+ channelID: channelId,
+ message: {
+ attachments: attachmentsToSend,
+ content: content ?? '',
+ thread_id: threadId,
+ mentions: mentions ?? [],
+ },
+ });
+
+ optimisticSend({
+ channelId,
+ messageId: data.id,
+ content: content ?? '',
+ threadId,
+ senderId: userId()!,
+ });
+ };
}
createConnectionBlockWebsocketEffect((msg) => {
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
new file mode 100644
index 0000000000..c45ddc2700
--- /dev/null
+++ b/js/app/packages/queries/channel/message.ts
@@ -0,0 +1,128 @@
+import { TrackingEvents, withAnalytics } from '@coparse/analytics';
+import { toast } from '@core/component/Toast/Toast';
+import { throwOnErr } from '@core/util/maybeResult';
+import { invalidateChannelWithID } from '@queries/channel/channel';
+import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import {
+ commsServiceClient,
+ type IdResponse,
+ type MessageResponse,
+} from '@service-comms/client';
+import type { PostMessageRequest } from '@service-comms/generated/models';
+import { useMutation } from '@tanstack/solid-query';
+
+const { track } = withAnalytics();
+
+type WithChannelID<T> = T & { channelID: string };
+
+type SendMessageParams = WithChannelID<{ message: PostMessageRequest }>;
+
+/**
+ * Mutation to send an channel message.
+ */
+export function useSendMessageMutation(
+ callbacks?: MutationCallbacks<IdResponse, Error, SendMessageParams>
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: SendMessageParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.postMessage({
+ channel_id: vars.channelID,
+ message: vars.message,
+ })
+ );
+ },
+ ...withCallbacks<IdResponse, Error, SendMessageParams>(
+ {
+ onError(error) {
+ console.error('failed to send message', error);
+ toast.failure('Failed to send message');
+ },
+ onSuccess(_data, variables) {
+ track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
+ channelId: variables.channelID,
+ contentLength: variables.message.content?.length ?? 0,
+ attachmentsLength: variables.message.attachments.length,
+ inThread: variables.message.thread_id !== undefined,
+ });
+ },
+ onSettled: (_data, _error, variables) => {
+ invalidateChannelWithID(variables.channelID);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+type DeleteMessageParams = { channelID: string; messageID: string };
+
+/**
+ * Mutation to delete a channel message
+ */
+export function useDeleteMessageMutation(
+ callbacks?: MutationCallbacks<void, Error, DeleteMessageParams>
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: DeleteMessageParams) => {
+ await throwOnErr(
+ async () =>
+ await commsServiceClient.deleteMessage({
+ channel_id: vars.channelID,
+ message_id: vars.messageID,
+ })
+ );
+ },
+ ...withCallbacks<void, Error, DeleteMessageParams>(
+ {
+ onError(error) {
+ console.error('failed to delete message', error);
+ toast.failure('Failed to delete message');
+ },
+ onSettled: (_data, _error, variables) => {
+ invalidateChannelWithID(variables.channelID);
+ },
+ },
+ callbacks
+ ),
+ }));
+}
+
+type PatchMessageParams = {
+ channelID: string;
+ messageID: string;
+ content: string;
+};
+
+/**
+ * Mutation to patch a channel message
+ */
+export function usePatchMessageMutation(
+ callbacks?: MutationCallbacks<MessageResponse, Error, PatchMessageParams>
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: PatchMessageParams) => {
+ return await throwOnErr(
+ async () =>
+ await commsServiceClient.patchMessage({
+ channel_id: vars.channelID,
+ message_id: vars.messageID,
+ content: vars.content,
+ })
+ );
+ },
+ ...withCallbacks<MessageResponse, Error, PatchMessageParams>(
+ {
+ onError(error) {
+ console.error('failed to update message', error);
+ toast.failure('Failed to update message');
+ },
+ onSettled: (_data, _error, variables) => {
+ invalidateChannelWithID(variables.channelID);
+ },
+ },
+ callbacks
+ ),
+ }));
+}