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(channels/documents): Stanalone channel thread + Full reactive thread in document cards (#2734)

teo2d4b3a3dce93
diff --git a/js/app/packages/block-channel/utils/link.ts b/js/app/packages/block-channel/utils/link.ts
index 7baafd70eb..4016d7a870 100644
--- a/js/app/packages/block-channel/utils/link.ts
+++ b/js/app/packages/block-channel/utils/link.ts
@@ -1,4 +1,7 @@
import { URL_PARAMS } from '@block-channel/constants';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import type { SplitManager } from '@app/component/split-layout/layoutManager';
+import type { BlockOrchestrator } from '@core/orchestrator';
export function getChannelParams(
messageId: string,
@@ -26,3 +29,35 @@ export function getUrlToMessage(
}
return url;
}
+
+export async function navigateToChannelMessage(
+ orchestrator: BlockOrchestrator,
+ channelId: string,
+ messageId: string,
+ threadId?: string,
+ options?: {
+ splitManager?: SplitManager;
+ preferNewSplit?: boolean;
+ }
+) {
+ const params = getChannelParams(messageId, threadId);
+ const splitManager = options?.splitManager ?? globalSplitManager();
+ if (!splitManager) return;
+
+ const existing = splitManager.getSplitByContent('channel', channelId);
+ if (existing) {
+ existing.activate();
+ } else {
+ splitManager.openWithSplit(
+ { type: 'channel', id: channelId, params },
+ {
+ activate: true,
+ referredFrom: null,
+ preferNewSplit: options?.preferNewSplit,
+ }
+ );
+ }
+
+ const handle = await orchestrator.getBlockHandle(channelId, 'channel');
+ await handle?.goToLocationFromParams(params);
+}
diff --git a/js/app/packages/channel/StandaloneThread/EditableThread.tsx b/js/app/packages/channel/StandaloneThread/EditableThread.tsx
new file mode 100644
index 0000000000..f1c7ec382c
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/EditableThread.tsx
@@ -0,0 +1,75 @@
+import type { ApiChannelMessage } from '@service-comms/client';
+import { createSignal, Show } from 'solid-js';
+import { useUserId } from '@core/context/user';
+import { useDeleteMessageMutation } from '@queries/channel/message';
+import {
+ useAddReactionMutation,
+ useRemoveReactionMutation,
+} from '@queries/channel/reaction';
+import { createChannelMessageActions } from '../Channel/create-channel-message-actions';
+import { Thread } from '../Thread';
+import type { InputSnapshot } from '../Input';
+import { StandaloneThread } from './StandaloneThread';
+import { useStandaloneThread } from './context';
+
+type EditableThreadProps = {
+ channelId: string;
+ messageId: string;
+ data?: ApiChannelMessage;
+};
+
+function EditableThreadInner() {
+ const ctx = useStandaloneThread();
+ const userId = useUserId();
+ const [replyInputState, setReplyInputState] = createSignal<
+ InputSnapshot | undefined
+ >();
+ const deleteMessageMutation = useDeleteMessageMutation();
+ const addReactionMutation = useAddReactionMutation();
+ const removeReactionMutation = useRemoveReactionMutation();
+
+ const getMessageActions = createChannelMessageActions({
+ channelId: ctx.channelId,
+ userId,
+ deleteMessage: deleteMessageMutation.mutate,
+ addReaction: addReactionMutation.mutate,
+ removeReaction: removeReactionMutation.mutate,
+ onReply: () => void ctx.setIsReplying(true),
+ });
+
+ const parentActions = () => {
+ const p = ctx.parent();
+ return p ? getMessageActions(p) : undefined;
+ };
+
+ return (
+ <>
+ <StandaloneThread.ParentMessage actions={parentActions()} />
+ <StandaloneThread.Replies
+ getMessageActions={getMessageActions}
+ showReplyButton
+ />
+ <Show when={ctx.isReplying()}>
+ <Thread.ReplyInput
+ channelId={ctx.channelId()}
+ messageId={ctx.messageId()}
+ replyInputState={replyInputState}
+ setReplyInputState={setReplyInputState}
+ setIsReplying={ctx.setIsReplying}
+ />
+ </Show>
+ </>
+ );
+}
+
+export function EditableThread(props: EditableThreadProps) {
+ return (
+ <StandaloneThread.Root
+ channelId={props.channelId}
+ messageId={props.messageId}
+ data={props.data}
+ >
+ <EditableThreadInner />
+ </StandaloneThread.Root>
+ );
+}
diff --git a/js/app/packages/channel/StandaloneThread/ParentMessage.tsx b/js/app/packages/channel/StandaloneThread/ParentMessage.tsx
new file mode 100644
index 0000000000..16e97ab48a
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/ParentMessage.tsx
@@ -0,0 +1,57 @@
+import { Show } from 'solid-js';
+import { Message, type MessageActions } from '../Message';
+import { useStandaloneThread } from './context';
+
+type ParentMessageProps = {
+ actions?: MessageActions;
+ onClickMessage?: (messageId: string, e: MouseEvent) => void;
+ class?: string;
+};
+
+export function ParentMessage(props: ParentMessageProps) {
+ const ctx = useStandaloneThread();
+
+ return (
+ <Show when={ctx.parent()}>
+ {(parentMsg) => (
+ <Message.Root
+ message={parentMsg()}
+ actions={props.actions}
+ onClick={
+ props.onClickMessage
+ ? (e: MouseEvent) => props.onClickMessage!(parentMsg().id, e)
+ : undefined
+ }
+ class={props.class}
+ >
+ <Message.Layout class="pt-(--regular-message-padding-t)">
+ <Message.Slot placement="icon">
+ <Message.SenderIcon />
+ </Message.Slot>
+ <Message.Slot
+ placement="header"
+ class="flex items-center gap-1 min-w-0"
+ >
+ <Message.SenderName />
+ <Message.EditedIndicator />
+ <Message.Timestamp
+ class="ml-auto shrink-0"
+ format="dateAndTime"
+ />
+ </Message.Slot>
+ <Message.Slot placement="content">
+ <Message.Content />
+ </Message.Slot>
+ <Message.Slot placement="footer" class="flex flex-col min-w-0">
+ <Message.Attachments />
+ <Message.Reactions />
+ </Message.Slot>
+ </Message.Layout>
+ <Show when={props.actions}>
+ <Message.ActionMenu />
+ </Show>
+ </Message.Root>
+ )}
+ </Show>
+ );
+}
diff --git a/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx b/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx
new file mode 100644
index 0000000000..bac93a7e07
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx
@@ -0,0 +1,32 @@
+import type { ApiChannelMessage } from '@service-comms/client';
+import { StandaloneThread } from './StandaloneThread';
+
+type ReadonlyThreadProps = {
+ channelId: string;
+ messageId: string;
+ data?: ApiChannelMessage;
+ onClickMessage?: (messageId: string, e: MouseEvent) => void;
+};
+
+export function ReadonlyThread(props: ReadonlyThreadProps) {
+ return (
+ <StandaloneThread.Root
+ channelId={props.channelId}
+ messageId={props.messageId}
+ data={props.data}
+ >
+ <StandaloneThread.ParentMessage
+ onClickMessage={props.onClickMessage}
+ class={
+ props.onClickMessage ? 'cursor-pointer hover:bg-hover' : undefined
+ }
+ />
+ <StandaloneThread.Replies
+ onClickMessage={props.onClickMessage}
+ class={
+ props.onClickMessage ? 'cursor-pointer hover:bg-hover' : undefined
+ }
+ />
+ </StandaloneThread.Root>
+ );
+}
diff --git a/js/app/packages/channel/StandaloneThread/Replies.tsx b/js/app/packages/channel/StandaloneThread/Replies.tsx
new file mode 100644
index 0000000000..9b61804a29
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/Replies.tsx
@@ -0,0 +1,143 @@
+import { createMemo, For, Show } from 'solid-js';
+import { Message, type MessageActions, type MessageData } from '../Message';
+import { Thread } from '../Thread';
+import { ThreadRail } from '../Thread/ThreadRail';
+import { buildThreadReplyListMeta } from '../Thread/reply-list-meta';
+import {
+ DEFAULT_VISIBLE_REPLY_COUNT,
+ getCollapsedRepliesCount,
+ getThreadLatestReplyAt,
+ getUniqueReplyUserIds,
+} from '../Thread/utils/thread-reply-indicator-helpers';
+import { useStandaloneThread } from './context';
+
+type RepliesProps = {
+ getMessageActions?: (message: MessageData) => MessageActions | undefined;
+ onClickMessage?: (messageId: string, e: MouseEvent) => void;
+ class?: string;
+ showReplyButton?: boolean;
+};
+
+export function Replies(props: RepliesProps) {
+ const ctx = useStandaloneThread();
+
+ const listMetaByReplyId = createMemo(() =>
+ buildThreadReplyListMeta(ctx.displayReplies())
+ );
+
+ const collapsedRepliesCount = () =>
+ getCollapsedRepliesCount(
+ ctx.parent()?.thread.reply_count ?? ctx.replies().length,
+ DEFAULT_VISIBLE_REPLY_COUNT
+ );
+
+ const collapsedReplyUsers = () =>
+ getUniqueReplyUserIds(ctx.replies().slice(DEFAULT_VISIBLE_REPLY_COUNT));
+
+ const collapsedLatestReplyAt = () =>
+ getThreadLatestReplyAt(ctx.parent()?.thread.latest_reply_at, ctx.replies());
+
+ const shouldShowCollapsedIndicator = () =>
+ !ctx.isReplying() && !ctx.isExpanded() && collapsedRepliesCount() > 0;
+
+ const shouldShowReplyButton = () =>
+ !!props.showReplyButton &&
+ ctx.hasReplies() &&
+ !ctx.isReplying() &&
+ !shouldShowCollapsedIndicator();
+
+ return (
+ <Show when={ctx.hasReplies() || ctx.isReplying()}>
+ <div class="relative w-full">
+ <Thread.ReplyRailDecorations
+ isReplying={ctx.isReplying}
+ firstThreadReplyNewMessage={false}
+ />
+ <Thread.RepliesContainer>
+ <For each={ctx.displayReplies()}>
+ {(reply) => {
+ const meta = () => listMetaByReplyId()[reply.id];
+ const replyActions = () => props.getMessageActions?.(reply);
+ return (
+ <div class="relative">
+ <ThreadRail />
+ <Message.Root
+ message={reply}
+ actions={replyActions()}
+ onClick={
+ props.onClickMessage
+ ? (e: MouseEvent) => props.onClickMessage!(reply.id, e)
+ : undefined
+ }
+ class={props.class}
+ >
+ <Message.Layout
+ class={
+ meta()?.isGroupedWithPrevious
+ ? undefined
+ : 'pt-(--regular-message-padding-t)'
+ }
+ >
+ <Message.Slot placement="icon">
+ <Message.SenderIcon
+ hidden={meta()?.isGroupedWithPrevious}
+ />
+ </Message.Slot>
+ <Show when={!meta()?.isGroupedWithPrevious}>
+ <Message.Slot
+ placement="header"
+ class="flex items-center gap-1 min-w-0"
+ >
+ <Message.SenderName />
+ <Message.EditedIndicator />
+ <Message.Timestamp
+ class="ml-auto shrink-0"
+ format="dateAndTime"
+ />
+ </Message.Slot>
+ </Show>
+ <Message.Slot placement="content">
+ <Message.Content />
+ </Message.Slot>
+ <Message.Slot
+ placement="footer"
+ class="flex flex-col min-w-0"
+ >
+ <Message.Attachments />
+ <Message.Reactions />
+ </Message.Slot>
+ </Message.Layout>
+ <Show when={replyActions()}>
+ <Message.ActionMenu />
+ </Show>
+ </Message.Root>
+ </div>
+ );
+ }}
+ </For>
+ <Show
+ when={shouldShowCollapsedIndicator() || shouldShowReplyButton()}
+ >
+ <Thread.ActionsFooter>
+ <Show when={shouldShowCollapsedIndicator()}>
+ <Thread.CollapsedIndicator
+ collapsedRepliesCount={collapsedRepliesCount()}
+ participants={collapsedReplyUsers()}
+ latestReplyAt={collapsedLatestReplyAt()}
+ onClick={() => ctx.setIsExpanded(true)}
+ />
+ </Show>
+ <Show when={shouldShowReplyButton()}>
+ <Thread.ReplyButton
+ getFocusTarget={() => null}
+ onClick={() => ctx.setIsReplying(true)}
+ aria-label="Reply"
+ />
+ </Show>
+ </Thread.ActionsFooter>
+ </Show>
+ </Thread.RepliesContainer>
+ </div>
+ </Show>
+ );
+}
diff --git a/js/app/packages/channel/StandaloneThread/Root.tsx b/js/app/packages/channel/StandaloneThread/Root.tsx
new file mode 100644
index 0000000000..eb52448c5f
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/Root.tsx
@@ -0,0 +1,76 @@
+import { useChannelMessagesByIdsQuery } from '@queries/channel/channel-messages';
+import { useThreadRepliesQuery } from '@queries/channel/thread-replies';
+import { DEFAULT_VISIBLE_REPLY_COUNT } from '../Thread/utils/thread-reply-indicator-helpers';
+import type { ApiChannelMessage, ApiThreadReply } from '@service-comms/client';
+import { createSignal, Show, type ParentProps } from 'solid-js';
+import { ThreadRail } from '../Thread/ThreadRail';
+import { StandaloneThreadContext } from './context';
+import { DebugSuspense } from '@channel/DebugSuspense';
+
+type RootProps = ParentProps<{
+ channelId: string;
+ messageId: string;
+ data?: ApiChannelMessage;
+}>;
+
+export function Root(props: RootProps) {
+ return (
+ <DebugSuspense name="StandaloneThread.Root">
+ <RootInner {...props} />
+ </DebugSuspense>
+ );
+}
+
+function RootInner(props: RootProps) {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const [isReplying, setIsReplying] = createSignal(false);
+
+ const parentQuery = useChannelMessagesByIdsQuery(
+ () => props.channelId,
+ () => (props.data ? [] : [props.messageId])
+ );
+
+ const parent = () => props.data ?? parentQuery.data?.[0];
+ const hasThread = () => (parent()?.thread.reply_count ?? 0) > 0;
+
+ const repliesQuery = useThreadRepliesQuery(
+ () => props.channelId,
+ () => props.messageId,
+ () => hasThread() || isReplying()
+ );
+
+ const replies = (): ApiThreadReply[] =>
+ repliesQuery.data ?? parent()?.thread.preview ?? [];
+
+ const hasReplies = () => replies().length > 0;
+
+ const displayReplies = (): ApiThreadReply[] => {
+ const all = replies();
+ if (isExpanded()) return all;
+ return all.slice(0, DEFAULT_VISIBLE_REPLY_COUNT);
+ };
+
+ return (
+ <StandaloneThreadContext.Provider
+ value={{
+ channelId: () => props.channelId,
+ messageId: () => props.messageId,
+ parent,
+ replies,
+ displayReplies,
+ hasReplies,
+ isExpanded,
+ setIsExpanded,
+ isReplying,
+ setIsReplying,
+ }}
+ >
+ <div class="relative">
+ <Show when={hasReplies() || isReplying()}>
+ <ThreadRail />
+ </Show>
+ {props.children}
+ </div>
+ </StandaloneThreadContext.Provider>
+ );
+}
diff --git a/js/app/packages/channel/StandaloneThread/StandaloneThread.ts b/js/app/packages/channel/StandaloneThread/StandaloneThread.ts
new file mode 100644
index 0000000000..171a662c29
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/StandaloneThread.ts
@@ -0,0 +1,9 @@
+import { Root } from './Root';
+import { ParentMessage } from './ParentMessage';
+import { Replies } from './Replies';
+
+export const StandaloneThread = {
+ Root,
+ ParentMessage,
+ Replies,
+};
diff --git a/js/app/packages/channel/StandaloneThread/context.ts b/js/app/packages/channel/StandaloneThread/context.ts
new file mode 100644
index 0000000000..69fd32d921
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/context.ts
@@ -0,0 +1,33 @@
+import type { ApiChannelMessage, ApiThreadReply } from '@service-comms/client';
+import {
+ createContext,
+ useContext,
+ type Accessor,
+ type Setter,
+} from 'solid-js';
+
+export type StandaloneThreadContextValue = {
+ channelId: Accessor<string>;
+ messageId: Accessor<string>;
+ parent: Accessor<ApiChannelMessage | undefined>;
+ replies: Accessor<ApiThreadReply[]>;
+ displayReplies: Accessor<ApiThreadReply[]>;
+ hasReplies: Accessor<boolean>;
+ isExpanded: Accessor<boolean>;
+ setIsExpanded: Setter<boolean>;
+ isReplying: Accessor<boolean>;
+ setIsReplying: Setter<boolean>;
+};
+
+const StandaloneThreadContext = createContext<StandaloneThreadContextValue>();
+
+export function useStandaloneThread(): StandaloneThreadContextValue {
+ const ctx = useContext(StandaloneThreadContext);
+ if (!ctx)
+ throw new Error(
+ 'useStandaloneThread must be used inside StandaloneThread.Root'
+ );
+ return ctx;
+}
+
+export { StandaloneThreadContext };
diff --git a/js/app/packages/channel/StandaloneThread/index.ts b/js/app/packages/channel/StandaloneThread/index.ts
new file mode 100644
index 0000000000..9936817897
--- /dev/null
+++ b/js/app/packages/channel/StandaloneThread/index.ts
@@ -0,0 +1,5 @@
+export { StandaloneThread } from './StandaloneThread';
+export { ReadonlyThread } from './ReadonlyThread';
+export { EditableThread } from './EditableThread';
+export { useStandaloneThread } from './context';
+export type { StandaloneThreadContextValue } from './context';
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/ChannelMessageThreadCard.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ChannelMessageThreadCard.tsx
new file mode 100644
index 0000000000..72c08378bf
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/ChannelMessageThreadCard.tsx
@@ -0,0 +1,29 @@
+import { ReadonlyThread } from '@channel/StandaloneThread';
+import { navigateToChannelMessage } from '@block-channel/utils/link';
+import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';
+
+type ChannelMessageThreadCardProps = {
+ channelId: string;
+ messageId: string;
+};
+
+export function ChannelMessageThreadCard(props: ChannelMessageThreadCardProps) {
+ const orchestrator = useGlobalBlockOrchestrator();
+
+ return (
+ <ReadonlyThread
+ channelId={props.channelId}
+ messageId={props.messageId}
+ onClickMessage={(clickedMessageId, e) => {
+ e.stopPropagation();
+ const isReply = clickedMessageId !== props.messageId;
+ navigateToChannelMessage(
+ orchestrator,
+ props.channelId,
+ clickedMessageId,
+ isReply ? props.messageId : undefined
+ );
+ }}
+ />
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
index 09336ef0bf..db47b2ff6d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
@@ -19,6 +19,7 @@ import {
isAccessiblePreviewItem,
type AccessiblePreviewItem,
} from '@queries/preview';
+import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import { matches } from '@core/util/match';
import TrashSimple from '@icon/duotone/trash-simple-duotone.svg';
import Minimize from '@icon/regular/arrows-in.svg';
@@ -68,6 +69,7 @@ import { floatWithElement } from '../../directive/floatWithElement';
import { UPDATE_DOCUMENT_NAME_COMMAND } from '../../plugins';
import { dispatchInternalLayoutShift } from '../../plugins/shared/utils';
import { BlockLink } from '../core/BlockLink';
+import { ChannelMessageThreadCard } from './ChannelMessageThreadCard';
false && floatWithElement;
@@ -100,6 +102,13 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
type: previewType(),
}));
+ const channelMessageId = () => {
+ if (previewType() !== 'channel') return undefined;
+ const messageId = props.blockParams?.[CHANNEL_PARAMS.message];
+ const threadId = props.blockParams?.[CHANNEL_PARAMS.thread];
+ return threadId ? threadId : messageId;
+ };
+
const [hasLoadedPreview, setHasLoadedPreview] = createSignal(false);
const isSelectedAsNode = () => {
@@ -180,8 +189,6 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
const blockOwner = useBlockOwner();
createEffect(() => {
- if (!editor) return;
- if (!isPreviewable()) return;
if (hasLoadedPreview()) return;
if (props.previewComponent) {
@@ -190,44 +197,60 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
return;
}
- let nodeId = editor()?.read(() => {
+ const msgId = channelMessageId();
+ const shouldCreateBlockPreview = !msgId && isPreviewable();
+
+ if (!msgId && !shouldCreateBlockPreview) return;
+
+ const nodeId = editor()?.read(() => {
const node = $getNodeByKey(props.key);
if (!node) return;
return $getId(node);
});
- if (!nodeId) {
- console.error('Unable to find node id for document card');
- return;
- }
+ if (!nodeId) return;
+
+ if (shouldCreateBlockPreview) {
+ const i = item();
+ if (!i || i.loading) return;
+
+ const preview = createBlockInstance(
+ resolveBlockAlias(verifyBlockName(props.blockName)),
+ i.id,
+ {
+ params: previewData(),
+ nested: { parentContext: previewContext() },
+ }
+ );
+ if (!preview) return;
+
+ const noDispose = runWithOwner(blockOwner, () => {
+ let disposeOnBlockUnmount: () => void = () => {};
+ onCleanup(() => disposeOnBlockUnmount());
+
+ return createRoot((dispose) => {
+ const element = createMemo(() => preview.element());
+ setDocumentCardPreviewComponent(nodeId, element, dispose);
+ disposeOnBlockUnmount = () => unsetDocumentCardPreviewCache(nodeId);
+ return element;
+ }, blockOwner);
+ });
- const i = item();
- if (!i || i.loading) {
+ setHasLoadedPreview(true);
+ setPreviewComponent(() => noDispose);
return;
}
- const documentId = i.id;
-
- const preview = createBlockInstance(
- resolveBlockAlias(verifyBlockName(props.blockName)),
- documentId,
- {
- params: previewData(),
- nested: {
- parentContext: previewContext(),
- },
- }
- );
const noDispose = runWithOwner(blockOwner, () => {
let disposeOnBlockUnmount: () => void = () => {};
- onCleanup(() => {
- disposeOnBlockUnmount();
- });
+ onCleanup(() => disposeOnBlockUnmount());
return createRoot((dispose) => {
- if (!preview || !nodeId) return;
-
- const element = createMemo(() => preview.element());
-
+ const element = createMemo(() =>
+ ChannelMessageThreadCard({
+ channelId: props.documentId,
+ messageId: msgId!,
+ })
+ );
setDocumentCardPreviewComponent(nodeId, element, dispose);
disposeOnBlockUnmount = () => unsetDocumentCardPreviewCache(nodeId);
return element;
@@ -403,13 +426,15 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
contentEditable={false}
class="relative my-2 rounded border border-edge-muted no-select-children select-none overflow-hidden flex flex-col"
classList={{
- 'bg-active outline-edge outline-4': isSelectedAsNode(),
+ 'bg-active outline-edge outline-4':
+ isSelectedAsNode() && !channelMessageId(),
'resize-y shrink-0 min-h-[100px]': isPreviewable(),
}}
style={{
height: isPreviewable() ? previewBoxHeight : 'auto',
}}
onClick={(e) => {
+ if (channelMessageId()) return;
e.preventDefault();
clickCardHandler();
}}
@@ -425,12 +450,15 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
{(item) => (
<>
<DocumentInfo item={item()} blockName={props.blockName} />
- <Show when={isPreviewable()}>
- <div class="relative grow overflow-y-scroll">
- <Show when={previewComponent()}>
+ <Show when={previewComponent()}>
+ <Show
+ when={isPreviewable()}
+ fallback={<Dynamic component={previewComponent()} />}
+ >
+ <div class="relative grow overflow-y-scroll">
<Dynamic component={previewComponent()} />
- </Show>
- </div>
+ </div>
+ </Show>
</Show>
</>
)}
diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.ts
index a103237fc1..c6eb07ee65 100644
--- a/js/app/packages/notifications/notification-navigation.ts
+++ b/js/app/packages/notifications/notification-navigation.ts
@@ -7,7 +7,10 @@ import { getNotificationById } from '@queries/notification/user-notifications';
import { errAsync, ResultAsync } from 'neverthrow';
import { match, P } from 'ts-pattern';
import type { NotificationSource } from './notification-source';
-import { getChannelParams } from '@block-channel/utils/link';
+import {
+ getChannelParams,
+ navigateToChannelMessage,
+} from '@block-channel/utils/link';
import { isChannelNotification } from './notification-helpers';
import { CHANNEL_EVENT_TYPES } from './notification-source';
import {
@@ -73,22 +76,18 @@ async function openChannelNotification(
newSplit: boolean = false
) {
const channelId = notification.entity_id;
- const { messageId, threadId, params } =
- getChannelNotificationParams(notification);
-
- openSplitIfNotOpen(layoutManager, 'channel', channelId, {
- newSplit,
- params,
- });
+ const { messageId, threadId } = getChannelNotificationParams(notification);
- if (!messageId) return;
+ if (!messageId) {
+ openSplitIfNotOpen(layoutManager, 'channel', channelId, { newSplit });
+ return;
+ }
- // Also call goToLocationFromParams for already-open channels where
- // the split existed before and params weren't applied as initial props.
const orchestrator = layoutManager.getOrchestrator();
- const handle = await orchestrator.getBlockHandle(channelId, 'channel');
-
- handle?.goToLocationFromParams(getChannelParams(messageId, threadId));
+ await navigateToChannelMessage(orchestrator, channelId, messageId, threadId, {
+ splitManager: layoutManager,
+ preferNewSplit: newSplit,
+ });
}
function safeFileTypeToBlockName(fileType: string | undefined | null) {
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index 746f1fc140..18b9c99d57 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -5,7 +5,11 @@ import {
type ApiThreadReply,
type ChannelMessagesPage,
} from '@service-comms/client';
-import { type InfiniteData, useInfiniteQuery } from '@tanstack/solid-query';
+import {
+ type InfiniteData,
+ useInfiniteQuery,
+ useQuery,
+} from '@tanstack/solid-query';
import { type Accessor, createEffect, on } from 'solid-js';
import type { ApiCountedReaction } from '@service-storage/generated/schemas';
import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
@@ -102,6 +106,31 @@ export function useChannelMessagesQuery(
);
}
+export function useChannelMessagesByIdsQuery(
+ channelId: Accessor<string>,
+ messageIds: Accessor<string[]>
+) {
+ return useQuery(() => {
+ const resolvedChannelId = channelId();
+ const resolvedMessageIds = messageIds();
+ return {
+ queryKey: channelKeys.messagesByIds(resolvedChannelId, resolvedMessageIds)
+ .queryKey,
+ queryFn: async (): Promise<ApiChannelMessage[]> => {
+ const page = await throwOnErr(() =>
+ commsServiceClient.postChannelMessages({
+ channel_id: resolvedChannelId,
+ filters: { message_ids: resolvedMessageIds },
+ })
+ );
+ return page.items;
+ },
+ enabled: resolvedMessageIds.length > 0,
+ staleTime: Infinity,
+ };
+ });
+}
+
/** Returns the cache key for one channel message query variant. */
export function getChannelMessagesQueryKey(
channelId: string,
@@ -562,6 +591,93 @@ export function softInvalidateChannelMessages(channelId: string) {
});
}
+/** Returns the shared prefix for all by-ids message queries in a channel. */
+export function getChannelMessagesByIdsQueryKeyPrefix(channelId: string) {
+ return [...channelKeys.messagesByIds._def, channelId];
+}
+
+/** Applies one updater to every cached by-ids message variant for a channel. */
+export function setChannelMessagesByIdsData(
+ channelId: string,
+ updater: (
+ data: ApiChannelMessage[] | undefined
+ ) => ApiChannelMessage[] | undefined
+) {
+ queryClient.setQueriesData<ApiChannelMessage[]>(
+ { queryKey: getChannelMessagesByIdsQueryKeyPrefix(channelId) },
+ updater
+ );
+}
+
+function mapChannelMessagesByIdsItems(
+ data: ApiChannelMessage[],
+ updater: (message: ApiChannelMessage) => ApiChannelMessage
+): ApiChannelMessage[] {
+ let didChange = false;
+ const next = data.map((message) => {
+ const nextMessage = updater(message);
+ if (nextMessage !== message) didChange = true;
+ return nextMessage;
+ });
+ return didChange ? next : data;
+}
+
+export function replaceTopLevelMessageReactionsInChannelMessagesByIds(
+ data: ApiChannelMessage[] | undefined,
+ messageId: string,
+ reactions: ApiCountedReaction[]
+): ApiChannelMessage[] | undefined {
+ if (!data) return data;
+ return mapChannelMessagesByIdsItems(data, (message) =>
+ message.id === messageId ? { ...message, reactions } : message
+ );
+}
+
+export function replaceTopLevelMessageAttachmentsInChannelMessagesByIds(
+ data: ApiChannelMessage[] | undefined,
+ messageId: string,
+ attachments: ApiMessageAttachment[]
+): ApiChannelMessage[] | undefined {
+ if (!data) return data;
+ return mapChannelMessagesByIdsItems(data, (message) =>
+ message.id === messageId ? { ...message, attachments } : message
+ );
+}
+
+export function replaceTopLevelMessageStateInChannelMessagesByIds(
+ data: ApiChannelMessage[] | undefined,
+ messageId: string,
+ nextState: {
+ content: string;
+ editedAt: string | null | undefined;
+ updatedAt: string;
+ attachments: ApiMessageAttachment[];
+ }
+): ApiChannelMessage[] | undefined {
+ if (!data) return data;
+ return mapChannelMessagesByIdsItems(data, (message) =>
+ message.id === messageId
+ ? {
+ ...message,
+ content: nextState.content,
+ edited_at: nextState.editedAt ?? undefined,
+ updated_at: nextState.updatedAt,
+ attachments: nextState.attachments,
+ }
+ : message
+ );
+}
+
+/**
+ * Marks the by-ids message queries as stale without triggering an immediate refetch.
+ */
+export function softInvalidateChannelMessagesByIds(channelId: string) {
+ queryClient.invalidateQueries({
+ queryKey: getChannelMessagesByIdsQueryKeyPrefix(channelId),
+ refetchType: 'inactive',
+ });
+}
+
/**
* Build a single oldest-first message index for display and lookup.
* Pages arrive newest-first, items within each page are newest-first,
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
index 0d44a887de..e29b2d1b47 100644
--- a/js/app/packages/queries/channel/keys.ts
+++ b/js/app/packages/queries/channel/keys.ts
@@ -10,6 +10,9 @@ export const channelKeys = createQueryKeys('channel', {
messages: (channelID: string, loadAroundMessageId: string | null = null) => ({
queryKey: [channelID, { loadAroundMessageId }],
}),
+ messagesByIds: (channelID: string, messageIds: string[]) => ({
+ queryKey: [channelID, { messageIds }],
+ }),
attachments: (channelID: string) => ({
queryKey: [channelID],
}),
diff --git a/js/app/packages/queries/channel/reconcile.ts b/js/app/packages/queries/channel/reconcile.ts
index 0745bb1a1f..e6d1268af0 100644
--- a/js/app/packages/queries/channel/reconcile.ts
+++ b/js/app/packages/queries/channel/reconcile.ts
@@ -16,8 +16,13 @@ import {
replaceTopLevelMessageIdInChannelMessages,
replaceTopLevelMessageReactionsInChannelMessages,
replaceTopLevelMessageAttachmentsInChannelMessages,
+ replaceTopLevelMessageReactionsInChannelMessagesByIds,
+ replaceTopLevelMessageAttachmentsInChannelMessagesByIds,
+ replaceTopLevelMessageStateInChannelMessagesByIds,
+ setChannelMessagesByIdsData,
setChannelMessagesData,
softInvalidateChannelMessages,
+ softInvalidateChannelMessagesByIds,
type ThreadPreviewReplySnapshot,
type TopLevelMessageSnapshot,
} from './channel-messages';
@@ -305,6 +310,13 @@ export function replaceTargetReactions(
reactions
)
);
+ setChannelMessagesByIdsData(channelId, (prev) =>
+ replaceTopLevelMessageReactionsInChannelMessagesByIds(
+ prev,
+ target.messageId,
+ reactions
+ )
+ );
}
/** Replaces attachments for a target message across all rendered caches. */
@@ -337,6 +349,13 @@ export function replaceTargetAttachments(
attachments
)
);
+ setChannelMessagesByIdsData(channelId, (prev) =>
+ replaceTopLevelMessageAttachmentsInChannelMessagesByIds(
+ prev,
+ target.messageId,
+ attachments
+ )
+ );
}
export function getTargetMessageState(
@@ -408,6 +427,13 @@ export function replaceTargetMessageState(
nextState
)
);
+ setChannelMessagesByIdsData(channelId, (prev) =>
+ replaceTopLevelMessageStateInChannelMessagesByIds(
+ prev,
+ target.messageId,
+ nextState
+ )
+ );
}
/** Soft-invalidates the rendered caches touched by a target message. */
@@ -416,6 +442,7 @@ export function softInvalidateTargetCaches(
target?: MessageTarget
) {
softInvalidateChannelMessages(channelId);
+ softInvalidateChannelMessagesByIds(channelId);
if (target?.kind === 'thread_reply') {
softInvalidateThreadReplies(channelId, target.threadId);
diff --git a/js/app/packages/service-clients/service-comms/client.ts b/js/app/packages/service-clients/service-comms/client.ts
index 29540abbb8..9938e9a0ee 100644
--- a/js/app/packages/service-clients/service-comms/client.ts
+++ b/js/app/packages/service-clients/service-comms/client.ts
@@ -44,6 +44,7 @@ import type { ApiChannelMessagesPage } from '@service-storage/generated/schemas/
import type { ApiChannelAttachmentsPage } from '@service-storage/generated/schemas/apiChannelAttachmentsPage';
import type { ApiChannelParticipant } from '@service-storage/generated/schemas/apiChannelParticipant';
import type { ApiThreadReply } from '@service-storage/generated/schemas';
+import type { ChannelMessageFilters } from '@service-storage/generated/schemas/channelMessageFilters';
export type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
export type { ApiChannelMessagesPage as ChannelMessagesPage } from '@service-storage/generated/schemas/apiChannelMessagesPage';
@@ -404,6 +405,24 @@ export const commsServiceClient = {
(result) => result
);
},
+ async postChannelMessages(
+ args: WithChannelId & { filters: ChannelMessageFilters; limit?: number }
+ ) {
+ const { channel_id, filters, limit } = args;
+ const params = new URLSearchParams();
+ if (limit !== undefined) params.append('limit', limit.toString());
+ const query = params.toString();
+ return mapOk(
+ await commsFetch<ApiChannelMessagesPage>(
+ `/channels/${channel_id}/messages${query ? `?${query}` : ''}`,
+ {
+ method: 'POST',
+ body: JSON.stringify(filters),
+ }
+ ),
+ (result) => result
+ );
+ },
async getChannelAttachments(
args: WithChannelId & { limit: number; cursor: string | null }
) {