Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(sidebar): polish unread widget hover preview (#4629)

gbirman267d9d651e42
diff --git a/js/app/packages/app/component/app-sidebar/channels-unread-widget.tsx b/js/app/packages/app/component/app-sidebar/channels-unread-widget.tsx
index 0f13c5342a..525889cd79 100644
--- a/js/app/packages/app/component/app-sidebar/channels-unread-widget.tsx
+++ b/js/app/packages/app/component/app-sidebar/channels-unread-widget.tsx
@@ -17,9 +17,17 @@ import { openNotification } from '@notifications';
import { isChannelNotification } from '@notifications/notification-helpers';
import { getChannelNotificationParams } from '@notifications/notification-navigation';
import type { UnifiedNotification } from '@notifications/types';
+import RefreshIcon from '@phosphor/arrow-clockwise.svg';
+import WarningIcon from '@phosphor/warning.svg';
+import { channelMessagesByIdsQueryOptions } from '@queries/channel/channel-messages';
+import { threadRepliesQueryOptions } from '@queries/channel/thread-replies';
+import { queryClient } from '@queries/client';
+import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
import { createElementSize } from '@solid-primitives/resize-observer';
-import { Avatar, cn, NavRow, Surface, Tooltip } from '@ui';
+import { Avatar, Button, cn, NavRow, Surface, Tooltip } from '@ui';
import {
+ type Accessor,
+ createContext,
createEffect,
createMemo,
createSignal,
@@ -29,6 +37,7 @@ import {
onMount,
type ParentProps,
Show,
+ useContext,
} from 'solid-js';
function getChannelInfo(notification: UnifiedNotification): {
@@ -122,6 +131,131 @@ function groupByChannel(
}
const HOVER_PREVIEW_COUNT = 3;
+const PREVIEW_OPEN_DELAY_MS = 450;
+const PREVIEW_WARM_OPEN_DELAY_MS = 100;
+const PREVIEW_CLOSE_DELAY_MS = 200;
+const PREVIEW_WARM_LINGER_MS = 400;
+const PREVIEW_ANCHOR_PIN_MS = 600;
+const PREVIEW_ANCHOR_WAIT_MS = 10_000;
+
+type UnreadPreviewManager = {
+ activeGroupId: Accessor<string | null>;
+ rowEnter: (groupId: string) => void;
+ rowLeave: () => void;
+ cardEnter: () => void;
+ cardLeave: () => void;
+ dismiss: (groupId?: string) => void;
+};
+
+// Single source of truth for which row's preview is open, so at most one
+// card exists and switching between rows skips the full hover-intent delay.
+function createUnreadPreviewManager(): UnreadPreviewManager {
+ const [activeGroupId, setActiveGroupId] = createSignal<string | null>(null);
+ let warm = false;
+ let pendingGroupId: string | null = null;
+ let openTimer: number | undefined;
+ let closeTimer: number | undefined;
+ let warmTimer: number | undefined;
+
+ const clearOpenTimer = () => {
+ window.clearTimeout(openTimer);
+ openTimer = undefined;
+ pendingGroupId = null;
+ };
+
+ const clearCloseTimer = () => {
+ window.clearTimeout(closeTimer);
+ closeTimer = undefined;
+ };
+
+ const startWarmLinger = () => {
+ warm = true;
+ window.clearTimeout(warmTimer);
+ warmTimer = window.setTimeout(() => {
+ warm = false;
+ }, PREVIEW_WARM_LINGER_MS);
+ };
+
+ const rowEnter = (groupId: string) => {
+ clearCloseTimer();
+ clearOpenTimer();
+ if (activeGroupId() === groupId) return;
+ const delay =
+ activeGroupId() !== null || warm
+ ? PREVIEW_WARM_OPEN_DELAY_MS
+ : PREVIEW_OPEN_DELAY_MS;
+ pendingGroupId = groupId;
+ openTimer = window.setTimeout(() => {
+ openTimer = undefined;
+ pendingGroupId = null;
+ window.clearTimeout(warmTimer);
+ setActiveGroupId(groupId);
+ }, delay);
+ };
+
+ const scheduleClose = () => {
+ clearCloseTimer();
+ if (activeGroupId() === null) return;
+ closeTimer = window.setTimeout(() => {
+ closeTimer = undefined;
+ setActiveGroupId(null);
+ startWarmLinger();
+ }, PREVIEW_CLOSE_DELAY_MS);
+ };
+
+ const rowLeave = () => {
+ clearOpenTimer();
+ scheduleClose();
+ };
+
+ const dismiss = (groupId?: string) => {
+ if (groupId === undefined || pendingGroupId === groupId) {
+ clearOpenTimer();
+ }
+ if (groupId !== undefined && activeGroupId() !== groupId) return;
+ clearCloseTimer();
+ if (activeGroupId() !== null) {
+ setActiveGroupId(null);
+ startWarmLinger();
+ }
+ };
+
+ createEffect(() => {
+ if (activeGroupId() === null) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') dismiss();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ onCleanup(() => window.removeEventListener('keydown', onKeyDown));
+ });
+
+ onCleanup(() => {
+ clearOpenTimer();
+ clearCloseTimer();
+ window.clearTimeout(warmTimer);
+ });
+
+ return {
+ activeGroupId,
+ rowEnter,
+ rowLeave,
+ cardEnter: clearCloseTimer,
+ cardLeave: scheduleClose,
+ dismiss,
+ };
+}
+
+const UnreadPreviewContext = createContext<UnreadPreviewManager>();
+
+function useUnreadPreviewManager(): UnreadPreviewManager {
+ const manager = useContext(UnreadPreviewContext);
+ if (!manager) {
+ throw new Error(
+ 'useUnreadPreviewManager must be used inside UnreadPreviewContext'
+ );
+ }
+ return manager;
+}
// Unique thread roots (a reply previews its whole thread), newest first.
function getPreviewThreadRoots(group: ChannelGroup): string[] {
@@ -137,15 +271,173 @@ function getPreviewThreadRoots(group: ChannelGroup): string[] {
return roots;
}
+// Every notification in the group is unread, so the unread ids per thread
+// root are just the notification message ids grouped by root.
+function getGroupUnreadInfo(group: ChannelGroup): {
+ unreadIdsByRoot: Map<string, string[]>;
+ anchorMessageId: string | null;
+} {
+ const unreadIdsByRoot = new Map<string, string[]>();
+ let anchorMessageId: string | null = null;
+ for (const notification of group.notifications) {
+ const { messageId, threadId } = getChannelNotificationParams(notification);
+ if (!messageId) continue;
+ const rootId = threadId ?? messageId;
+ anchorMessageId ??= messageId;
+ const ids = unreadIdsByRoot.get(rootId);
+ if (ids) {
+ ids.push(messageId);
+ } else {
+ unreadIdsByRoot.set(rootId, [messageId]);
+ }
+ }
+ return { unreadIdsByRoot, anchorMessageId };
+}
+
+function prefetchGroupPreview(group: ChannelGroup) {
+ const roots = getPreviewThreadRoots(group).slice(0, HOVER_PREVIEW_COUNT);
+ const replyRootIds = new Set<string>();
+ for (const notification of group.notifications) {
+ const { threadId } = getChannelNotificationParams(notification);
+ if (threadId) replyRootIds.add(threadId);
+ }
+
+ for (const rootId of roots) {
+ const parentOptions = channelMessagesByIdsQueryOptions(group.entityId, [
+ rootId,
+ ]);
+ const parentPrefetch = queryClient.prefetchQuery(parentOptions);
+ if (replyRootIds.has(rootId)) {
+ void queryClient.prefetchQuery(
+ threadRepliesQueryOptions(group.entityId, rootId)
+ );
+ } else {
+ void parentPrefetch.then(() => {
+ const parent = queryClient.getQueryData<ApiChannelMessage[]>(
+ parentOptions.queryKey
+ )?.[0];
+ if ((parent?.thread.reply_count ?? 0) > 0) {
+ void queryClient.prefetchQuery(
+ threadRepliesQueryOptions(group.entityId, rootId)
+ );
+ }
+ });
+ }
+ }
+}
+
+function PreviewThreadError(props: { retry: () => void }) {
+ return (
+ <div class="flex items-center gap-3 px-3 py-2.5">
+ <div class="flex size-8 shrink-0 items-center justify-center rounded-full bg-failure/10 text-failure [&_svg]:size-4">
+ <WarningIcon />
+ </div>
+ <p class="min-w-0 flex-1 text-sm text-ink-muted">Failed to load thread</p>
+ <Button
+ variant="base"
+ size="sm"
+ depth={2}
+ class="w-fit shrink-0 bg-surface"
+ onClick={props.retry}
+ >
+ <RefreshIcon class="size-3.5" />
+ Try again
+ </Button>
+ </div>
+ );
+}
+
+function PreviewThreadSkeleton() {
+ return (
+ <div class="flex flex-col gap-3 px-3 py-2">
+ <div class="flex items-center gap-2">
+ <div class="skeleton-shimmer size-5 rounded-full bg-ink/10" />
+ <div class="skeleton-shimmer h-3 w-24 rounded-sm bg-ink/10" />
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <div class="skeleton-shimmer h-3 w-full rounded-sm bg-ink/10" />
+ <div class="skeleton-shimmer h-3 w-2/3 rounded-sm bg-ink/10" />
+ </div>
+ </div>
+ );
+}
+
function GroupHoverPreview(props: { group: ChannelGroup }) {
const orchestrator = useGlobalBlockOrchestrator();
const roots = () => getPreviewThreadRoots(props.group);
// Show the latest few threads oldest → newest, like the channel reads.
const visible = () => roots().slice(0, HOVER_PREVIEW_COUNT).reverse();
const hiddenCount = () => roots().length - visible().length;
+ const unreadInfo = createMemo(() => getGroupUnreadInfo(props.group));
+
+ let scrollRef: HTMLDivElement | undefined;
+
+ // Pin the newest unread message into view, waiting out slow thread
+ // loads, until the user scrolls the card themselves.
+ onMount(() => {
+ const container = scrollRef;
+ if (!container) return;
+ const anchorId = unreadInfo().anchorMessageId;
+ const startedAt = performance.now();
+ let anchorFoundAt = anchorId ? undefined : startedAt;
+ let cancelled = false;
+ let frame: number | undefined;
+
+ const cancel = () => {
+ cancelled = true;
+ };
+ container.addEventListener('wheel', cancel, { passive: true });
+ container.addEventListener('pointerdown', cancel);
+
+ const pin = () => {
+ frame = undefined;
+ if (cancelled) return;
+ const target = anchorId
+ ? container.querySelector<HTMLElement>(
+ `[data-message-id="${anchorId}"]`
+ )
+ : null;
+ if (target) {
+ anchorFoundAt ??= performance.now();
+ const containerRect = container.getBoundingClientRect();
+ const targetRect = target.getBoundingClientRect();
+ const bottomDelta = targetRect.bottom - containerRect.bottom;
+ const topDelta = targetRect.top - containerRect.top;
+ // A message taller than the card can never fit, so align its top
+ // once instead of oscillating between top and bottom alignment.
+ if (targetRect.height >= containerRect.height) {
+ if (Math.abs(topDelta) > 1) container.scrollTop += topDelta;
+ } else if (bottomDelta > 1) {
+ container.scrollTop += bottomDelta;
+ } else if (topDelta < -1) {
+ container.scrollTop += topDelta;
+ }
+ } else {
+ container.scrollTop = container.scrollHeight;
+ }
+ const deadline =
+ anchorFoundAt === undefined
+ ? startedAt + PREVIEW_ANCHOR_WAIT_MS
+ : anchorFoundAt + PREVIEW_ANCHOR_PIN_MS;
+ if (performance.now() < deadline) {
+ frame = requestAnimationFrame(pin);
+ }
+ };
+ frame = requestAnimationFrame(pin);
+
+ onCleanup(() => {
+ cancelled = true;
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ container.removeEventListener('wheel', cancel);
+ container.removeEventListener('pointerdown', cancel);
+ });
+ });
return (
- <div class="w-90 min-h-12 max-h-96 overflow-y-auto overscroll-contain flex flex-col py-1">
+ <div
+ ref={scrollRef}
+ class="w-90 min-h-12 max-h-96 overflow-y-auto overscroll-contain flex flex-col py-1"
+ >
<Show when={hiddenCount() > 0}>
<span class="px-3 py-1 text-xs text-ink-extra-muted">
+{hiddenCount()} earlier
@@ -156,6 +448,9 @@ function GroupHoverPreview(props: { group: ChannelGroup }) {
<ReadonlyThread
channelId={props.group.entityId}
messageId={rootMessageId}
+ unreadMessageIds={unreadInfo().unreadIdsByRoot.get(rootMessageId)}
+ fallback={<PreviewThreadSkeleton />}
+ errorFallback={(retry) => <PreviewThreadError retry={retry} />}
onClickMessage={(clickedMessageId, e) => {
e.stopPropagation();
const isReply = clickedMessageId !== rootMessageId;
@@ -176,30 +471,48 @@ function GroupHoverPreview(props: { group: ChannelGroup }) {
function UnreadHoverCard(
props: ParentProps<{ group: ChannelGroup; disabled?: boolean }>
) {
- const [hovered, setHovered] = createSignal(false);
- const open = () => hovered() && !props.disabled;
+ const manager = useUnreadPreviewManager();
+ const groupId = () => props.group.entityId;
+ const open = () => manager.activeGroupId() === groupId() && !props.disabled;
+
+ createEffect(() => {
+ if (props.disabled) manager.dismiss(groupId());
+ });
+
+ onCleanup(() => manager.dismiss(groupId()));
return (
<Show when={!isTouchDevice()} fallback={props.children}>
<KobalteTooltip
open={open()}
- onOpenChange={setHovered}
+ triggerOnFocusOnly={true}
placement="right"
overflowPadding={16}
fitViewport={true}
- closeDelay={250}
- openDelay={1000}
flip={true}
gutter={4}
>
<KobalteTooltip.Trigger
class="inline-flex items-center w-full"
as="div"
+ onPointerEnter={(e: PointerEvent) => {
+ if (e.pointerType === 'touch') return;
+ prefetchGroupPreview(props.group);
+ manager.rowEnter(groupId());
+ }}
+ onPointerLeave={(e: PointerEvent) => {
+ if (e.pointerType === 'touch') return;
+ manager.rowLeave();
+ }}
>
{props.children}
</KobalteTooltip.Trigger>
<KobalteTooltip.Portal>
- <KobalteTooltip.Content class="z-tool-tip max-w-[calc(100vw-32px)] menu-open-animation">
+ <KobalteTooltip.Content
+ class="z-tool-tip max-w-[calc(100vw-32px)] menu-open-animation"
+ onPointerEnter={() => manager.cardEnter()}
+ onPointerLeave={() => manager.cardLeave()}
+ >
<Surface depth={3}>
<GroupHoverPreview group={props.group} />
</Surface>
@@ -381,6 +694,7 @@ function filterUnreadNotDone(notifications: UnifiedNotification[]) {
export const ChannelsUnreadWidget = (props: { sidebarState: SidebarState }) => {
const notificationSource = useGlobalNotificationSource();
+ const previewManager = createUnreadPreviewManager();
const allNotifications = () => [...notificationSource.notifications()];
const filteredNotifications = () => filterUnreadNotDone(allNotifications());
@@ -418,14 +732,22 @@ export const ChannelsUnreadWidget = (props: { sidebarState: SidebarState }) => {
.filter((g): g is ChannelGroup => g != null);
});
+ // Iterate stable entity ids so notification refreshes update rows in place
+ // instead of remounting them, which would close an open hover preview.
+ const visibleGroupIds = createMemo(() =>
+ orderedIds().filter((id) => channelGroupsMap().has(id))
+ );
+
+ const groupById = (id: string) => channelGroupsMap().get(id);
+
const channelLettersMap = createMemo(() =>
computeChannelLetters(channelGroups())
);
const isSlim = () => props.sidebarState === 'slim';
const SLIM_MAX = 4;
- const slimVisible = () => channelGroups().slice(0, SLIM_MAX);
- const slimOverflow = () => Math.max(0, channelGroups().length - SLIM_MAX);
+ const slimVisibleIds = () => visibleGroupIds().slice(0, SLIM_MAX);
+ const slimOverflow = () => Math.max(0, visibleGroupIds().length - SLIM_MAX);
const [hasOverflowTop, setHasOverflowTop] = createSignal(false);
const [hasOverflowBottom, setHasOverflowBottom] = createSignal(false);
const [scrollRef, setScrollRef] = createSignal<HTMLDivElement>();
@@ -500,65 +822,74 @@ export const ChannelsUnreadWidget = (props: { sidebarState: SidebarState }) => {
});
return (
- <Show when={channelGroups().length > 0}>
- <Show
- when={!isSlim()}
- fallback={
- <section class="w-full py-1.5 flex flex-col items-start gap-0.5">
- <For each={slimVisible()}>
- {(group) => (
- <ChannelGroupItem
- group={group}
- animate={false}
- isSlim
- channelLetters={channelLettersMap().get(group.entityId)}
- />
- )}
- </For>
- <Show when={slimOverflow() > 0}>
- <span class="w-full text-center text-xxs text-ink-muted mt-1">
- +{slimOverflow()}
- </span>
- </Show>
- </section>
- }
- >
- <section class="size-full min-h-0 flex flex-col px-0 py-1.5">
- <header class="shrink-0 text-xs font-medium text-ink-extra-muted/50 my-1 px-1">
- <h1>Unread</h1>
- </header>
-
- <div ref={setScrollFrameRef} class="relative min-h-0 flex-1">
- <div
- ref={attachScrollEl}
- onScroll={updateScrollShadows}
- class="size-full overflow-y-auto overscroll-contain flex flex-col gap-0.5 pr-1 -mr-1"
- >
- <For each={channelGroups()}>
- {(group) => (
- <ChannelGroupItem
- group={group}
- animate={false}
- channelLetters={channelLettersMap().get(group.entityId)}
- />
+ <UnreadPreviewContext.Provider value={previewManager}>
+ <Show when={channelGroups().length > 0}>
+ <Show
+ when={!isSlim()}
+ fallback={
+ <section class="w-full py-1.5 flex flex-col items-start gap-0.5">
+ <For each={slimVisibleIds()}>
+ {(entityId) => (
+ <Show when={groupById(entityId) != null}>
+ <ChannelGroupItem
+ group={groupById(entityId)!}
+ animate={false}
+ isSlim
+ channelLetters={channelLettersMap().get(entityId)}
+ />
+ </Show>
)}
</For>
+ <Show when={slimOverflow() > 0}>
+ <span class="w-full text-center text-xxs text-ink-muted mt-1">
+ +{slimOverflow()}
+ </span>
+ </Show>
+ </section>
+ }
+ >
+ <section class="size-full min-h-0 flex flex-col px-0 py-1.5">
+ <header class="shrink-0 text-xs font-medium text-ink-extra-muted/50 my-1 px-1">
+ <h1>Unread</h1>
+ </header>
+
+ <div ref={setScrollFrameRef} class="relative min-h-0 flex-1">
+ <div
+ ref={attachScrollEl}
+ onScroll={() => {
+ updateScrollShadows();
+ previewManager.dismiss();
+ }}
+ class="size-full overflow-y-auto overscroll-contain flex flex-col gap-0.5 pr-1 -mr-1"
+ >
+ <For each={visibleGroupIds()}>
+ {(entityId) => (
+ <Show when={groupById(entityId) != null}>
+ <ChannelGroupItem
+ group={groupById(entityId)!}
+ animate={false}
+ channelLetters={channelLettersMap().get(entityId)}
+ />
+ </Show>
+ )}
+ </For>
+ </div>
+ <div
+ class={cn(
+ 'pointer-events-none absolute inset-x-0 top-0 h-3 transition-opacity bg-gradient-to-b from-surface to-transparent',
+ hasOverflowTop() ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ <div
+ class={cn(
+ 'pointer-events-none absolute inset-x-0 bottom-0 h-3 transition-opacity bg-gradient-to-t from-surface to-transparent',
+ hasOverflowBottom() ? 'opacity-100' : 'opacity-0'
+ )}
+ />
</div>
- <div
- class={cn(
- 'pointer-events-none absolute inset-x-0 top-0 h-3 transition-opacity bg-gradient-to-b from-surface to-transparent',
- hasOverflowTop() ? 'opacity-100' : 'opacity-0'
- )}
- />
- <div
- class={cn(
- 'pointer-events-none absolute inset-x-0 bottom-0 h-3 transition-opacity bg-gradient-to-t from-surface to-transparent',
- hasOverflowBottom() ? 'opacity-100' : 'opacity-0'
- )}
- />
- </div>
- </section>
+ </section>
+ </Show>
</Show>
- </Show>
+ </UnreadPreviewContext.Provider>
);
};
diff --git a/js/app/packages/channel/DebugSuspense.tsx b/js/app/packages/channel/DebugSuspense.tsx
index bf969fafca..f25ad23868 100644
--- a/js/app/packages/channel/DebugSuspense.tsx
+++ b/js/app/packages/channel/DebugSuspense.tsx
@@ -3,6 +3,7 @@ import { type JSX, Suspense } from 'solid-js';
type DebugSuspenseProps = {
name: string;
children: JSX.Element;
+ fallback?: JSX.Element;
};
function DebugSuspenseFallback(props: Pick<DebugSuspenseProps, 'name'>) {
@@ -12,7 +13,9 @@ function DebugSuspenseFallback(props: Pick<DebugSuspenseProps, 'name'>) {
export function DebugSuspense(props: DebugSuspenseProps) {
return (
- <Suspense fallback={<DebugSuspenseFallback name={props.name} />}>
+ <Suspense
+ fallback={props.fallback ?? <DebugSuspenseFallback name={props.name} />}
+ >
{props.children}
</Suspense>
);
diff --git a/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx b/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx
index be1dab243a..38773f7ce1 100644
--- a/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx
+++ b/js/app/packages/channel/StandaloneThread/ReadonlyThread.tsx
@@ -1,10 +1,14 @@
import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
+import type { JSX } from 'solid-js';
import { StandaloneThread } from './StandaloneThread';
type ReadonlyThreadProps = {
channelId: string;
messageId: string;
data?: ApiChannelMessage;
+ unreadMessageIds?: string[];
+ fallback?: JSX.Element;
+ errorFallback?: (retry: () => void) => JSX.Element;
onClickMessage?: (messageId: string, e: MouseEvent) => void;
};
@@ -14,6 +18,9 @@ export function ReadonlyThread(props: ReadonlyThreadProps) {
channelId={props.channelId}
messageId={props.messageId}
data={props.data}
+ unreadMessageIds={props.unreadMessageIds}
+ fallback={props.fallback}
+ errorFallback={props.errorFallback}
>
<StandaloneThread.ParentMessage
onClickMessage={props.onClickMessage}
diff --git a/js/app/packages/channel/StandaloneThread/Replies.tsx b/js/app/packages/channel/StandaloneThread/Replies.tsx
index c5a34139aa..5b2e3aafc1 100644
--- a/js/app/packages/channel/StandaloneThread/Replies.tsx
+++ b/js/app/packages/channel/StandaloneThread/Replies.tsx
@@ -1,5 +1,10 @@
import { createMemo, For, Show } from 'solid-js';
-import { Message, type MessageActions, type MessageData } from '../Message';
+import {
+ Message,
+ type MessageActions,
+ type MessageData,
+ MessageFlag,
+} from '../Message';
import { Thread } from '../Thread';
import { buildThreadReplyListMeta } from '../Thread/reply-list-meta';
import { ThreadRail } from '../Thread/ThreadRail';
@@ -22,7 +27,9 @@ export function Replies(props: RepliesProps) {
const ctx = useStandaloneThread();
const listMetaByReplyId = createMemo(() =>
- buildThreadReplyListMeta(ctx.displayReplies())
+ buildThreadReplyListMeta(ctx.displayReplies(), (reply) =>
+ ctx.unreadMessageIds().has(reply.id)
+ )
);
const collapsedRepliesCount = () =>
@@ -38,7 +45,15 @@ export function Replies(props: RepliesProps) {
getThreadLatestReplyAt(ctx.parent()?.thread.latest_reply_at, ctx.replies());
const shouldShowCollapsedIndicator = () =>
- !ctx.isReplying() && !ctx.isExpanded() && collapsedRepliesCount() > 0;
+ !ctx.isReplying() &&
+ !ctx.isExpanded() &&
+ ctx.hiddenEarlierReplyCount() === 0 &&
+ collapsedRepliesCount() > 0;
+
+ const earlierReplyUsers = () =>
+ getUniqueReplyUserIds(
+ ctx.replies().slice(0, ctx.hiddenEarlierReplyCount())
+ );
const replyAction = () => {
const parent = ctx.parent();
@@ -61,6 +76,15 @@ export function Replies(props: RepliesProps) {
firstThreadReplyNewMessage={false}
/>
<Thread.RepliesContainer>
+ <Show when={ctx.hiddenEarlierReplyCount() > 0}>
+ <Thread.ActionsFooter>
+ <Thread.CollapsedIndicator
+ collapsedRepliesCount={ctx.hiddenEarlierReplyCount()}
+ participants={earlierReplyUsers()}
+ onClick={() => ctx.setIsExpanded(true)}
+ />
+ </Thread.ActionsFooter>
+ </Show>
<For each={ctx.displayReplies()}>
{(reply) => {
const replyMessage = () =>
@@ -70,7 +94,10 @@ export function Replies(props: RepliesProps) {
props.getMessageActions?.(replyMessage());
return (
<div class="relative">
- <ThreadRail />
+ <ThreadRail newMessage={meta()?.isNewMessage} />
+ <Show when={meta()?.isFirstNewMessage}>
+ <MessageFlag text="New" highlightBelow class="h-8" />
+ </Show>
<Message.Root
message={replyMessage()}
actions={replyActions()}
diff --git a/js/app/packages/channel/StandaloneThread/Root.tsx b/js/app/packages/channel/StandaloneThread/Root.tsx
index 42597f6c81..beb2e0f4a7 100644
--- a/js/app/packages/channel/StandaloneThread/Root.tsx
+++ b/js/app/packages/channel/StandaloneThread/Root.tsx
@@ -3,7 +3,15 @@ import { useChannelMessagesByIdsQuery } from '@queries/channel/channel-messages'
import { useThreadRepliesQuery } from '@queries/channel/thread-replies';
import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
import type { ApiThreadReply } from '@service-storage/generated/schemas/apiThreadReply';
-import { createSignal, type ParentProps, Show } from 'solid-js';
+import {
+ createMemo,
+ createSignal,
+ type JSX,
+ Match,
+ type ParentProps,
+ Show,
+ Switch,
+} from 'solid-js';
import { createFocusRequest } from '../Thread/focus-request';
import { ThreadRail } from '../Thread/ThreadRail';
import { DEFAULT_VISIBLE_REPLY_COUNT } from '../Thread/utils/thread-reply-indicator-helpers';
@@ -13,11 +21,14 @@ type RootProps = ParentProps<{
channelId: string;
messageId: string;
data?: ApiChannelMessage;
+ unreadMessageIds?: string[];
+ fallback?: JSX.Element;
+ errorFallback?: (retry: () => void) => JSX.Element;
}>;
export function Root(props: RootProps) {
return (
- <DebugSuspense name="StandaloneThread.Root">
+ <DebugSuspense name="StandaloneThread.Root" fallback={props.fallback}>
<RootInner {...props} />
</DebugSuspense>
);
@@ -47,12 +58,43 @@ function RootInner(props: RootProps) {
const hasReplies = () => replies().length > 0;
+ const unreadMessageIds = createMemo(
+ () => new Set(props.unreadMessageIds ?? [])
+ );
+
+ // Window the visible replies so the first unread reply is always shown,
+ // while keeping at least the default count when the thread is short.
+ const unreadWindowStart = createMemo(() => {
+ const ids = unreadMessageIds();
+ if (ids.size === 0) return -1;
+ const all = replies();
+ const firstUnread = all.findIndex((reply) => ids.has(reply.id));
+ if (firstUnread < 0) return -1;
+ return Math.min(
+ firstUnread,
+ Math.max(0, all.length - DEFAULT_VISIBLE_REPLY_COUNT)
+ );
+ });
+
const displayReplies = (): ApiThreadReply[] => {
const all = replies();
if (isExpanded()) return all;
+ const windowStart = unreadWindowStart();
+ if (windowStart >= 0) return all.slice(windowStart);
return all.slice(0, DEFAULT_VISIBLE_REPLY_COUNT);
};
+ const hiddenEarlierReplyCount = () =>
+ isExpanded() ? 0 : Math.max(unreadWindowStart(), 0);
+
+ const showLoadingFallback = () =>
+ props.fallback !== undefined &&
+ !parent() &&
+ (parentQuery.isPending || parentQuery.isFetching);
+
+ const showErrorFallback = () =>
+ props.errorFallback !== undefined && !parent() && parentQuery.isError;
+
return (
<StandaloneThreadContext.Provider
value={{
@@ -61,6 +103,8 @@ function RootInner(props: RootProps) {
parent,
replies,
displayReplies,
+ unreadMessageIds,
+ hiddenEarlierReplyCount,
hasReplies,
isExpanded,
setIsExpanded,
@@ -69,12 +113,21 @@ function RootInner(props: RootProps) {
replyInputFocusRequest,
}}
>
- <div class="relative">
- <Show when={hasReplies() || isReplying()}>
- <ThreadRail />
- </Show>
- {props.children}
- </div>
+ <Switch
+ fallback={
+ <div class="relative">
+ <Show when={hasReplies() || isReplying()}>
+ <ThreadRail />
+ </Show>
+ {props.children}
+ </div>
+ }
+ >
+ <Match when={showLoadingFallback()}>{props.fallback}</Match>
+ <Match when={showErrorFallback()}>
+ {props.errorFallback?.(() => void parentQuery.refetch())}
+ </Match>
+ </Switch>
</StandaloneThreadContext.Provider>
);
}
diff --git a/js/app/packages/channel/StandaloneThread/context.ts b/js/app/packages/channel/StandaloneThread/context.ts
index 5737936a89..cc7dea4880 100644
--- a/js/app/packages/channel/StandaloneThread/context.ts
+++ b/js/app/packages/channel/StandaloneThread/context.ts
@@ -14,6 +14,8 @@ export type StandaloneThreadContextValue = {
parent: Accessor<ApiChannelMessage | undefined>;
replies: Accessor<ApiThreadReply[]>;
displayReplies: Accessor<ApiThreadReply[]>;
+ unreadMessageIds: Accessor<ReadonlySet<string>>;
+ hiddenEarlierReplyCount: Accessor<number>;
hasReplies: Accessor<boolean>;
isExpanded: Accessor<boolean>;
setIsExpanded: Setter<boolean>;
diff --git a/js/app/packages/channel/Thread/reply-list-meta.ts b/js/app/packages/channel/Thread/reply-list-meta.ts
index c34c5167ee..81c3888d61 100644
--- a/js/app/packages/channel/Thread/reply-list-meta.ts
+++ b/js/app/packages/channel/Thread/reply-list-meta.ts
@@ -1,11 +1,10 @@
import type { ApiThreadReply } from '@service-storage/generated/schemas/apiThreadReply';
import { shouldGroupWithPreviousMessage } from '../Channel/message-grouping-meta';
-import type { NewMessageCheckable } from '../Channel/util';
import type { ChannelMessageListMeta } from '../Message';
export function buildThreadReplyListMeta(
replies: ApiThreadReply[],
- isNewMessageFn?: (message: NewMessageCheckable) => boolean
+ isNewMessageFn?: (message: ApiThreadReply) => boolean
): Record<string, ChannelMessageListMeta> {
let foundFirstNewMessage = false;
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index d9a0a4d25b..b7125f515a 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -118,29 +118,33 @@ export function useChannelMessagesQuery(
);
}
+export function channelMessagesByIdsQueryOptions(
+ channelId: string,
+ messageIds: string[]
+) {
+ return {
+ queryKey: channelKeys.messagesByIds(channelId, messageIds).queryKey,
+ queryFn: async (): Promise<ApiChannelMessage[]> => {
+ const page = await throwOnErr(() =>
+ storageServiceClient.postChannelMessages({
+ channel_id: channelId,
+ filters: { message_ids: messageIds },
+ })
+ );
+ return page.items.map(normalizeChannelMessageSender);
+ },
+ staleTime: Infinity,
+ };
+}
+
export function useChannelMessagesByIdsQuery(
channelId: Accessor<string>,
messageIds: Accessor<string[]>
) {
- return useQuery(() => {
- const resolvedChannelId = channelId();
- const resolvedMessageIds = messageIds();
- return {
- queryKey: channelKeys.messagesByIds(resolvedChannelId, resolvedMessageIds)
- .queryKey,
- queryFn: async (): Promise<ApiChannelMessage[]> => {
- const page = await throwOnErr(() =>
- storageServiceClient.postChannelMessages({
- channel_id: resolvedChannelId,
- filters: { message_ids: resolvedMessageIds },
- })
- );
- return page.items.map(normalizeChannelMessageSender);
- },
- enabled: resolvedMessageIds.length > 0,
- staleTime: Infinity,
- };
- });
+ return useQuery(() => ({
+ ...channelMessagesByIdsQueryOptions(channelId(), messageIds()),
+ enabled: messageIds().length > 0,
+ }));
}
/** Returns the cache key for one channel message query variant. */