Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): simplify channels, fix mid-list insert virtualization problems (#1284)
teo431b83ea2ef2
diff --git a/js/app/packages/block-channel/component/AttachmentsModal.tsx b/js/app/packages/block-channel/component/AttachmentsModal.tsxindex 58f76d73e9..23f39f175f 100644--- a/js/app/packages/block-channel/component/AttachmentsModal.tsx+++ b/js/app/packages/block-channel/component/AttachmentsModal.tsx@@ -8,22 +8,17 @@ import { Tooltip } from '@core/component/Tooltip';import { UserIcon } from '@core/component/UserIcon';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';-import { useChannelQuery } from '@queries/channel/channel';-import {- getTopLevelMessages,- getThreadMessages,-} from '@queries/channel/derived';import { tryMacroId, useDisplayName } from '@core/user';-import { isErr } from '@core/util/maybeResult';import BracketLeft from '@macro-icons/macro-group-bracket-left.svg';import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';-import { commsServiceClient } from '@service-comms/client';import type { MessageMention } from '@service-comms/generated/models';import type { Attachment } from '@service-comms/generated/models/attachment';import type { ItemType } from '@service-storage/client';-import { createMemo, createResource, Show, Suspense } from 'solid-js';+import { useMentionsQuery } from '@queries/channel/mentions';+import { createMemo, Show, Suspense } from 'solid-js';import { VList } from 'virtua/solid';import { useSplitLayout } from '../../app/component/split-layout/layout';+import { useChannelContext } from '@block-channel/hooks/channel';const DRAWER_ID = 'attachments';@@ -31,31 +26,18 @@ export function AttachmentsModal() {const drawerControl = useDrawerControl(DRAWER_ID);const currentBlockId = useBlockId();const { replaceOrInsertSplit } = useSplitLayout();+ const channelContext = useChannelContext();- const channel = useChannelQuery(() => currentBlockId);-- const [mentionsResource] = createResource(() =>- commsServiceClient.getMentions({ channel_id: currentBlockId })- );+ const mentionsQuery = useMentionsQuery(() => currentBlockId);const attachments = createMemo(() => {- if (mentionsResource.loading || mentionsResource.error) return [];-- const mentions: Attachment[] = (() => {- let res = mentionsResource();- if (!res || isErr(res)) {- console.error('failed to get mentions', res);- return [];- }-- const mentions = (res[1] ?? { mentions: [] }).mentions.map((m) =>- makeAttachmentFromMention(m, currentBlockId)- );-- return mentions;- })();+ const mentions: Attachment[] = !mentionsQuery.isSuccess+ ? []+ : (mentionsQuery.data?.mentions ?? []).map((m) =>+ makeAttachmentFromMention(m, currentBlockId)+ );- const channelAttachments = channel.data?.attachments ?? [];+ const channelAttachments = channelContext.attachments() ?? [];const safeAttachments = filterSafeAttachments(channelAttachments);const all = [...safeAttachments, ...mentions];return all@@ -73,15 +55,6 @@ export function AttachmentsModal() {replaceOrInsertSplit({ type: blockName, id: blockId });};- const messageSenderMap = createMemo(() => {- const data = channel.data;- if (!data) return new Map<string, string>();- const topLevel = getTopLevelMessages(data);- const threads = getThreadMessages(data);- const all = [...topLevel, ...Object.values(threads).flat()];- return new Map(all.map((m) => [m.id, m.sender_id]));- });-return (<><Tooltip tooltip={'View all attachments'}>@@ -121,7 +94,9 @@ export function AttachmentsModal() {<AttachmentItemattachment={attachment}onNavigate={navigateToItem}- senderId={messageSenderMap().get(attachment.message_id)}+ senderId={channelContext+ .messageSenderMap()+ .get(attachment.message_id)}/></Suspense>)}diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsxindex 8d2e0d473e..e6370957e8 100644--- a/js/app/packages/block-channel/component/Block.tsx+++ b/js/app/packages/block-channel/component/Block.tsx@@ -1,24 +1,11 @@-import {- doesChannelRequireJoin,- isValidChannelData,-} from '@block-channel/signal/channel';import { useBlockId } from '@core/block';import { useChannelName } from '@core/context/channels';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';-import { useChannelQuery } from '@queries/channel/channel';-import { commsServiceClient } from '@service-comms/client';-import { useUserId } from '@core/context/user';-import {- createSignal,- type JSXElement,- Match,- Suspense,- Switch,-} from 'solid-js';+import { type JSXElement, Suspense } from 'solid-js';import { Channel } from './Channel';-import { JoinChannelDialog } from './JoinChannelDialog';import { URL_PARAMS } from '@block-channel/constants';import type { TargetMessageInfo } from '@block-channel/component/MessageList/MessageList';+import { ChannelContextProvider } from '@block-channel/hooks/channel';export function WithTopBar(props: { children: JSXElement }) {return <div>{props.children}</div>;@@ -32,66 +19,7 @@ export type BlockChannelProps = IncomingParams & {};export default function BlockChannel(props: BlockChannelProps) {const channelId = useBlockId();-- const channel = useChannelQuery(- () => channelId,- () => ({- placeholderData: (p) => p,- })- );- const userId = useUserId();-- const [error] = createSignal<string>();- const [joinState, setJoinState] = createSignal<JoinState>();-- const validChannelData = () => {- const blockData_ = channel.data;- const userId_ = userId();- if (!userId_) return;- if (!blockData_) return;- if (!isValidChannelData(blockData_)) return;-- setJoinState(- doesChannelRequireJoin(blockData_, userId_) ? 'REQUIRED' : 'NOT_REQUIRED'- );-- return blockData_;- };-- function handleJoinChannel(- channelId: string,- selection: 'ACCEPTED' | 'REJECTED'- ) {- if (selection === 'ACCEPTED') {- commsServiceClient- .joinChannel({- channel_id: channelId,- })- .then(() => {- setJoinState('NOT_REQUIRED');- });- setJoinState('NOT_REQUIRED');- } else {- setJoinState('REQUIRED');- }- }-- const validChannelDataWithJoinState = () => {- if (joinState() === 'REQUIRED' && validChannelData()) {- let data = validChannelData();- return data;- }- return undefined;- };-- const channelName = () => {- const data = channel.data;- if (!data) return undefined;- const id = data.channel.id;- const name = data.channel.name;- const maybeChannelName = useChannelName(id, name as string);- return maybeChannelName();- };+ const channelName = useChannelName(channelId);const targetMessage = () => {const messageID = props[URL_PARAMS.message];@@ -107,37 +35,9 @@ export default function BlockChannel(props: BlockChannelProps) {return (<Suspense><DocumentBlockContainer title={channelName() ?? 'Channel'}>- <Switch- fallback={- <WithTopBar>- <h1 />- </WithTopBar>- }- >- <Match when={error()}>- <WithTopBar>- <h1>{error()}</h1>- </WithTopBar>- </Match>- <Match when={validChannelDataWithJoinState()}>- {(channelData) => (- <WithTopBar>- <JoinChannelDialog- channelName={channelData().channel.name ?? ''}- participantCount={channelData().participants.length}- onSelect={(selection) =>- handleJoinChannel(channelData().channel.id, selection)- }- />- </WithTopBar>- )}- </Match>- <Match when={validChannelData()}>- {(channelData) => (- <Channel data={channelData()} target={targetMessage()} />- )}- </Match>- </Switch>+ <ChannelContextProvider channelId={() => channelId}>+ <Channel channelId={channelId} target={targetMessage()} />+ </ChannelContextProvider></DocumentBlockContainer></Suspense>);diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsxindex a35c47761e..505d9d2046 100644--- a/js/app/packages/block-channel/component/Channel.tsx+++ b/js/app/packages/block-channel/component/Channel.tsx@@ -1,7 +1,6 @@import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';import { URL_PARAMS } from '@block-channel/constants';-import type { ChannelData } from '@block-channel/definition';import {isDraggingOverChannelSignal,isValidChannelDragSignal,@@ -10,7 +9,6 @@ import { activeThreadIdSignal } from '@block-channel/signal/threads';import { handleFileUpload } from '@block-channel/utils/inputAttachments';import { withAnalytics } from '@coparse/analytics';import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';-import { useBlockId } from '@core/block';import type { EntityDragEvent } from '@macro-entity';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { fileTypeToBlockName } from '@core/constant/allBlocks';@@ -32,11 +30,6 @@ import {useEntityHasUnreadNotifications,} from '@notifications';import { useUpdateChannelsActivityMutation } from '@queries/channel/activity';-import { useChannelQuery } from '@queries/channel/channel';-import {- getTopLevelMessages,- getThreadMessages,-} from '@queries/channel/derived';import type { Message } from '@service-comms/generated/models';import { connectionGatewayClient } from '@service-connection/client';import { useBeforeLeave, useSearchParams } from '@solidjs/router';@@ -62,6 +55,7 @@ import {} from './MessageList/MessageList';import { Top } from './Top';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import { useChannelContext } from '@block-channel/hooks/channel';false && fileFolderDrop;@@ -83,24 +77,13 @@ function createChannelTrackingEffect(channelId: string) {}export function Channel(props: {- data: Required<ChannelData>;+ channelId: string;target?: TargetMessageInfo;}) {const [_activeThreadId, setActiveThreadId] = activeThreadIdSignal;- const channel = useChannelQuery(- () => props.data.channel.id,- () => ({ refetchOnWindowFocus: true })- );-- // Derive messages and threads from query data- const messages = () => getTopLevelMessages(channel.data);- const threads = () => getThreadMessages(channel.data);- const reactions = () => channel.data?.reactions ?? {};- const attachments = () => channel.data?.attachments ?? [];-- const channelId = useBlockId();- const latestActivity = useChannelActivity(channelId);+ const channelContext = useChannelContext();+ const latestActivity = useChannelActivity(props.channelId);const [openedChannel, setOpenedChannel] = createSignal<Date>();@@ -108,11 +91,17 @@ export function Channel(props: {const updateActivityOnOpen = () => {setOpenedChannel(new Date());- updateActivityMutation.mutate({ channelId, activityType: 'view' });+ updateActivityMutation.mutate({+ channelId: props.channelId,+ activityType: 'view',+ });};const updateActivityOnClose = () =>- updateActivityMutation.mutate({ channelId, activityType: 'view' });+ updateActivityMutation.mutate({+ channelId: props.channelId,+ activityType: 'view',+ });const { track } = withAnalytics();let containerRef!: HTMLDivElement;@@ -178,13 +167,13 @@ export function Channel(props: {track(TrackingEvents.BLOCKCHANNEL.CHANNEL.OPEN);});- createChannelTrackingEffect(channelId);+ createChannelTrackingEffect(props.channelId);useBeforeLeave(() => {updateActivityOnClose();});- const droppable = createDroppable('channel-input-' + channelId);+ const droppable = createDroppable('channel-input-' + props.channelId);false && droppable;@@ -194,12 +183,12 @@ export function Channel(props: {];function handleAttach(attachment: InputAttachment) {- const list = channelInputAttachmentsStore[channelId] ?? [];+ const list = channelInputAttachmentsStore[props.channelId] ?? [];if (list.find((a) => a.id === attachment.id))return toast.failure('Attachment already attached');if (list.length >= 10)return toast.failure('You can only attach up to 10 files at a time');- setChannelInputAttachmentsStore(channelId, (prev = []) => [+ setChannelInputAttachmentsStore(props.channelId, (prev = []) => [...prev,attachment,]);@@ -207,7 +196,7 @@ export function Channel(props: {onDragEnd((event: EntityDragEvent) => {if (!event.droppable) return;- if (event.droppable?.id !== 'channel-input-' + channelId) return;+ if (event.droppable?.id !== 'channel-input-' + props.channelId) return;if (event.droppable.node === containerRef) {const { track, TrackingEvents } = withAnalytics();track(TrackingEvents.BLOCKCHANNEL.ATTACHMENT.DRAG);@@ -331,7 +320,7 @@ export function Channel(props: {const debouncedMarkAsRead = makeDebouncedChannelNotificationReadMarker({notificationSource: notificationSource,- channelId,+ channelId: props.channelId,debounceTime: 500,});@@ -343,7 +332,7 @@ export function Channel(props: {(notification) => {if (!splitContext.isPanelActive() ||- notification.entity_id !== channelId+ notification.entity_id !== props.channelId) {return;}@@ -354,7 +343,7 @@ export function Channel(props: {const hasNotifications = useEntityHasUnreadNotifications(notificationSource, {type: 'channel',- id: channelId,+ id: props.channelId,});const splitContext = useSplitPanelOrThrow();@@ -380,12 +369,17 @@ export function Channel(props: {><ChannelDebouncedNotificationReadMarkernotificationSource={notificationSource}- channelId={channelId}+ channelId={props.channelId}debounceTime={500}/><StaticMarkdownContext><Suspense>- <Top channelID={channelId} />+ <Top+ channelId={props.channelId}+ channelType={channelContext.channelType()}+ participants={channelContext.channel()?.participants ?? []}+ channelName={channelContext.channelName()}+ /></Suspense><divclass="h-full flex flex-col min-h-0 flex-1 relative w-full"@@ -395,7 +389,7 @@ export function Channel(props: {handleFileUpload(uploadEntries, {store: channelInputAttachmentsStore,setStore: setChannelInputAttachmentsStore,- key: channelId,+ key: props.channelId,}));},@@ -414,12 +408,12 @@ export function Channel(props: {ref={containerRef}/><MessageList- channelId={channelId}- messages={messages()}- threads={threads()}- reactions={reactions()}- attachments={attachments()}- participants={channel.data?.participants ?? []}+ channelId={props.channelId}+ messages={channelContext.messages()}+ threads={channelContext.threads()}+ reactions={channelContext.reactions()}+ attachments={channelContext.attachments()}+ participants={channelContext.channel()?.participants ?? []}focusedMessageId={selectedMessageId}setFocusedMessageId={setSelectedMessageId}targetMessage={targetMessage}@@ -434,12 +428,12 @@ export function Channel(props: {<div class="mx-auto -translate-x-1 w-full macro-message-width"><Suspense><ChannelInput- channelId={channelId}- channelName={channel.data?.channel?.name ?? ''}- participants={channel.data?.participants ?? []}+ channelId={props.channelId}+ channelName={channelContext.channelName()}+ participants={channelContext.channel()?.participants ?? []}inputAttachmentsStore={channelInputAttachmentsStore}setInputAttachmentsStore={setChannelInputAttachmentsStore}- inputAttachmentsKey={channelId}+ inputAttachmentsKey={props.channelId}onFocusLeaveStart={onChannelInputFocusLeaveStart}autoFocusOnMount={autoFocusOnMount()}domRef={setChannelInputRef}diff --git a/js/app/packages/block-channel/component/JoinChannelDialog.tsx b/js/app/packages/block-channel/component/JoinChannelDialog.tsxdeleted file mode 100644index 3cc8b8b81a..0000000000--- a/js/app/packages/block-channel/component/JoinChannelDialog.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';-import { EntityIcon } from '@core/component/EntityIcon';-import CheckIcon from '@icon/regular/arrow-right.svg';--export type JoinChannelDialogProps = {- channelName: string;- participantCount: number;- onSelect: (selection: 'ACCEPTED' | 'REJECTED') => void;-};--export function JoinChannelDialog(props: JoinChannelDialogProps) {- return (- <div class="flex-1 w-full h-full flex flex-col items-center justify-center">- <div class="flex flex-col items-center justify-center gap-4 bg-dialog ">- <div class="flex flex-col items-center gap-1">- <p class="text-sm">You've been invited to join</p>- <div class="flex flex-row items-center gap-2 ">- <div class="h-8 w-8">- <EntityIcon targetType="channel" size="fill" />- </div>-- <h1 class="text-3xl font-bold flex-wrap">{props.channelName}</h1>- </div>-- <p class="text-sm text-ink-muted">- {props.participantCount}{' '}- {props.participantCount === 1 ? 'participant' : 'participants'}- </p>- </div>- <DeprecatedTextButton- theme="base"- icon={() => <CheckIcon class="w-4 h-4" />}- text="Join Channel"- onClick={() => props.onSelect('ACCEPTED')}- />- </div>- </div>- );-}diff --git a/js/app/packages/block-channel/component/Message/MessageContainer.tsx b/js/app/packages/block-channel/component/Message/MessageContainer.tsxindex a0542de747..d0c681fcfb 100644--- a/js/app/packages/block-channel/component/Message/MessageContainer.tsx+++ b/js/app/packages/block-channel/component/Message/MessageContainer.tsx@@ -174,11 +174,10 @@ export function MessageContainer(props: MessageProps) {});// We're only checking new messages that are not part of a thread- const isNewMessage = () => props.listContext?.isNewMessage ?? false;+ const isNewMessage = () => props.listContext.isNewMessage;// Works for one-level of nesting. In the future we'll need to track at which depths a message is part of a new message chain.- const isParentNewMessage = () =>- props.listContext?.isParentNewMessage ?? false;+ const isParentNewMessage = () => props.listContext.isParentNewMessage;const previousMessage = () => {return props.index() > 0@@ -187,7 +186,7 @@ export function MessageContainer(props: MessageProps) {};const newDayPreviousNonThreadMessage = () => {- const prev = props.listContext?.previousNonThreadedMessage;+ const prev = props.listContext.previousNonThreadedMessage;if (!prev) return false;return !isSameDay(new Date(message.created_at), new Date(prev.created_at));};diff --git a/js/app/packages/block-channel/component/MessageList/MessageList.tsx b/js/app/packages/block-channel/component/MessageList/MessageList.tsxindex ed4c228817..7f9e7c693b 100644--- a/js/app/packages/block-channel/component/MessageList/MessageList.tsx+++ b/js/app/packages/block-channel/component/MessageList/MessageList.tsx@@ -35,6 +35,7 @@ import {createRenderEffect,createSelector,createSignal,+ For,Match,mapArray,on,@@ -50,25 +51,52 @@ import { type VirtualizerHandle, VList } from 'virtua/solid';import type { ScrollToIndexOpts } from 'virtua/unstable_core';import { MessageContainer } from '../Message/MessageContainer';import { ReplyInputsPortaler } from '../ReplyInputsPortaler';+import type { MessageListContext } from '@block-channel/utils/listContext';+import { match } from 'ts-pattern';false && observedSize;-// Provide stable row models to VList so item instances are preserved across moves/insertions-type RowModel = {+type ThreadRow = {id: string;message: Message;+ children: Message[];+};++type MessageListItemProps = {+ message: Message;+ index: Accessor<number>;+ listContext: MessageListContext;+ isFocused: boolean;+ isTarget: boolean;+ threadChildren?: Message[];+ threadSiblings?: Message[];};// The size of a message with a profile picture and a one line messageconst BASE_ITEM_SIZE = 50;+const createDefaultMessageListContext = (index: Accessor<number>) =>+ createMemo<MessageListContext>(() => ({+ index: index(),+ isNewMessage: false,+ isParentNewMessage: false,+ threadIndex: -1,+ previousNonThreadedMessage: undefined,+ isInLastThread: false,+ }));+type MessageListContentContextValues = {setFocusedMessageId: Setter<string | undefined>;registerVirtualHandle: (handle: VirtualizerHandle) => void;scrollContainerRef: Accessor<HTMLElement | undefined>;registerScrollContainer: (el: HTMLElement) => void;scrollToIndex: (index: number, alignOpts?: ScrollToIndexOpts) => void;- scrollToMessage: (messageID: string, index: number, focus?: boolean) => void;+ scrollToMessage: (+ messageID: string,+ index: number,+ focus?: boolean,+ alignOpts?: ScrollToIndexOpts+ ) => void;createReply: (id: string, focus?: boolean) => void;toggleThread: (threadID: string, value?: boolean) => void;closeThreadReply: (threadID: string, expanded?: boolean) => void;@@ -84,8 +112,12 @@ const MessageListContentContext =export const useMessageListContext = () => {const context = useContext(MessageListContentContext);-- return context!;+ if (!context) {+ throw new Error(+ 'useMessageListContext must be used within MessageListContentContext.Provider'+ );+ }+ return context;};export type TargetMessageInfo = { messageId: string; threadId?: string };@@ -140,10 +172,99 @@ export function MessageList(props: MessageListProps) {const [threadViewStore, setThreadViewStore] = createStore<ThreadViewData>({});- const normalizeIndex = (index: number) => {- const length = props.orderedMessages().length;+ const topLevelMessages = createMemo(() =>+ props.messages.filter(+ (message) =>+ !message.thread_id &&+ (!message.deleted_at || (props.threads[message.id]?.length ?? 0) > 0)+ )+ );++ const topLevelIndexByMessageId = createMemo(() => {+ const list = topLevelMessages();+ const map = new Map<string, number>();+ for (let i = 0; i < list.length; i++) {+ const parent = list[i];+ map.set(parent.id, i);+ const children = props.threads[parent.id] ?? [];+ for (const child of children) {+ map.set(child.id, i);+ }+ }+ return map;+ });++ const getVirtualIndexForMessageId = (messageId: string) => {+ const list = topLevelMessages();+ const topLevelIndex = topLevelIndexByMessageId().get(messageId);+ if (topLevelIndex === undefined) return undefined;+ return list.length - 1 - topLevelIndex;+ };++ const scrollElementIntoView = (+ targetEl: HTMLElement,+ align: ScrollToIndexOpts['align'] = 'nearest'+ ) => {+ const handle = virtualHandle();+ const container = scrollContainerRef();+ if (!handle || !container) return;++ const targetBounds = targetEl.getBoundingClientRect();+ const containerBounds = container.getBoundingClientRect();+ const currentOffset = handle.scrollOffset;+ const targetTop = targetBounds.top - containerBounds.top + currentOffset;+ const targetBottom = targetTop + targetBounds.height;+ const visibleTop = currentOffset;+ const visibleBottom = currentOffset + handle.viewportSize;++ const nextOffset = match(align)+ .with('start', () => targetTop)+ .with('end', () => targetBottom - handle.viewportSize)+ .with(+ 'center',+ () => targetTop - (handle.viewportSize - targetBounds.height) / 2+ )+ .otherwise(() => {+ if (targetTop < visibleTop) {+ return targetTop;+ } else if (targetBottom > visibleBottom) {+ return targetBottom - handle.viewportSize;+ }+ return undefined;+ });++ if (nextOffset !== undefined) {+ handle.scrollTo(nextOffset);+ }+ };++ const tryAlignMessageElement = (+ messageId: string,+ align: ScrollToIndexOpts['align'],+ focus: boolean+ ) => {+ const container = scrollContainerRef();+ if (!container) return false;+ const targetEl = container.querySelector<HTMLElement>(+ `[data-message-body-id="${messageId}"]`+ );+ if (!targetEl) return false;+ scrollElementIntoView(targetEl, align);+ if (focus) targetEl.focus();+ return true;+ };- return length - 1 - index;+ const scheduleAlignMessageElement = (+ messageId: string,+ align: ScrollToIndexOpts['align'] = 'nearest',+ focus: boolean = false+ ) => {+ requestAnimationFrame(() => {+ if (tryAlignMessageElement(messageId, align, focus)) return;+ setTimeout(() => {+ tryAlignMessageElement(messageId, align, focus);+ }, 0);+ });};const context: MessageListContentContextValues = {@@ -152,27 +273,25 @@ export function MessageList(props: MessageListProps) {scrollContainerRef,registerScrollContainer: setScrollContainerRef,scrollToIndex: function (index: number, opts?: ScrollToIndexOpts): void {- virtualHandle()?.scrollToIndex(normalizeIndex(index), opts);+ const messageId = props.orderedMessages()[index]?.id;+ if (!messageId) return;+ const virtualIndex = getVirtualIndexForMessageId(messageId);+ if (virtualIndex === undefined) return;+ virtualHandle()?.scrollToIndex(virtualIndex, opts);+ scheduleAlignMessageElement(messageId, opts?.align, false);},scrollToMessage: function (messageID: string,- index: number,- focus: boolean = true+ _index: number,+ focus: boolean = true,+ alignOpts?: ScrollToIndexOpts): void {- const handle = virtualHandle();-- if (!handle) return;-- handle.scrollToIndex(normalizeIndex(index), { align: 'end' });- if (!focus) return;- const targetEl = scrollContainerRef()?.querySelector<HTMLElement>(- `[data-message-body-id="${messageID}"]`- );- if (targetEl) {- requestAnimationFrame(() => {- targetEl.focus();- });- }+ const virtualIndex = getVirtualIndexForMessageId(messageID);+ if (virtualIndex === undefined) return;+ virtualHandle()?.scrollToIndex(virtualIndex, {+ align: alignOpts?.align ?? 'nearest',+ });+ scheduleAlignMessageElement(messageID, alignOpts?.align, focus);},createReply: function (id: string, focus = false): void {setThreadViewStore(id, (prev) => {@@ -256,23 +375,14 @@ function MessageListImpl(props: MessageListProps) {const [isNearBottom, setIsNearBottom] = createSignal(true);const [initialScrollComplete, setInitialScrollComplete] = createSignal(false);- const normalizeIndex = (index: number) => {- const length = props.orderedMessages().length;-- return length - 1 - index;- };-// Navigation methods for keyboard navigationconst navigateToMessage = (messageId: string): boolean => {const messages = props.orderedMessages();const index = messages.findIndex((m) => m.id === messageId);if (index === -1) return false;-- const handle = virtualHandle();- if (!handle) return false;-- // Scroll to the message- handle.scrollToIndex(normalizeIndex(index), { align: 'nearest' });+ listContext.scrollToMessage(messageId, index, false, {+ align: 'nearest',+ });// Focus after scroll completesrequestAnimationFrame(() => {@@ -372,10 +482,7 @@ function MessageListImpl(props: MessageListProps) {forceBottom ||((!target || delta > TARGET_MESSAGE_ACTIVE_TIME) && isNearBottom())) {- const lastIndex = 0;- virtualHandle()?.scrollToIndex(lastIndex, {- align: 'end',- });+ virtualHandle()?.scrollToIndex(0, { align: 'end' });return;}@@ -421,7 +528,7 @@ function MessageListImpl(props: MessageListProps) {}setTargetMessageActive(true);- virtualHandle()?.scrollToIndex(normalizeIndex(index), {+ listContext.scrollToMessage(targetMessageId, index, false, {align: 'center',});setTimeout(() => {@@ -549,21 +656,25 @@ function MessageListImpl(props: MessageListProps) {return currentTypingId;});- const rows = mapArray(- () => props.orderedMessages().toReversed(),- (msg) => {- return { id: msg.id, message: msg } as RowModel;+ const threadRows = createMemo<ThreadRow[]>(() => {+ const list = filteredTopLevelMessages();+ const out: ThreadRow[] = [];+ for (let i = list.length - 1; i >= 0; i--) {+ const message = list[i];+ const children = (viewThreads[message.id] ?? []).filter(messageFilterFn);+ out.push({ id: message.id, message, children });}- );+ return out;+ });createEffect(() => {- rows();+ threadRows();setIsPrepend(false);});// Ensure thread view store store reflects drafts. Only sets when no entry exists to avoid overriding user actions.createEffect(() => {- const base = filteredTopLevelMessages() ?? [];+ const base = filteredTopLevelMessages();for (const message of base) {const hasDraft = !!loadDraftMessage(message.channel_id, message.id);const threadDetails = listContext.getThreadState(message.id);@@ -573,34 +684,18 @@ function MessageListImpl(props: MessageListProps) {}});- // Indices of messages that should remain mounted even when off screen.- // Criteria: message is last in its thread AND that thread has an active reply.+ // Indices of top-level rows that should remain mounted even when off screen.+ // Criteria: thread has an active reply, so keep its parent row mounted.+ // NOTE: VList receives reversed top-level rows, so indices must be normalized.const keepMountedIndices = createMemo(() => {- const list = props.orderedMessages() ?? [];+ const list = filteredTopLevelMessages();+ const length = list.length;const indices: number[] = [];- for (let i = 0; i < list.length; i++) {+ for (let i = 0; i < length; i++) {const msg = list[i];- const next = list[i + 1];- const threadId = msg.thread_id;-- if (!threadId) continue;-- const threadState = listContext.getThreadState(threadId);-- // Since orderedMessages is a flat list: if the next message' thread id is different OR- // there is no next message, then this message is the last message in the thread- const isLastInThread =- (next && next.thread_id !== msg.thread_id) || !next;-- // We captured this thread reply but there was no message. The user might be- // typing or want to type a reply- const isLocallyFrozenWithEmptyMessage = !viewThreads[msg.id]?.length;-- if (- (isLastInThread && threadState?.hasActiveReply) ||- (threadState?.hasActiveReply && isLocallyFrozenWithEmptyMessage)- ) {- indices.push(i);+ const threadState = listContext.getThreadState(msg.id);+ if (threadState?.hasActiveReply) {+ indices.push(length - 1 - i);}}return indices;@@ -623,7 +718,7 @@ function MessageListImpl(props: MessageListProps) {});const lastMessageThread = createMemo(() => {- const base = filteredTopLevelMessages() ?? [];+ const base = filteredTopLevelMessages();const lastTopLevelId = base[base.length - 1]?.id;return viewThreads[lastTopLevelId];});@@ -746,7 +841,9 @@ function MessageListImpl(props: MessageListProps) {.orderedMessages()?.findIndex((m) => m.id === messages[0].id);if (firstUnviewedIndex === undefined) return;- virtualHandle()?.scrollToIndex(normalizeIndex(firstUnviewedIndex), {+ const targetMessageId = props.orderedMessages()?.[firstUnviewedIndex]?.id;+ if (!targetMessageId) return;+ listContext.scrollToMessage(targetMessageId, firstUnviewedIndex, false, {align: 'start',});}@@ -764,6 +861,87 @@ function MessageListImpl(props: MessageListProps) {const listHeight = createMemo(() => size()?.height ?? 0);+ const MessageListItem = (params: MessageListItemProps) => (+ <MessageContainer+ message={params.message}+ lastViewed={lastViewed}+ isFocused={params.isFocused}+ index={params.index}+ orderedMessages={props.orderedMessages}+ threadChildren={params.threadChildren}+ threadSiblings={params.threadSiblings}+ newIndicatorShown={newIndicatorShown}+ setNewIndicatorShown={setNewIndicatorShown}+ virtualHandle={virtualHandle()!}+ container={containerRef()}+ listContext={params.listContext}+ isTarget={params.isTarget}+ channelId={() => props.channelId}+ attachments={props.attachments}+ reactions={props.reactions}+ />+ );++ const ThreadRowItem = (rowProps: { row: ThreadRow }) => {+ const row = () => rowProps.row;+ const threadChildren = () => row().children;+ const threadState = createMemo(() =>+ listContext.getThreadState(row().message.id)+ );+ const isThreadExpanded = () => threadState()?.threadExpanded === true;+ const parentIndex = () => messageListContext[row().id]?.index ?? 0;+ const parentDefaultContext = createDefaultMessageListContext(parentIndex);+ const parentContext = () =>+ messageListContext[row().id] ?? parentDefaultContext();++ const renderThreadChild = (child: Message) => {+ const childId = () => child.id;+ const childContext = () => messageListContext[childId()];+ const childIndexAccessor = () => childContext()?.index ?? 0;+ const childDefaultContext =+ createDefaultMessageListContext(childIndexAccessor);+ const resolvedChildContext = () =>+ childContext() ?? childDefaultContext();+ const isThreadIndexWithinCutoff = createMemo(() => {+ const ctx = childContext();+ if (!ctx) return false;+ return (+ ctx.threadIndex !== -1 &&+ ctx.threadIndex <= COLLAPSED_THREAD_INDEX_CUTOFF+ );+ });++ return (+ <Show when={isThreadExpanded() || isThreadIndexWithinCutoff()}>+ <MessageListItem+ message={child}+ isFocused={isFocused(childId())}+ index={childIndexAccessor}+ threadSiblings={threadChildren()}+ listContext={resolvedChildContext()}+ isTarget={isActiveTargetMessage(child.id)}+ />+ </Show>+ );+ };++ return (+ <Show when={virtualHandle()}>+ <div>+ <MessageListItem+ message={row().message}+ isFocused={isFocused(row().id)}+ index={parentIndex}+ threadChildren={threadChildren()}+ listContext={parentContext()}+ isTarget={isActiveTargetMessage(row().message.id)}+ />+ <For each={threadChildren()}>{renderThreadChild}</For>+ </div>+ </Show>+ );+ };+return (<divclass="flex-1 overflow-y-hidden suppress-css-brackets"@@ -810,7 +988,7 @@ function MessageListImpl(props: MessageListProps) {}}class="scrollbar-hidden [&>div]:mb-auto"data-channel-message-list- data={rows() ?? []}+ data={threadRows()}shift={isPrepend()}itemSize={BASE_ITEM_SIZE}bufferSize={10 * BASE_ITEM_SIZE}@@ -822,60 +1000,7 @@ function MessageListImpl(props: MessageListProps) {}}}>- {(row: { id: string; message: Message }, i) => {- const isParentless = () => !row.message.thread_id;- const isThreadExpanded = createMemo(() => {- if (!row.message.thread_id) return false;-- const state = listContext.getThreadState(- row.message.thread_id- );-- return state?.threadExpanded === true;- });- const isThreadIndexWithinCutoff = createMemo(- () =>- messageListContext[row.id].threadIndex !== -1 &&- messageListContext[row.id].threadIndex <=- COLLAPSED_THREAD_INDEX_CUTOFF- );- return (- <Show- when={- (isParentless() ||- isThreadExpanded() ||- isThreadIndexWithinCutoff()) &&- virtualHandle()- }- // For the last message in the channel, we display this- // empty small div. This is a temporary fix for last thread elements not rendering- fallback={i() === 0 ? <div class="h-[0.05px]" /> : null}- >- <MessageContainer- message={row.message}- lastViewed={lastViewed}- isFocused={isFocused(row.id)}- index={() => normalizeIndex(i())}- orderedMessages={props.orderedMessages}- threadSiblings={viewThreads[- row.message.thread_id ?? ''- ]?.filter(messageFilterFn)}- threadChildren={viewThreads[row.message.id ?? '']?.filter(- messageFilterFn- )}- newIndicatorShown={newIndicatorShown}- setNewIndicatorShown={setNewIndicatorShown}- virtualHandle={virtualHandle()!}- container={containerRef()}- listContext={messageListContext[row.id]}- isTarget={isActiveTargetMessage(row.message.id)}- channelId={() => props.channelId}- attachments={props.attachments}- reactions={props.reactions}- />- </Show>- );- }}+ {(row: ThreadRow) => <ThreadRowItem row={row} />}</VList></Match></Switch>diff --git a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsxindex fb8bcf4a55..0447257891 100644--- a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx+++ b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx@@ -52,7 +52,15 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {const onSend = (threadId: string) => async (args: SendMessageArgs) => {clearDraftMessage(props.channelId, threadId);- await sendMessage({ ...args, threadId });+ listContext.closeThreadReply(threadId, true);++ try {+ await sendMessage({ ...args, threadId });+ } catch {+ listContext.createReply(threadId, true);+ return;+ }+// 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.@@ -78,10 +86,6 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {}, 100);};- const onAfterSend = (threadId: string) => () => {- listContext.closeThreadReply(threadId, true);- };-const closeDraft = (threadId: string) => () => {clearDraftMessage(props.channelId, threadId);listContext.closeThreadReply(threadId, true);@@ -134,7 +138,6 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {><BaseInputonSend={onSend(threadId)}- afterSend={onAfterSend(threadId)}placeholder={`Send a reply`}autoFocusOnMount={false}shouldFocus={threadState()?.replyInputShouldFocus}diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsxindex e382e5ef03..300264b885 100644--- a/js/app/packages/block-channel/component/Top.tsx+++ b/js/app/packages/block-channel/component/Top.tsx@@ -15,7 +15,6 @@ import { UserIcon } from '@core/component/UserIcon';import { buildSimpleEntityUrl } from '@core/util/url';import HashIcon from '@icon/regular/hash.svg';import LinkIcon from '@icon/regular/link.svg';-import { useChannelQuery } from '@queries/channel/channel';import type { ChannelParticipant } from '@service-comms/generated/models/channelParticipant';import type { ChannelType } from '@service-comms/generated/models/channelType';import { useUserId } from '@core/context/user';@@ -48,12 +47,15 @@ function TopIcon(props: TopIconProps) {);}-export function Top(props: { channelID: string }) {- const channel = useChannelQuery(() => props.channelID);+type TopProps = {+ channelType: ChannelType;+ participants: ChannelParticipant[];+ channelName: string;+ channelId: string;+};- const channelType = () => channel.data?.channel?.channel_type ?? 'private';- const participantCount = () => channel.data?.participants.length ?? 0;- const participants = () => channel.data?.participants ?? [];+export function Top(props: TopProps) {+ const participantCount = () => props.participants.length;const blockId = useBlockId();const notificationSource = useGlobalNotificationSource();@@ -69,27 +71,23 @@ export function Top(props: { channelID: string }) {);toast.success('Link copied to clipboard');}- const _channelName = useChannelName(+ const channelName = useChannelName(blockId,- channel.data?.channel?.name ?? 'New Channel'+ props.channelName ?? 'New Channel');- const channelName = () => {- return channel.data?.channel?.name ?? _channelName() ?? 'New Channel';- };-return (<><SplitHeaderLeft><div class="h-full my-auto flex gap-2 justify-center items-center"><div class="z-3 relative flex items-center gap-2 max-w-full h-full shrink"><TopIcon- channelType={channelType()}- participants={participants()}+ channelType={props.channelType}+ participants={props.participants}/><SplitLabel- label={channelName()}- id={channel.data?.channel.id}+ label={channelName() ?? 'New Channel'}+ id={props.channelId}itemType="channel"/></div>@@ -100,7 +98,7 @@ export function Top(props: { channelID: string }) {</SplitHeaderRight><SplitToolbarRight><div class="p-1 flex flex-row gap-1 items-center h-full">- <Show when={channelType() === 'public'}>+ <Show when={props.channelType === 'public'}><DeprecatedIconButtontheme="clear"size="sm"@@ -115,11 +113,11 @@ export function Top(props: { channelID: string }) {buttonSize="sm"/><AttachmentsModal />- <Show when={channelType() !== 'direct_message'}>+ <Show when={props.channelType !== 'direct_message'}><ParticipantManager- channelId={props.channelID}- channelType={channelType()}- participants={participants()}+ channelId={props.channelId}+ channelType={props.channelType}+ participants={props.participants}participantCount={participantCount()}/></Show>diff --git a/js/app/packages/block-channel/hooks/channel.tsx b/js/app/packages/block-channel/hooks/channel.tsxnew file mode 100644index 0000000000..912ccefaf4--- /dev/null+++ b/js/app/packages/block-channel/hooks/channel.tsx@@ -0,0 +1,62 @@+import { createAssertedContextProvider } from '@core/context/createContext';+import { useChannelQuery } from '@queries/channel/channel';+import {+ getThreadMessages,+ getTopLevelMessages,+} from '@queries/channel/derived';+import type {+ Attachment,+ ChannelType,+ GetChannelResponse,+ GetChannelResponseReactions,+} from '@service-comms/generated/models';+import type { Message } from '@service-comms/generated/models/message';+import { createMemo, type Accessor } from 'solid-js';++export type MessageSenderLookup = Map<string, string>;++type ChannelContextValue = {+ channel: Accessor<GetChannelResponse>;+ channelName: Accessor<string>;+ messages: Accessor<Message[]>;+ threads: Accessor<ReturnType<typeof getThreadMessages>>;+ reactions: Accessor<GetChannelResponseReactions>;+ attachments: Accessor<Attachment[]>;+ messageSenderMap: Accessor<MessageSenderLookup>;+ channelType: Accessor<ChannelType>;+};++type ChannelContextProps = {+ channelId: Accessor<string>;+};++export const [ChannelContextProvider, useChannelContext] =+ createAssertedContextProvider<ChannelContextValue>(+ 'ChannelContext',+ (props: ChannelContextProps): ChannelContextValue => {+ const channelQuery = useChannelQuery(props.channelId);+ const channel = createMemo(() => channelQuery.data);+ const channelType = createMemo(() => channel().channel.channel_type);+ const channelName = createMemo(() => channel().channel.name ?? '');+ const messages = createMemo(() => getTopLevelMessages(channel()));+ const threads = createMemo(() => getThreadMessages(channel()));+ const reactions = createMemo(() => channel().reactions ?? {});+ const attachments = createMemo(() => channel().attachments ?? []);++ const messageSenderMap = createMemo(() => {+ const all = [...messages(), ...Object.values(threads()).flat()];+ return new Map(all.map((m) => [m.id, m.sender_id]));+ });++ return {+ channel,+ channelName,+ channelType,+ messages,+ threads,+ reactions,+ attachments,+ messageSenderMap,+ };+ }+ );diff --git a/js/app/packages/block-channel/signal/channel.ts b/js/app/packages/block-channel/signal/channel.tsindex 2a2d5d9f44..6bbfcca5e4 100644--- a/js/app/packages/block-channel/signal/channel.ts+++ b/js/app/packages/block-channel/signal/channel.ts@@ -1,4 +1,3 @@-import type { ChannelData } from '@block-channel/definition';import {type InputAttachment,isStaticAttachmentType,@@ -12,25 +11,6 @@ import { useUserId } from '@core/context/user';import { blockNameToItemType } from '@service-storage/client';import type { Accessor } from 'solid-js';-export function isValidChannelData(- data: ChannelData-): data is Required<ChannelData> {- if (!data.channel) return false;- if (!data.channel.id) return false;- if (!data.participants) return false;- return true;-}--export function doesChannelRequireJoin(- data: Required<ChannelData>,- userId: string-) {- return (- data.channel.channel_type === 'public' &&- data.participants.find((p) => p.user_id === userId) === undefined- );-}-function isMessageSendable(content: string | undefined,attachments: InputAttachment[]diff --git a/js/app/packages/core/context/createContext.ts b/js/app/packages/core/context/createContext.tsindex 74e4eac4db..cd54280aab 100644--- a/js/app/packages/core/context/createContext.ts+++ b/js/app/packages/core/context/createContext.ts@@ -12,12 +12,14 @@ import {* @param factory - Factory function that creates the context value* @returns Tuple of [Provider, useContext] where useContext throws if undefined*/-export function createAssertedContextProvider<T>(+export function createAssertedContextProvider<+ T,+ P extends ContextProviderProps = ContextProviderProps,+>(name: string,- factory: () => T-): [provider: ContextProvider<ContextProviderProps>, useContext: () => T] {+ factory: (props: P) => T+): [provider: ContextProvider<P>, useContext: () => T] {const [Provider, useContext] = createContextProvider(factory);-const useAssertedContext = (): T => {const ctx = useContext();if (ctx === undefined) {@@ -25,6 +27,5 @@ export function createAssertedContextProvider<T>(}return ctx;};-return [Provider, useAssertedContext];}diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.tsindex d807489c5d..8faa2d6b8c 100644--- a/js/app/packages/notifications/notification-source.ts+++ b/js/app/packages/notifications/notification-source.ts@@ -86,7 +86,9 @@ export function createNotificationSource(const markNotificationsAsSeenMutation = useMarkNotificationsAsSeenMutation();const markNotificationsAsDoneMutation = useMarkNotificationsAsDoneMutation();- const notifications = createMemo(() => notificationsQuery.data ?? []);+ const notifications = createMemo(() =>+ notificationsQuery.isSuccess ? notificationsQuery.data : []+ );const notificationsByEntity = createMemo(() => {const data = notifications();diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.tsindex 5405232549..d1dfd0324f 100644--- a/js/app/packages/queries/channel/channel.ts+++ b/js/app/packages/queries/channel/channel.ts@@ -26,9 +26,8 @@ type ChannelQueryOptions = UseBaseQueryOptions<getChannelResponseError>;-function channelQueryOptions(channelId: string): ChannelQueryOptions {+export function channelQueryOptions(channelId: string): ChannelQueryOptions {return {- gcTime: 0,queryKey: channelKeys.withID(channelId).queryKey,queryFn: async () => {const result = await throwOnErr(diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.tsindex 5ca75fb21d..dee6d8b768 100644--- a/js/app/packages/queries/channel/keys.ts+++ b/js/app/packages/queries/channel/keys.ts@@ -4,6 +4,9 @@ export const channelKeys = createQueryKeys('channel', {withID: (channelID: string) => ({queryKey: [channelID],}),+ mentions: (channelID: string) => ({+ queryKey: [channelID],+ }),activity: null,listChannels: null,});diff --git a/js/app/packages/queries/channel/mentions.ts b/js/app/packages/queries/channel/mentions.tsnew file mode 100644index 0000000000..30a90e0fc3--- /dev/null+++ b/js/app/packages/queries/channel/mentions.ts@@ -0,0 +1,19 @@+import { throwOnErr } from '@core/util/maybeResult';+import { commsServiceClient } from '@service-comms/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { channelKeys } from './keys';++export function useMentionsQuery(channelId: Accessor<string>) {+ return useQuery(() => {+ return {+ queryKey: channelKeys.mentions(channelId()).queryKey,+ queryFn: () =>+ throwOnErr(() =>+ commsServiceClient.getMentions({ channel_id: channelId() })+ ),+ staleTime: Infinity,+ refetchOnMount: false,+ };+ });+}diff --git a/js/app/packages/queries/client.ts b/js/app/packages/queries/client.tsindex 0573cce11e..ee23b4f590 100644--- a/js/app/packages/queries/client.ts+++ b/js/app/packages/queries/client.ts@@ -21,6 +21,14 @@ setupQueryPersistence({queryClient,buster: import.meta.env.__APP_VERSION__ ?? 'dev',scopes: [+ {+ persister: createIDBPersister({+ key: createPersistenceKey('channels', 0),+ }),+ // 7 days in milliseconds+ maxAgeMs: 1000 * 60 * 60 * 24 * 7,+ shouldDehydrateQuery: (q) => queryKeyHasPrefix(q.queryKey, ['channel']),+ },{persister: createIDBPersister({key: createPersistenceKey('email-threads', 0),