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.

chore(old-channels): remove old channel logic (#2451)

teo6695a81152b2
diff --git a/js/app/packages/block-channel/component/AttachmentsModal.tsx b/js/app/packages/block-channel/component/AttachmentsModal.tsx
deleted file mode 100644
index 5684bc2c42..0000000000
--- a/js/app/packages/block-channel/component/AttachmentsModal.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-import { SplitDrawer } from '@app/component/split-layout/components/SplitDrawer';
-import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
-import { filterSafeAttachments } from '@block-channel/utils/attachments';
-import { type BlockAlias, type BlockName, useBlockId } from '@core/block';
-import type { DateValue } from '@core/util/date';
-import { InlineItemPreview } from '@core/component/ItemPreview';
-import { toast } from '@core/component/Toast/Toast';
-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 { tryMacroId, useDisplayName } from '@core/user';
-import BracketLeft from '@macro-icons/macro-group-bracket-left.svg';
-import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
-import type { MessageMention } from '@service-comms/generated/models';
-import type { Attachment } from '@queries/channel/types';
-import type { ItemType } from '@service-storage/client';
-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';
-
-export function useAttachments() {
- const currentBlockId = useBlockId();
- const channelContext = useChannelContext();
- const mentionsQuery = useMentionsQuery(() => currentBlockId);
-
- return createMemo(() => {
- const mentions: Attachment[] = !mentionsQuery.isSuccess
- ? []
- : (mentionsQuery.data?.mentions ?? []).map((m) =>
- makeAttachmentFromMention(m, currentBlockId)
- );
-
- const channelAttachments = channelContext.attachments() ?? [];
- const safeAttachments = filterSafeAttachments(channelAttachments);
- const all = [...safeAttachments, ...mentions];
- return all
- .filter(
- (a) => !a.entity_type.startsWith('static/') && a.entity_type !== 'user'
- )
- .sort(
- (a, b) =>
- new Date(b.created_at || 0).getTime() -
- new Date(a.created_at || 0).getTime()
- );
- });
-}
-
-export function AttachmentsButton(props: { attachments: () => Attachment[] }) {
- const drawerControl = useDrawerControl(DRAWER_ID);
-
- return (
- <Tooltip tooltip={'View all attachments'}>
- <div
- class="flex items-center gap-1 py-1 font-mono text-xs text-ink-disabled hover:bg-hover relative"
- tabIndex={0}
- role="button"
- onClick={drawerControl.toggle}
- >
- <BracketLeft class="h-4 w-2 text-edge" />
- <PaperclipIcon class="size-4 text-ink" />
- <span class="text-xs">{props.attachments().length}</span>
- <BracketLeft class="h-4 w-2 rotate-180 text-edge" />
- </div>
- </Tooltip>
- );
-}
-
-export function AttachmentsDrawer(props: { attachments: () => Attachment[] }) {
- const { openWithSplit } = useSplitLayout();
- const channelContext = useChannelContext();
-
- const onClickAttachment = (
- event: MouseEvent,
- details: { blockName: BlockName; blockId: string }
- ) => {
- openWithSplit(
- { type: details.blockName, id: details.blockId },
- { preferNewSplit: !event.shiftKey }
- );
- };
-
- return (
- <SplitDrawer
- id={DRAWER_ID}
- title="Channel Attachments"
- side="right"
- size={768}
- >
- <div class="flex justify-center items-center max-w-full h-full max-h-full">
- <div class="flex-1 size-full overflow-x-hidden overflow-y-auto">
- <Show
- when={props.attachments().length > 0}
- fallback={
- <div class="py-8 text-ink-muted text-sm text-center">
- No attachments in this channel
- </div>
- }
- >
- <div class="flex flex-col h-full">
- <VList data={props.attachments()}>
- {(attachment) => (
- <Suspense>
- <AttachmentItem
- attachment={attachment}
- onNavigate={onClickAttachment}
- senderId={channelContext
- .messageSenderMap()
- .get(attachment.message_id)}
- />
- </Suspense>
- )}
- </VList>
- </div>
- </Show>
- </div>
- </div>
- </SplitDrawer>
- );
-}
-
-function makeAttachmentFromMention(
- mention: MessageMention,
- channelId: string
-): Attachment {
- return {
- channel_id: channelId,
- created_at: mention.created_at,
- entity_id: mention.entity_id,
- entity_type: mention.entity_type,
- id: mention.message_id,
- message_id: mention.message_id,
- };
-}
-
-type AttachmentItemProps = {
- attachment: Attachment;
- onNavigate: (
- event: MouseEvent,
- details: { blockName: BlockName | BlockAlias; blockId: string }
- ) => void;
- senderId: string | undefined;
-};
-
-function AttachmentItem(props: AttachmentItemProps) {
- const senderId = () => props.senderId ?? '';
- const [userName] = useDisplayName(tryMacroId(senderId()));
-
- const [preview] = useItemPreview(() => ({
- id: props.attachment.entity_id,
- type: props.attachment.entity_type as ItemType,
- }));
-
- const handleClick = (event: MouseEvent) => {
- const item = preview();
- if (isAccessiblePreviewItem(item) && item.type === 'document') {
- props.onNavigate(event, {
- blockName: fileTypeToBlockName(item.fileType),
- blockId: item.id,
- });
- } else {
- toast.failure('Failed to open attachment');
- }
- };
-
- return (
- <button
- class="bg-menu hover:bg-hover p-2 pb-3 border-edge-muted border-b w-full text-left"
- onClick={handleClick}
- >
- <div class="flex justify-start items-center gap-2 mb-4 font-mono text-ink-muted text-xs uppercase">
- <div class="bg-ink-extra-muted size-2" />
- <div>ATTACHED ITEM</div>
- <div class="grow" />
- <div>{formatTimestamp(props.attachment.created_at)}</div>
- </div>
- <span class="inline-flex items-center gap-1 pl-4 text-sm">
- <Show when={senderId()}>
- <UserIcon id={senderId()} size="xs" isDeleted={false} />
- <span class="font-medium text-ink">{userName()}</span>
- </Show>
-
- <span class="text-ink-extra-muted">attached</span>
- <InlineItemPreview
- id={props.attachment.entity_id}
- type={props.attachment.entity_type as ItemType}
- />
- </span>
- </button>
- );
-}
-
-const formatTimestamp = (date: DateValue) => {
- const d = date instanceof Date ? date : new Date(date);
- const datePart = d
- .toLocaleDateString('en-US', {
- month: 'numeric',
- day: 'numeric',
- year: 'numeric',
- })
- .replaceAll('/', '-');
-
- const timePart = d.toLocaleTimeString('en-US', {
- hour: 'numeric',
- minute: 'numeric',
- });
-
- return `${datePart} @ ${timePart}`;
-};
diff --git a/js/app/packages/block-channel/component/Block.tsx b/js/app/packages/block-channel/component/Block.tsx
deleted file mode 100644
index adfcf595db..0000000000
--- a/js/app/packages/block-channel/component/Block.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useBlockId } from '@core/block';
-import { useChannelName } from '@core/context/channels';
-import { EntityPermissionsGate } from '@core/component/EntityPermissionsGate';
-import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
-import { useBlockEntityCommands } from '@app/component/next-soup/actions';
-import { type JSXElement, onMount, Suspense } from 'solid-js';
-import { URL_PARAMS } from '@block-channel/constants';
-import type { TargetMessageInfo } from '@block-channel/component/MessageList/MessageList';
-import { useChannelQuery } from '@queries/channel/channel';
-import { ChannelContextProvider } from '@block-channel/hooks/channel';
-import { Channel } from './Channel';
-
-export function WithTopBar(props: { children: JSXElement }) {
- return <div>{props.children}</div>;
-}
-function ChannelBlockSuspenseFallback() {
- onMount(() => {
- console.warn('[block-channel] Top-level BlockChannel suspense triggered');
- });
- return null;
-}
-
-export type JoinState = 'REQUIRED' | 'NOT_REQUIRED';
-
-type IncomingParams = Record<string, string>;
-
-export type BlockChannelProps = IncomingParams & {};
-
-export default function BlockChannel(props: BlockChannelProps) {
- useBlockEntityCommands();
- const channelId = useBlockId();
-
- const targetMessage = () => {
- const messageID = props[URL_PARAMS.message];
- if (!messageID) return;
- const threadID = props[URL_PARAMS.thread];
-
- return {
- messageId: messageID,
- threadId: threadID,
- } satisfies TargetMessageInfo;
- };
- const channelName = useChannelName(channelId);
- const channelQuery = useChannelQuery(() => channelId);
-
- return (
- <EntityPermissionsGate entityType="channel" entityId={channelId}>
- <Suspense fallback={<ChannelBlockSuspenseFallback />}>
- <DocumentBlockContainer title={channelName() ?? 'Channel'}>
- <ChannelContextProvider query={channelQuery}>
- <Channel channelId={channelId} target={targetMessage()} />
- </ChannelContextProvider>
- </DocumentBlockContainer>
- </Suspense>
- </EntityPermissionsGate>
- );
-}
diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsx
deleted file mode 100644
index 5728e4a590..0000000000
--- a/js/app/packages/block-channel/component/Channel.tsx
+++ /dev/null
@@ -1,458 +0,0 @@
-import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';
-import { URL_PARAMS } from '@block-channel/constants';
-import { handleFileUpload } from '@block-channel/utils/inputAttachments';
-import type { EntityDragEvent } from '@entity';
-import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import { useChannelActivity } from '@core/context/channels';
-import { fileFolderDrop } from '@core/directive/fileFolderDrop';
-import { TOKENS } from '@core/hotkey/tokens';
-import {
- blockElementSignal,
- blockHotkeyScopeSignal,
-} from '@core/signal/blockElement';
-import { blockHandleSignal } from '@core/signal/load';
-import { createTabFocusEffect } from '@core/signal/tabFocus';
-import type { InputAttachment } from '@core/store/cacheChannelInput';
-import { handleFileFolderDrop } from '@core/util/upload';
-import {
- ChannelDebouncedNotificationReadMarker,
- makeDebouncedChannelNotificationReadMarker,
- createEffectOnEntityTypeNotification,
- useEntityHasUnreadNotifications,
-} from '@notifications';
-import {
- invalidateChannelsActivity,
- useUpdateChannelsActivityMutation,
-} from '@queries/channel/activity';
-import type { Message } from '@queries/channel/types';
-import { connectionGatewayClient } from '@service-connection/client';
-import { useBeforeLeave, useSearchParams } from '@solidjs/router';
-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
-import { toast } from 'core/component/Toast/Toast';
-import { registerHotkey } from 'core/hotkey/hotkeys';
-import { createMethodRegistration } from 'core/orchestrator';
-import {
- createEffect,
- createRenderEffect,
- createSignal,
- on,
- onMount,
- Suspense,
-} from 'solid-js';
-import { createStore } from 'solid-js/store';
-import { type FocusableElement, tabbable } from 'tabbable';
-import { ChannelInput } from './ChannelInput';
-import {
- MessageList,
- type MessageListNavigation,
- type TargetMessageInfo,
-} from './MessageList/MessageList';
-import { Top } from './Top';
-import { ModalsProvider } from './ModalsProvider';
-import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
-import { useChannelContext } from '@block-channel/hooks/channel';
-import { FloatingInputLoader } from '@core/component/FloatingInputLoader';
-import {
- invalidateChannelWithID,
- useChannelQuery,
-} from '@queries/channel/channel';
-
-false && fileFolderDrop;
-
-/** Tracks channel entity when tab regains focus (throttled to 10s) */
-function createChannelTrackingEffect(channelId: string) {
- let lastTrackTime = Date.now();
- const TRACK_THROTTLE_MS = 10_000;
-
- createTabFocusEffect((isTabFocused) => {
- if (isTabFocused && Date.now() - lastTrackTime > TRACK_THROTTLE_MS) {
- connectionGatewayClient.trackEntity({
- entity_type: 'channel',
- entity_id: channelId,
- action: 'open',
- });
- lastTrackTime = Date.now();
- }
- });
-}
-
-export function Channel(props: {
- channelId: string;
- target?: TargetMessageInfo;
-}) {
- const channelContext = useChannelContext();
- const channelQuery = useChannelQuery(() => props.channelId);
- const latestActivity = useChannelActivity(props.channelId);
-
- const [openedChannel, setOpenedChannel] = createSignal<Date>();
-
- const updateActivityMutation = useUpdateChannelsActivityMutation({
- onSuccess: () => {
- invalidateChannelsActivity();
- },
- });
-
- const updateActivityOnOpen = () => {
- setOpenedChannel(new Date());
- updateActivityMutation.mutate({
- channelId: props.channelId,
- activityType: 'view',
- });
- };
-
- const updateActivityOnClose = () =>
- updateActivityMutation.mutate({
- channelId: props.channelId,
- activityType: 'view',
- });
-
- let containerRef!: HTMLDivElement;
- const [searchParams] = useSearchParams();
- const [channelInputAttachmentsStore, setChannelInputAttachmentsStore] =
- createStore<Record<string, InputAttachment[]>>({});
- // All messages, including threads, in order of how they should be displayed, i.e. thread children are placed after their parent message
- const [orderedMessages, setOrderedMessages] = createSignal<Message[]>([]);
- const scopeId = blockHotkeyScopeSignal.get;
- const blockRef = blockElementSignal.get;
- const [isDraggingOverChannel, setIsDraggingOverChannel] = createSignal(false);
- const notificationSource = useGlobalNotificationSource();
-
- const blockHandle = blockHandleSignal.get;
-
- // use props if available, fallback to search params
- const initialTargetMessage = (): TargetMessageInfo | undefined => {
- const target = props.target;
- if (target) return target;
-
- const messageId = searchParams[URL_PARAMS.message];
- const threadId = searchParams[URL_PARAMS.thread];
-
- if (!messageId) return;
-
- return {
- messageId: Array.isArray(messageId) ? messageId[0] : messageId,
- threadId: Array.isArray(threadId) ? threadId[0] : threadId,
- };
- };
-
- const [targetMessage, setTargetMessage] = createSignal<
- TargetMessageInfo | undefined
- >(initialTargetMessage());
-
- createMethodRegistration(blockHandle, {
- goToLocationFromParams: async (params: Record<string, unknown>) => {
- const threadId = params[URL_PARAMS.thread] as string | undefined;
- const messageId = params[URL_PARAMS.message] as string | undefined;
- if (messageId) {
- setTargetMessage({
- messageId,
- threadId,
- });
- }
- },
- });
-
- const [selectedMessageId, setSelectedMessageId] = createSignal<
- string | undefined
- >(undefined);
-
- const [messageListNav, setMessageListNav] =
- createSignal<MessageListNavigation>();
-
- onMount(() => {
- updateActivityOnOpen();
-
- const STALE_THRESHOLD_MS = 1_000;
- const age = Date.now() - channelQuery.dataUpdatedAt;
- if (age > STALE_THRESHOLD_MS) {
- invalidateChannelWithID(props.channelId);
- }
- });
-
- createChannelTrackingEffect(props.channelId);
-
- useBeforeLeave(() => {
- updateActivityOnClose();
- });
-
- const droppable = createDroppable('channel-input-' + props.channelId);
-
- false && droppable;
-
- const [, { onDragEnd }] = useDragDropContext() ?? [
- undefined,
- { onDragEnd: () => {} },
- ];
-
- function handleAttach(attachment: InputAttachment) {
- 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(props.channelId, (prev = []) => [
- ...prev,
- attachment,
- ]);
- }
-
- onDragEnd((event: EntityDragEvent) => {
- if (!event.droppable) return;
- if (event.droppable?.id !== 'channel-input-' + props.channelId) return;
- const draggableId = event.draggable?.data.id;
- const draggableName = event.draggable?.data.name;
- const blockName = fileTypeToBlockName(
- event.draggable?.data.fileType ??
- event.draggable?.data.itemType ??
- event.draggable?.data.type,
- true
- );
- if (!blockName || !draggableId || !draggableName) return;
- handleAttach({
- id: draggableId,
- name: draggableName,
- blockName,
- });
- });
-
- /**
- * Hybrid navigation: tries DOM-based tabbable navigation first,
- * falls back to message ID navigation if element was unmounted (which can happen if you're moving rapidly with virtualization)
- */
- const navigateChannel = (direction: 'previous' | 'next') => {
- const block = blockRef();
- if (!block) return false;
-
- const tabbableEls = tabbable(block);
- let activeEl = document.activeElement;
-
- const selectedMessageEl = block.querySelector(
- `[data-message-id="${selectedMessageId()}"]`
- );
-
- if (selectedMessageEl && !selectedMessageEl?.contains(activeEl)) {
- // Selected message gets set on hover without actually becoming focused. If the active element is not inside the selected message, it is probably because the user has hovered over a new message, and so we should proceed as if the selected message were the active element.
- activeEl = selectedMessageEl;
- }
-
- const activeElIndex = tabbableEls.indexOf(activeEl as FocusableElement);
-
- // DOM-based navigation: element is in tabbable list
- if (activeElIndex !== -1) {
- const targetIndex =
- direction === 'previous' ? activeElIndex - 1 : activeElIndex + 1;
-
- if (targetIndex >= 0 && targetIndex < tabbableEls.length) {
- const targetEl = tabbableEls[targetIndex];
- targetEl?.focus();
- return;
- }
- }
-
- // Fallback: element not in tabbable list (this can happen if moving too quickly thru the virtualized list)
- // Use message ID-based navigation
- const nav = messageListNav();
- if (nav) {
- return direction === 'previous'
- ? nav.navigatePrevious()
- : nav.navigateNext();
- }
- };
-
- const onChannelInputFocusLeaveStart = (e: KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
- return navigateChannel('previous');
- };
-
- registerHotkey({
- hotkey: 'enter',
- scopeId: scopeId(),
- description: 'Focus Channel Input',
- keyDownHandler: () => {
- if (channelInputRef()) {
- channelInputRef()?.focus();
- return true;
- }
- return false;
- },
- hotkeyToken: TOKENS.block.focus,
- hide: true,
- });
-
- registerHotkey({
- hotkey: ['arrowup', 'shift+tab'],
- scopeId: scopeId(),
- description: 'Focus previous',
- keyDownHandler: () => {
- navigateChannel('previous');
- return true;
- },
- hotkeyToken: TOKENS.channel.focusPreviousMessage,
- hide: true,
- });
-
- registerHotkey({
- hotkey: ['arrowdown', 'tab'],
- scopeId: scopeId(),
- description: 'Focus next',
- keyDownHandler: () => {
- navigateChannel('next');
- return true;
- },
- hotkeyToken: TOKENS.channel.focusNextMessage,
- hide: true,
- });
- const [channelInputRef, setChannelInputRef] = createSignal<
- HTMLDivElement | undefined
- >();
- const [autoFocusOnMount, setAutoFocusOnMount] = createSignal(true);
-
- const { navigatedFromJK } = useNavigatedFromJK();
-
- createRenderEffect(() => {
- if (navigatedFromJK()) {
- setAutoFocusOnMount(false);
- }
- });
-
- const debouncedMarkAsRead = makeDebouncedChannelNotificationReadMarker({
- notificationSource: notificationSource,
- channelId: props.channelId,
- debounceTime: 500,
- });
-
- // Listen for any incoming notifications and while the panel is active,
- // mark them as read
- createEffectOnEntityTypeNotification(
- notificationSource,
- 'channel',
- (notification) => {
- if (
- !splitContext.isPanelActive() ||
- notification.entity_id !== props.channelId
- ) {
- return;
- }
-
- debouncedMarkAsRead();
- }
- );
-
- const hasNotifications = useEntityHasUnreadNotifications(notificationSource, {
- type: 'channel',
- id: props.channelId,
- });
-
- const splitContext = useSplitPanelOrThrow();
-
- // Track panel active state. When the panel is focused and it was not previously
- // mark notifications as read if there are any
- createEffect(
- on(splitContext.isPanelActive, (isPanelActive, wasPanelActive) => {
- if (wasPanelActive !== false) return;
-
- if (!isPanelActive || !hasNotifications()) {
- return;
- }
-
- debouncedMarkAsRead();
- })
- );
-
- return (
- <div
- class={`relative flex flex-col w-full h-full bg-panel bracket-never`}
- tabIndex={-1}
- >
- <ChannelDebouncedNotificationReadMarker
- notificationSource={notificationSource}
- channelId={props.channelId}
- debounceTime={500}
- />
- <StaticMarkdownContext>
- <ModalsProvider>
- <Suspense>
- <Top
- channelId={props.channelId}
- channelType={channelContext.channelType()}
- participants={channelContext.channel()?.participants ?? []}
- channelName={channelContext.channelName()}
- />
- </Suspense>
- <div
- class="h-full flex flex-col min-h-0 flex-1 relative w-full"
- use:fileFolderDrop={{
- onDrop: (files, folders) => {
- handleFileFolderDrop(files, folders, (uploadEntries) =>
- handleFileUpload(uploadEntries, {
- store: channelInputAttachmentsStore,
- setStore: setChannelInputAttachmentsStore,
- key: props.channelId,
- })
- );
- },
- onDragStart: () => {
- setIsDraggingOverChannel(true);
- },
- onDragEnd: () => {
- setIsDraggingOverChannel(false);
- },
- }}
- >
- <div
- class="absolute pointer-events-none top-1/2 left-1/2 w-[60%] h-full -translate-x-1/2 -translate-y-1/2"
- use:droppable
- ref={containerRef}
- />
- <FloatingInputLoader
- minShowTime={200}
- successDuration={100}
- isLoading={() => channelQuery.isFetching}
- loadingText="Refreshing messages"
- class="top-0 bottom-auto mt-2 mb-0 z-10"
- />
- <MessageList
- 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}
- latestActivity={latestActivity()}
- openedChannel={openedChannel()}
- orderedMessages={orderedMessages}
- setOrderedMessages={setOrderedMessages}
- onNavigationReady={setMessageListNav}
- />
- <div class="shrink-0 w-full pb-2 @min-[40rem]:px-4">
- {/* seamus: note this element is below the scroll so we translate it back to account for the scroll above */}
- <div class="mx-auto w-full macro-message-width macro-message-padding">
- <Suspense>
- <ChannelInput
- channelId={props.channelId}
- channelName={channelContext.channelName()}
- participants={channelContext.channel()?.participants ?? []}
- inputAttachmentsStore={channelInputAttachmentsStore}
- setInputAttachmentsStore={setChannelInputAttachmentsStore}
- inputAttachmentsKey={props.channelId}
- onFocusLeaveStart={onChannelInputFocusLeaveStart}
- autoFocusOnMount={autoFocusOnMount()}
- domRef={setChannelInputRef}
- isDraggingOverChannel={isDraggingOverChannel}
- isValidChannelDrag={() => true}
- />
- </Suspense>
- </div>
- </div>
- </div>
- </ModalsProvider>
- </StaticMarkdownContext>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/ChannelBlockSwitch.tsx b/js/app/packages/block-channel/component/ChannelBlockSwitch.tsx
deleted file mode 100644
index 3d4b25feef..0000000000
--- a/js/app/packages/block-channel/component/ChannelBlockSwitch.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { ShowFeatureFlag } from '@app/lib/analytics/posthog';
-import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
-import type { BlockChannelProps } from './Block';
-import BlockChannel from './Block';
-import { NewChannelBlockAdapter } from './NewChannelBlockAdapter';
-
-export function ChannelBlockSwitch(props: BlockChannelProps) {
- return (
- <ShowFeatureFlag
- key="enable-new-channels"
- enabledOverride={ENABLE_NEW_CHANNELS()}
- fallback={<BlockChannel {...props} />}
- >
- <NewChannelBlockAdapter {...props} />
- </ShowFeatureFlag>
- );
-}
diff --git a/js/app/packages/block-channel/component/Compose.tsx b/js/app/packages/block-channel/component/Compose.tsx
index 1ed4dcb9cb..f26831b2fd 100644
--- a/js/app/packages/block-channel/component/Compose.tsx
+++ b/js/app/packages/block-channel/component/Compose.tsx
@@ -18,8 +18,8 @@ import { handleFileFolderDrop } from '@core/util/upload';
import InfoIcon from '@icon/regular/info.svg';
import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
-import { handleFileUpload } from '../utils/inputAttachments';
-import { DraftChannelInput } from './ChannelInput';
+import { handleFileUpload } from './DeprecatedChannelInput/inputAttachments';
+import { DraftChannelInput } from './DeprecatedChannelInput/ChannelInput';
false && fileFolderDrop;
diff --git a/js/app/packages/block-channel/component/ActionButton.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/ActionButton.tsx
similarity index 100%
rename from js/app/packages/block-channel/component/ActionButton.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/ActionButton.tsx
diff --git a/js/app/packages/block-channel/component/AttachMenu.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx
similarity index 98%
rename from js/app/packages/block-channel/component/AttachMenu.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx
index 1d45b10003..330eed74a1 100644
--- a/js/app/packages/block-channel/component/AttachMenu.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx
@@ -1,4 +1,4 @@
-import { handleFileUpload } from '@block-channel/utils/inputAttachments';
+import { handleFileUpload } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
import { EntityIcon } from '@core/component/EntityIcon';
import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
import { blockAcceptedFileExtensions } from '@core/constant/allBlocks';
diff --git a/js/app/packages/block-channel/component/Attachment.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/Attachment.tsx
similarity index 100%
rename from js/app/packages/block-channel/component/Attachment.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/Attachment.tsx
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx
similarity index 97%
rename from js/app/packages/block-channel/component/BaseInput.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx
index 26139a55bc..1a8f4572e9 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx
@@ -1,14 +1,14 @@
-import { handleFileUpload } from '@block-channel/utils/inputAttachments';
+import { handleFileUpload } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
import {
$convertSingleMentionToCard,
expandGroupParticipants,
toSimpleMention,
-} from '@block-channel/utils/mentionExpansion';
+} from '@block-channel/component/DeprecatedChannelInput/mentionExpansion';
import {
createTasksFromPotential,
replaceCheckboxesWithMentions,
-} from '@block-channel/utils/taskModeConversion';
-import { useTaskMode } from '@block-channel/hooks/taskmode';
+} from '@block-channel/component/DeprecatedChannelInput/taskModeConversion';
+import { useTaskMode } from '@block-channel/component/DeprecatedChannelInput/taskmode';
import { LabelAndHotKey } from '@core/component/Tooltip';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import {
@@ -65,7 +65,7 @@ import { TaskPreviewPanel } from './TaskPreviewPanel';
import { useUserId } from '@core/context/user';
import { isMobile } from '@core/mobile/isMobile';
import { ENABLE_STATIC_DOCUMENT_CARDS } from '@core/constant/featureFlags';
-import type { SendMessageArgs } from '@block-channel/hooks/message';
+import type { SendMessageArgs } from '@block-channel/component/DeprecatedChannelInput/message';
false && fileFolderDrop;
diff --git a/js/app/packages/block-channel/component/ChannelInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx
similarity index 94%
rename from js/app/packages/block-channel/component/ChannelInput.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx
index 5d05bb48ed..dc65fd1acf 100644
--- a/js/app/packages/block-channel/component/ChannelInput.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx
@@ -2,7 +2,7 @@ import {
clearDraftMessage,
loadDraftMessage,
saveDraftMessage,
-} from '@block-channel/utils/draftMessages';
+} from '@block-channel/component/DeprecatedChannelInput/draftMessages';
import type {
DraftMessage,
InputAttachment,
@@ -14,7 +14,7 @@ import type { ChannelParticipant } from '@queries/channel/types';
import { type Accessor, createMemo, createSignal, onMount } from 'solid-js';
import type { SetStoreFunction } from 'solid-js/store';
import { BaseInput } from './BaseInput';
-import { useSendChannelMessage } from '@block-channel/hooks/message';
+import { useSendChannelMessage } from '@block-channel/component/DeprecatedChannelInput/message';
export type ChannelInputProps = {
channelId: string;
diff --git a/js/app/packages/block-channel/component/DraftChannelInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx
similarity index 97%
rename from js/app/packages/block-channel/component/DraftChannelInput.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx
index 5f430d8b82..7c438886bf 100644
--- a/js/app/packages/block-channel/component/DraftChannelInput.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx
@@ -1,4 +1,4 @@
-import { mapAttachmentsForSend } from '@block-channel/utils/inputAttachments';
+import { mapAttachmentsForSend } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
import { getDestinationFromOptions } from '@core/component/NewMessage';
import type { InputAttachment } from '@core/store/cacheChannelInput';
import type { WithCustomUserInput } from '@core/user';
diff --git a/js/app/packages/block-channel/component/FormatRibbon.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/FormatRibbon.tsx
similarity index 100%
rename from js/app/packages/block-channel/component/FormatRibbon.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/FormatRibbon.tsx
diff --git a/js/app/packages/block-channel/component/MarkdownArea.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/MarkdownArea.tsx
similarity index 100%
rename from js/app/packages/block-channel/component/MarkdownArea.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/MarkdownArea.tsx
diff --git a/js/app/packages/block-channel/component/TaskPreviewPanel.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx
similarity index 93%
rename from js/app/packages/block-channel/component/TaskPreviewPanel.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx
index 8b8f159a49..8dcc0821b3 100644
--- a/js/app/packages/block-channel/component/TaskPreviewPanel.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx
@@ -1,5 +1,5 @@
import type { PropertyApiValues } from '@core/component/Properties/types';
-import type { TaskWithProperties } from '@block-channel/hooks/taskmode';
+import type { TaskWithProperties } from '@block-channel/component/DeprecatedChannelInput/taskmode';
import { For } from 'solid-js';
import { TaskPreviewRow } from './TaskPreviewRow';
diff --git a/js/app/packages/block-channel/component/TaskPreviewRow.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx
similarity index 98%
rename from js/app/packages/block-channel/component/TaskPreviewRow.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx
index 68ca3dbd6e..f7dc637593 100644
--- a/js/app/packages/block-channel/component/TaskPreviewRow.tsx
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx
@@ -1,4 +1,4 @@
-import type { TaskWithProperties } from '@block-channel/hooks/taskmode';
+import type { TaskWithProperties } from '@block-channel/component/DeprecatedChannelInput/taskmode';
import { EntityIcon } from '@core/component/EntityIcon';
import { propertyApiValuesToNormalized } from '@core/component/Properties/api/converters';
import { Modals } from '@core/component/Properties/component/modal';
diff --git a/js/app/packages/block-channel/utils/draftMessages.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/draftMessages.ts
similarity index 100%
rename from js/app/packages/block-channel/utils/draftMessages.ts
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/draftMessages.ts
diff --git a/js/app/packages/block-channel/utils/inputAttachments.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/inputAttachments.ts
similarity index 100%
rename from js/app/packages/block-channel/utils/inputAttachments.ts
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/inputAttachments.ts
diff --git a/js/app/packages/block-channel/utils/mentionExpansion.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/mentionExpansion.ts
similarity index 100%
rename from js/app/packages/block-channel/utils/mentionExpansion.ts
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/mentionExpansion.ts
diff --git a/js/app/packages/block-channel/hooks/message.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/message.tsx
similarity index 100%
rename from js/app/packages/block-channel/hooks/message.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/message.tsx
diff --git a/js/app/packages/block-channel/utils/taskModeConversion.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts
similarity index 98%
rename from js/app/packages/block-channel/utils/taskModeConversion.ts
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts
index f3891fed48..8399e83f5c 100644
--- a/js/app/packages/block-channel/utils/taskModeConversion.ts
+++ b/js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts
@@ -1,4 +1,4 @@
-import type { TaskWithProperties } from '../hooks/taskmode';
+import type { TaskWithProperties } from './taskmode';
import { propertyValueToApi } from '@core/component/Properties/api/converters';
import {
PROPERTY_OPTION_IDS,
diff --git a/js/app/packages/block-channel/hooks/taskmode.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/taskmode.tsx
similarity index 100%
rename from js/app/packages/block-channel/hooks/taskmode.tsx
rename to js/app/packages/block-channel/component/DeprecatedChannelInput/taskmode.tsx
diff --git a/js/app/packages/block-channel/component/Message/ActionMenu.tsx b/js/app/packages/block-channel/component/Message/ActionMenu.tsx
deleted file mode 100644
index 34670a3d2c..0000000000
--- a/js/app/packages/block-channel/component/Message/ActionMenu.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { useReactToMessage } from '@block-channel/hooks/reactions';
-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
-import clickOutside from '@core/directive/clickOutside';
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-import { Popover } from '@kobalte/core/popover';
-import SmileIcon from '@phosphor-icons/core/regular/smiley.svg?component-solid';
-import {
- type Accessor,
- type Component,
- createSignal,
- For,
- type Setter,
-} from 'solid-js';
-import { EmojiSearchSelector } from '../ReactionSelector';
-import type { MessageAction } from './actions';
-
-false && clickOutside;
-
-export type Action = {
- text: string;
- icon: Component;
- onClick: () => void;
- enabled: boolean;
-};
-
-export function ActionMenu(props: {
- messageId: string;
- channelId: Accessor<string>;
- reactions: Accessor<GetChannelResponseReactions>;
- actions: MessageAction[];
- setReactionMenuActivated?: Setter<boolean>;
-}) {
- // default emojis
- const defaultEmojis = ['❤️', '👍', '😂'];
-
- const [openEmojiPopover, setOpenEmojiPopover] = createSignal(false);
-
- const reactToMessage = useReactToMessage(props.channelId, props.reactions);
- const react = (emoji: string) => reactToMessage(emoji, props.messageId);
-
- const handleOpenChange = (isOpen: boolean) => {
- setOpenEmojiPopover(isOpen);
- props.setReactionMenuActivated?.(isOpen);
- };
-
- const handleClose = () => {
- setOpenEmojiPopover(false);
- props.setReactionMenuActivated?.(false);
- };
-
- return (
- <div class="flex flex-row bg-menu items-center allow-css-brackets">
- <For each={defaultEmojis}>
- {(emoji) => (
- <DeprecatedIconButton
- onMouseDown={() => react(emoji)}
- icon={() => <span>{emoji}</span>}
- tabIndex={-1}
- />
- )}
- </For>
-
- <Popover
- placement="left"
- onOpenChange={handleOpenChange}
- open={openEmojiPopover()}
- overflowPadding={8}
- slide={true}
- >
- <Popover.Trigger tabIndex={-1}>
- <DeprecatedIconButton icon={SmileIcon} tabIndex={-1} />
- </Popover.Trigger>
- <Popover.Portal>
- <Popover.Content class="z-modal">
- <Popover.Arrow class="fill-menu" />
- <EmojiSearchSelector
- onEmojiClick={(emoji) => {
- react(emoji.emoji);
- handleClose();
- }}
- handleClose={handleClose}
- />
- </Popover.Content>
- </Popover.Portal>
- </Popover>
-
- <For each={props.actions.filter((a) => a.enabled)}>
- {(a) => (
- <DeprecatedIconButton
- onMouseDown={a.onClick}
- icon={a.icon}
- tooltip={{ label: a.text, delayOverride: 0 }}
- tabIndex={-1}
- />
- )}
- </For>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/DynamicImageList.tsx b/js/app/packages/block-channel/component/Message/DynamicImageList.tsx
deleted file mode 100644
index 87636edcea..0000000000
--- a/js/app/packages/block-channel/component/Message/DynamicImageList.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { ImageGalleryPreview } from '@core/component/ImageGalleryPreview';
-import { ImagePreview } from '@core/component/ImagePreview';
-import { commsServiceClient } from '@service-comms/client';
-import { Match, Switch } from 'solid-js';
-
-type ImageData = {
- id: string;
- width?: string | number | undefined;
- height?: string | number | undefined;
-};
-
-type DynamicImageListProps = {
- images: ImageData[];
- attachmentIds: string[];
- isCurrentUser: boolean;
- channelId?: string;
- messageId?: string;
- content?: string;
- isContext?: boolean;
-};
-
-// TODO: wip
-export function DynamicImageList(props: DynamicImageListProps) {
- const handleDelete = async (attachmentId: string) => {
- if (!props.isCurrentUser || !props.channelId || !props.messageId) return;
- await commsServiceClient.patchMessage({
- channel_id: props.channelId,
- message_id: props.messageId,
- content: props.content,
- attachment_ids_to_delete: [attachmentId],
- });
- };
-
- return (
- <Switch>
- <Match when={props.images.length === 1}>
- <div class="max-w-[400px] w-fit mt-0.5">
- <ImagePreview
- image={props.images[0]}
- variant="dynamic"
- onDelete={
- props.isCurrentUser
- ? () => handleDelete(props.attachmentIds[0])
- : undefined
- }
- isContext={props.isContext}
- />
- </div>
- </Match>
-
- <Match when={props.images.length > 1}>
- <div class={`flex flex-wrap gap-2 mt-0.5`}>
- <ImageGalleryPreview
- images={props.images}
- variant="dynamic"
- attachmentIds={props.attachmentIds}
- onDelete={props.isCurrentUser ? handleDelete : undefined}
- isContext={props.isContext}
- />
- </div>
- </Match>
- </Switch>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/EditMessageInput.tsx b/js/app/packages/block-channel/component/Message/EditMessageInput.tsx
deleted file mode 100644
index bb2ca37675..0000000000
--- a/js/app/packages/block-channel/component/Message/EditMessageInput.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import FormatIcon from '@icon/regular/text-aa.svg';
-import Check from '@phosphor-icons/core/regular/check.svg?component-solid';
-import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
-import { createSignal, onCleanup, onMount, type Setter, Show } from 'solid-js';
-import { ActionButton } from '../ActionButton';
-import { FormatRibbon } from '../FormatRibbon';
-import { useChannelMarkdownArea } from '../MarkdownArea';
-import { isMobile } from '@core/mobile/isMobile';
-
-export function EditMessageInput(props: {
- setEditing: Setter<boolean>;
- save: (input: string) => void;
- content: string;
-}) {
- const originalContent = props.content;
- const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);
-
- const {
- focus: focusMarkdownArea,
- state: markdownState,
- formatState: markdownFormatState,
- setInlineFormat,
- setNodeFormat,
- MarkdownArea,
- } = useChannelMarkdownArea();
-
- onMount(() => {
- setTimeout(() => {
- focusMarkdownArea();
- }, 200);
-
- const handleEscape = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- props.setEditing(false);
- }
- };
-
- document.addEventListener('keydown', handleEscape);
-
- onCleanup(() => {
- document.removeEventListener('keydown', handleEscape);
- });
- });
-
- return (
- <div class="relative -left-3 text-sm w-full bg-input overflow-hidden border border-edge-muted focus-within:border-accent flex flex-col gap-1 items-center mt-4 ">
- <Show when={showFormatRibbon()}>
- <FormatRibbon
- state={markdownFormatState}
- inlineFormat={setInlineFormat}
- nodeFormat={setNodeFormat}
- />
- </Show>
- <div class="w-full px-3">
- <MarkdownArea
- initialValue={originalContent}
- onEnter={(e: KeyboardEvent) => {
- if (isMobile()) return false;
- e.preventDefault();
- const currentContent = markdownState();
- if (
- currentContent !== originalContent &&
- currentContent.length > 0
- ) {
- props.save(currentContent);
- }
- props.setEditing(false);
- return true;
- }}
- />
- </div>
- <div class="w-full flex flex-row gap-1 items-center justify-between p-2">
- <ActionButton
- tooltip="Format"
- onClick={(e) => {
- e.preventDefault();
- setShowFormatRibbon((prev) => !prev);
- }}
- clicked={showFormatRibbon()}
- >
- <FormatIcon width={20} height={20} />
- </ActionButton>
- <div class="flex flex-row gap-1 items-center">
- <DeprecatedTextButton
- icon={XIcon}
- text="Cancel"
- theme="clear"
- onClick={() => props.setEditing(false)}
- />
- <DeprecatedTextButton
- icon={Check}
- text="Save"
- theme="accent"
- onClick={() => {
- const currentContent = markdownState();
- if (
- currentContent !== originalContent &&
- currentContent.length > 0
- ) {
- props.save(currentContent);
- }
- props.setEditing(false);
- }}
- />
- </div>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx b/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
deleted file mode 100644
index 1fdeaa6512..0000000000
--- a/js/app/packages/block-channel/component/Message/MessageAttachments.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { ItemPreview } from '@core/component/ItemPreview';
-import { VideoPreview } from '@core/component/VideoPreview';
-import type { Attachment } from '@queries/channel/types';
-import { stringToItemType } from '@service-storage/client';
-import { type Accessor, For, Show } from 'solid-js';
-import { DynamicImageList } from './DynamicImageList';
-import { cn } from '@ui/utils/classname';
-
-type MessageAttachmentsProps = {
- videoAttachments: Accessor<Attachment[]>;
- imageAttachments: Accessor<Attachment[]>;
- documentAttachments: Accessor<Attachment[]>;
- isDeleted: Accessor<boolean>;
- isCurrentUser: Accessor<boolean>;
- channelId: string;
- messageId: string;
- content: string;
-};
-
-export function MessageAttachments(props: MessageAttachmentsProps) {
- return (
- <div
- class={cn(
- 'ph-no-capture allow-css-brackets mb-2',
- (!(
- props.documentAttachments()?.length > 0 ||
- props.imageAttachments()?.length > 0 ||
- props.videoAttachments()?.length > 0
- ) ||
- props.isDeleted()) &&
- 'hidden'
- )}
- >
- {/* Video attachments */}
- <Show when={props.videoAttachments()?.length > 0}>
- <For each={props.videoAttachments()}>
- {(item) => (
- <VideoPreview
- id={item.entity_id}
- variant="dynamic"
- width={item.width}
- height={item.height}
- />
- )}
- </For>
- </Show>
- {/* Image attachments */}
- <Show when={props.imageAttachments()?.length > 0}>
- <div class="flex not-first:mt-2">
- <DynamicImageList
- images={props.imageAttachments()?.map((a) => ({
- id: a.entity_id,
- width: a.width ?? undefined,
- height: a.height ?? undefined,
- }))}
- attachmentIds={props.imageAttachments()?.map((a) => a.id)}
- isCurrentUser={props.isCurrentUser()}
- channelId={props.channelId}
- messageId={props.messageId}
- content={props.content}
- />
- </div>
- </Show>
- {/* Document attachments */}
- <Show when={props.documentAttachments()?.length > 0}>
- <div class={`flex flex-row mt-2 gap-2 flex-wrap max-w-full`}>
- <For each={props.documentAttachments()}>
- {(attachment) => (
- <ItemPreview
- type={stringToItemType(attachment.entity_type)}
- id={attachment.entity_id}
- />
- )}
- </For>
- </div>
- </Show>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/MessageContainer.tsx b/js/app/packages/block-channel/component/Message/MessageContainer.tsx
deleted file mode 100644
index 70f771d465..0000000000
--- a/js/app/packages/block-channel/component/Message/MessageContainer.tsx
+++ /dev/null
@@ -1,775 +0,0 @@
-import { useMessageListContext } from '@block-channel/component/MessageList/MessageList';
-import { COLLAPSED_THREAD_INDEX_CUTOFF } from '@block-channel/constants';
-import { useReactToMessage } from '@block-channel/hooks/reactions';
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-import type { Attachment } from '@queries/channel/types';
-import type { MessageListContext } from '@block-channel/utils/listContext';
-import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { channelTheme } from '@core/component/LexicalMarkdown/theme';
-import {
- ContextMenuContent,
- MENU_CONTENT_CLASS,
- MenuItem,
- MenuSeparator,
-} from '@core/component/Menu';
-import { Message as MessageComponent } from '@core/component/Message';
-import { TOKENS } from '@core/hotkey/tokens';
-import { isMobile } from '@core/mobile/isMobile';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import {
- isStaticAttachmentType,
- STATIC_IMAGE,
- STATIC_VIDEO,
-} from '@core/store/cacheChannelInput';
-import { tryMacroId, useDisplayName } from '@core/user';
-import type { DateValue } from '@core/util/date';
-import { isEmojiOnly } from '@core/util/string';
-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 '@queries/channel/types';
-import { useUserId } from '@core/context/user';
-import { activeElement } from 'app/signal/focus';
-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- For,
- Match,
- onMount,
- type Setter,
- Show,
- Switch,
-} from 'solid-js';
-import type { VirtualizerHandle } from 'virtua/solid';
-import { TypingIndicator } from '../MessageList/TypingIndicator';
-import {
- EmojiSearchSelector,
- ReactionQuickSelector,
-} from '../ReactionSelector';
-import { ActionMenu } from './ActionMenu';
-import { createMessageActions } from './actions';
-import { EditMessageInput } from './EditMessageInput';
-import { MessageAttachments } from './MessageAttachments';
-import { MessageReactions } from './MessageReactions';
-import { ThreadReplyIndicator } from './ThreadReplyIndicator';
-import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
-import { cn } from '@ui/utils/classname';
-
-type MessageFlagProps = {
- text: string;
- highlightAbove?: boolean;
- highlightBelow?: boolean;
-};
-
-export function MessageFlag(props: MessageFlagProps) {
- return (
- <div class="flex flex-row items-stretch justify-start ml-[var(--left-of-connector)]">
- <div class="flex flex-col items-center justify-center">
- <div
- class={cn(
- 'border-l border-edge-muted min-h-1/2',
- props.highlightAbove && 'border-accent'
- )}
- />
- <div
- class={cn(
- 'border-l border-edge-muted min-h-1/2',
- props.highlightBelow && 'border-accent'
- )}
- />
- </div>
- <div class="flex flex-col items-center justify-center">
- <div
- class={cn(
- 'w-7 border-b border-edge-muted',
- props.highlightBelow && 'border-accent'
- )}
- />
- </div>
- <div
- class={cn(
- 'text-xs text-panel uppercase font-mono p-1 my-6 mt bg-edge',
- props.highlightBelow && 'bg-accent'
- )}
- >
- {props.text}
- </div>
- </div>
- );
-}
-
-function NewMessageIndicator(props: { onClick?: () => void }) {
- return (
- <button type="button" class="w-full text-left" onClick={props.onClick}>
- <MessageFlag text="New" highlightBelow />
- </button>
- );
-}
-
-type MessageProps = {
- message: MessageType;
- lastViewed: Accessor<DateValue | null | undefined>;
- isFocused: boolean;
- index: Accessor<number>;
- orderedMessages: Accessor<MessageType[]>;
- threadChildren?: MessageType[];
- threadSiblings?: MessageType[];
- virtualHandle: VirtualizerHandle;
- container?: HTMLDivElement;
- listContext: MessageListContext;
- setMessageContainerRef?: Setter<HTMLDivElement | undefined>;
- isTarget: boolean;
- channelId: Accessor<string>;
- attachments: Attachment[];
- reactions: GetChannelResponseReactions;
- onDismissNewMessages?: () => void;
-};
-
-export function MessageContainer(props: MessageProps) {
- const { message } = props;
-
- const listContext = useMessageListContext();
-
- const [editing, setEditing] = createSignal(false);
- const [contextMenuOpen, setContextMenuOpen] = createSignal(false);
- const [reactionSearchOpen, setReactionSearchOpen] = createSignal(false);
- const [topBarEmojiMenuOpen, setTopBarEmojiMenuOpen] = createSignal(false);
- const [messageBodyRef, setMessageBodyRef] = createSignal<HTMLDivElement>();
-
- 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(tryMacroId(userId() ?? ''));
-
- const [displayName] = useDisplayName(tryMacroId(message.sender_id));
-
- let messageContainerRef!: HTMLDivElement;
-
- // Scroll message to have editing input visible
- createEffect(() => {
- const handle = props.virtualHandle;
- if (editing() && handle) {
- requestAnimationFrame(() => {
- const messageBounds = messageContainerRef.getBoundingClientRect();
- const containerBounds = props.container?.getBoundingClientRect();
- if (!containerBounds) return;
-
- const messageTop =
- messageBounds.top - containerBounds.top + handle.scrollOffset;
- const messageBottom = messageTop + messageBounds.height;
-
- const visibleTop = handle.scrollOffset;
- const visibleBottom = handle.scrollOffset + handle.viewportSize;
-
- if (messageBottom > visibleBottom) {
- handle.scrollTo(messageBottom - handle.viewportSize + 20);
- } else if (messageTop < visibleTop) {
- handle.scrollTo(messageTop - 20);
- }
- });
- }
- });
-
- // We're only checking new messages that are not part of a thread
- 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;
-
- const previousMessage = () => {
- return props.index() > 0
- ? props.orderedMessages()[props.index() - 1]
- : undefined;
- };
-
- const newDayPreviousNonThreadMessage = () => {
- const prev = props.listContext.previousNonThreadedMessage;
- if (!prev) return false;
- return !isSameDay(new Date(message.created_at), new Date(prev.created_at));
- };
-
- // We consider a message consecutive if it's from the same user, within 10 minutes, and has the same thread id.
- const isConsecutive = () => {
- const prevMessage_ = previousMessage();
- if (!prevMessage_) return false;
- const prevSenderId = prevMessage_?.sender_id;
- const withinTimeWindow =
- Math.abs(
- new Date(message.created_at).getTime() -
- new Date(prevMessage_.created_at).getTime()
- ) <
- 10 * 60 * 1000;
- return (
- (prevMessage_.thread_id ?? '') === (message.thread_id ?? '') &&
- prevSenderId === message.sender_id &&
- withinTimeWindow
- );
- };
-
- const threadState = createMemo(() => {
- const threadID = message.thread_id;
- if (!threadID) return;
-
- return listContext.getThreadState(threadID);
- });
-
- const messageState = createMemo(() => {
- return listContext.getThreadState(message.id);
- });
-
- const isFirstMessage = createMemo(() => {
- return props.index() === 0;
- });
-
- // A message can be the last message if it's 1. the last message or 2. in the last thread at the collapsed thread index cutoff and the thread is not expanded
- const isLastMessage = createMemo(() => {
- return (
- props.index() === props.orderedMessages().length - 1 ||
- (props.listContext.isInLastThread &&
- !threadState()?.threadExpanded &&
- props.listContext.threadIndex === COLLAPSED_THREAD_INDEX_CUTOFF)
- );
- });
-
- // currently arbitrarily limiting thread depth to 1, in the future we may want to support deeper threads
- const threadDepth = createMemo(() => {
- return message.thread_id ? 1 : 0;
- });
-
- const hasThreadChildren = createMemo(() => {
- return props.threadChildren && props.threadChildren.length > 0;
- });
-
- const isFirstInThread = createMemo(() => {
- return (
- !!message.thread_id && previousMessage()?.thread_id !== message.thread_id
- );
- });
-
- const isLastInThread = createMemo(() => {
- return (
- !!message.thread_id && props.threadSiblings?.at(-1)?.id === message.id
- );
- });
-
- const isLastInCollapsedThread = createMemo(() => {
- return (
- !threadState()?.threadExpanded &&
- props.threadSiblings &&
- props.threadSiblings.length > COLLAPSED_THREAD_INDEX_CUTOFF + 1 &&
- props.listContext.threadIndex === COLLAPSED_THREAD_INDEX_CUTOFF
- );
- });
-
- const shouldShowThreadAppendInput = createMemo(() => {
- return threadState()?.hasActiveReply === true;
- });
-
- const shouldShowFirstReply = createMemo(() => {
- return !props.threadChildren?.length && messageState()?.hasActiveReply;
- });
-
- const collapsedThreadMessages = createMemo(() => {
- if (isLastInCollapsedThread()) {
- return props.threadSiblings?.slice(COLLAPSED_THREAD_INDEX_CUTOFF + 1);
- }
- return [];
- });
- const lastReplyTimestamp = createMemo(() => {
- if (collapsedThreadMessages()) {
- return collapsedThreadMessages()?.at(-1)?.created_at;
- }
- return;
- });
- const threadReplyUsers = createMemo(() => {
- if (collapsedThreadMessages()) {
- const messages = collapsedThreadMessages() ?? [];
- const seenUserIds = new Set<string>();
- const uniqueUserIds: string[] = [];
- for (const message of messages) {
- const userId = message.sender_id;
- if (userId && !seenUserIds.has(userId)) {
- seenUserIds.add(userId);
- uniqueUserIds.push(userId);
- }
- }
- return uniqueUserIds;
- }
- return [];
- });
-
- const attachments = createMemo(() =>
- props.attachments.filter((a) => a.message_id === message.id)
- );
- const imageAttachments = createMemo(() =>
- attachments().filter((a: Attachment) => a.entity_type === STATIC_IMAGE)
- );
- const videoAttachments = createMemo(() =>
- attachments().filter((a: Attachment) => a.entity_type === STATIC_VIDEO)
- );
- const documentAttachments = createMemo(() =>
- attachments().filter(
- (a: Attachment) => !isStaticAttachmentType(a.entity_type)
- )
- );
-
- const reactToMessage = useReactToMessage(
- props.channelId,
- () => props.reactions
- );
-
- const react = (emoji: string) => reactToMessage(emoji, message.id);
-
- const onThreadAppend = () => {
- const threadId = message.thread_id;
- if (!threadId) return;
- listContext.createReply(threadId, true);
- listContext.scrollToIndex(props.index(), {
- align: 'nearest',
- });
- };
-
- const onCreateReply = () => {
- listContext.createReply(message.id, true);
- listContext.scrollToIndex(props.index(), {
- align: 'nearest',
- });
- };
-
- const actions = createMessageActions({
- channelId: message.channel_id,
- messageId: message.id,
- messageContent: message.content ?? '',
- threadId: message.thread_id ?? undefined,
- senderId: message.sender_id,
- onEdit: () => setEditing(true),
- onReply: onCreateReply,
- });
-
- const [attachFn, scopeId] = useHotkeyDOMScope('channel.messageContainer');
-
- onMount(() => {
- attachFn(messageContainerRef);
- });
-
- registerHotkey({
- hotkey: 'e',
- scopeId: scopeId,
- description: 'Edit message',
- condition: () => {
- return (
- props.isFocused &&
- userId() === message.sender_id &&
- !editing() &&
- (messageBodyRef()?.contains(activeElement()) ?? false)
- );
- },
- keyDownHandler: () => {
- setEditing(true);
- return true;
- },
- hotkeyToken: TOKENS.channel.editMessage,
- displayPriority: 10,
- });
-
- registerHotkey({
- hotkey: ['enter'],
- scopeId: scopeId,
- description: 'Reply to message',
- condition: () => {
- return props.isFocused && !message.thread_id;
- },
- keyDownHandler: () => {
- const focusedIndex = props
- .orderedMessages()
- .findIndex((m) => m.id === message.id);
- if (focusedIndex === -1) return false;
- listContext.createReply(message.id);
- listContext.scrollToIndex(focusedIndex);
- return true;
- },
- hotkeyToken: TOKENS.channel.replyToMessage,
- displayPriority: 10,
- });
-
- const expandThreadCondition = createMemo(() => {
- const hasThreadParent = !!message.thread_id;
- if (!hasThreadParent && !hasThreadChildren()) return false;
-
- if (hasThreadParent) {
- // Don't allow expansion toggle if thread has less than COLLAPSED_THREAD_INDEX_CUTOFF + 1 messages
- if (
- props.threadSiblings &&
- props.threadSiblings.length < COLLAPSED_THREAD_INDEX_CUTOFF + 1
- )
- return false;
- } else if (hasThreadChildren()) {
- const childCount = props.threadChildren?.length || 0;
- if (childCount < COLLAPSED_THREAD_INDEX_CUTOFF + 1) return false;
- }
-
- return hasThreadChildren()
- ? !messageState()?.threadExpanded
- : !threadState()?.threadExpanded;
- });
-
- const setThreadExpansion = (shouldExpand: boolean) => {
- const threadId = hasThreadChildren() ? message.id : message.thread_id;
- if (!threadId) return;
-
- listContext.toggleThread(threadId, shouldExpand);
- };
-
- registerHotkey({
- hotkey: 'arrowright',
- scopeId: scopeId,
- description: 'Expand thread',
- condition: () => expandThreadCondition(),
- hotkeyToken: TOKENS.channel.expandThread,
- keyDownHandler: () => {
- setThreadExpansion(true);
- listContext.scrollToMessage(message.id, props.index());
- return true;
- },
- displayPriority: 10,
- });
-
- registerHotkey({
- hotkey: 'arrowleft',
- scopeId: scopeId,
- description: 'Go to thread parent',
- condition: () => !!message.thread_id,
- keyDownHandler: () => {
- setThreadExpansion(false);
- const parentId = message.thread_id;
- if (!parentId) return true;
-
- // Ensure the parent message is in view before focusing
- const parentIndex = props
- .orderedMessages()
- .findIndex((m) => m.id === parentId);
- if (parentIndex >= 0) {
- listContext.scrollToMessage(parentId, parentIndex);
- }
- return true;
- },
- hotkeyToken: TOKENS.channel.collapseThread,
- displayPriority: 10,
- });
-
- const isEmptyMessage = createMemo(() => {
- return message.content.trim() === '';
- });
-
- const isEmojiOnlyMessage = createMemo(() => {
- return isEmojiOnly(message.content ?? '');
- });
-
- const handleThreadToggle = () => {
- if (!message.thread_id) return;
- const threadState_ = threadState();
-
- if (!threadState_) {
- listContext.toggleThread(message.thread_id, true);
- return;
- }
-
- listContext.toggleThread(message.thread_id);
- };
-
- const { isKeypressActive } = useIsKeyPressActive();
-
- const setSelectedMessage = () => {
- listContext.setFocusedMessageId(message.id);
- };
-
- const setSelectedMessageFromMouse = () => {
- if (isKeypressActive()) return;
- listContext.setFocusedMessageId(message.id);
- };
-
- return (
- <div
- class={`macro-message-width macro-message-padding mx-auto ${isTouchDevice() ? 'no-select-children' : ''}`}
- ref={(el) => {
- props.setMessageContainerRef?.(el);
- messageContainerRef = el;
- }}
- onFocusIn={() => {
- setSelectedMessage();
- }}
- onMouseMove={() => {
- if (isTouchDevice()) return;
- setSelectedMessageFromMouse();
- }}
- data-message-id={message.id}
- >
- {/* New message indicator */}
- <Show when={props.listContext.isFirstNewMessage}>
- <NewMessageIndicator onClick={props.onDismissNewMessages} />
- </Show>
-
- {/* Date separator */}
- <Show
- when={
- !message.thread_id &&
- (props.index() === 0 ||
- (props.index() > 0 &&
- !message.thread_id &&
- newDayPreviousNonThreadMessage()))
- }
- >
- <MessageFlag
- text={formatRelativeDate(message.created_at)}
- highlightAbove={isNewMessage()}
- highlightBelow={isNewMessage()}
- />
- </Show>
-
- {/* Message item */}
- <ContextMenu
- onOpenChange={(isOpen) => {
- setContextMenuOpen(isOpen);
- }}
- >
- <ContextMenu.Trigger disabled={editing()}>
- <MessageComponent
- id={message.id}
- focused={props.isFocused}
- senderId={message.sender_id}
- isFirstMessage={isFirstMessage()}
- isLastMessage={isLastMessage()}
- isConsecutive={isConsecutive()}
- timestamp={message.created_at}
- shouldHover={contextMenuOpen() || topBarEmojiMenuOpen()}
- hoverActions={() => (
- <ActionMenu
- messageId={message.id}
- channelId={props.channelId}
- reactions={() => props.reactions}
- actions={actions()}
- setReactionMenuActivated={setTopBarEmojiMenuOpen}
- />
- )}
- threadDepth={threadDepth()}
- hasThreadChildren={hasThreadChildren() || shouldShowFirstReply()}
- isFirstInThread={isFirstInThread()}
- isLastInThread={isLastInThread()}
- isDeleted={!!message.deleted_at}
- isNewMessage={isNewMessage()}
- isParentNewMessage={isParentNewMessage()}
- onThreadAppend={onThreadAppend}
- shouldShowThreadAppendInput={shouldShowThreadAppendInput()}
- isTarget={props.isTarget}
- setThreadAppendMountTarget={(el) => {
- if (!message.thread_id) return;
-
- listContext.registerThreadAppendMountTarget(
- message.thread_id,
- el
- );
- }}
- setMessageBodyRef={setMessageBodyRef}
- >
- <MessageComponent.TopBar
- name={displayName()}
- timestamp={message.created_at}
- />
- <Show
- when={!editing()}
- fallback={
- <EditMessageInput
- content={props.message?.content ?? ''}
- setEditing={setEditing}
- save={editMessage}
- />
- }
- >
- <MessageComponent.Body isDeleted={!!message.deleted_at}>
- <Show when={!isEmptyMessage()}>
- <div
- class="max-w-full overflow-auto min-w-0"
- classList={{ 'text-3xl': isEmojiOnlyMessage() }}
- >
- <StaticMarkdown
- markdown={message.content ?? ''}
- theme={channelTheme}
- target="internal"
- />
- </div>
- </Show>
- </MessageComponent.Body>
- </Show>
- <MessageAttachments
- videoAttachments={videoAttachments}
- imageAttachments={imageAttachments}
- documentAttachments={documentAttachments}
- isDeleted={() => !!message.deleted_at}
- isCurrentUser={() => userId() === message.sender_id}
- channelId={message.channel_id}
- messageId={message.id}
- content={message.content}
- />
- <Show when={!message.deleted_at}>
- <MessageReactions
- messageId={props.message?.id ?? ''}
- channelId={props.channelId}
- reactions={() => props.reactions}
- />
- </Show>
- </MessageComponent>
- <Show when={isLastInCollapsedThread()}>
- <div
- class={cn(
- 'border-l border-edge-muted pb-1',
- isParentNewMessage() && 'border-accent'
- )}
- style={{
- 'margin-left': `var(--left-of-connector)`,
- }}
- >
- <div
- class="relative"
- style={{
- 'margin-left': `calc(var(--thread-shift) * ${threadDepth()} - 1px - var(--user-icon-width) / 2)`,
- }}
- >
- <ThreadReplyIndicator
- countCollapsedMessages={
- collapsedThreadMessages()?.length || 0
- }
- timestamp={lastReplyTimestamp()}
- users={threadReplyUsers()}
- onClick={handleThreadToggle}
- isThreadOpen={threadState()?.threadExpanded}
- isParentNewMessage={isParentNewMessage()}
- />
- </div>
- </div>
- </Show>
- </ContextMenu.Trigger>
- <ContextMenu.Portal>
- <ContextMenuContent
- onCloseAutoFocus={() => {
- setReactionSearchOpen(false);
- }}
- mobileFullScreen
- overrideStyling
- >
- <Switch>
- <Match when={!reactionSearchOpen()}>
- <ReactionQuickSelector
- onEmojiClick={(emoji) => react(emoji.emoji)}
- handleClose={() => {
- setReactionSearchOpen(false);
- }}
- setSearchOpen={setReactionSearchOpen}
- insideMenu
- showFocusRing={true}
- />
- </Match>
- <Match when={reactionSearchOpen()}>
- <EmojiSearchSelector
- onEmojiClick={(emoji) => react(emoji.emoji)}
- handleClose={() => {
- setReactionSearchOpen(false);
- }}
- fullWidth={isMobile()}
- insideMenu={true}
- />
- </Match>
- </Switch>
- <Show when={isMobile()}>
- <ContextMenu.Item class="mt-4 shrink-1 overflow-y-scroll overflow-x-hidden">
- <MessageComponent
- focused={props.isFocused}
- senderId={message.sender_id}
- isFirstMessage={isFirstMessage()}
- isLastMessage={isLastMessage()}
- hideConnectors
- >
- <MessageComponent.TopBar
- name={displayName()}
- timestamp={message.created_at}
- />
- <MessageComponent.Body>
- <StaticMarkdown
- markdown={message.content ?? ''}
- theme={channelTheme}
- target="internal"
- />
- </MessageComponent.Body>
- <MessageAttachments
- videoAttachments={videoAttachments}
- imageAttachments={imageAttachments}
- documentAttachments={documentAttachments}
- isDeleted={() => !!message.deleted_at}
- isCurrentUser={() => userId() === message.sender_id}
- channelId={message.channel_id}
- messageId={message.id}
- content={message.content}
- />
- </MessageComponent>
- </ContextMenu.Item>
- </Show>
- <Show when={!reactionSearchOpen()}>
- <div class={`${MENU_CONTENT_CLASS} mt-4`}>
- <For each={actions().filter((a) => a.enabled)}>
- {(a) => (
- <>
- <Show when={a.dividerBefore}>
- <MenuSeparator />
- </Show>
- <MenuItem
- onClick={a.onClick}
- text={a.text}
- icon={a.icon}
- />
- </>
- )}
- </For>
- </div>
- </Show>
- </ContextMenuContent>
- </ContextMenu.Portal>
- </ContextMenu>
- <Show when={shouldShowFirstReply()}>
- <MessageComponent
- focused={false}
- unfocusable
- senderId={userId()}
- isFirstMessage={false}
- isLastMessage={false}
- threadDepth={threadDepth() + 1}
- isFirstInThread
- isLastInThread
- shouldShowThreadAppendInput
- setThreadAppendMountTarget={(el) =>
- listContext.registerThreadAppendMountTarget(message.id, el)
- }
- >
- <MessageComponent.TopBar name={currentUserName()} />
- <div class="h-4" />
- </MessageComponent>
- </Show>
- <Show when={isLastMessage()}>
- <TypingIndicator
- // threadId={message.thread_id ?? undefined}
- previousMessage={message}
- />
- </Show>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/MessageReactions.tsx b/js/app/packages/block-channel/component/Message/MessageReactions.tsx
deleted file mode 100644
index 597b37e828..0000000000
--- a/js/app/packages/block-channel/component/Message/MessageReactions.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { useReactToMessage } from '@block-channel/hooks/reactions';
-import { EmojiButton } from '@core/component/Emoji/EmojiButton';
-import { resolveEmojiFromUnicode } from '@core/component/Emoji/emojis';
-import clickOutside from '@core/directive/clickOutside';
-import { touchHandler } from '@core/directive/touchHandler';
-import { idToDisplayName } from '@core/user';
-import Tooltip from '@corvu/tooltip';
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-
-import { useUserId } from '@core/context/user';
-import { createMemo, createSignal, For, Show, type Accessor } from 'solid-js';
-import { ReactionSelector } from '../ReactionSelector';
-
-false && clickOutside;
-false && touchHandler;
-
-type MessageReactionsProps = {
- messageId: string;
- channelId: Accessor<string>;
- reactions: Accessor<GetChannelResponseReactions>;
-};
-
-export function MessageReactions(props: MessageReactionsProps) {
- const userId = useUserId();
-
- const reactionsForMessage = createMemo(() => {
- return props.reactions()?.[props.messageId] ?? [];
- });
-
- const reactToMessage = useReactToMessage(props.channelId, props.reactions);
-
- const react = (emoji: string) => reactToMessage(emoji, props.messageId);
-
- return (
- <Show when={reactionsForMessage().length > 0}>
- <div class="flex flex-row flex-wrap items-center gap-2 mt-0.5 mb-1">
- <For each={reactionsForMessage().slice(0, 10)}>
- {(reaction) => {
- const didCurrentUserReact = !userId()
- ? false
- : reaction.users.includes(userId()!);
-
- const tooltipContent = createMemo(() => {
- const users = reaction.users.map((userId_) => {
- if (userId_ === userId()!) {
- return 'You';
- }
- return idToDisplayName(userId_);
- });
-
- if (users.length === 1) {
- return users[0];
- }
-
- const first = users.slice(0, -1);
- const lastUser = users.slice(-1)[0];
- // Team oxford comma
- return first.join(', ') + ', and ' + lastUser;
- });
-
- const [isOpen, setIsOpen] = createSignal(false);
-
- return (
- <Tooltip group="channel" open={isOpen()} onOpenChange={setIsOpen}>
- <Tooltip.Trigger as="div">
- <div
- class={`flex flex-row items-center gap-2 py-1 px-2 bg-menu
- ${
- didCurrentUserReact
- ? 'text-accent-ink border border-accent'
- : 'hover:bg-hover transition-transform border border-edge-muted transition-none hover:transition hover:scale-105'
- }
- cursor-default h-8
- `}
- onClick={() => react(reaction.emoji)}
- use:touchHandler={{
- onLongPress: (e) => {
- e.preventDefault();
- setIsOpen(true);
- },
- onShortTouch: (e) => {
- e.preventDefault();
- react(reaction.emoji);
- },
- }}
- use:clickOutside={() => setIsOpen(false)}
- >
- <EmojiButton
- emoji={resolveEmojiFromUnicode(reaction.emoji)!}
- size="sm"
- />
- {reaction.users.length > 1 ? reaction.users.length : ''}
- </div>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content class="mt-3 z-tool-tip">
- <Tooltip.Arrow class="text-ink text-xs w-1 h-1" />
- <div class="flex flex-col gap-1 bg-ink rounded-md p-2 max-w-[220px]">
- <p class="text-xs text-panel font-semibold">
- {tooltipContent()}{' '}
- <span class="text-edge font-medium">
- reacted with{' '}
- <span class="text-md">{reaction.emoji}</span>
- </span>
- </p>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip>
- );
- }}
- </For>
- <ReactionSelector onEmojiClick={(emoji) => react(emoji.emoji)} />
- </div>
- </Show>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/ThreadReplyIndicator.tsx b/js/app/packages/block-channel/component/Message/ThreadReplyIndicator.tsx
deleted file mode 100644
index dc8b3dede7..0000000000
--- a/js/app/packages/block-channel/component/Message/ThreadReplyIndicator.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { Tooltip } from '@core/component/Tooltip';
-import { UserIcon } from '@core/component/UserIcon';
-import { isMobileWidth } from '@core/mobile/mobileWidth';
-import { onKeyDownClick, onKeyUpClick } from '@core/util/click';
-import type { DateValue } from '@core/util/date';
-import { formatRelativeDate } from '@core/util/time';
-import CaretRight from '@phosphor-icons/core/regular/caret-right.svg?component-solid';
-import { cn } from '@ui/utils/classname';
-import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
-
-export function ThreadReplyIndicator(props: {
- countCollapsedMessages: number;
- timestamp?: DateValue;
- users: string[];
- onClick: () => void;
- justifyRight?: boolean;
- isThreadOpen?: boolean;
- hasDraft?: boolean;
- isParentNewMessage?: boolean;
-}) {
- const [hover, setHover] = createSignal(false);
- let countText = () => {
- return props.hasDraft
- ? `${props.countCollapsedMessages} more repl${props.countCollapsedMessages > 1 ? 'ies' : 'y'} & 1 draft`
- : `${props.countCollapsedMessages} more repl${props.countCollapsedMessages > 1 ? 'ies' : 'y'}`;
- };
-
- const MAX_USERS = createMemo(() => (isMobileWidth() ? 3 : 6));
- const MAX_USERS_INDEX = createMemo(() => MAX_USERS() - 1);
-
- return (
- <div
- class={cn(
- 'flex flex-row gap-2 items-center justify-between pb-2 pt-2 text-xs w-full max-w-fit border-edge-muted border pr-2 select-none hover:bg-hover focus:bracket-offset-2',
- props.isParentNewMessage && 'border-accent'
- )}
- onClick={props.onClick}
- onKeyDown={onKeyDownClick(props.onClick)}
- onKeyUp={onKeyUpClick(props.onClick)}
- tabIndex={0}
- onMouseEnter={() => setHover(true)}
- onMouseLeave={() => setHover(false)}
- >
- <div
- class={`flex flex-row items-center gap-2 w-full px-2 ${props.justifyRight ? 'justify-end' : ''}`}
- >
- <div class="flex flex-row gap-1 items-center relative">
- <For
- each={
- props.users.length > MAX_USERS()
- ? props.users.slice(0, MAX_USERS_INDEX())
- : props.users
- }
- >
- {(userId) => (
- <UserIcon
- id={userId}
- isDeleted={false}
- size="sm"
- suppressClick={true}
- fetchUrl={false}
- />
- )}
- </For>
- <Show when={props.users.length > MAX_USERS()}>
- <Tooltip tooltip={props.users.slice(MAX_USERS_INDEX()).join(', ')}>
- <div class="relative">
- <UserIcon
- id={props.users[MAX_USERS_INDEX()]}
- isDeleted={false}
- size="sm"
- suppressClick={true}
- fetchUrl={false}
- />
- <div class="absolute top-0 left-0 w-full h-full flex items-center justify-center rounded-full bg-ink/50 text-panel">
- +{props.users.length - MAX_USERS_INDEX()}
- </div>
- </div>
- </Tooltip>
- </Show>
- </div>
- <p class="text-accent-ink font-medium min-w-[60px] shrink-0">
- {countText()}
- </p>
- <div class="min-w-[17ch] hidden @min-[40rem]:block">
- <Switch>
- <Match when={hover()}>
- <p class="text-ink-muted">
- {props.isThreadOpen ? 'Close thread' : 'Expand thread'}
- </p>
- </Match>
- <Match when={!hover() && props.timestamp}>
- {(timestamp) => (
- <p class="text-ink-muted">
- Last reply {formatRelativeDate(timestamp())}
- </p>
- )}
- </Match>
- </Switch>
- </div>
- </div>
- <CaretRight class={`w-4 h-4 ${hover() ? '' : 'invisible'}`} />
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/Message/actions.ts b/js/app/packages/block-channel/component/Message/actions.ts
deleted file mode 100644
index 29acd72860..0000000000
--- a/js/app/packages/block-channel/component/Message/actions.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { getUrlToMessage } from '@block-channel/utils/link';
-import { useBlockId } from '@core/block';
-import { logger } from '@observability';
-import ReplyIcon from '@phosphor-icons/core/regular/arrow-bend-up-left.svg?component-solid';
-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 '@core/context/user';
-import { toast } from 'core/component/Toast/Toast';
-import type { Accessor, Component } from 'solid-js';
-import { createMemo } from 'solid-js';
-
-export type MessageAction = {
- text: string;
- icon: Component;
- onClick: () => void;
- enabled: boolean;
- dividerBefore?: boolean;
-};
-
-export function createMessageActions(params: {
- channelId: string;
- messageId: string;
- messageContent: string;
- threadId?: string;
- senderId: string;
- onEdit: () => void;
- onReply: () => void;
-}): Accessor<MessageAction[]> {
- const blockId = useBlockId();
- const userId = useUserId();
-
- const deleteMessageMutation = useDeleteMessageMutation();
-
- const deleteMessage = () => {
- deleteMessageMutation.mutate({
- channelID: params.channelId,
- messageID: params.messageId,
- });
- };
-
- function copyLinkToMessage() {
- const normalizedThreadId =
- params.threadId == null ? undefined : String(params.threadId);
- const url = getUrlToMessage(blockId, params.messageId, normalizedThreadId);
- navigator.clipboard.writeText(url);
- toast.success('Link copied to clipboard');
- }
-
- function copyMessageText() {
- const text = params.messageContent;
- if (!text) return toast.failure('No message to copy');
-
- navigator.clipboard
- .writeText(text)
- .then(() => {
- toast.success('Message copied to clipboard');
- })
- .catch((cause) => {
- logger.error('failed to copy message', { cause });
- toast.failure('Failed to copy message');
- });
- }
-
- return createMemo<MessageAction[]>(() => [
- {
- text: 'Reply',
- onClick: params.onReply,
- enabled: !params.threadId,
- icon: ReplyIcon,
- },
- {
- text: 'Copy Link',
- onClick: copyLinkToMessage,
- icon: LinkIcon,
- enabled: true,
- },
- {
- text: 'Copy Message',
- onClick: copyMessageText,
- icon: CopyIcon,
- enabled: true,
- },
- {
- text: 'Edit Message',
- onClick: params.onEdit,
- enabled: userId() === params.senderId,
- icon: Pencil,
- dividerBefore: true,
- },
- {
- text: 'Delete Message',
- onClick: deleteMessage,
- enabled: userId() === params.senderId,
- icon: Trash,
- },
- ]);
-}
diff --git a/js/app/packages/block-channel/component/Message/index.css b/js/app/packages/block-channel/component/Message/index.css
deleted file mode 100644
index b39cd53f95..0000000000
--- a/js/app/packages/block-channel/component/Message/index.css
+++ /dev/null
@@ -1,48 +0,0 @@
-.highlight-enter-active,
-.highlight-exit-active {
- transition: opacity 700ms ease-in-out;
-}
-
-.highlight-enter,
-.highlight-exit-to {
- opacity: 0;
-}
-
-.highlight-enter-to,
-.highlight-exit {
- opacity: 20%;
-}
-
-.current-user-message-enter-active {
- transition: all 200ms cubic-bezier(.78,.4,.68,1.38);
- transform-origin: 95% 100%;
-}
-
-.current-user-message-enter {
- opacity: 0;
- transform: translateY(100%) scale(0);
-}
-
-.current-user-message-enter-to {
- opacity: 1;
- transform: translateY(0) scale(1);
-}
-
-.typing-indicator-message-enter-active,
-.typing-indicator-message-exit-active {
- transition: transform 200ms cubic-bezier(.78,.4,.68,1.38), opacity 200ms linear;
- transform-origin: 40px 100%;
-}
-
-
-.typing-indicator-message-enter,
-.typing-indicator-message-exit-to {
- opacity: 0;
- transform: translateY(100%) scaleY(0);
-}
-
-.typing-indicator-message-enter-to,
-.typing-indicator-message-exit {
- opacity: 1;
- transform: translateY(0) scaleY(1);
-}
diff --git a/js/app/packages/block-channel/component/MessageList/MessageList.tsx b/js/app/packages/block-channel/component/MessageList/MessageList.tsx
deleted file mode 100644
index 48db8878a2..0000000000
--- a/js/app/packages/block-channel/component/MessageList/MessageList.tsx
+++ /dev/null
@@ -1,1095 +0,0 @@
-import {
- COLLAPSED_THREAD_INDEX_CUTOFF,
- TARGET_MESSAGE_ACTIVE_TIME,
-} from '@block-channel/constants';
-import type { MessageWithThreadId } from '@block-channel/signal/threads';
-import type {
- ThreadView,
- ThreadViewData,
-} from '@block-channel/type/threadView';
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-import { loadDraftMessage } from '@block-channel/utils/draftMessages';
-import {
- createMessageListContextLookup,
- type MessageListContextLookup,
-} from '@block-channel/utils/listContext';
-import { CustomScrollbar } from '@core/component/CustomScrollbar';
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import { toast } from '@core/component/Toast/Toast';
-import { observedSize } from '@core/directive/observedSize';
-import type { InputAttachment } from '@core/store/cacheChannelInput';
-import SunIcon from '@icon/duotone/sun-horizon-duotone.svg';
-import ArrowDownIcon from '@icon/regular/arrow-down.svg';
-import XIcon from '@icon/regular/x.svg';
-import type { ApiActivity as ChannelActivity } from '@service-comms/generated/models';
-import type {
- Attachment,
- ChannelParticipant,
- Message,
-} from '@queries/channel/types';
-import { useUserId } from '@core/context/user';
-import type { DateValue } from '@core/util/date';
-import { debounce } from '@solid-primitives/scheduled';
-import {
- type Accessor,
- createContext,
- createEffect,
- createMemo,
- createRenderEffect,
- createSelector,
- createSignal,
- For,
- Match,
- mapArray,
- on,
- onMount,
- type Setter,
- Show,
- Switch,
- untrack,
- useContext,
-} from 'solid-js';
-import { createStore, reconcile } from 'solid-js/store';
-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';
-
-false && observedSize;
-
-type ThreadRow = {
- id: string;
- message: Message;
- children: Accessor<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 message
-const BASE_ITEM_SIZE = 50;
-
-const createDefaultMessageListContext = (index: Accessor<number>) =>
- createMemo<MessageListContext>(() => ({
- index: index(),
- isNewMessage: false,
- isFirstNewMessage: 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,
- alignOpts?: ScrollToIndexOpts
- ) => void;
- createReply: (id: string, focus?: boolean) => void;
- toggleThread: (threadID: string, value?: boolean) => void;
- closeThreadReply: (threadID: string, expanded?: boolean) => void;
- toggleReplyInputFocus: (threadID: string, value?: boolean) => void;
- getThreadsWithActiveReplies: () => string[];
- registerThreadAppendMountTarget: (threadID: string, el: HTMLElement) => void;
- getThreadState: (threadID: string) => ThreadView | undefined;
- orderedMessages: Accessor<Message[]>;
-};
-
-const MessageListContentContext =
- createContext<MessageListContentContextValues>();
-
-export const useMessageListContext = () => {
- const context = useContext(MessageListContentContext);
- if (!context) {
- throw new Error(
- 'useMessageListContext must be used within MessageListContentContext.Provider'
- );
- }
- return context;
-};
-
-export type TargetMessageInfo = { messageId: string; threadId?: string };
-
-export type MessageListNavigation = {
- /** Navigate to previous message (up in the list) */
- navigatePrevious: () => boolean;
- /** Navigate to next message (down in the list) */
- navigateNext: () => boolean;
- /** Navigate to a specific message by ID */
- navigateToMessage: (messageId: string) => boolean;
-};
-
-export type ThreadStoreData = Record<string, MessageWithThreadId[]>;
-
-export type MessageListProps = {
- channelId: string;
- messages: Message[];
- threads: ThreadStoreData;
- reactions: GetChannelResponseReactions;
- attachments: Attachment[];
- participants: ChannelParticipant[];
- latestActivity?: ChannelActivity;
- openedChannel?: Date;
- containerRef?: HTMLDivElement;
- targetMessage: Accessor<TargetMessageInfo | undefined>;
- focusedMessageId: Accessor<string | undefined>;
- setFocusedMessageId: Setter<string | undefined>;
- /** Callback to expose navigation methods to parent */
- onNavigationReady?: (nav: MessageListNavigation) => void;
- orderedMessages: Accessor<Message[]>;
- setOrderedMessages: Setter<Message[]>;
-};
-
-function EmptyMessageList() {
- return (
- <div class="flex flex-col items-center justify-center w-full h-full gap-1">
- <SunIcon class="w-16 h-16 text-ink-muted" />
- <p class="text-ink text-md">Beginning of something new...</p>
- <p class="text-ink-muted text-xs">
- Start a conversation, by sending a message.
- </p>
- </div>
- );
-}
-
-export function MessageList(props: MessageListProps) {
- const [virtualHandle, setVirtualHandle] = createSignal<VirtualizerHandle>();
- const [scrollContainerRef, setScrollContainerRef] = createSignal<
- HTMLDivElement | undefined
- >();
-
- const [threadViewStore, setThreadViewStore] = createStore<ThreadViewData>({});
-
- 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 topLevelIndex = topLevelIndexByMessageId().get(messageId);
- if (topLevelIndex === undefined) return undefined;
- return topLevelIndex;
- };
-
- 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;
- targetEl.scrollIntoView({ block: align });
- if (focus) targetEl.focus();
- return true;
- };
-
- 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 = {
- setFocusedMessageId: props.setFocusedMessageId,
- registerVirtualHandle: setVirtualHandle,
- scrollContainerRef,
- registerScrollContainer: setScrollContainerRef,
- scrollToIndex: function (index: number, opts?: ScrollToIndexOpts): void {
- 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,
- alignOpts?: ScrollToIndexOpts
- ): void {
- 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) => {
- return {
- ...prev,
- threadExpanded: true,
- hasActiveReply: true,
- replyInputShouldFocus: focus,
- };
- });
- },
- toggleThread: function (threadID: string, value?: boolean): void {
- setThreadViewStore(threadID, (prev) => {
- return {
- ...prev,
- threadExpanded: value ?? (prev ? !prev.threadExpanded : true),
- };
- });
- },
- closeThreadReply: function (threadID: string, expanded?: boolean): void {
- setThreadViewStore(threadID, (prev) => {
- return {
- ...prev,
- threadExpanded: expanded,
- hasActiveReply: false,
- };
- });
- },
- toggleReplyInputFocus: function (threadID: string, value?: boolean): void {
- setThreadViewStore(threadID, (prev) => {
- return {
- ...prev,
- replyInputShouldFocus:
- value ?? (prev ? !prev.replyInputShouldFocus : true),
- };
- });
- },
- getThreadsWithActiveReplies: () => {
- return Object.keys(threadViewStore).filter(
- (threadId) => threadViewStore[threadId].hasActiveReply
- );
- },
- registerThreadAppendMountTarget: function (
- threadID: string,
- el: HTMLElement
- ): void {
- setThreadViewStore(threadID, (prev) => ({
- ...prev,
- replyInputMountTarget: el,
- }));
- },
- getThreadState: function (threadID: string): ThreadView | undefined {
- return threadViewStore[threadID];
- },
- orderedMessages: props.orderedMessages,
- };
- return (
- <MessageListContentContext.Provider value={context}>
- <MessageListImpl {...props} />
- </MessageListContentContext.Provider>
- );
-}
-
-function MessageListImpl(props: MessageListProps) {
- const listContext = useMessageListContext();
-
- const [virtualHandle, setVirtualHandle] = createSignal<VirtualizerHandle>();
- const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();
-
- const [hasUserScrolled, setHasUserScrolled] = createSignal(false);
- const [messageListContext, setMessageListContext] =
- createStore<MessageListContextLookup>({});
-
- const userId = useUserId();
- const [viewThreads, setViewThreads] = createStore<ThreadStoreData>({});
-
- const [threadInputAttachmentsStore, setThreadInputAttachmentsStore] =
- createStore<Record<string, InputAttachment[]>>({});
-
- const [isNearBottom, setIsNearBottom] = createSignal(true);
- const [initialScrollComplete, setInitialScrollComplete] = createSignal(false);
- const [isScrolledBackSignificantly, setIsScrolledBackSignificantly] =
- createSignal(false);
- const [isScrollingDown, setIsScrollingDown] = createSignal(false);
- let prevScrollOffset: number | undefined;
- let prevScrollSize: number | undefined;
- let downwardScrollAccumulator = 0;
-
- // Navigation methods for keyboard navigation
- const navigateToMessage = (messageId: string): boolean => {
- const messages = props.orderedMessages();
- const index = messages.findIndex((m) => m.id === messageId);
- if (index === -1) return false;
- listContext.scrollToMessage(messageId, index, false, {
- align: 'nearest',
- });
-
- // Focus after scroll completes
- requestAnimationFrame(() => {
- const targetEl = containerRef()?.querySelector<HTMLElement>(
- `[data-message-body-id="${messageId}"]`
- );
- targetEl?.focus();
- });
-
- return true;
- };
-
- const navigateByOffset = (
- direction: -1 | 1,
- fallbackToLast: boolean
- ): boolean => {
- const messages = props.orderedMessages();
- const currentId = props.focusedMessageId();
- const currentIndex = currentId
- ? messages.findIndex((m) => m.id === currentId)
- : -1;
-
- if (currentIndex === -1) {
- if (fallbackToLast && messages.length > 0) {
- return navigateToMessage(messages[messages.length - 1].id);
- }
- return false;
- }
-
- const nextIndex = currentIndex + direction;
- if (nextIndex < 0 || nextIndex >= messages.length) return false;
-
- return navigateToMessage(messages[nextIndex].id);
- };
-
- const navigatePrevious = (): boolean => navigateByOffset(-1, true);
- const navigateNext = (): boolean => navigateByOffset(1, false);
-
- // Expose navigation methods to parent
- onMount(() => {
- props.onNavigationReady?.({
- navigatePrevious,
- navigateNext,
- navigateToMessage,
- });
- });
-
- // Snapshot the lastViewed time so it reflects the pre-session value.
- // Without this, the activity mutation on channel open would update
- // lastViewed reactively, causing the "New" indicator to disappear.
- const lastViewed = createMemo<DateValue | null | undefined>((prev) => {
- if (prev !== undefined) return prev;
- return props?.latestActivity?.viewed_at;
- });
-
- const [newMessagesDismissed, setNewMessagesDismissed] = createSignal(false);
-
- const checkIfNewMessage = (message: Message) => {
- if (newMessagesDismissed()) return false;
- const lastViewed_ = lastViewed();
- const openedChannel_ = props.openedChannel;
- return (
- !!lastViewed_ &&
- !!openedChannel_ &&
- new Date(message.created_at) > new Date(lastViewed_) &&
- userId() !== message.sender_id &&
- new Date(message.created_at) < openedChannel_
- );
- };
-
- const dismissNewMessages = () => {
- setNewMessagesDismissed(true);
- computeListContext(flattenedThreaded());
- };
-
- // Keep some additional timing information for goToLocationFromParams
- // race conditions.
- const [lastTargetMessageTimestamp, setLastTargetMessageTimestamp] =
- createSignal<number>(Date.now());
-
- // Track missing target message retries
- let missingTargetRetryCount = 0;
- let lastMissingTargetId: string | undefined;
-
- // represents active highlighted state on the target message
- const [targetMessageActive, setTargetMessageActive] =
- createSignal<boolean>(false);
-
- const activeTargetMessageId = createMemo(() => {
- if (!targetMessageActive()) return;
- return untrack(props.targetMessage)?.messageId;
- });
-
- const isActiveTargetMessage = createSelector(activeTargetMessageId);
-
- /**
- * Scroll to the bottom of the document or the target message depending on the
- * current state.
- * @param params.forceBottom - force the scroll to bottom ignoring target message
- * @returns
- */
- const scrollToBottomOrTarget = (params: { forceBottom?: boolean } = {}) => {
- const { forceBottom } = params;
- const timeStamp = Date.now();
- const delta = timeStamp - lastTargetMessageTimestamp();
- const target = props.targetMessage();
-
- if (
- forceBottom ||
- ((!target || delta > TARGET_MESSAGE_ACTIVE_TIME) && isNearBottom())
- ) {
- virtualHandle()?.scrollBy(Number.MAX_SAFE_INTEGER);
- return;
- }
-
- const { messageId: targetMessageId, threadId } = target || {};
-
- if (!targetMessageId) return;
-
- // If we have a target message, scroll to it and focus it
- const index = props
- .orderedMessages()
- ?.findIndex((m) => m.id === targetMessageId);
-
- if (index === -1) {
- // Retry briefly to allow hydration to complete before showing an error. Necessary for push notifications.
- if (lastMissingTargetId !== targetMessageId) {
- lastMissingTargetId = targetMessageId;
- missingTargetRetryCount = 0;
- }
-
- const retries = missingTargetRetryCount;
- if (retries < 6) {
- missingTargetRetryCount = retries + 1;
- setLastTargetMessageTimestamp(Date.now());
- setTimeout(() => {
- scrollToBottomOrTarget();
- }, 200);
- return;
- }
-
- console.warn('Target message not found');
- toast.failure('Message not found.');
- scrollToBottomOrTarget({ forceBottom: true });
- return;
- }
-
- // Reset retry state on success.
- if (lastMissingTargetId === targetMessageId) {
- missingTargetRetryCount = 0;
- }
-
- if (threadId) {
- listContext.toggleThread(threadId, true);
- }
-
- setTargetMessageActive(true);
- listContext.scrollToMessage(targetMessageId, index, false, {
- align: 'center',
- });
- setTimeout(() => {
- setTargetMessageActive(false);
- }, TARGET_MESSAGE_ACTIVE_TIME);
- };
-
- const debouncedScrollToBottomOrTarget = debounce(scrollToBottomOrTarget, 5);
-
- /**
- * Track context for messages as they are rendered in the list
- */
- function computeListContext(messages: Message[]) {
- const context = createMessageListContextLookup({
- messages,
- isNewMessageFn: checkIfNewMessage,
- });
-
- setMessageListContext(reconcile(context));
- }
-
- const isFocused = createSelector(props.focusedMessageId);
-
- // Keep the message if:
- // 1. It's not deleted, OR
- // 2. It's deleted but is a parent message
- const messageFilterFn = (message: Message) =>
- !message.deleted_at || viewThreads[message.id]?.length > 0;
-
- const filteredTopLevelMessages = createMemo(() =>
- props.messages.filter(messageFilterFn)
- );
-
- // Construct a list with thread children placed after their parent message using mapArray for referential stability.
- // mapFn is not tracking, so wrap thread-dependent logic in a memo per parent.
- const segments = mapArray(filteredTopLevelMessages, (message) =>
- createMemo(() => {
- const children = viewThreads[message.id] ?? [];
- const filteredChildren = children.filter(messageFilterFn);
- return filteredChildren.length
- ? [message, ...filteredChildren]
- : [message];
- })
- );
-
- const flattenedThreaded = createMemo(() => {
- const segs = segments();
- const out: Message[] = [];
- for (let i = 0; i < segs.length; i++) out.push(...segs[i]());
- return out;
- });
-
- createEffect(
- on(flattenedThreaded, (flat, prev) => {
- const oldFlat = prev;
- if (oldFlat !== flat) {
- props.setOrderedMessages(flat);
- computeListContext(flat);
- }
- })
- );
-
- // Thread reply inputs are portaled to the correct message container. This keeps them in the correct location even as new thread replies come in, but if they are re-portaled while a user is typing, the user can momentarily lose input. To address this, we gate updates to the thread that a user is currently typing in.
- const [localTypingThreadId, setLocalTypingThreadId] = createSignal<
- string | undefined
- >();
-
- let dirtyTypingThreadId: string | undefined;
-
- // Maintain a local snapshot of threads that freezes changes for threads in which a user is actively typing.
- createEffect(() => {
- const baseMessages = props.messages;
- const activeThreadId = untrack(localTypingThreadId);
-
- for (const message of baseMessages) {
- const id = message.id;
- const threadArr = props.threads[id] ?? [];
- const currentView = viewThreads[id];
- const isTypingThisThread = id === activeThreadId;
-
- if (isTypingThisThread) {
- if (currentView !== threadArr) {
- dirtyTypingThreadId = id;
- }
- continue;
- }
-
- if (currentView !== threadArr) {
- setViewThreads(id, reconcile(threadArr));
- }
-
- if (dirtyTypingThreadId === id) {
- dirtyTypingThreadId = undefined;
- }
- }
- });
-
- // When active typing thread changes flush any pending changes for the previous typing thread.
- createEffect((prevTypingId: string | undefined) => {
- const currentTypingId = localTypingThreadId();
-
- if (
- prevTypingId &&
- prevTypingId !== currentTypingId &&
- dirtyTypingThreadId === prevTypingId
- ) {
- const threadArr = untrack(() => props.threads[prevTypingId] ?? []);
- setViewThreads(prevTypingId, reconcile(threadArr));
- dirtyTypingThreadId = undefined;
- }
-
- return currentTypingId;
- });
-
- const threadRows = mapArray(
- () => filteredTopLevelMessages(),
- (message) => {
- const children = () =>
- (viewThreads[message.id] ?? []).filter(messageFilterFn);
- return { id: message.id, message, children };
- }
- );
-
- // Ensure thread view store store reflects drafts. Only sets when no entry exists to avoid overriding user actions.
- createEffect(() => {
- const base = filteredTopLevelMessages();
- for (const message of base) {
- const hasDraft = !!loadDraftMessage(message.channel_id, message.id);
- const threadDetails = listContext.getThreadState(message.id);
- if (hasDraft && threadDetails) {
- listContext.createReply(message.id);
- }
- }
- });
-
- // 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.
- const keepMountedIndices = createMemo(() => {
- const list = filteredTopLevelMessages();
- const length = list.length;
- const indices: number[] = [];
- for (let i = 0; i < length; i++) {
- const msg = list[i];
- const threadState = listContext.getThreadState(msg.id);
- if (threadState?.hasActiveReply) {
- indices.push(i);
- }
- }
- return indices;
- });
-
- const checkIfNearBottom = () => {
- const handle = virtualHandle();
- if (!handle) return false;
- if (!initialScrollComplete()) return true;
-
- const THRESHOLD = 100;
- const scrollHeight = handle.scrollSize;
- const viewportHeight = handle.viewportSize;
- const scrollTop = handle.scrollOffset;
- const distanceFromBottom = scrollHeight - viewportHeight - scrollTop;
- return distanceFromBottom <= THRESHOLD;
- };
-
- const checkIfScrolledBackSignificantly = () => {
- const handle = virtualHandle();
- if (!handle) return false;
- const THRESHOLD = 2000;
- const scrollHeight = handle.scrollSize;
- const viewportHeight = handle.viewportSize;
- const scrollTop = handle.scrollOffset;
- const distanceFromBottom = scrollHeight - viewportHeight - scrollTop;
- return distanceFromBottom > THRESHOLD;
- };
-
- // Track scroll direction.
- // Requires 100px of cumulative downward scrolling before triggering.
- const updateScrollDirection = (offset: number) => {
- const handle = virtualHandle();
- const scrollSize = handle?.scrollSize ?? 0;
-
- if (prevScrollOffset === undefined) {
- prevScrollOffset = offset;
- prevScrollSize = scrollSize;
- return;
- }
-
- const delta = offset - prevScrollOffset; // positive = scrolling down
- const scrollSizeChanged = prevScrollSize !== scrollSize;
-
- prevScrollOffset = offset;
- prevScrollSize = scrollSize;
-
- // Ignore scroll events where scrollSize changed - virtualization adjustments
- // can cause offset jumps that don't reflect actual user scroll direction
- if (scrollSizeChanged) {
- return;
- }
-
- if (delta > 0) {
- downwardScrollAccumulator += delta;
- if (downwardScrollAccumulator >= 100) {
- setIsScrollingDown(true);
- }
- } else {
- downwardScrollAccumulator = 0;
- setIsScrollingDown(false);
- }
- };
-
- const lastMessageReaction = createMemo(() => {
- const list = props.orderedMessages();
- const lastMessageId = list[list.length - 1]?.id;
- return props.reactions[lastMessageId];
- });
-
- const lastMessageThread = createMemo(() => {
- const base = filteredTopLevelMessages();
- const lastTopLevelId = base[base.length - 1]?.id;
- return viewThreads[lastTopLevelId];
- });
-
- const lastMessageThreadCount = createMemo(
- () => lastMessageThread()?.length ?? 0
- );
-
- // scroll to bottom on change to last message state (including new messages)
- createEffect(
- on(
- [lastMessageReaction, lastMessageThread, lastMessageThreadCount],
- () => {
- if (!isNearBottom()) return;
- debouncedScrollToBottomOrTarget({ forceBottom: true });
- },
- { defer: true }
- )
- );
-
- let mountScrolled = false;
- createEffect(
- on(virtualHandle, (handle) => {
- if (mountScrolled || !handle || props.targetMessage()) return;
-
- mountScrolled = true;
-
- scrollToBottomOrTarget({ forceBottom: true });
- })
- );
-
- const [unviewedMessages, setUnviewedMessages] = createSignal<Message[]>();
- const [dismissUnviewedMessages, setDismissUnviewedMessages] =
- createSignal(false);
- const [dismissJumpToLatest, setDismissJumpToLatest] = createSignal(false);
-
- // Record new unviewed messages
- // TODO: show new reply state for threads with new messages
- createEffect(
- on(filteredTopLevelMessages, (newFilteredMessages, oldFilteredMessages) => {
- const handle = virtualHandle();
- if (!handle) return;
-
- // Don't track unviewed messages if we're near the bottom
- if (isNearBottom()) return;
-
- // Find the last visible item index
- const bottomOfViewport = handle.scrollOffset + handle.viewportSize;
- const lastIndexInView = handle.findItemIndex(bottomOfViewport);
-
- // Only track if we have enough messages to scroll
- const oldLength = oldFilteredMessages?.length ?? 0;
- if (oldLength === 0) return;
-
- const prevUnviewedMessages = unviewedMessages();
- const messages = newFilteredMessages ?? [];
- const newUnviewedMessages = messages
- .slice(lastIndexInView + 1)
- .filter(
- (msg) =>
- msg.sender_id !== userId() &&
- !oldFilteredMessages?.some((m) => m.id === msg.id) &&
- !prevUnviewedMessages?.some((m) => m.id === msg.id)
- );
-
- if (newUnviewedMessages.length > 0) {
- setUnviewedMessages((prev) => [
- ...(prev ?? []),
- ...newUnviewedMessages,
- ]);
- setDismissUnviewedMessages(false);
- }
- })
- );
-
- // TODO: do we want this?
- // Scroll to the bottom on new typing updates
- // createEffect(
- // on(usersTypingSignal.get, (typing) => {
- // if (isNearBottom()) {
- // virtualHandle()?.scrollToIndex(props.orderedMessages()?.length - 1, {
- // align: 'end',
- // });
- // }
- // })
- // );
-
- const [size, setSize] = createSignal<DOMRect>();
-
- createRenderEffect(
- on(props.targetMessage, (target) => {
- if (!target) return;
- setLastTargetMessageTimestamp(Date.now());
- debouncedScrollToBottomOrTarget();
- })
- );
-
- // Handle vlistscroll events
- const handleScroll = (offset: number) => {
- if (!initialScrollComplete()) return;
-
- const nearBottom = checkIfNearBottom();
- setIsNearBottom(nearBottom);
-
- setIsScrolledBackSignificantly(checkIfScrolledBackSignificantly());
- updateScrollDirection(offset);
-
- if (!nearBottom && dismissJumpToLatest()) {
- setDismissJumpToLatest(false);
- }
-
- // Clear unviewed messages when we scroll to see them or reach the bottom
- const messages = unviewedMessages();
-
- if (!messages?.length) return;
-
- if (nearBottom) {
- setUnviewedMessages(undefined);
- return;
- }
-
- const handle = virtualHandle();
- if (!handle) return;
-
- const firstUnviewed = messages[0];
- const topLevelMessages = filteredTopLevelMessages();
- const firstUnviewedIndex = topLevelMessages.findIndex(
- (m) => m.id === firstUnviewed.id
- );
-
- if (firstUnviewedIndex === -1) {
- // Message no longer exists in the list
- setUnviewedMessages(undefined);
- return;
- }
-
- const bottomOfViewport = handle.scrollOffset + handle.viewportSize;
- const lastVisibleIndex = handle.findItemIndex(bottomOfViewport);
-
- if (lastVisibleIndex >= firstUnviewedIndex) {
- setUnviewedMessages(undefined);
- }
- };
-
- // Jump to the first unviewed message
- const jumpToUnviewedMessages = () => {
- const messages = unviewedMessages();
- if (messages?.length) {
- const firstUnviewedIndex = props
- .orderedMessages()
- ?.findIndex((m) => m.id === messages[0].id);
- if (firstUnviewedIndex === undefined) return;
- const targetMessageId = props.orderedMessages()?.[firstUnviewedIndex]?.id;
- if (!targetMessageId) return;
- listContext.scrollToMessage(targetMessageId, firstUnviewedIndex, false, {
- align: 'start',
- });
- }
- };
-
- const showJumpToUnviewedMessages = createMemo(
- () => !dismissUnviewedMessages() && !!unviewedMessages()?.length
- );
-
- const markUserScrolled = () => {
- if (!hasUserScrolled()) {
- setHasUserScrolled(true);
- }
- };
-
- 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}
- virtualHandle={virtualHandle()!}
- container={containerRef()}
- listContext={params.listContext}
- isTarget={params.isTarget}
- channelId={() => props.channelId}
- attachments={props.attachments}
- reactions={props.reactions}
- onDismissNewMessages={dismissNewMessages}
- />
- );
-
- 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 (
- <div
- class="flex-1 overflow-y-hidden suppress-css-brackets"
- ref={(el) => setContainerRef(el)}
- >
- <div
- class="flex flex-col h-full relative"
- ref={(el) => {
- onMount(() => {
- const scrollContainer = el.querySelector(
- '[data-channel-message-list]'
- ) as HTMLDivElement | null;
-
- if (!scrollContainer) return;
-
- listContext.registerScrollContainer(scrollContainer);
- });
- }}
- onWheel={markUserScrolled}
- onTouchMove={markUserScrolled}
- onPointerDown={markUserScrolled}
- use:observedSize={{
- setSize,
- }}
- >
- <Switch fallback={<EmptyMessageList />}>
- <Match when={props.messages.length > 0}>
- <VList
- ref={(handle) => {
- if (handle) {
- listContext.registerVirtualHandle(handle);
- }
- setVirtualHandle(handle);
- }}
- style={{
- 'max-height': `${listHeight()}px`,
- height: '100%',
- contain: 'none',
- 'overflow-x': 'hidden',
- 'overflow-y': 'scroll',
- 'overflow-anchor': 'none',
- display: 'flex',
- }}
- class="scrollbar-hidden"
- data-channel-message-list
- data={threadRows()}
- itemSize={BASE_ITEM_SIZE}
- bufferSize={10 * BASE_ITEM_SIZE}
- keepMounted={keepMountedIndices()}
- onScroll={handleScroll}
- onScrollEnd={() => {
- if (!initialScrollComplete()) {
- setInitialScrollComplete(true);
- }
- }}
- >
- {(row: ThreadRow) => <ThreadRowItem row={row} />}
- </VList>
- </Match>
- </Switch>
- <Show when={showJumpToUnviewedMessages() && unviewedMessages()}>
- {(messages) => (
- <DeprecatedTextButton
- icon={ArrowDownIcon}
- theme="base"
- onMouseDown={jumpToUnviewedMessages}
- text={`${messages().length} new message${messages().length === 1 ? '' : 's'}`}
- secondaryIcon={XIcon}
- onOptionClick={() => setDismissUnviewedMessages(true)}
- showSeparator
- class="absolute top-4 left-1/2 -translate-x-1/2"
- />
- )}
- </Show>
- <Show
- when={
- initialScrollComplete() &&
- !dismissJumpToLatest() &&
- !showJumpToUnviewedMessages() &&
- isScrolledBackSignificantly() &&
- isScrollingDown()
- }
- >
- <DeprecatedTextButton
- icon={ArrowDownIcon}
- theme="base"
- text="Jump to latest"
- onMouseDown={() =>
- debouncedScrollToBottomOrTarget({ forceBottom: true })
- }
- secondaryIcon={XIcon}
- onOptionClick={() => setDismissJumpToLatest(true)}
- showSeparator
- class="absolute top-4 left-1/2 -translate-x-1/2 transition-opacity duration-200"
- />
- </Show>
- <CustomScrollbar
- scrollContainer={listContext.scrollContainerRef}
- enabled={hasUserScrolled()}
- />
- </div>
- <ReplyInputsPortaler
- channelId={props.channelId}
- threads={viewThreads}
- threadInputAttachmentsStore={threadInputAttachmentsStore}
- setThreadInputAttachmentsStore={setThreadInputAttachmentsStore}
- setLocalTypingThreadId={setLocalTypingThreadId}
- participants={props.participants}
- />
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx b/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx
deleted file mode 100644
index 5dc247a9e6..0000000000
--- a/js/app/packages/block-channel/component/MessageList/TypingIndicator.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useBlockId } from '@core/block';
-import { Message } from '@core/component/Message';
-import { idToDisplayName } from '@core/user';
-import { getTypingUsersForChannel } from '@queries/channel/typing';
-import type { Message as MessageType } from '@queries/channel/types';
-import { createMemo, Show } from 'solid-js';
-
-type TypingIndicatorProps = {
- threadId?: string;
- previousMessage?: MessageType;
-};
-
-export function TypingIndicator(props: TypingIndicatorProps) {
- const channelId = useBlockId();
-
- const typingUsers = createMemo(() => {
- const users = getTypingUsersForChannel(channelId, props.threadId ?? null);
- return Array.from(users);
- });
-
- const typingText = () => {
- switch (typingUsers().length) {
- case 0: {
- return '';
- }
- case 1: {
- return `${idToDisplayName(typingUsers()[0])} is typing...`;
- }
- case 2: {
- return `${idToDisplayName(typingUsers()[0])} and ${idToDisplayName(typingUsers()[1])} are typing...`;
- }
- default: {
- return 'multiple people are typing...';
- }
- }
- };
-
- const isConsecutive = createMemo(() => {
- if (!props.previousMessage) return false;
- return (
- typingUsers().length === 1 &&
- props.previousMessage.sender_id === typingUsers()[0]
- );
- });
-
- return (
- <Show when={typingUsers().length > 0}>
- <Message
- senderId={typingUsers().length > 1 ? undefined : typingUsers()[0]}
- focused={false}
- isFirstMessage={false}
- isLastMessage={false}
- isFirstInThread={false}
- isLastInThread={false}
- isConsecutive={isConsecutive()}
- >
- <Message.TopBar name={typingText()} />
- <Message.Body>
- <div class="flex flex-row items-center font-mono text-xs">
- <div class="my-1.5 flex">
- <span class="animate-typing-dot [animation-delay:0ms]">.</span>
- <span class="animate-typing-dot [animation-delay:200ms]">.</span>
- <span class="animate-typing-dot [animation-delay:400ms]">.</span>
- </div>
- </div>
- </Message.Body>
- </Message>
- </Show>
- );
-}
diff --git a/js/app/packages/block-channel/component/ModalsProvider.tsx b/js/app/packages/block-channel/component/ModalsProvider.tsx
deleted file mode 100644
index 468fb197bc..0000000000
--- a/js/app/packages/block-channel/component/ModalsProvider.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { useBlockId } from '@core/block';
-import { NotificationsDrawer } from '@core/component/NotificationsModal';
-import { ChannelTypeEnum } from '@service-comms/client';
-import { createContext, createSignal, Show, useContext } from 'solid-js';
-import type { ParentProps } from 'solid-js';
-import { AttachmentsDrawer, useAttachments } from './AttachmentsModal';
-import type { Attachment } from '@queries/channel/types';
-import { ParticipantManagerDialog } from './ParticipantManager';
-import { useChannelContext } from '@block-channel/hooks/channel';
-import { CallProvider, CallOverlay, useCall } from '@channel/Call';
-
-type ChannelModalsContextValue = {
- openParticipants: () => void;
- attachments: () => Attachment[];
- joinCall: () => Promise<void>;
- leaveCall: () => Promise<void>;
- isInCall: () => boolean;
-};
-
-export const ChannelModalsContext = createContext<ChannelModalsContextValue>();
-
-export function useChannelModals() {
- const ctx = useContext(ChannelModalsContext);
- if (!ctx)
- throw new Error('useChannelModals must be used within ModalsProvider');
- return ctx;
-}
-
-export function ModalsProvider(props: ParentProps) {
- return (
- <CallProvider>
- <ModalsProviderInner>{props.children}</ModalsProviderInner>
- </CallProvider>
- );
-}
-
-function ModalsProviderInner(props: ParentProps) {
- const blockId = useBlockId();
- const notificationSource = useGlobalNotificationSource();
- const channelContext = useChannelContext();
- const [participantsOpen, setParticipantsOpen] = createSignal(false);
- const attachments = useAttachments();
- const call = useCall(() => blockId);
-
- return (
- <ChannelModalsContext.Provider
- value={{
- openParticipants: () => setParticipantsOpen(true),
- attachments,
- joinCall: call.joinCall,
- leaveCall: call.leaveCall,
- isInCall: call.isInThisChannel,
- }}
- >
- <div class="relative h-full">
- {props.children}
- <Show when={call.isInThisChannel()}>
- <div class="absolute inset-0 z-50">
- <CallOverlay onLeave={call.leaveCall} />
- </div>
- </Show>
- </div>
- <NotificationsDrawer
- entity={{ id: blockId, type: 'channel' }}
- notificationSource={notificationSource}
- />
- <AttachmentsDrawer attachments={attachments} />
- <Show
- when={channelContext.channelType() !== ChannelTypeEnum.DirectMessage}
- >
- <ParticipantManagerDialog
- open={participantsOpen()}
- onOpenChange={setParticipantsOpen}
- />
- </Show>
- </ChannelModalsContext.Provider>
- );
-}
diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
index 596d7d5848..9c1cdaca7e 100644
--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
@@ -28,7 +28,6 @@ import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTa
import { ChannelParticipantsTab } from '@channel/Participants/ChannelParticipantsTab';
import { ChannelDebouncedNotificationReadMarker } from '@notifications/components/DebouncedNotificationReadMarker';
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import type { BlockChannelProps } from './Block';
import {
CallProvider,
ChannelCallButton,
@@ -44,6 +43,8 @@ type ChannelTargetMessageParams = {
[URL_PARAMS.thread]?: string;
};
+export type BlockChannelProps = ChannelTargetMessageParams;
+
type ChannelPropsTargetMessage = Pick<
ChannelProps,
'targetMessageId' | 'targetMessageReplyId'
diff --git a/js/app/packages/block-channel/component/ParticipantManager.tsx b/js/app/packages/block-channel/component/ParticipantManager.tsx
deleted file mode 100644
index c5b6a2830c..0000000000
--- a/js/app/packages/block-channel/component/ParticipantManager.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import {
- useAddParticipantsToChannel,
- useRemoveParticipantsFromChannel,
-} from '@block-channel/hooks/participants';
-import { useChannelContext } from '@block-channel/hooks/channel';
-import { useBlockId } from '@core/block';
-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
-import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
-import { DialogWrapper } from '@core/component/DialogWrapper';
-import { getDestinationFromOptions } from '@core/component/NewMessage';
-import { RecipientSelector } from '@core/component/RecipientSelector';
-import { Tooltip } from '@core/component/Tooltip';
-import {
- idToEmail,
- recipientEntityMapper,
- useContacts,
- type WithCustomUserInput,
-} from '@core/user';
-import InvitedIcon from '@icon/regular/paper-plane-tilt.svg';
-import UsersIcon from '@icon/regular/users.svg';
-import CloseIcon from '@icon/regular/x.svg';
-import { Dialog } from '@kobalte/core/dialog';
-import BracketLeft from '@macro-icons/macro-group-bracket-left.svg';
-import type { ChannelParticipant } from '@queries/channel/types';
-import { ChannelType } from '@service-comms/generated/models/channelType';
-import { useUserId } from '@core/context/user';
-import { createMemo, createSignal, Show } from 'solid-js';
-import { VList } from 'virtua/solid';
-import { UserItem } from './UserItem';
-
-export function ParticipantManagerButton(props: { onClick: () => void }) {
- const channelContext = useChannelContext();
- const channelType = () => channelContext.channelType();
- const canManageParticipants = () =>
- channelType() !== ChannelType.organization;
- const title = () =>
- canManageParticipants() ? 'Manage Participants' : 'View Participants';
- const participantCount = () =>
- channelContext.channel()?.participants.length ?? 0;
-
- return (
- <Tooltip tooltip={title()}>
- <div
- class="flex items-center gap-1 py-1 font-mono text-xs text-ink-disabled hover:bg-hover relative"
- tabIndex={0}
- role="button"
- onClick={props.onClick}
- >
- <BracketLeft class="h-4 w-2 text-edge" />
- <UsersIcon class="size-4 text-ink" />
- <span class="text-xs">{participantCount().toString()}</span>
- <BracketLeft class="h-4 w-2 rotate-180 text-edge" />
- </div>
- </Tooltip>
- );
-}
-
-export function ParticipantManagerDialog(props: {
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}) {
- const blockId = useBlockId();
- const channelContext = useChannelContext();
- const users = useContacts();
- const userId = useUserId();
-
- const channelType = () => channelContext.channelType() ?? 'private';
- const participants = () => channelContext.channel()?.participants ?? [];
-
- const [usersToInvite, setUsersToInvite] = createSignal<
- WithCustomUserInput<'user'>[]
- >([]);
- const canManageParticipants = () =>
- channelType() !== ChannelType.organization;
- const addParticipantsToChannel = useAddParticipantsToChannel(() => blockId);
-
- function handleAddParticipants() {
- const destination = getDestinationFromOptions(usersToInvite());
- const userIds = destination.users;
- addParticipantsToChannel(userIds);
- setUsersToInvite([]);
- }
-
- const title = () =>
- canManageParticipants() ? 'Manage Participants' : 'View Participants';
-
- const options = () =>
- users()
- ?.filter((user) => {
- return !participants().find(
- (participant) => participant.user_id === user.id
- );
- })
- .map(recipientEntityMapper('user')) ?? [];
-
- return (
- <Dialog open={props.open} onOpenChange={props.onOpenChange}>
- <Dialog.Portal>
- <DialogWrapper>
- <div class="flex flex-row items-center px-2 h-[40px] gap-2 border-b-1 border-b-edge-muted">
- <Dialog.CloseButton>
- <DeprecatedIconButton
- tooltip={{ label: 'Close' }}
- icon={CloseIcon}
- iconSize={16}
- theme="clear"
- size="sm"
- />
- </Dialog.CloseButton>
- <Dialog.Title class="text-sm">{title()}</Dialog.Title>
- </div>
- <Show
- when={
- channelType() &&
- ['private'].includes(channelType()!) &&
- canManageParticipants()
- }
- >
- <div class="flex flex-row justify-between gap-2 min-h-[40px] text-ink-muted border-b border-edge-muted/50 p-2 items-center">
- <RecipientSelector<'user'>
- setSelectedOptions={setUsersToInvite}
- selectedOptions={usersToInvite()}
- placeholder={'Search'}
- options={options}
- hideBorder
- noPadding
- />
- <DeprecatedTextButton
- disabled={usersToInvite().length === 0}
- onClick={handleAddParticipants}
- icon={InvitedIcon}
- text={
- usersToInvite().length > 1
- ? 'Add Participants'
- : 'Add Participant'
- }
- theme="accent"
- />
- </div>
- </Show>
-
- <div class="flex flex-col">
- <ParticipantList
- channelId={blockId}
- editable={canManageParticipants()}
- participants={participants()}
- userId={userId()!}
- />
- </div>
- </DialogWrapper>
- </Dialog.Portal>
- </Dialog>
- );
-}
-
-function EmptyParticipantList(props: { query: string }) {
- return (
- <div class="flex flex-col items-center justify-center gap-2 text-ink-muted h-[300px] w-full">
- <div class="max-w-full px-4">
- <p class="whitespace-normal break-words">
- No matches found for "
- <span class="font-semibold break-all">{props.query}</span>"
- </p>
- </div>
- </div>
- );
-}
-
-export function ParticipantList(props: {
- channelId: string;
- participants: ChannelParticipant[];
- userId: string;
- editable: boolean;
-}) {
- let ref!: HTMLDivElement;
-
- const [searchQuery, setSearchQuery] = createSignal('');
- const removeParticipants = useRemoveParticipantsFromChannel(
- () => props.channelId
- );
-
- const filteredParticipants = createMemo(() => {
- if (searchQuery().trim().length === 0) return props.participants;
- return props.participants.filter((p) => {
- return (
- p.user_id.toLowerCase().includes(searchQuery().toLowerCase()) ||
- idToEmail(p.user_id).toLowerCase().includes(searchQuery().toLowerCase())
- );
- });
- });
-
- return (
- <div ref={ref} class="flex flex-col w-full">
- <Show when={props.participants.length > 10}>
- <input
- placeholder="Search"
- class="w-full border-edge-muted/50 border-b-1 px-2 h-[40px] text-sm text-ink-muted"
- value={searchQuery()}
- onInput={(e) => setSearchQuery(e.currentTarget.value)}
- />
- </Show>
- <div class="flex flex-col gap-3 max-h-[300px] w-full overflow-y-auto overflow-x-hidden">
- <Show
- when={filteredParticipants().length > 0}
- fallback={<EmptyParticipantList query={searchQuery()} />}
- >
- <VList
- data={filteredParticipants()}
- style={{
- 'scrollbar-width': 'none',
- height: '300px',
- width: '100%',
- }}
- bufferSize={500}
- >
- {(participant) => (
- <UserItem
- mountPoint={ref}
- id={participant.user_id}
- description={participant.role}
- currentUserId={props.userId}
- removeParticipant={() =>
- removeParticipants([participant.user_id])
- }
- editable={props.editable}
- />
- )}
- </VList>
- </Show>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/ReactionSelector.tsx b/js/app/packages/block-channel/component/ReactionSelector.tsx
deleted file mode 100644
index f00f5e1a13..0000000000
--- a/js/app/packages/block-channel/component/ReactionSelector.tsx
+++ /dev/null
@@ -1,256 +0,0 @@
-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
-import { EmojiSelector } from '@core/component/Emoji/EmojiSelector';
-import type { SimpleEmoji } from '@core/component/Emoji/emojis';
-import { resolveEmojiFromUnicode } from '@core/component/Emoji/emojis';
-import { DEV_MODE_ENV } from '@core/constant/featureFlags';
-import { ContextMenu } from '@kobalte/core/context-menu';
-import { Popover } from '@kobalte/core/popover';
-import SearchIcon from '@phosphor-icons/core/regular/magnifying-glass.svg?component-solid';
-import PlusIcon from '@phosphor-icons/core/regular/plus.svg';
-import SmileIcon from '@phosphor-icons/core/regular/smiley.svg?component-solid';
-import {
- createEffect,
- createSignal,
- For,
- Match,
- onMount,
- Show,
- Switch,
-} from 'solid-js';
-import { Dynamic } from 'solid-js/web';
-
-type ReactionQuickSelectorProps = {
- onEmojiClick: (emoji: SimpleEmoji) => void;
- setSearchOpen?: (open: boolean) => void;
- handleClose?: () => void;
- hideSearchButton?: boolean;
- insideMenu?: boolean;
- showFocusRing?: boolean;
-};
-
-export function ReactionQuickSelector(props: ReactionQuickSelectorProps) {
- const [selectedIndex, setSelectedIndex] = createSignal(-1);
- let containerRef: HTMLDivElement | undefined;
-
- const reactions = DEV_MODE_ENV
- ? ['❤️', '👍', '👎', '😂', '😡', '‼️', '🎫']
- : ['❤️', '👍', '👎', '😂', '😡', '‼️'];
-
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'ArrowLeft') {
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => {
- if (prev === -1) return reactions.length;
- return (prev - 1 + (reactions.length + 1)) % (reactions.length + 1);
- });
- } else if (e.key === 'ArrowRight') {
- e.preventDefault();
- e.stopPropagation();
- setSelectedIndex((prev) => {
- if (prev === -1) return 0;
- return (prev + 1) % (reactions.length + 1);
- });
- } else if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- e.stopPropagation();
- if (selectedIndex() === -1) return;
-
- if (selectedIndex() === reactions.length) {
- props.setSearchOpen?.(true);
- return;
- }
-
- const emoji = resolveEmojiFromUnicode(reactions[selectedIndex()]);
- if (emoji) {
- props.onEmojiClick(emoji);
- props.handleClose?.();
- }
- }
- };
-
- return (
- <Dynamic
- component={props.insideMenu ? ContextMenu.Item : 'div'}
- ref={containerRef}
- class={`w-fit flex items-center gap-1.5 px-4 py-2 bg-menu rounded-full shadow-lg border border-edge-muted ${props.showFocusRing ? 'focus-visible:focus-border' : ''}`}
- onKeyDown={handleKeyDown}
- tabIndex={-1}
- {...(props.insideMenu && {
- closeOnSelect: !(selectedIndex() === reactions.length + 1),
- })}
- >
- <For each={reactions}>
- {(reaction, index) => (
- <button
- class={`select-none rounded-full text-[32px]/[32px] hover:scale-110 transition-all duration-200 ${
- index() === selectedIndex()
- ? 'ring-2 ring-offset-4 ring-accent'
- : ''
- }`}
- onClick={() => {
- const emoji = resolveEmojiFromUnicode(reaction);
- if (emoji) props.onEmojiClick?.(emoji);
- props.handleClose?.();
- }}
- onTouchStart={() => {
- const emoji = resolveEmojiFromUnicode(reaction);
- if (emoji) props.onEmojiClick?.(emoji);
- props.handleClose?.();
- }}
- role="option"
- aria-selected={index() === selectedIndex()}
- >
- {reaction}
- </button>
- )}
- </For>
- <Show when={!props.hideSearchButton}>
- <DeprecatedIconButton
- icon={PlusIcon}
- iconSize={20}
- class={`h-8! w-8! bg-menu! hover:bg-hover! hover-transition-bg rounded-full! p-2 ${selectedIndex() === reactions.length ? 'ring-2 ring-offset-4 ring-accent' : ''}`}
- onClick={() => {
- props.setSearchOpen?.(true);
- }}
- onTouchStart={() => {
- props.setSearchOpen?.(true);
- }}
- tabIndex={selectedIndex() === reactions.length ? 0 : -1}
- role="button"
- aria-label="More reactions"
- />
- </Show>
- </Dynamic>
- );
-}
-
-type EmojiSearchSelectorProps = {
- onEmojiClick?: (emoji: SimpleEmoji) => void;
- handleClose: () => void;
- fullWidth?: boolean;
- insideMenu?: boolean;
-};
-
-export function EmojiSearchSelector(props: EmojiSearchSelectorProps) {
- const [input, setInput] = createSignal('');
- let searchInputRef: HTMLInputElement | undefined;
- let containerRef: HTMLDivElement | undefined;
-
- onMount(() => {
- setTimeout(() => {
- searchInputRef?.focus();
- }, 0);
- });
-
- createEffect(() => {
- if (containerRef && !containerRef.contains(document.activeElement)) {
- containerRef?.focus();
- }
- });
-
- return (
- <Dynamic
- component={props.insideMenu ? ContextMenu.Item : 'div'}
- class={`${props.fullWidth ? 'w-full' : 'w-[258px]'} h-[315px] pl-2 pt-2 rounded-md flex flex-col bg-menu shadow-lg border border-edge-muted`}
- role="dialog"
- aria-label="Emoji search"
- ref={containerRef}
- {...(props.insideMenu && { closeOnSelect: false })}
- >
- <div class="flex pr-2 w-full">
- <div class="flex flex-row items-center text-ink gap-1 border border-edge-muted rounded-md px-2 py-1 text-xs w-full">
- <SearchIcon class="w-3 h-3" />
- <input
- ref={searchInputRef}
- value={input()}
- onInput={(e) => setInput(e.target.value)}
- placeholder="Search emojis"
- role="searchbox"
- aria-label="Search emojis"
- />
- </div>
- </div>
- <div class="flex-grow overflow-y-auto overflow-x-hidden mt-2">
- <EmojiSelector
- nameFilter={input()}
- onEmojiClick={(emoji) => {
- props.onEmojiClick?.(emoji);
- props.handleClose();
- }}
- />
- </div>
- </Dynamic>
- );
-}
-
-type ReactionSelectorProps = {
- onEmojiClick: (emoji: SimpleEmoji) => void;
- onOpenChange?: (isOpen: boolean) => void;
-};
-
-export function ReactionSelector(props: ReactionSelectorProps) {
- let searchInputRef: HTMLInputElement | undefined;
-
- const [openPopover, setOpenPopover] = createSignal(false);
-
- const [searchOpen, setSearchOpen] = createSignal(false);
-
- createEffect(() => {
- if (searchOpen()) {
- setTimeout(() => {
- if (searchInputRef) {
- searchInputRef.focus();
- }
- });
- }
- });
-
- const handleClose = () => {
- setSearchOpen(false);
- setOpenPopover(false);
- };
-
- const onOpenChange = (isOpen: boolean) => {
- if (!isOpen) {
- handleClose();
- }
- setOpenPopover(isOpen);
- props.onOpenChange?.(isOpen);
- };
-
- return (
- <Popover
- placement="top"
- onOpenChange={onOpenChange}
- overflowPadding={8}
- slide={true}
- open={openPopover()}
- >
- <Popover.Trigger tabIndex={-1}>
- <DeprecatedIconButton icon={SmileIcon} tabIndex={-1} />
- </Popover.Trigger>
-
- <Popover.Portal>
- <Popover.Content class="z-modal">
- <Popover.Arrow class="fill-menu" />
- <Switch>
- <Match when={!searchOpen()}>
- <ReactionQuickSelector
- onEmojiClick={props.onEmojiClick}
- setSearchOpen={setSearchOpen}
- handleClose={handleClose}
- />
- </Match>
- <Match when={searchOpen()}>
- <EmojiSearchSelector
- onEmojiClick={props.onEmojiClick}
- handleClose={handleClose}
- />
- </Match>
- </Switch>
- </Popover.Content>
- </Popover.Portal>
- </Popover>
- );
-}
diff --git a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
deleted file mode 100644
index 3494d08fa0..0000000000
--- a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import { useMessageListContext } from '@block-channel/component/MessageList/MessageList';
-import {
- type SendMessageArgs,
- useSendChannelMessage,
-} from '@block-channel/hooks/message';
-import type { MessageWithThreadId } from '@block-channel/signal/threads';
-import {
- clearDraftMessage,
- loadDraftMessage,
- saveDraftMessage,
-} from '@block-channel/utils/draftMessages';
-import { blockElementSignal } from '@core/signal/blockElement';
-import type { InputAttachment } from '@core/store/cacheChannelInput';
-import { channelParticipantInfo } from '@core/user/util';
-import { usePostTypingUpdateMutation } from '@queries/channel/typing';
-import type { ChannelParticipant } from '@queries/channel/types';
-import {
- createEffect,
- createMemo,
- createSignal,
- For,
- type Setter,
-} from 'solid-js';
-import type { SetStoreFunction } from 'solid-js/store';
-import { Portal } from 'solid-js/web';
-import { BaseInput } from './BaseInput';
-
-export type ThreadStoreData = Record<string, MessageWithThreadId[]>;
-
-export type ReplyInputsPortalerProps = {
- channelId: string;
- threads: ThreadStoreData;
- threadInputAttachmentsStore: Record<string, InputAttachment[]>;
- setThreadInputAttachmentsStore: SetStoreFunction<
- Record<string, InputAttachment[]>
- >;
- setLocalTypingThreadId?: Setter<string | undefined>;
- participants: ChannelParticipant[];
-};
-
-export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
- const listContext = useMessageListContext();
- const sendMessage = useSendChannelMessage(() => props.channelId);
- const typingMutation = usePostTypingUpdateMutation();
-
- const blockRef = blockElementSignal.get;
-
- const channelUsers = () => props.participants.map(channelParticipantInfo);
-
- const [focusedReplyInputThreadId, setFocusedReplyInputThreadId] =
- createSignal<string>();
-
- const onSend = (threadId: string) => async (args: SendMessageArgs) => {
- clearDraftMessage(props.channelId, 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.
- setTimeout(() => {
- const list = listContext.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
- listContext.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);
- };
-
- const closeDraft = (threadId: string) => () => {
- clearDraftMessage(props.channelId, threadId);
- listContext.closeThreadReply(threadId, true);
- };
-
- const onFocusLeaveStart = (e: KeyboardEvent, threadId: string) => {
- e.preventDefault();
- e.stopPropagation();
- const orderedMessages = listContext
- .orderedMessages()
- .filter((item) => item.thread_id === threadId);
- if (!orderedMessages.length) return;
- const lastMessageId = orderedMessages[orderedMessages.length - 1].id;
- const lastMessageBody = blockRef()?.querySelector(
- `[data-message-body-id="${lastMessageId}"]`
- );
- if (!lastMessageBody) return;
- (lastMessageBody as HTMLElement).focus();
- };
-
- let replyFocusTimeout: ReturnType<typeof setTimeout> | undefined;
-
- return (
- <For each={listContext.getThreadsWithActiveReplies()}>
- {(threadId) => {
- const threadState = createMemo(() =>
- listContext.getThreadState(threadId)
- );
- // This create effect maintains focus on reply inputs when the mount target changes due to new messages in the thread coming in
- // TODO: this should only fire if this reply input was focused
- createEffect((prev) => {
- const state = threadState();
- if (
- focusedReplyInputThreadId() === threadId &&
- state?.replyInputMountTarget &&
- prev &&
- prev !== state?.replyInputMountTarget
- ) {
- listContext.toggleReplyInputFocus(threadId, true);
- }
- return state?.replyInputMountTarget;
- });
- return (
- <Portal mount={threadState()?.replyInputMountTarget ?? document.body}>
- <div
- classList={{
- 'fixed top-0 left-0 width-[1px] height-[1px] overflow-hidden opacity-0 pointer-events-none':
- !threadState()?.replyInputMountTarget,
- }}
- >
- <BaseInput
- onSend={onSend(threadId)}
- placeholder={`Send a reply`}
- autoFocusOnMount={false}
- shouldFocus={threadState()?.replyInputShouldFocus}
- clearShouldFocus={() =>
- listContext.toggleReplyInputFocus(threadId, false)
- }
- onFocus={() => {
- if (replyFocusTimeout) clearTimeout(replyFocusTimeout);
- setFocusedReplyInputThreadId(threadId);
- }}
- onBlur={() => {
- replyFocusTimeout = setTimeout(() => {
- setFocusedReplyInputThreadId(undefined);
- }, 100);
- }}
- onStartTyping={() =>
- typingMutation.mutate({
- channelId: props.channelId,
- action: 'start',
- threadId,
- })
- }
- onStopTyping={() =>
- typingMutation.mutate({
- channelId: props.channelId,
- action: 'stop',
- threadId,
- })
- }
- inputAttachments={{
- store: props.threadInputAttachmentsStore,
- setStore: props.setThreadInputAttachmentsStore,
- key: threadId,
- }}
- channelUsers={channelUsers}
- setLocalTyping={
- props.setLocalTypingThreadId
- ? (isTyping) =>
- props.setLocalTypingThreadId?.(
- isTyping ? threadId : undefined
- )
- : undefined
- }
- onChange={(content) =>
- saveDraftMessage(props.channelId, {
- content,
- attachments:
- props.threadInputAttachmentsStore[threadId] ?? [],
- threadId,
- })
- }
- initialValue={() =>
- loadDraftMessage(props.channelId, threadId)?.content ?? ''
- }
- onFocusLeaveStart={(e) => {
- onFocusLeaveStart(e, threadId);
- }}
- closeDraft={closeDraft(threadId)}
- isReplyInput
- />
- </div>
- </Portal>
- );
- }}
- </For>
- );
-}
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index 90ed15be14..b365e07cd1 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -1,43 +1,16 @@
-import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
-import type { BlockTool } from '@app/component/ResponsiveBlockToolbar';
-import { ResponsiveBlockToolbar } from '@app/component/ResponsiveBlockToolbar';
-import {
- SplitHeaderLeft,
- SplitHeaderRight,
-} from '@app/component/split-layout/components/SplitHeader';
+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
import { SplitLabel } from '@app/component/split-layout/components/SplitLabel';
import { useBlockId } from '@core/block';
import { useChannelName } from '@core/context/channels';
-import { BlockLiveIndicators } from '@core/component/LiveIndicators';
-import {
- NotificationsButton,
- NOTIFICATIONS_DRAWER_ID,
-} from '@core/component/NotificationsModal';
-import { toast } from '@core/component/Toast/Toast';
import { UserIcon } from '@core/component/UserIcon';
-import { buildSimpleEntityUrl } from '@core/util/url';
-import Bell from '@icon/regular/bell.svg';
import HashIcon from '@icon/regular/hash.svg';
-import LinkIcon from '@icon/regular/link.svg';
-import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';
-import PhoneIcon from '@icon/regular/phone.svg';
-import PhoneDisconnectIcon from '@icon/regular/phone-disconnect.svg';
-import UsersIcon from '@icon/regular/users.svg';
import type { ChannelParticipant } from '@queries/channel/types';
import type { ChannelType } from '@service-comms/generated/models/channelType';
import { ChannelTypeEnum } from '@service-comms/client';
import { useUserId } from '@core/context/user';
-import { type Component, createMemo, Show } from 'solid-js';
-import { AttachmentsButton } from './AttachmentsModal';
-import { useChannelContext } from '@block-channel/hooks/channel';
-import { isChannelAdminOrOwner } from '@queries/channel/derived';
-import { useChannelModals } from './ModalsProvider';
-import { ParticipantManagerButton } from './ParticipantManager';
-import { useAnalytics } from '@app/component/analytics-context';
+import { Show } from 'solid-js';
import { Tabs, type TabItem } from '@core/component/Tabs';
import type { ChannelTabId } from '@channel/Channel/channel-tabs';
-import { ENABLE_CALLS } from '@core/constant/featureFlags';
type TopIconProps = {
channelType: ChannelType;
@@ -113,140 +86,3 @@ export function ChannelTopLeft(props: ChannelTopLeftProps) {
</SplitHeaderLeft>
);
}
-
-const CallIcon: Component = (iconProps) => {
- const channelModals = useChannelModals();
- return (
- <Show
- when={channelModals.isInCall()}
- fallback={<PhoneIcon {...iconProps} />}
- >
- <PhoneDisconnectIcon {...iconProps} />
- </Show>
- );
-};
-
-export function Top(props: TopProps) {
- const analytics = useAnalytics();
-
- const blockId = useBlockId();
- const notificationSource = useGlobalNotificationSource();
- const channelContext = useChannelContext();
-
- const notificationsControl = useDrawerControl(NOTIFICATIONS_DRAWER_ID);
- const attachmentsControl = useDrawerControl('attachments');
- const channelModals = useChannelModals();
-
- const isAdminOrOwner = createMemo(() => {
- const channelData = channelContext.channel();
- return isChannelAdminOrOwner(channelData);
- });
-
- function handleCopyLink() {
- navigator.clipboard.writeText(
- buildSimpleEntityUrl({
- type: 'channel',
- id: blockId,
- })
- );
- toast.success('Link copied to clipboard');
- }
- const channelName = useChannelName(
- blockId,
- props.channelName ?? 'New Channel'
- );
-
- const tools: BlockTool[] = [
- {
- label: 'Copy Link',
- icon: LinkIcon,
- action: handleCopyLink,
- condition: () => props.channelType === ChannelTypeEnum.Public,
- },
- {
- label: 'Notifications',
- icon: Bell,
- action: notificationsControl.toggle,
- buttonComponent: () => (
- <NotificationsButton
- entity={{ id: blockId, type: 'channel' }}
- notificationSource={notificationSource}
- onOpenChange={(open) =>
- open &&
- analytics.track('notifications_panel_open', {
- blockType: 'channel',
- })
- }
- />
- ),
- },
- {
- label: 'Attachments',
- icon: PaperclipIcon,
- action: attachmentsControl.toggle,
- buttonComponent: () => (
- <AttachmentsButton attachments={channelModals.attachments} />
- ),
- },
- {
- label: () => (channelModals.isInCall() ? 'Leave Call' : 'Call'),
- icon: CallIcon,
- action: (() => {
- let isTogglingCall = false;
- return async () => {
- if (isTogglingCall) return;
- isTogglingCall = true;
- try {
- if (channelModals.isInCall()) {
- await channelModals.leaveCall();
- } else {
- await channelModals.joinCall();
- }
- } catch (e) {
- console.error('Call action failed', e);
- } finally {
- isTogglingCall = false;
- }
- };
- })(),
- isActive: () => channelModals.isInCall(),
- condition: () => ENABLE_CALLS(),
- },
- {
- label: 'Participants',
- icon: UsersIcon,
- action: () => channelModals.openParticipants(),
- condition: () => props.channelType !== ChannelTypeEnum.DirectMessage,
- buttonComponent: () => (
- <ParticipantManagerButton onClick={channelModals.openParticipants} />
- ),
- },
- ];
-
- return (
- <>
- <ChannelTopLeft
- channelId={props.channelId}
- channelType={props.channelType}
- participants={props.participants}
- channelName={props.channelName}
- lockRename={
- props.channelType === ChannelTypeEnum.DirectMessage ||
- !isAdminOrOwner()
- }
- />
-
- <SplitHeaderRight>
- <BlockLiveIndicators />
- </SplitHeaderRight>
-
- <ResponsiveBlockToolbar
- tools={tools}
- ops={[]}
- id={blockId}
- itemType="channel"
- name={channelName() ?? 'New Channel'}
- />
- </>
- );
-}
diff --git a/js/app/packages/block-channel/component/UserIconWithContact.tsx b/js/app/packages/block-channel/component/UserIconWithContact.tsx
deleted file mode 100644
index aafba7b722..0000000000
--- a/js/app/packages/block-channel/component/UserIconWithContact.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { UserIcon } from '@core/component/UserIcon';
-import { idToEmail } from '@core/user';
-import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
-import type { Component } from 'solid-js';
-import { useSplitLayout } from '../../app/component/split-layout/layout';
-
-interface UserIconWithContactProps {
- userId: string;
- size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'fill';
- class?: string;
-}
-
-export const UserIconWithContact: Component<UserIconWithContactProps> = (
- props
-) => {
- const { replaceOrInsertSplit } = useSplitLayout();
-
- const handleClick = (e: MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
-
- // Extract email from user ID
- const email = idToEmail(props.userId);
-
- // Open contact block with the email
- replaceOrInsertSplit({ type: 'contact', id: email });
- };
-
- const navHandlers = useSplitNavigationHandler(handleClick);
-
- return (
- <div {...navHandlers} class="cursor-pointer" title="View contact">
- <UserIcon id={props.userId} size={props.size} isDeleted={false} />
- </div>
- );
-};
diff --git a/js/app/packages/block-channel/component/UserItem.tsx b/js/app/packages/block-channel/component/UserItem.tsx
deleted file mode 100644
index 22035f0896..0000000000
--- a/js/app/packages/block-channel/component/UserItem.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { BozzyBracket } from '@core/component/BozzyBracket';
-import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
-import { TruncatedText } from '@core/component/FileList/TruncatedText';
-import { UserIcon } from '@core/component/UserIcon';
-import { idToEmail } from '@core/user';
-import IconX from '@icon/regular/x.svg';
-import { createSignal, Show } from 'solid-js';
-
-export type UserItemProps = {
- id: string;
- description: string;
- currentUserId?: string;
- mountPoint?: HTMLDivElement;
- removeParticipant?: () => void;
- editable?: boolean;
-};
-
-export function UserItem(props: UserItemProps) {
- const [hovered, setHovered] = createSignal(false);
-
- return (
- <BozzyBracket hover={hovered()} active={false} class="w-full">
- <div
- class={`flex group flex-row items-center justify-between overflow-x-hidden w-full p-2`}
- onMouseEnter={() => setHovered(true)}
- onMouseLeave={() => setHovered(false)}
- >
- <div class="flex flex-row gap-2 items-center w-full">
- <UserIcon id={props.id} size="md" isDeleted={false} />
- <div class="flex flex-col gap-0 w-full">
- <TruncatedText>
- <p class="text-sm">{idToEmail(props.id)}</p>
- </TruncatedText>
- <p class="text-xs text-ink-muted">{props.description}</p>
- </div>
- </div>
- <Show
- when={props.currentUserId !== props.id && props.editable && hovered()}
- >
- <DeprecatedIconButton
- tooltip={{ label: 'Remove participant' }}
- icon={IconX}
- iconSize={16}
- theme="clear"
- size="sm"
- onClick={props.removeParticipant}
- />
- </Show>
- </div>
- </BozzyBracket>
- );
-}
diff --git a/js/app/packages/block-channel/constants.ts b/js/app/packages/block-channel/constants.ts
index 3052aad99a..1894d60f31 100644
--- a/js/app/packages/block-channel/constants.ts
+++ b/js/app/packages/block-channel/constants.ts
@@ -2,9 +2,3 @@ export const URL_PARAMS = {
thread: 'channel_thread_id',
message: 'channel_message_id',
};
-
-// The index of the last message in a collapsed thread that will be shown
-export const COLLAPSED_THREAD_INDEX_CUTOFF = 2;
-
-// The time in milliseconds that a target message will be active before it is considered stale.
-export const TARGET_MESSAGE_ACTIVE_TIME = 800;
diff --git a/js/app/packages/block-channel/definition.ts b/js/app/packages/block-channel/definition.ts
index 2f4f589d3c..bbda9cbad5 100644
--- a/js/app/packages/block-channel/definition.ts
+++ b/js/app/packages/block-channel/definition.ts
@@ -1,19 +1,14 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { ok } from '@core/util/maybeResult';
-import { fetchAndCacheChannel } from '@queries/channel/channel';
-import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
-import { ChannelBlockSwitch } from './component/ChannelBlockSwitch';
+import { NewChannelBlockAdapter } from './component/NewChannelBlockAdapter';
export const definition = defineBlock({
name: 'channel',
description: '',
- component: ChannelBlockSwitch,
+ component: NewChannelBlockAdapter,
liveTrackingEnabled: true,
async load(source, _intent) {
if (source.type === 'dss') {
- if (!ENABLE_NEW_CHANNELS()) {
- await fetchAndCacheChannel(source.id);
- }
return ok({ id: source.id });
}
return LoadErrors.MISSING;
diff --git a/js/app/packages/block-channel/hooks/channel.tsx b/js/app/packages/block-channel/hooks/channel.tsx
deleted file mode 100644
index 9788449725..0000000000
--- a/js/app/packages/block-channel/hooks/channel.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { createAssertedContextProvider } from '@core/context/createContext';
-import type { useChannelQuery } from '@queries/channel/channel';
-import {
- getThreadMessages,
- getTopLevelMessages,
-} from '@queries/channel/derived';
-import type {
- ChannelType,
- GetChannelResponseReactions,
-} from '@service-comms/generated/models';
-import type {
- Attachment,
- GetChannelResponse,
- Message,
-} from '@queries/channel/types';
-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 = {
- query: ReturnType<typeof useChannelQuery>;
-};
-
-export const [ChannelContextProvider, useChannelContext] =
- createAssertedContextProvider<ChannelContextValue>(
- 'ChannelContext',
- (props: ChannelContextProps): ChannelContextValue => {
- const channel = createMemo(() => props.query.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/hooks/participants.tsx b/js/app/packages/block-channel/hooks/participants.tsx
deleted file mode 100644
index 8bbb691dc7..0000000000
--- a/js/app/packages/block-channel/hooks/participants.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useAnalytics } from '@app/component/analytics-context';
-import {
- useAddParticipantsMutation,
- useRemoveParticipantsMutation,
-} from '@queries/channel/participants';
-import type { Accessor } from 'solid-js';
-
-/**
- * Hook to add participants to a channel with optimistic updates
- */
-export function useAddParticipantsToChannel(channelId: Accessor<string>) {
- const analytics = useAnalytics();
-
- const mutation = useAddParticipantsMutation({
- onSuccess: () => {
- analytics.track('channel_participant_add');
- },
- });
-
- return (participants: string[]) => {
- const id = channelId();
- if (!id) {
- console.error(
- 'tried to add participants to a channel that does not exist'
- );
- return;
- }
-
- mutation.mutate({ channelId: id, participants });
- };
-}
-
-/**
- * Hook to remove participants from a channel with optimistic updates
- */
-export function useRemoveParticipantsFromChannel(channelId: Accessor<string>) {
- const analytics = useAnalytics();
-
- const mutation = useRemoveParticipantsMutation({
- onSuccess: () => {
- analytics.track('channel_participant_remove');
- },
- });
-
- return (participants: string[]) => {
- const id = channelId();
- if (!id) {
- console.error(
- 'tried to remove participants from a channel that does not exist'
- );
- return;
- }
-
- mutation.mutate({ channelId: id, participants });
- };
-}
diff --git a/js/app/packages/block-channel/hooks/reactions.tsx b/js/app/packages/block-channel/hooks/reactions.tsx
deleted file mode 100644
index c424772cb7..0000000000
--- a/js/app/packages/block-channel/hooks/reactions.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useUserId } from '@core/context/user';
-import {
- useAddReactionMutation,
- useRemoveReactionMutation,
-} from '@queries/channel/reaction';
-import type { Accessor } from 'solid-js';
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-import { useAnalytics } from '@app/component/analytics-context';
-
-type CountedReaction = {
- emoji: string;
- users: string[];
-};
-
-/**
- * Hook to react to a message. Uses the reaction mutations with optimistic updates.
- */
-export function useReactToMessage(
- channelId: Accessor<string>,
- reactions: Accessor<GetChannelResponseReactions>
-) {
- const analytics = useAnalytics();
- const userId_ = useUserId();
-
- const addReaction = useAddReactionMutation();
- const removeReaction = useRemoveReactionMutation();
-
- return async (emoji: string, messageId: string) => {
- const userId = userId_();
- const channelIdValue = channelId();
- if (!channelIdValue || !userId) return;
-
- const messageReactions = reactions()?.[messageId] ?? [];
- const hasReacted = messageReactions.some(
- (reaction: CountedReaction) =>
- reaction.emoji === emoji && reaction.users.includes(userId)
- );
-
- if (hasReacted) {
- await removeReaction.mutateAsync({
- channelId: channelIdValue,
- messageId,
- emoji,
- userId,
- });
- } else {
- await addReaction.mutateAsync({
- channelId: channelIdValue,
- messageId,
- emoji,
- userId,
- });
- }
-
- analytics.track('channel_reaction', {
- emoji,
- action: hasReacted ? 'remove' : 'add',
- });
- };
-}
diff --git a/js/app/packages/block-channel/signal/threads.ts b/js/app/packages/block-channel/signal/threads.ts
deleted file mode 100644
index 7e2a316e28..0000000000
--- a/js/app/packages/block-channel/signal/threads.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import type { Message } from '@queries/channel/types';
-
-export type MessageWithThreadId = Message & {
- thread_id: NonNullable<Message['thread_id']>;
-};
diff --git a/js/app/packages/block-channel/tests/listContext.test.ts b/js/app/packages/block-channel/tests/listContext.test.ts
deleted file mode 100644
index 466fe53c25..0000000000
--- a/js/app/packages/block-channel/tests/listContext.test.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- createMessageListContextLookup,
- type MinimalMessage,
-} from '../utils/listContext';
-
-describe('createMessageListContextLookup', () => {
- const mockMessages: MinimalMessage[] = [
- {
- id: 'msg0',
- created_at: '2024-01-01T10:00:00Z',
- sender_id: 'user1',
- },
- {
- id: 'msg1',
- created_at: '2024-01-01T10:00:00Z',
- sender_id: 'user1',
- },
- {
- id: 'msg2',
- created_at: '2024-01-01T10:01:00Z',
- sender_id: 'user2',
- thread_id: 'msg1',
- },
- {
- id: 'msg3',
- created_at: '2024-01-01T10:02:00Z',
- sender_id: 'user1',
- thread_id: 'msg1',
- },
- {
- id: 'msg4',
- created_at: '2024-01-01T10:03:00Z',
- sender_id: 'user3',
- },
- ];
-
- const neverNewMessage = () => false;
- const alwaysNewMessage = () => true;
-
- it('should create context for all messages', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: neverNewMessage,
- });
-
- expect(Object.keys(context)).toHaveLength(5);
- expect(context).toHaveProperty('msg0');
- expect(context).toHaveProperty('msg1');
- expect(context).toHaveProperty('msg2');
- expect(context).toHaveProperty('msg3');
- expect(context).toHaveProperty('msg4');
- });
-
- it('should set correct indices', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: neverNewMessage,
- });
-
- expect(context.msg0.index).toBe(0);
- expect(context.msg1.index).toBe(1);
- expect(context.msg2.index).toBe(2);
- expect(context.msg3.index).toBe(3);
- expect(context.msg4.index).toBe(4);
- });
-
- it('should calculate thread indices correctly', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: neverNewMessage,
- });
-
- expect(context.msg0.threadIndex).toBe(-1);
- expect(context.msg1.threadIndex).toBe(-1);
- expect(context.msg2.threadIndex).toBe(0);
- expect(context.msg3.threadIndex).toBe(1);
- expect(context.msg4.threadIndex).toBe(-1);
- });
-
- it('should identify new messages for all messages including threaded', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: alwaysNewMessage,
- });
-
- expect(context.msg0.isNewMessage).toBe(true);
- expect(context.msg1.isNewMessage).toBe(true);
- expect(context.msg2.isNewMessage).toBe(true);
- expect(context.msg3.isNewMessage).toBe(true);
- expect(context.msg4.isNewMessage).toBe(true);
- });
-
- it('should set previous non-threaded messages correctly', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: neverNewMessage,
- });
-
- expect(context.msg1.previousNonThreadedMessage?.id).toBe('msg0');
- expect(context.msg2.previousNonThreadedMessage?.id).toBe('msg0');
- expect(context.msg3.previousNonThreadedMessage?.id).toBe('msg0');
- expect(context.msg4.previousNonThreadedMessage?.id).toBe('msg1');
- });
-
- it('should identify parent new messages', () => {
- const isMsg1New = (msg: MinimalMessage) => {
- return msg.thread_id ? msg.thread_id === 'msg1' : msg.id === 'msg1';
- };
-
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: isMsg1New,
- });
-
- expect(context.msg1.isNewMessage).toBe(true);
- expect(context.msg1.isParentNewMessage).toBe(false);
- expect(context.msg2.isParentNewMessage).toBe(true);
- expect(context.msg3.isParentNewMessage).toBe(true);
- expect(context.msg4.isParentNewMessage).toBe(false);
- });
-
- it('should mark only the first new top-level message as isFirstNewMessage', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: alwaysNewMessage,
- });
-
- // msg0 is the first top-level message marked as new
- // threaded messages (msg2, msg3) are new but not isFirstNewMessage
- expect(context.msg0.isFirstNewMessage).toBe(true);
- expect(context.msg1.isFirstNewMessage).toBe(false);
- expect(context.msg2.isFirstNewMessage).toBe(false);
- expect(context.msg3.isFirstNewMessage).toBe(false);
- expect(context.msg4.isFirstNewMessage).toBe(false);
- });
-
- it('should not mark any message as isFirstNewMessage when none are new', () => {
- const context = createMessageListContextLookup({
- messages: mockMessages,
- isNewMessageFn: neverNewMessage,
- });
-
- expect(context.msg0.isFirstNewMessage).toBe(false);
- expect(context.msg1.isFirstNewMessage).toBe(false);
- expect(context.msg4.isFirstNewMessage).toBe(false);
- });
-
- it('should identify messages in the last thread when messages are threaded to last top-level', () => {
- const messagesWithLastThread: MinimalMessage[] = [
- {
- id: 'msg0',
- created_at: '2024-01-01T10:00:00Z',
- sender_id: 'user1',
- },
- {
- id: 'msg1',
- created_at: '2024-01-01T10:01:00Z',
- sender_id: 'user2',
- },
- {
- id: 'msg2',
- created_at: '2024-01-01T10:02:00Z',
- sender_id: 'user3',
- thread_id: 'msg1',
- },
- {
- id: 'msg3',
- created_at: '2024-01-01T10:03:00Z',
- sender_id: 'user1',
- thread_id: 'msg1',
- },
- ];
-
- const context = createMessageListContextLookup({
- messages: messagesWithLastThread,
- isNewMessageFn: neverNewMessage,
- });
-
- // msg1 is the last top-level message
- expect(context.msg0.isInLastThread).toBe(false);
- expect(context.msg1.isInLastThread).toBe(false);
-
- // msg2 and msg3 are threaded to msg1, which is the last top-level message
- expect(context.msg2.isInLastThread).toBe(true);
- expect(context.msg3.isInLastThread).toBe(true);
- });
-});
diff --git a/js/app/packages/block-channel/type/threadView.ts b/js/app/packages/block-channel/type/threadView.ts
deleted file mode 100644
index 2bf7ba7ac6..0000000000
--- a/js/app/packages/block-channel/type/threadView.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export type ThreadView = {
- threadExpanded: boolean;
- hasActiveReply: boolean;
- replyInputMountTarget?: HTMLElement | undefined;
- replyInputShouldFocus?: boolean;
-};
-
-export type ThreadViewData = Record<string, ThreadView>;
diff --git a/js/app/packages/block-channel/type/typingIndicatorMessage.ts b/js/app/packages/block-channel/type/typingIndicatorMessage.ts
deleted file mode 100644
index 35e34c4b1a..0000000000
--- a/js/app/packages/block-channel/type/typingIndicatorMessage.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import type { Message } from '@queries/channel/types';
-
-export type TypingIndicatorMessage = Partial<Message> & {
- typingUsers: string[];
- created_at: Date;
-};
diff --git a/js/app/packages/block-channel/utils/attachments.ts b/js/app/packages/block-channel/utils/attachments.ts
deleted file mode 100644
index 9aaf0cc393..0000000000
--- a/js/app/packages/block-channel/utils/attachments.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { isStaticAttachmentType } from '@core/store/cacheChannelInput';
-import type { Attachment } from '@queries/channel/types';
-import { isItemType } from '@service-storage/client';
-
-/**
- * Filter out unsafe attachments that might have been sent with block names
- * instead of itemTypes as the entity type.
- */
-export function isSafeAttachment(attachment: Attachment) {
- if (isStaticAttachmentType(attachment.entity_type)) return true;
- if (isItemType(attachment.entity_type)) return true;
- return false;
-}
-
-/**
- * Filter attachments to only safe ones
- */
-export function filterSafeAttachments(attachments: Attachment[]): Attachment[] {
- return attachments.filter(isSafeAttachment);
-}
diff --git a/js/app/packages/block-channel/utils/listContext.ts b/js/app/packages/block-channel/utils/listContext.ts
deleted file mode 100644
index d5a8156680..0000000000
--- a/js/app/packages/block-channel/utils/listContext.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import type { DateValue } from '@core/util/date';
-import type { Message } from '@queries/channel/types';
-
-export type MinimalMessage = {
- id: string;
- created_at: DateValue;
- sender_id: string;
- thread_id?: string | null;
-};
-
-export type MessageListContext<T extends MinimalMessage = Message> = {
- index: number;
- isNewMessage: boolean;
- isParentNewMessage: boolean;
- /** True only for the first (oldest) new message — where the "New" indicator should appear */
- isFirstNewMessage: boolean;
- threadIndex: number;
- /** The previous non-threaded message outside of the current thread */
- previousNonThreadedMessage: T | undefined;
- /** True if the message is in a thread and the parent is the last top-level message */
- isInLastThread: boolean;
-};
-
-export type MessageListContextLookup<T extends MinimalMessage = Message> =
- Record<string, MessageListContext<T>>;
-
-function findLastNonThreadedMessageIndex(
- messages: MinimalMessage[],
- fromIndex: number
-) {
- for (let i = fromIndex; i >= 0; i--) {
- const message = messages[i];
- if (!message.thread_id) {
- return i;
- }
- }
- return -1;
-}
-
-export function createMessageListContextLookup<
- T extends MinimalMessage = Message,
->({
- messages,
- isNewMessageFn,
-}: {
- messages: T[];
- isNewMessageFn: (message: T) => boolean;
-}) {
- const context: MessageListContextLookup<T> = {};
- const threadIndexCounters = new Map<string, number>();
- const messagesById = new Map<string, [number, T]>();
- let foundFirstNewMessage = false;
-
- for (const [index, message] of messages.entries()) {
- messagesById.set(message.id, [index, message]);
- }
-
- // Find the last top-level message (last message without a thread_id)
- let lastTopLevelMessageId: string | undefined;
- for (let i = messages.length - 1; i >= 0; i--) {
- if (!messages[i].thread_id) {
- lastTopLevelMessageId = messages[i].id;
- break;
- }
- }
-
- for (const [messageIndex, message] of messages.entries()) {
- const isNewMessage = isNewMessageFn(message);
- let threadIndex = -1;
- let previousNonThreadedMessage: T | undefined;
- let isParentNewMessage = false;
- let backTrackIndex = messageIndex;
-
- if (message.thread_id) {
- const foundParent = messagesById.get(message.thread_id);
-
- if (foundParent) {
- const [parentIndex, parentMessage] = foundParent;
- backTrackIndex = parentIndex;
- isParentNewMessage = isNewMessageFn(parentMessage);
-
- const currentCount = threadIndexCounters.get(message.thread_id) || 0;
- threadIndex = currentCount;
- threadIndexCounters.set(message.thread_id, currentCount + 1);
- } else {
- console.error(
- 'expected parent message for threaded message not found',
- message
- );
- }
- }
-
- if (messagesById.has(message.id)) {
- const previousNonThreadedMessageIndex = findLastNonThreadedMessageIndex(
- messages,
- backTrackIndex - 1
- );
-
- if (previousNonThreadedMessageIndex >= 0) {
- previousNonThreadedMessage = messages[previousNonThreadedMessageIndex];
- }
- }
-
- // Check if message is in the last thread
- const isInLastThread =
- message.thread_id !== null &&
- message.thread_id !== undefined &&
- message.thread_id === lastTopLevelMessageId;
-
- const isFirstNewMessage =
- isNewMessage && !message.thread_id && !foundFirstNewMessage;
- if (isFirstNewMessage) {
- foundFirstNewMessage = true;
- }
-
- context[message.id] = {
- index: messageIndex,
- isNewMessage: isNewMessage,
- isFirstNewMessage,
- isParentNewMessage: isParentNewMessage,
- threadIndex,
- previousNonThreadedMessage,
- isInLastThread,
- };
- }
-
- return context;
-}
diff --git a/js/app/packages/block-channel/utils/scrollAndFocus.ts b/js/app/packages/block-channel/utils/scrollAndFocus.ts
deleted file mode 100644
index 5acd1f739a..0000000000
--- a/js/app/packages/block-channel/utils/scrollAndFocus.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import type { VirtualizerHandle } from 'virtua/solid';
-
-export const scrollIntoViewAndFocus = ({
- virtualHandle,
- container,
- targetIndex,
- targetId,
-}: {
- virtualHandle: VirtualizerHandle;
- container: HTMLElement | undefined;
- targetIndex: number;
- targetId: string;
-}) => {
- virtualHandle.scrollToIndex(targetIndex);
- const targetEl = container?.querySelector<HTMLElement>(
- `[data-message-body-id="${targetId}"]`
- );
- if (targetEl) {
- requestAnimationFrame(() => {
- targetEl.focus();
- });
- }
-};
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index e25a7e5506..293e7b2c8f 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -1,5 +1,5 @@
import { fileSelector } from '@core/directive/fileSelector';
-import { FormatRibbon } from '@block-channel/component/FormatRibbon';
+import { FormatRibbon } from '@block-channel/component/DeprecatedChannelInput/FormatRibbon';
import { MacroSignatureButton } from '@block-email/component/MacroSignatureButton';
import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';
import {
diff --git a/js/app/packages/block-email/component/compose/ComposeToolbar.tsx b/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
index fe9a99d283..07c87ab200 100644
--- a/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
+++ b/js/app/packages/block-email/component/compose/ComposeToolbar.tsx
@@ -1,5 +1,5 @@
import { SplitHeaderRight } from '@app/component/split-layout/components/SplitHeader';
-import { FormatRibbon } from '@block-channel/component/FormatRibbon';
+import { FormatRibbon } from '@block-channel/component/DeprecatedChannelInput/FormatRibbon';
import { EmailDateSelector } from '@block-email/component/email-date-selector';
import { MAX_ATTACHMENTS_BYTES_SIZE } from '@block-email/constants';
import { DropdownMenuContent, MenuItem } from '@core/component/Menu';
diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.ts
index a348a48eac..39f9d7de39 100644
--- a/js/app/packages/core/block.ts
+++ b/js/app/packages/core/block.ts
@@ -1,5 +1,5 @@
import type { BlockCanvasProps } from '@block-canvas/component/Block';
-import type { BlockChannelProps } from '@block-channel/component/Block';
+import type { BlockChannelProps } from '@block-channel/component/NewChannelBlockAdapter';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
diff --git a/js/app/packages/core/component/ForwardToChannel.tsx b/js/app/packages/core/component/ForwardToChannel.tsx
index dba41b1039..80e4c12e19 100644
--- a/js/app/packages/core/component/ForwardToChannel.tsx
+++ b/js/app/packages/core/component/ForwardToChannel.tsx
@@ -1,4 +1,4 @@
-import { useChannelMarkdownArea } from '@block-channel/component/MarkdownArea';
+import { useChannelMarkdownArea } from '@block-channel/component/DeprecatedChannelInput/MarkdownArea';
import { useAnalytics } from '@app/component/analytics-context';
import { useIsAuthenticated } from '@core/auth';
import {
diff --git a/js/app/packages/core/component/NewMessage.tsx b/js/app/packages/core/component/NewMessage.tsx
index 0733847413..ceb215db23 100644
--- a/js/app/packages/core/component/NewMessage.tsx
+++ b/js/app/packages/core/component/NewMessage.tsx
@@ -1,5 +1,5 @@
-import { FormatRibbon } from '@block-channel/component/FormatRibbon';
-import { useChannelMarkdownArea } from '@block-channel/component/MarkdownArea';
+import { FormatRibbon } from '@block-channel/component/DeprecatedChannelInput/FormatRibbon';
+import { useChannelMarkdownArea } from '@block-channel/component/DeprecatedChannelInput/MarkdownArea';
import { useBlockId, useBlockName } from '@core/block';
import { RecipientSelector } from '@core/component/RecipientSelector';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.ts
index 25c921a3fc..bd453f8c4b 100644
--- a/js/app/packages/macro-entity/src/queries/rename.ts
+++ b/js/app/packages/macro-entity/src/queries/rename.ts
@@ -1,11 +1,8 @@
import { renameItem } from '@core/component/FileList/itemOperations';
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import {
- optimisticUpdateChannelName,
- rollbackUpdateChannelName,
- type UpdateChannelNameContext,
-} from '@queries/channel/channel';
+import { channelKeys } from '@queries/channel/keys';
+import { queryClient } from '@queries/client';
import { setHistoryItemName } from '@queries/history/history';
import { setPreviewName } from '@queries/preview';
import {
@@ -15,6 +12,7 @@ import {
} from '@queries/soup/cache';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import { ChannelTypeEnum } from '@service-comms/client';
+import type { ApiChannelWithLatest } from '@service-comms/generated/models';
import type { ItemType } from '@service-storage/client';
import { useMutation } from '@tanstack/solid-query';
@@ -30,14 +28,10 @@ type EntityRenameOperationResult = {
success: boolean;
};
-// Maps channel ID to its update context, which lets us rollback the updated at timestamp as well as name
-type ChannelRenameContexts = Map<string, UpdateChannelNameContext | undefined>;
-
// Keyed by entity ID so rollback indices stay aligned even when flatMap filters out types
type SoupTransactionMap = Map<string, SoupTransaction>;
type RenameRollbackContext = {
- channels: ChannelRenameContexts;
soupTransactions: SoupTransactionMap;
};
@@ -128,24 +122,23 @@ const renameDssSetData = (
return txns;
};
-const renameChannelSetData = (
- entities: EntityRenameOptimisticInfo[]
-): ChannelRenameContexts => {
- const contexts: ChannelRenameContexts = new Map();
-
- entities.forEach(({ id, itemType, newName }) => {
- if (itemType === 'channel') {
- const context = optimisticUpdateChannelName({
- channelId: id,
- name: newName,
+const renameChannelSetData = (entities: EntityRenameOptimisticInfo[]): void => {
+ const channelUpdates = entities.filter(
+ ({ itemType }) => itemType === 'channel'
+ );
+ if (channelUpdates.length === 0) return;
+
+ queryClient.setQueryData<ApiChannelWithLatest[]>(
+ channelKeys.listChannels.queryKey,
+ (prev) => {
+ if (!prev) return prev;
+ return prev.map((channel) => {
+ const update = channelUpdates.find(({ id }) => id === channel.id);
+ if (!update) return channel;
+ return { ...channel, name: update.newName };
});
- if (context) {
- contexts.set(id, context);
- }
}
- });
-
- return contexts;
+ );
};
const renamePreviewSetData = (entities: EntityRenameOptimisticInfo[]) => {
@@ -169,10 +162,10 @@ function performOptimisticRenameUpdates(
): RenameRollbackContext {
renamePreviewSetData(entities);
renameHistorySetData(entities);
+ renameChannelSetData(entities);
const soupTransactions = renameDssSetData(entities);
- const channels = renameChannelSetData(entities);
- return { channels, soupTransactions };
+ return { soupTransactions };
}
function rollbackOptimisticRenameUpdates({
@@ -183,19 +176,15 @@ function rollbackOptimisticRenameUpdates({
txn.rollback();
}
- updates.forEach(({ id, oldName, itemType }) => {
- renameHistorySetData([{ id, itemType, newName: oldName }]);
- renamePreviewSetData([{ id, itemType, newName: oldName }]);
+ const rollbackEntities = updates.map(({ id, oldName, itemType }) => ({
+ id,
+ itemType,
+ newName: oldName,
+ }));
- if (itemType === 'channel') {
- const context = contexts.channels.get(id);
- if (context) {
- rollbackUpdateChannelName(id, context);
- } else {
- console.error(`No rollback context provided for channel item ${id}`);
- }
- }
- });
+ renameHistorySetData(rollbackEntities);
+ renamePreviewSetData(rollbackEntities);
+ renameChannelSetData(rollbackEntities);
}
const bulkRenameMutationFn = async (
@@ -243,7 +232,6 @@ const bulkRenameOnSettled = (
// Rollback only the failed items by entity ID
const failedUpdates: EntityRenameData[] = [];
- const failedChannelContexts: ChannelRenameContexts = new Map();
const failedSoupTransactions: SoupTransactionMap = new Map();
data.forEach((result, index) => {
@@ -253,12 +241,6 @@ const bulkRenameOnSettled = (
failedUpdates.push(update);
const txn = onMutateResult.contexts.soupTransactions.get(update.id);
if (txn) failedSoupTransactions.set(update.id, txn);
- if (update.itemType === 'channel') {
- const context = onMutateResult.contexts.channels.get(update.id);
- if (context !== undefined) {
- failedChannelContexts.set(update.id, context);
- }
- }
}
}
});
@@ -267,7 +249,6 @@ const bulkRenameOnSettled = (
if (failedUpdates.length > 0) {
rollbackOptimisticRenameUpdates({
contexts: {
- channels: failedChannelContexts,
soupTransactions: failedSoupTransactions,
},
updates: failedUpdates,
diff --git a/js/app/packages/notifications/components/Playground.tsx b/js/app/packages/notifications/components/Playground.tsx
index 468f928102..d4a7db1194 100644
--- a/js/app/packages/notifications/components/Playground.tsx
+++ b/js/app/packages/notifications/components/Playground.tsx
@@ -1,5 +1,5 @@
import { globalSplitManager } from '@app/signal/splitLayout';
-import { useChannelMarkdownArea } from '@block-channel/component/MarkdownArea';
+import { useChannelMarkdownArea } from '@block-channel/component/DeprecatedChannelInput/MarkdownArea';
import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
import { NotificationRenderer } from '@core/component/NotificationRenderer';
import { formatDate } from '@core/util/date';
diff --git a/js/app/packages/queries/channel/channel.ts b/js/app/packages/queries/channel/channel.ts
deleted file mode 100644
index 5377513667..0000000000
--- a/js/app/packages/queries/channel/channel.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import type { DateValue } from '@core/util/date';
-import {
- catchToResult,
- isErr,
- type MaybeResult,
- ok,
- throwOnErr,
-} from '@core/util/maybeResult';
-import { commsServiceClient } from '@service-comms/client';
-import type { getChannelResponseError } from '@service-comms/generated/client';
-import type { ApiChannelWithLatest } from '@service-comms/generated/models';
-import type { GetChannelResponse } from './types';
-import {
- type QueryClient,
- type UseBaseQueryOptions,
- useQuery,
-} from '@tanstack/solid-query';
-import type { Accessor } from 'solid-js';
-import { queryClient } from '../client';
-import { channelKeys } from './keys';
-
-type ChannelQueryOptions = UseBaseQueryOptions<
- GetChannelResponse,
- getChannelResponseError
->;
-
-export function channelQueryOptions(channelId: string): ChannelQueryOptions {
- return {
- queryKey: channelKeys.withID(channelId).queryKey,
- queryFn: async () => {
- const result = await throwOnErr(
- async () =>
- await commsServiceClient.getChannel({
- channel_id: channelId,
- })
- );
-
- return result;
- },
- staleTime: Infinity,
- };
-}
-
-export async function fetchAndCacheChannel(
- channelId: string
-): Promise<MaybeResult<string, { channel: GetChannelResponse }>> {
- const result = await catchToResult(
- async () =>
- await queryClient.ensureQueryData(channelQueryOptions(channelId))
- );
-
- if (isErr(result)) {
- return result;
- }
-
- return ok({ channel: result[1] });
-}
-
-export function useChannelQuery(
- channelId: Accessor<string>,
- options?: Accessor<Omit<ChannelQueryOptions, 'queryKey' | 'queryFn'>>,
- queryClient?: Accessor<QueryClient>
-) {
- return useQuery(() => {
- return {
- initialData: undefined,
- ...options?.(),
- ...channelQueryOptions(channelId()),
- };
- }, queryClient);
-}
-
-type WithChannelId<T> = T & { channelId: string };
-
-export type UpdateChannelNameContext = {
- previousName: string | null | undefined;
- previousUpdatedAt: DateValue;
-};
-
-/** Helper to update channel name in both single channel and list queries. */
-function updateChannelNameInQueries(
- channelId: string,
- name: string | null | undefined,
- updatedAt: DateValue
-): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
- const listQueryKey = channelKeys.listChannels.queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- return {
- ...prev,
- channel: {
- ...prev.channel,
- name,
- updated_at: updatedAt,
- },
- };
- }
- );
-
- queryClient.setQueriesData(
- { queryKey: listQueryKey },
- (prev: ApiChannelWithLatest[] | undefined) => {
- if (!prev) return prev;
-
- return prev.map((channel) =>
- channel.id === channelId
- ? { ...channel, name, updated_at: updatedAt }
- : channel
- );
- }
- );
-}
-
-/**
- * Optimistically update the channel name.
- * Returns context needed to rollback the update.
- */
-export function optimisticUpdateChannelName(
- vars: WithChannelId<{ name: string }>
-): UpdateChannelNameContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
- const listQueryKey = channelKeys.listChannels.queryKey;
-
- queryClient.cancelQueries({ queryKey });
- queryClient.cancelQueries({ queryKey: listQueryKey });
-
- let context: UpdateChannelNameContext | undefined;
-
- // Capture previous state for rollback
- const prev = queryClient.getQueryData<GetChannelResponse>(queryKey);
- if (prev) {
- context = {
- previousName: prev.channel.name,
- previousUpdatedAt: prev.channel.updated_at,
- };
- }
-
- const now = new Date().toISOString();
- updateChannelNameInQueries(vars.channelId, vars.name, now);
-
- return context;
-}
-
-/** Rollback an optimistic channel name update. */
-export function rollbackUpdateChannelName(
- channelId: string,
- context: UpdateChannelNameContext
-): void {
- updateChannelNameInQueries(
- channelId,
- context.previousName,
- context.previousUpdatedAt
- );
-}
-
-export function invalidateChannelWithID(channelID: string) {
- queryClient.invalidateQueries({
- queryKey: channelKeys.withID(channelID).queryKey,
- });
-}
-
-/**
- * Marks the channel query as stale without triggering an immediate refetch.
- * Uses `refetchType: 'inactive'` so queries only refetch when they become active again.
- * Use this after WebSocket updates to ensure eventual consistency without redundant fetches.
- */
-export function softInvalidateChannelWithID(channelID: string) {
- queryClient.invalidateQueries({
- queryKey: channelKeys.withID(channelID).queryKey,
- refetchType: 'inactive',
- });
-}
diff --git a/js/app/packages/queries/channel/derived.ts b/js/app/packages/queries/channel/derived.ts
deleted file mode 100644
index 999d41dd69..0000000000
--- a/js/app/packages/queries/channel/derived.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import type { GetChannelResponseReactions } from '@service-comms/generated/models';
-import type { Attachment, GetChannelResponse, Message } from './types';
-
-export type MessageWithThreadId = Message & {
- thread_id: NonNullable<Message['thread_id']>;
-};
-
-/**
- * Get top-level messages (messages that are not replies in a thread)
- */
-export function getTopLevelMessages(data: GetChannelResponse): Message[] {
- return data.messages.filter((m) => !m.thread_id);
-}
-
-/**
- * Get thread messages grouped by parent message ID
- */
-export function getThreadMessages(
- data: GetChannelResponse
-): Record<string, MessageWithThreadId[]> {
- const threads: Record<string, MessageWithThreadId[]> = {};
-
- for (const message of data.messages) {
- if (message.thread_id) {
- const threadId = message.thread_id;
- if (!threads[threadId]) {
- threads[threadId] = [];
- }
- threads[threadId].push(message as MessageWithThreadId);
- }
- }
-
- return threads;
-}
-
-/**
- * Check if the current user is an admin or owner of the channel
- */
-export function isChannelAdminOrOwner(data: GetChannelResponse): boolean {
- const access = data.access;
- if (!access || access === 'NoAccess') return false;
- return ['admin', 'owner'].includes(access.Access.role);
-}
-
-export function getReactionsForMessage(
- reactions: GetChannelResponseReactions,
- messageId: string
-) {
- return reactions[messageId] ?? [];
-}
-
-export function getAttachmentsByMessageId(
- attachments: Attachment[]
-): Record<string, Attachment[]> {
- return attachments.reduce(
- (acc, attachment) => {
- const id = attachment.message_id;
- if (!acc[id]) {
- acc[id] = [];
- }
- acc[id].push(attachment);
- return acc;
- },
- {} as Record<string, Attachment[]>
- );
-}
-
-/**
- * Get a message by ID from the channel data
- */
-export function getMessageById(
- data: GetChannelResponse,
- messageId: string
-): Message | undefined {
- return data.messages.find((m) => m.id === messageId);
-}
-
-/**
- * Get attachments for a specific message
- */
-export function getAttachmentsForMessage(
- attachments: Attachment[],
- messageId: string
-): Attachment[] {
- return attachments.filter((a) => a.message_id === messageId);
-}
-
-/**
- * Get a participant by user ID
- */
-export function getParticipantById(data: GetChannelResponse, userId: string) {
- return data.participants.find((p) => p.user_id === userId);
-}
-
-/**
- * Check if a user has reacted to a message with a specific emoji
- */
-export function hasUserReacted(
- reactions: GetChannelResponseReactions,
- messageId: string,
- userId: string,
- emoji: string
-): boolean {
- const messageReactions = reactions[messageId] ?? [];
- const reaction = messageReactions.find((r) => r.emoji === emoji);
- return reaction?.users.includes(userId) ?? false;
-}
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index 5836447eb0..6b1f8dfb16 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -1,8 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
-import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import type { DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/maybeResult';
-import { softInvalidateChannelWithID } from '@queries/channel/channel';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
@@ -16,7 +14,7 @@ import type {
CountedReaction,
PostMessageRequest,
} from '@service-comms/generated/models';
-import type { Attachment, GetChannelResponse, Message } from './types';
+import type { Attachment, Message } from '@service-comms/generated/models';
import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { channelKeys, ChannelNonceKeys } from './keys';
@@ -179,47 +177,20 @@ export function optimisticInsertChannelMessage(
target,
};
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- const newMessage: Message = {
- id: vars.optimisticId,
- channel_id: vars.channelId,
- sender_id: vars.senderId,
- content: vars.content,
- thread_id: vars.thread_id ?? undefined,
- created_at: now,
- updated_at: now,
- deleted_at: undefined,
- edited_at: undefined,
- };
-
- return {
- ...prev,
- messages: [...prev.messages, newMessage],
- attachments: [...prev.attachments, ...newAttachments],
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- if (target.kind === 'thread_reply') {
- const optimisticReply = makeOptimisticThreadReply(
- vars,
- newAttachments,
- now
- );
- insertMessageIntoTargetCaches(vars.channelId, target, optimisticReply);
- } else {
- const optimisticMessage = makeOptimisticTopLevelMessage(
- vars,
- newAttachments,
- now
- );
- insertMessageIntoTargetCaches(vars.channelId, target, optimisticMessage);
- }
+ if (target.kind === 'thread_reply') {
+ const optimisticReply = makeOptimisticThreadReply(
+ vars,
+ newAttachments,
+ now
+ );
+ insertMessageIntoTargetCaches(vars.channelId, target, optimisticReply);
+ } else {
+ const optimisticMessage = makeOptimisticTopLevelMessage(
+ vars,
+ newAttachments,
+ now
+ );
+ insertMessageIntoTargetCaches(vars.channelId, target, optimisticMessage);
}
return context;
@@ -232,26 +203,7 @@ export function rollbackInsertChannelMessage(
channelId: string,
context: InsertMessageContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- return {
- ...prev,
- messages: prev.messages.filter((m) => m.id !== context.optimisticId),
- attachments: prev.attachments.filter(
- (a) => a.message_id !== context.optimisticId
- ),
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- removeMessageFromTargetCaches(channelId, context.target);
- }
+ removeMessageFromTargetCaches(channelId, context.target);
}
/**
@@ -265,56 +217,15 @@ export function replaceOptimisticMessage(
threadId?: string;
}>
): void {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- const messageIndex = prev.messages.findIndex(
- (m) => m.id === vars.optimisticId
- );
-
- if (messageIndex === -1) return prev;
-
- const hasAuthoritativeAttachments = prev.attachments.some(
- (attachment) => attachment.message_id === vars.realId
- );
-
- const updatedMessages = [...prev.messages];
- updatedMessages[messageIndex] = {
- ...updatedMessages[messageIndex],
- id: vars.realId,
- };
-
- return {
- ...prev,
- messages: updatedMessages,
- attachments: hasAuthoritativeAttachments
- ? prev.attachments.filter(
- (attachment) => attachment.message_id !== vars.optimisticId
- )
- : prev.attachments.map((attachment) =>
- attachment.message_id === vars.optimisticId
- ? { ...attachment, message_id: vars.realId }
- : attachment
- ),
- };
- }
+ replaceTargetMessageId(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.optimisticId,
+ threadId: vars.threadId,
+ }),
+ vars.realId
);
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetMessageId(
- vars.channelId,
- resolveMessageTarget({
- channelId: vars.channelId,
- messageId: vars.optimisticId,
- threadId: vars.threadId,
- }),
- vars.realId
- );
- }
}
/**
@@ -326,9 +237,6 @@ export function optimisticDeleteChannelMessage(
Pick<ChannelMessage, 'message_id'> & { threadId?: string }
>
): DeleteMessageContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
- queryClient.cancelQueries({ queryKey });
-
const target = resolveMessageTarget({
channelId: vars.channelId,
messageId: vars.message_id,
@@ -340,51 +248,11 @@ export function optimisticDeleteChannelMessage(
target,
};
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- const deletedMessage = prev.messages.find(
- (m) => m.id === vars.message_id
- );
- if (!deletedMessage) return prev;
-
- context.deletedMessage = deletedMessage;
- context.deletedReactions = prev.reactions[vars.message_id] ?? [];
- context.deletedAttachments = prev.attachments.filter(
- (a) => a.message_id === vars.message_id
- );
-
- const filteredMessages = prev.messages.filter(
- (m) => m.id !== vars.message_id
- );
-
- // Remove reactions for the deleted message
- const { [vars.message_id]: _removedReactions, ...remainingReactions } =
- prev.reactions;
-
- // Remove attachments linked to the deleted message
- const filteredAttachments = prev.attachments.filter(
- (a) => a.message_id !== vars.message_id
- );
-
- return {
- ...prev,
- messages: filteredMessages,
- reactions: remainingReactions,
- attachments: filteredAttachments,
- };
- }
+ context.targetSnapshot = captureDeleteSnapshotForTarget(
+ vars.channelId,
+ target
);
-
- if (ENABLE_NEW_CHANNELS()) {
- context.targetSnapshot = captureDeleteSnapshotForTarget(
- vars.channelId,
- target
- );
- removeMessageFromTargetCaches(vars.channelId, target);
- }
+ removeMessageFromTargetCaches(vars.channelId, target);
return context;
}
@@ -396,29 +264,7 @@ export function rollbackDeleteChannelMessage(
channelId: string,
context: DeleteMessageContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
- if (!context.deletedMessage) return prev;
-
- return {
- ...prev,
- messages: [...prev.messages, context.deletedMessage],
- reactions: {
- ...prev.reactions,
- ...(context.deletedReactions.length > 0 && {
- [context.deletedMessage.id]: context.deletedReactions,
- }),
- },
- attachments: [...prev.attachments, ...context.deletedAttachments],
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS() && context.targetSnapshot) {
+ if (context.targetSnapshot) {
restoreMessageInTargetCaches(
channelId,
context.target,
@@ -438,7 +284,6 @@ export function optimisticUpdateChannelMessage(
}
>
): UpdateMessageContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
const target = resolveMessageTarget({
channelId: vars.channelId,
messageId: vars.message_id,
@@ -464,42 +309,7 @@ export function optimisticUpdateChannelMessage(
};
}
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- const message = prev.messages.find((m) => m.id === vars.message_id);
- if (!message) return prev;
-
- context = {
- messageId: vars.message_id,
- target,
- previousContent: message.content,
- previousEditedAt: message.edited_at,
- previousUpdatedAt: message.updated_at,
- previousAttachments: prev.attachments.filter(
- (attachment) => attachment.message_id === vars.message_id
- ),
- };
-
- return {
- ...prev,
- messages: prev.messages.map((m) =>
- m.id === vars.message_id
- ? { ...m, content: vars.content, edited_at: now, updated_at: now }
- : m
- ),
- attachments: prev.attachments.filter(
- (attachment) =>
- attachment.message_id !== vars.message_id ||
- !deletedAttachmentIDs.has(attachment.id)
- ),
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS() && context) {
+ if (context) {
replaceTargetMessageState(vars.channelId, target, {
content: vars.content,
editedAt: now,
@@ -520,43 +330,12 @@ export function rollbackUpdateChannelMessage(
channelId: string,
context: UpdateMessageContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- return {
- ...prev,
- messages: prev.messages.map((m) =>
- m.id === context.messageId
- ? {
- ...m,
- content: context.previousContent,
- edited_at: context.previousEditedAt,
- updated_at: context.previousUpdatedAt,
- }
- : m
- ),
- attachments: [
- ...prev.attachments.filter(
- (attachment) => attachment.message_id !== context.messageId
- ),
- ...context.previousAttachments,
- ],
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetMessageState(channelId, context.target, {
- content: context.previousContent,
- editedAt: normalizeDateValue(context.previousEditedAt),
- updatedAt: normalizeDateValue(context.previousUpdatedAt) ?? '',
- attachments: context.previousAttachments,
- });
- }
+ replaceTargetMessageState(channelId, context.target, {
+ content: context.previousContent,
+ editedAt: normalizeDateValue(context.previousEditedAt),
+ updatedAt: normalizeDateValue(context.previousUpdatedAt) ?? '',
+ attachments: context.previousAttachments,
+ });
}
type SendMessageParams = {
@@ -633,17 +412,14 @@ export function useSendMessageMutation(
}
},
onSettled: (_data, _error, variables) => {
- softInvalidateChannelWithID(variables.channelID);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- variables.channelID,
- resolveMessageTarget({
- channelId: variables.channelID,
- messageId: variables.optimisticId,
- threadId: variables.message.thread_id ?? undefined,
- })
- );
- }
+ softInvalidateTargetCaches(
+ variables.channelID,
+ resolveMessageTarget({
+ channelId: variables.channelID,
+ messageId: variables.optimisticId,
+ threadId: variables.message.thread_id ?? undefined,
+ })
+ );
},
},
callbacks
@@ -709,17 +485,14 @@ export function useDeleteMessageMutation(
},
onSettled: (_data, _error, vars) => {
deleteNonce.cleanup(vars);
- softInvalidateChannelWithID(vars.channelID);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- vars.channelID,
- resolveMessageTarget({
- channelId: vars.channelID,
- messageId: vars.messageID,
- threadId: vars.threadID,
- })
- );
- }
+ softInvalidateTargetCaches(
+ vars.channelID,
+ resolveMessageTarget({
+ channelId: vars.channelID,
+ messageId: vars.messageID,
+ threadId: vars.threadID,
+ })
+ );
},
},
callbacks
@@ -794,16 +567,13 @@ export function usePatchMessageMutation(
},
onSettled: (_data, _error, vars) => {
patchNonce.cleanup(vars);
- softInvalidateChannelWithID(vars.channelID);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- vars.channelID,
- resolveMessageTarget({
- channelId: vars.channelID,
- messageId: vars.messageID,
- })
- );
- }
+ softInvalidateTargetCaches(
+ vars.channelID,
+ resolveMessageTarget({
+ channelId: vars.channelID,
+ messageId: vars.messageID,
+ })
+ );
},
},
callbacks
diff --git a/js/app/packages/queries/channel/reaction.ts b/js/app/packages/queries/channel/reaction.ts
index 64c1f9416f..cdf29c615d 100644
--- a/js/app/packages/queries/channel/reaction.ts
+++ b/js/app/packages/queries/channel/reaction.ts
@@ -1,16 +1,16 @@
import { toast } from '@core/component/Toast/Toast';
-import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/maybeResult';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import {
commsServiceClient,
type MessageResponse,
} from '@service-comms/client';
-import type { PostReactionRequest } from '@service-comms/generated/models';
-import type { GetChannelResponse } from './types';
+import type {
+ CountedReaction,
+ PostReactionRequest,
+} from '@service-comms/generated/models';
import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
-import { softInvalidateChannelWithID } from './channel';
import { channelKeys, ChannelNonceKeys } from './keys';
import { createMutationNonce } from '../nonce';
import {
@@ -23,7 +23,7 @@ import {
type WithChannelId<T> = T & { channelId: string };
type WithUserId<T> = T & { userId: string };
-type ReactionList = GetChannelResponse['reactions'][string];
+type ReactionList = CountedReaction[];
type WithReactionState<T> = T & {
currentReactions?: ReactionList;
threadId?: string;
@@ -123,12 +123,7 @@ export function optimisticAddReaction(
>
>
): AddReactionContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
- queryClient.cancelQueries({ queryKey });
- const fallbackChannelData =
- queryClient.getQueryData<GetChannelResponse>(queryKey);
- const currentReactions =
- vars.currentReactions ?? fallbackChannelData?.reactions[vars.message_id];
+ const currentReactions = vars.currentReactions;
const target = resolveMessageTarget({
channelId: vars.channelId,
messageId: vars.message_id,
@@ -146,24 +141,7 @@ export function optimisticAddReaction(
target,
};
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- return {
- ...prev,
- reactions: {
- ...prev.reactions,
- [vars.message_id]: result.reactions,
- },
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetReactions(vars.channelId, context.target, result.reactions);
- }
+ replaceTargetReactions(vars.channelId, context.target, result.reactions);
return context;
}
@@ -175,34 +153,7 @@ export function rollbackAddReaction(
channelId: string,
context: AddReactionContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
- if (context.previousReactions.length === 0) {
- const { [context.messageId]: _, ...rest } = prev.reactions;
- return { ...prev, reactions: rest };
- }
-
- return {
- ...prev,
- reactions: {
- ...prev.reactions,
- [context.messageId]: context.previousReactions,
- },
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetReactions(
- channelId,
- context.target,
- context.previousReactions
- );
- }
+ replaceTargetReactions(channelId, context.target, context.previousReactions);
}
/**
@@ -216,12 +167,7 @@ export function optimisticRemoveReaction(
>
>
): RemoveReactionContext | undefined {
- const queryKey = channelKeys.withID(vars.channelId).queryKey;
- queryClient.cancelQueries({ queryKey });
- const fallbackChannelData =
- queryClient.getQueryData<GetChannelResponse>(queryKey);
- const currentReactions =
- vars.currentReactions ?? fallbackChannelData?.reactions[vars.message_id];
+ const currentReactions = vars.currentReactions;
const target = resolveMessageTarget({
channelId: vars.channelId,
messageId: vars.message_id,
@@ -239,26 +185,7 @@ export function optimisticRemoveReaction(
target,
};
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
-
- if (result.reactions.length === 0) {
- const { [vars.message_id]: _, ...rest } = prev.reactions;
- return { ...prev, reactions: rest };
- }
-
- return {
- ...prev,
- reactions: { ...prev.reactions, [vars.message_id]: result.reactions },
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetReactions(vars.channelId, context.target, result.reactions);
- }
+ replaceTargetReactions(vars.channelId, context.target, result.reactions);
return context;
}
@@ -270,36 +197,7 @@ export function rollbackRemoveReaction(
channelId: string,
context: RemoveReactionContext
): void {
- const queryKey = channelKeys.withID(channelId).queryKey;
-
- queryClient.setQueriesData(
- { queryKey },
- (prev: GetChannelResponse | undefined) => {
- if (!prev) return prev;
- return {
- ...prev,
- reactions:
- context.previousReactions.length === 0
- ? Object.fromEntries(
- Object.entries(prev.reactions).filter(
- ([messageId]) => messageId !== context.messageId
- )
- )
- : {
- ...prev.reactions,
- [context.messageId]: context.previousReactions,
- },
- };
- }
- );
-
- if (ENABLE_NEW_CHANNELS()) {
- replaceTargetReactions(
- channelId,
- context.target,
- context.previousReactions
- );
- }
+ replaceTargetReactions(channelId, context.target, context.previousReactions);
}
type ReactionParams = {
@@ -379,17 +277,14 @@ export function useAddReactionMutation(
},
onSettled: (_, __, vars) => {
addReactionNonce.cleanup(vars);
- softInvalidateChannelWithID(vars.channelId);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- vars.channelId,
- resolveMessageTarget({
- channelId: vars.channelId,
- messageId: vars.messageId,
- threadId: vars.threadId,
- })
- );
- }
+ softInvalidateTargetCaches(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.messageId,
+ threadId: vars.threadId,
+ })
+ );
},
},
callbacks
@@ -452,17 +347,14 @@ export function useRemoveReactionMutation(
},
onSettled: (_, __, vars) => {
removeReactionNonce.cleanup(vars);
- softInvalidateChannelWithID(vars.channelId);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- vars.channelId,
- resolveMessageTarget({
- channelId: vars.channelId,
- messageId: vars.messageId,
- threadId: vars.threadId,
- })
- );
- }
+ softInvalidateTargetCaches(
+ vars.channelId,
+ resolveMessageTarget({
+ channelId: vars.channelId,
+ messageId: vars.messageId,
+ threadId: vars.threadId,
+ })
+ );
},
},
callbacks
diff --git a/js/app/packages/queries/channel/reconcile.ts b/js/app/packages/queries/channel/reconcile.ts
index 8fc565423f..0745bb1a1f 100644
--- a/js/app/packages/queries/channel/reconcile.ts
+++ b/js/app/packages/queries/channel/reconcile.ts
@@ -41,9 +41,7 @@ import type {
CountedReaction,
} from '@service-comms/generated/models';
import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
-import type { GetChannelResponse } from './types';
import { queryClient } from '../client';
-import { channelKeys } from './keys';
export type MessageTarget =
| {
@@ -92,12 +90,6 @@ export function makeMessageTarget(args: {
};
}
-function getCachedChannel(channelId: string): GetChannelResponse | undefined {
- return queryClient.getQueryData<GetChannelResponse>(
- channelKeys.withID(channelId).queryKey
- );
-}
-
/** Finds a reply's parent thread id from cached channel data. */
export function findThreadIdForMessage(
channelId: string,
@@ -111,11 +103,7 @@ export function findThreadIdForMessage(
return queryKey.at(-1) as string | undefined;
}
- return (
- getCachedChannel(channelId)?.messages.find(
- (message) => message.id === messageId
- )?.thread_id ?? undefined
- );
+ return undefined;
}
/** Resolves whether a message target is top-level or a thread reply. */
diff --git a/js/app/packages/queries/channel/sync.ts b/js/app/packages/queries/channel/sync.ts
index debd8f3c99..ac823ba29d 100644
--- a/js/app/packages/queries/channel/sync.ts
+++ b/js/app/packages/queries/channel/sync.ts
@@ -3,12 +3,8 @@ import type {
CountedReaction,
Message as ApiMessage,
} from '@service-comms/generated/models';
-import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import type { ApiThreadReply } from '@service-comms/client';
-import type { GetChannelResponse } from './types';
-import { queryClient } from '../client';
-import { softInvalidateChannelWithID } from './channel';
-import { channelKeys, ChannelNonceKeys } from './keys';
+import { ChannelNonceKeys } from './keys';
import { consumeNonce } from '../nonce';
import {
getTargetMessageState,
@@ -47,7 +43,7 @@ type CommsAttachmentPayload = {
* update since it was already applied. Otherwise, this is an external update
* (other user, other tab, or server-initiated) and we apply it to the cache.
*
- * We always call softInvalidateChannelWithID to ensure eventual consistency:
+ * We always call softInvalidateTargetCaches to ensure eventual consistency:
* - Marks query as stale for background refetch when component remounts
* - Handles cross-tab sync where optimistic state may differ
* - Catches edge cases like server-side message modifications
@@ -60,79 +56,59 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {
if (isExternalUpdate) {
try {
- const queryKey = channelKeys.withID(payload.channel_id).queryKey;
-
- queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
- if (!prev) return prev;
-
- if (prev.messages.some((m) => m.id === payload.id)) {
- return prev;
- }
-
- return {
- ...prev,
- messages: [...prev.messages, payload],
- };
- });
-
- if (ENABLE_NEW_CHANNELS()) {
- if (payload.deleted_at) {
- removeMessageFromTargetCaches(
- payload.channel_id,
- resolveMessageTarget({
- channelId: payload.channel_id,
- messageId: payload.id,
- threadId: payload.thread_id ?? undefined,
- })
- );
- } else {
- const target = resolveMessageTarget({
+ if (payload.deleted_at) {
+ removeMessageFromTargetCaches(
+ payload.channel_id,
+ resolveMessageTarget({
channelId: payload.channel_id,
messageId: payload.id,
threadId: payload.thread_id ?? undefined,
+ })
+ );
+ } else {
+ const target = resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.id,
+ threadId: payload.thread_id ?? undefined,
+ });
+ const existingState = getTargetMessageState(payload.channel_id, target);
+
+ if (existingState) {
+ replaceTargetMessageState(payload.channel_id, target, {
+ content: payload.content,
+ editedAt: payload.edited_at,
+ updatedAt: payload.updated_at,
+ attachments: existingState.attachments,
+ });
+ } else if (target.kind === 'thread_reply') {
+ const reply: ApiThreadReply = {
+ id: payload.id,
+ sender_id: payload.sender_id,
+ content: payload.content,
+ created_at: payload.created_at,
+ updated_at: payload.updated_at,
+ edited_at: payload.edited_at,
+ attachments: [],
+ reactions: [],
+ };
+ insertMessageIntoTargetCaches(payload.channel_id, target, reply);
+ } else {
+ insertMessageIntoTargetCaches(payload.channel_id, target, {
+ id: payload.id,
+ channel_id: payload.channel_id,
+ sender_id: payload.sender_id,
+ content: payload.content,
+ created_at: payload.created_at,
+ updated_at: payload.updated_at,
+ edited_at: payload.edited_at,
+ attachments: [],
+ reactions: [],
+ thread: {
+ preview: [],
+ reply_count: 0,
+ latest_reply_at: null,
+ },
});
- const existingState = getTargetMessageState(
- payload.channel_id,
- target
- );
-
- if (existingState) {
- replaceTargetMessageState(payload.channel_id, target, {
- content: payload.content,
- editedAt: payload.edited_at,
- updatedAt: payload.updated_at,
- attachments: existingState.attachments,
- });
- } else if (target.kind === 'thread_reply') {
- const reply: ApiThreadReply = {
- id: payload.id,
- sender_id: payload.sender_id,
- content: payload.content,
- created_at: payload.created_at,
- updated_at: payload.updated_at,
- edited_at: payload.edited_at,
- attachments: [],
- reactions: [],
- };
- insertMessageIntoTargetCaches(payload.channel_id, target, reply);
- } else {
- insertMessageIntoTargetCaches(payload.channel_id, target, {
- id: payload.id,
- channel_id: payload.channel_id,
- sender_id: payload.sender_id,
- content: payload.content,
- created_at: payload.created_at,
- updated_at: payload.updated_at,
- edited_at: payload.edited_at,
- attachments: [],
- reactions: [],
- thread: {
- preview: [],
- reply_count: 0,
- latest_reply_at: null,
- },
- });
- }
}
}
} catch (error) {
@@ -140,17 +116,14 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {
}
}
- softInvalidateChannelWithID(payload.channel_id);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(
- payload.channel_id,
- resolveMessageTarget({
- channelId: payload.channel_id,
- messageId: payload.id,
- threadId: payload.thread_id ?? undefined,
- })
- );
- }
+ softInvalidateTargetCaches(
+ payload.channel_id,
+ resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.id,
+ threadId: payload.thread_id ?? undefined,
+ })
+ );
}
/**
@@ -165,40 +138,20 @@ export function handleCommsReaction(payload: CommsReactionPayload): void {
payload.nonce
);
+ const target = resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.message_id,
+ });
+
if (isExternalUpdate) {
try {
- const queryKey = channelKeys.withID(payload.channel_id).queryKey;
- queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
- if (!prev) return prev;
- return {
- ...prev,
- reactions: {
- ...prev.reactions,
- [payload.message_id]: payload.reactions,
- },
- };
- });
-
- if (ENABLE_NEW_CHANNELS()) {
- const target = resolveMessageTarget({
- channelId: payload.channel_id,
- messageId: payload.message_id,
- });
- replaceTargetReactions(payload.channel_id, target, payload.reactions);
- }
+ replaceTargetReactions(payload.channel_id, target, payload.reactions);
} catch (error) {
console.error('Failed to update reaction cache from websocket:', error);
}
}
- softInvalidateChannelWithID(payload.channel_id);
- if (ENABLE_NEW_CHANNELS()) {
- const target = resolveMessageTarget({
- channelId: payload.channel_id,
- messageId: payload.message_id,
- });
- softInvalidateTargetCaches(payload.channel_id, target);
- }
+ softInvalidateTargetCaches(payload.channel_id, target);
}
/**
@@ -208,53 +161,15 @@ export function handleCommsReaction(payload: CommsReactionPayload): void {
* Soft invalidation ensures eventual consistency across tabs/devices.
*/
export function handleCommsAttachment(payload: CommsAttachmentPayload): void {
- const isExternalUpdate = !consumeNonce(
- ChannelNonceKeys.ATTACHMENT,
- payload.nonce
- );
- const target = ENABLE_NEW_CHANNELS()
- ? resolveMessageTarget({
- channelId: payload.channel_id,
- messageId: payload.message_id,
- })
- : undefined;
+ const target = resolveMessageTarget({
+ channelId: payload.channel_id,
+ messageId: payload.message_id,
+ });
try {
- const queryKey = channelKeys.withID(payload.channel_id).queryKey;
- queryClient.setQueryData<GetChannelResponse>(queryKey, (prev) => {
- if (!prev) return prev;
-
- const remainingAttachments = prev.attachments.filter(
- (attachment) => attachment.message_id !== payload.message_id
- );
- const nextAttachments = isExternalUpdate
- ? [
- ...remainingAttachments,
- ...payload.attachments.filter(
- (attachment) =>
- !remainingAttachments.some(
- (existingAttachment) =>
- existingAttachment.id === attachment.id
- )
- ),
- ]
- : [...remainingAttachments, ...payload.attachments];
-
- return {
- ...prev,
- attachments: nextAttachments,
- };
- });
-
- if (ENABLE_NEW_CHANNELS() && target) {
- replaceTargetAttachments(payload.channel_id, target, payload.attachments);
- }
+ replaceTargetAttachments(payload.channel_id, target, payload.attachments);
} catch (error) {
console.error('Failed to update attachment cache from websocket:', error);
}
-
- softInvalidateChannelWithID(payload.channel_id);
- if (ENABLE_NEW_CHANNELS()) {
- softInvalidateTargetCaches(payload.channel_id, target);
- }
+ softInvalidateTargetCaches(payload.channel_id, target);
}
diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
index b59db1d0b5..5cab707ed4 100644
--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts
@@ -18,11 +18,6 @@ vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: vi.fn(), success: vi.fn() },
}));
-vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
- ENABLE_NEW_CHANNELS: () => true,
-}));
-
vi.mock('@service-comms/client', () => ({
commsServiceClient: {},
}));
@@ -35,11 +30,9 @@ import {
getChannelMessagesQueryKey,
type ChannelMessagesData,
} from '../channel-messages';
-import { channelKeys } from '../keys';
import {
optimisticInsertChannelMessage,
optimisticUpdateChannelMessage,
- replaceOptimisticMessage,
rollbackInsertChannelMessage,
rollbackUpdateChannelMessage,
} from '../message';
@@ -50,7 +43,6 @@ import {
rollbackRemoveReaction,
} from '../reaction';
import { getThreadRepliesQueryKey } from '../thread-replies';
-import type { GetChannelResponse } from '../types';
function createPaginatedMessage(
id: string,
@@ -123,25 +115,6 @@ function getChannelMessagesFromCache(
);
}
-function createLegacyChannelResponse(
- overrides: Partial<GetChannelResponse> = {}
-): GetChannelResponse {
- return {
- channel: {
- id: 'channel-1',
- created_at: '2024-01-03T00:00:00.000Z',
- updated_at: '2024-01-03T00:00:00.000Z',
- },
- users: {},
- messages: [],
- attachments: [],
- participants: [],
- reactions: {},
- read_state: {},
- ...overrides,
- } as GetChannelResponse;
-}
-
function seedThreadRepliesCache(
channelId: string,
messageId: string,
@@ -204,61 +177,6 @@ describe('channel optimistic cache regressions', () => {
]);
});
- it('drops optimistic attachments when authoritative ones already exist for the real message id', () => {
- testQueryClient.setQueryData(
- channelKeys.withID('channel-1').queryKey,
- createLegacyChannelResponse({
- messages: [
- {
- id: 'optimistic-msg',
- channel_id: 'channel-1',
- sender_id: 'user-2',
- content: 'Uploading image',
- created_at: '2024-01-03T00:00:00.000Z',
- updated_at: '2024-01-03T00:00:00.000Z',
- deleted_at: undefined,
- edited_at: undefined,
- },
- ],
- attachments: [
- {
- id: 'optimistic-att',
- channel_id: 'channel-1',
- message_id: 'optimistic-msg',
- entity_id: 'image-1',
- entity_type: 'static/image',
- created_at: '2024-01-03T00:00:00.000Z',
- },
- {
- id: 'server-att',
- channel_id: 'channel-1',
- message_id: 'real-msg',
- entity_id: 'image-1',
- entity_type: 'static/image',
- created_at: '2024-01-03T00:00:01.000Z',
- },
- ],
- })
- );
-
- replaceOptimisticMessage({
- channelId: 'channel-1',
- optimisticId: 'optimistic-msg',
- realId: 'real-msg',
- });
-
- const cached = testQueryClient.getQueryData<GetChannelResponse>(
- channelKeys.withID('channel-1').queryKey
- );
-
- expect(cached?.messages).toEqual([
- expect.objectContaining({ id: 'real-msg' }),
- ]);
- expect(cached?.attachments).toEqual([
- expect.objectContaining({ id: 'server-att', message_id: 'real-msg' }),
- ]);
- });
-
it('rolls back optimistic thread replies when only the new caches are warm', () => {
seedChannelMessagesCache(
'channel-1',
diff --git a/js/app/packages/queries/channel/tests/sync.test.ts b/js/app/packages/queries/channel/tests/sync.test.ts
index a96926dc3a..1bd542c081 100644
--- a/js/app/packages/queries/channel/tests/sync.test.ts
+++ b/js/app/packages/queries/channel/tests/sync.test.ts
@@ -15,18 +15,10 @@ vi.mock('../../client', () => ({
},
}));
-vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
- ENABLE_NEW_CHANNELS: () => true,
-}));
-
import type { ChannelMessagesData } from '../channel-messages';
import { getChannelMessagesQueryKey } from '../channel-messages';
-import { channelKeys, ChannelNonceKeys } from '../keys';
-import { registerNonce } from '../../nonce';
import { handleCommsAttachment, handleCommsReaction } from '../sync';
import { getThreadRepliesQueryKey } from '../thread-replies';
-import type { GetChannelResponse } from '../types';
function createPaginatedMessage(
id: string,
@@ -100,27 +92,6 @@ function createChannelMessagesData(
};
}
-function createMockChannelResponse(
- overrides: Partial<GetChannelResponse> = {}
-): GetChannelResponse {
- return {
- channel: {
- id: 'channel-1',
- name: 'Test Channel',
- owner_id: 'user-1',
- created_at: '2024-01-01T00:00:00.000Z',
- updated_at: '2024-01-01T00:00:00.000Z',
- channel_type: 'direct_message',
- },
- messages: [],
- reactions: {},
- attachments: [],
- participants: [],
- access: 'Participant',
- ...overrides,
- } as GetChannelResponse;
-}
-
describe('channel sync', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -159,47 +130,6 @@ describe('channel sync', () => {
]);
});
- it('reconciles local optimistic attachments with authoritative websocket payloads', () => {
- testQueryClient.setQueryData(
- getChannelMessagesQueryKey('channel-1'),
- createChannelMessagesData([
- [
- createPaginatedMessage('real-msg-1', '2024-01-03T00:00:00.000Z', {
- attachments: [createAttachment('optimistic-att', 'real-msg-1')],
- }),
- ],
- ])
- );
- testQueryClient.setQueryData(
- channelKeys.withID('channel-1').queryKey,
- createMockChannelResponse({
- attachments: [createAttachment('optimistic-att', 'real-msg-1')],
- })
- );
- registerNonce(ChannelNonceKeys.ATTACHMENT, 'local-attachment');
-
- handleCommsAttachment({
- channel_id: 'channel-1',
- message_id: 'real-msg-1',
- nonce: 'local-attachment',
- attachments: [createAttachment('server-att', 'real-msg-1')],
- });
-
- const cached = testQueryClient.getQueryData<ChannelMessagesData>(
- getChannelMessagesQueryKey('channel-1')
- );
- expect(cached?.pages[0].items[0].attachments).toEqual([
- expect.objectContaining({ id: 'server-att' }),
- ]);
-
- const legacy = testQueryClient.getQueryData<GetChannelResponse>(
- channelKeys.withID('channel-1').queryKey
- );
- expect(legacy?.attachments).toEqual([
- expect.objectContaining({ id: 'server-att' }),
- ]);
- });
-
it('updates thread reply reactions without the legacy channel cache', () => {
testQueryClient.setQueryData(
getChannelMessagesQueryKey('channel-1'),
diff --git a/js/app/packages/queries/channel/types.ts b/js/app/packages/queries/channel/types.ts
index b87169fd5d..8723321bfd 100644
--- a/js/app/packages/queries/channel/types.ts
+++ b/js/app/packages/queries/channel/types.ts
@@ -1,29 +1,3 @@
-import type {
- Activity as ApiActivity,
- Attachment as ApiAttachment,
- Channel as ApiChannel,
- ChannelParticipant as ApiChannelParticipant,
- GetChannelResponse as ApiGetChannelResponse,
- Message as ApiMessage,
-} from '@service-comms/generated/models';
-
-export type Message = ApiMessage;
-
-export type Attachment = ApiAttachment;
+import type { ChannelParticipant as ApiChannelParticipant } from '@service-comms/generated/models';
export type ChannelParticipant = ApiChannelParticipant;
-
-export type Channel = ApiChannel;
-
-export type Activity = ApiActivity;
-
-export type GetChannelResponse = Omit<
- ApiGetChannelResponse,
- 'channel' | 'messages' | 'attachments' | 'participants' | 'activity'
-> & {
- channel: Channel;
- messages: Message[];
- attachments: Attachment[];
- participants: ChannelParticipant[];
- activity?: Activity | null;
-};
diff --git a/js/app/packages/queries/persistence-scopes.ts b/js/app/packages/queries/persistence-scopes.ts
index 033adcc670..af60c494ac 100644
--- a/js/app/packages/queries/persistence-scopes.ts
+++ b/js/app/packages/queries/persistence-scopes.ts
@@ -4,7 +4,6 @@ import { createPersistenceKey, type PersistScope } from './persistence';
import { createPerQueryIDBStore } from './persistence/per-query-idb';
const persistedChannelQueryPrefixes = [
- channelKeys.withID._def,
channelKeys.mentions._def,
channelKeys.activity.queryKey,
channelKeys.listChannels.queryKey,
diff --git a/js/app/packages/queries/persistence.test.ts b/js/app/packages/queries/persistence.test.ts
index a6e8a7b13c..2bc791f8ec 100644
--- a/js/app/packages/queries/persistence.test.ts
+++ b/js/app/packages/queries/persistence.test.ts
@@ -47,6 +47,9 @@ function createScope(
describe('setupQueryPersistence', () => {
it('allowlists persisted channel query families', () => {
expect(shouldPersistChannelQuery(channelKeys.withID('a').queryKey)).toBe(
+ false
+ );
+ expect(shouldPersistChannelQuery(channelKeys.listChannels.queryKey)).toBe(
true
);
expect(
@@ -153,13 +156,13 @@ describe('setupQueryPersistence', () => {
queryClient.setQueryData(messageQueryKey, { value: 'skip' });
expect(store.set).not.toHaveBeenCalled();
- queryClient.setQueryData(channelKeys.withID('b').queryKey, {
+ queryClient.setQueryData(channelKeys.listChannels.queryKey, {
value: 'persist',
});
expect(store.set).toHaveBeenCalledTimes(1);
expect(
(store.set.mock.calls[0]![0] as PersistedQueryEntry).queryKey
- ).toEqual(channelKeys.withID('b').queryKey);
+ ).toEqual(channelKeys.listChannels.queryKey);
});
it('restores query data from store on added event', async () => {