Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat: recent channel widget (#5321)

Peter Chinmana9fa216b0fdb
diff --git a/apps/web/src/components/app/app-sidebar/collapsible-sidebar-section.tsx b/apps/web/src/components/app/app-sidebar/collapsible-sidebar-section.tsx
index 5113839aeb..667358ac75 100644
--- a/apps/web/src/components/app/app-sidebar/collapsible-sidebar-section.tsx
+++ b/apps/web/src/components/app/app-sidebar/collapsible-sidebar-section.tsx
@@ -1,4 +1,5 @@
import CaretDownIcon from '@phosphor/caret-down.svg';
+import { makePersisted } from '@solid-primitives/storage';
import { cn } from '@ui';
import { createSignal, For, type JSX, onCleanup, Show } from 'solid-js';
@@ -13,9 +14,18 @@ export function CollapsibleSidebarSection(props: {
items: readonly CollapsibleSidebarSectionItem[];
headerMenu?: () => JSX.Element;
defaultOpen?: boolean;
+ /** Persist the open state locally under this key. */
+ persistKey?: string;
onOpenChange?: (open: boolean) => void;
}) {
- const [open, setOpen] = createSignal(props.defaultOpen ?? true);
+ // With a `persistKey` the signal itself is persisted — the setter writes
+ // through to local storage, so a refresh restores the toggled state.
+ const [open, setOpen] =
+ props.persistKey !== undefined
+ ? makePersisted(createSignal(props.defaultOpen ?? true), {
+ name: `sidebar-section-open:${props.persistKey}`,
+ })
+ : createSignal(props.defaultOpen ?? true);
let openChangeTimer: ReturnType<typeof setTimeout> | undefined;
onCleanup(() => {
diff --git a/apps/web/src/components/app/app-sidebar/sidebar.tsx b/apps/web/src/components/app/app-sidebar/sidebar.tsx
index 70beb11590..9fe1c723bf 100644
--- a/apps/web/src/components/app/app-sidebar/sidebar.tsx
+++ b/apps/web/src/components/app/app-sidebar/sidebar.tsx
@@ -1,7 +1,7 @@
import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';
import { LIST_VIEW_PATHS, type ListView } from '@app/constants/list-views';
import { SidebarActiveCallWidget } from '@app/features/block-call/sidebar/active-call-widget';
-import { ChannelsUnreadWidget } from '@app/features/channel/sidebar/channels-unread-widget';
+import { ChannelsRecentWidget } from '@app/features/channel/sidebar/channels-recent-widget';
import { CommandState } from '@app/features/command';
import { SidebarCreateMenu } from '@app/features/command/sidebar/sidebar-create-menu';
import { FavoritesSection } from '@app/features/favorites/sidebar/favorites-section';
@@ -145,8 +145,10 @@ type TryItemId = 'connect' | 'invite' | 'mobile';
type TryItemVisibility = Record<TryItemId, boolean>;
-const COMMUNICATIONS_LINK_IDS = ['mail', 'channels', 'calls'] as const;
const WORKSPACE_LINK_IDS = [
+ 'mail',
+ 'channels',
+ 'calls',
'documents',
'tasks',
'agents',
@@ -1259,9 +1261,6 @@ export const AppSidebar = (props: AppSidebarProps) => {
.filter((link): link is SidebarItem => link !== undefined)
.map(toSectionItem);
- const communicationsItems = createMemo(() =>
- sectionItemsFor(COMMUNICATIONS_LINK_IDS)
- );
const workspaceItems = createMemo(() => sectionItemsFor(WORKSPACE_LINK_IDS));
const toggleSectionVisibility = (id: SidebarSectionLinkId) => {
@@ -1351,7 +1350,6 @@ export const AppSidebar = (props: AppSidebarProps) => {
createEffect(() => {
middleScrollSize.width;
middleScrollSize.height;
- communicationsItems().length;
workspaceItems().length;
tryItems().length;
props.overlayOpen;
@@ -1444,39 +1442,20 @@ export const AppSidebar = (props: AppSidebarProps) => {
onScroll={updateMiddleScrollShadows}
class="size-full overflow-y-auto flex flex-col gap-3"
>
- <Show
- when={sectionMenuOptionsFor(COMMUNICATIONS_LINK_IDS).length > 0}
- >
- <CollapsibleSidebarSection
- label="Conversations"
- items={communicationsItems()}
- headerMenu={() => (
- <SidebarSectionMenu
- label="Conversations"
- options={sectionMenuOptionsFor(COMMUNICATIONS_LINK_IDS)}
- onToggle={toggleSectionVisibility}
- onOpenChange={handleWorkspaceContextMenuOpenChange}
- />
- )}
- onOpenChange={scheduleMiddleScrollUpdate}
- />
- </Show>
-
- <Show when={sectionMenuOptionsFor(WORKSPACE_LINK_IDS).length > 0}>
- <CollapsibleSidebarSection
- label="Workspace"
- items={workspaceItems()}
- headerMenu={() => (
- <SidebarSectionMenu
- label="Workspace"
- options={sectionMenuOptionsFor(WORKSPACE_LINK_IDS)}
- onToggle={toggleSectionVisibility}
- onOpenChange={handleWorkspaceContextMenuOpenChange}
- />
- )}
- onOpenChange={scheduleMiddleScrollUpdate}
- />
- </Show>
+ <CollapsibleSidebarSection
+ label="Workspace"
+ persistKey="workspace"
+ items={workspaceItems()}
+ headerMenu={() => (
+ <SidebarSectionMenu
+ label="Workspace"
+ options={sectionMenuOptionsFor(WORKSPACE_LINK_IDS)}
+ onToggle={toggleSectionVisibility}
+ onOpenChange={handleWorkspaceContextMenuOpenChange}
+ />
+ )}
+ onOpenChange={scheduleMiddleScrollUpdate}
+ />
<Suspense>
<FavoritesSection
@@ -1485,15 +1464,10 @@ export const AppSidebar = (props: AppSidebarProps) => {
/>
</Suspense>
- <ChannelsUnreadWidget
- sidebarState={sidebarDisplayState()}
- onSectionOpenChange={scheduleMiddleScrollUpdate}
- onDropdownOpenChange={handleOverlayDropdownOpenChange}
- />
-
<Show when={tryItems().length > 0}>
<CollapsibleSidebarSection
label="Try"
+ persistKey="try"
items={tryItems()}
onOpenChange={scheduleMiddleScrollUpdate}
/>
@@ -1525,6 +1499,13 @@ export const AppSidebar = (props: AppSidebarProps) => {
<InCallPanel isSlim={() => false} />
</div>
</Show>
+ <Suspense>
+ <ChannelsRecentWidget
+ sidebarState={sidebarDisplayState()}
+ onSectionOpenChange={scheduleMiddleScrollUpdate}
+ onDropdownOpenChange={handleOverlayDropdownOpenChange}
+ />
+ </Suspense>
<Show keyed when={isExpandedView() ? firstTeamInvite() : undefined}>
{(invite) => <TeamInviteSidebarPromo invite={invite} />}
</Show>
diff --git a/apps/web/src/features/channel/sidebar/channels-recent-widget.tsx b/apps/web/src/features/channel/sidebar/channels-recent-widget.tsx
new file mode 100644
index 0000000000..cae4a1c390
--- /dev/null
+++ b/apps/web/src/features/channel/sidebar/channels-recent-widget.tsx
@@ -0,0 +1,455 @@
+import {
+ compileToAst,
+ defineQueryFilters,
+ queryStateFrom,
+} from '@app/features/next-soup/filters/filter-store';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { navigateToChannelMessage } from '@block-channel/utils/link';
+import { ReadonlyThread } from '@channel/StandaloneThread';
+import {
+ CollapsibleSidebarSection,
+ type CollapsibleSidebarSectionItem,
+} from '@components/app/app-sidebar/collapsible-sidebar-section';
+import type { SidebarState } from '@components/app/app-sidebar/sidebar';
+import {
+ useGlobalBlockOrchestrator,
+ useGlobalNotificationSource,
+} from '@components/app/GlobalAppState';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import {
+ ContextMenuContent,
+ MenuGroup,
+ MenuItem,
+ MenuSeparator,
+} from '@core/component/ContextMenu';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { compareDateDesc } from '@core/util/date';
+import {
+ type ChannelEntity,
+ EntityRowIcon,
+ isChannelEntity,
+ UnreadIndicator,
+} from '@entity';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import { Tooltip as KobalteTooltip } from '@kobalte/core/tooltip';
+import { openNotification } from '@notifications';
+import {
+ isChannelNotification,
+ notificationIsRead,
+} from '@notifications/notification-helpers';
+import { getChannelNotificationParams } from '@notifications/notification-navigation';
+import type { UnifiedNotification } from '@notifications/types';
+import { useSoupAstItemsQuery } from '@queries/soup/items';
+import { cn, NavRow, Surface, Tooltip } from '@ui';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ onCleanup,
+ type ParentProps,
+ Show,
+} from 'solid-js';
+
+/** Rows the channel list shows before it scrolls internally. */
+const VISIBLE_CHANNEL_COUNT = 5;
+/**
+ * How long the user must be done scrolling the list before a new channel
+ * message snaps it back to the top.
+ */
+const SCROLL_IDLE_SNAP_MS = 5000;
+/** Icon rows shown in the slim rail (unread channels only). */
+const SLIM_MAX = 4;
+const RECENT_CHANNELS_LIMIT = 100;
+const RECENT_CHANNELS_STALE_MS = 5 * 60 * 1000;
+
+/** A channel from the recent-channels query plus its unread notifications. */
+interface RecentChannel {
+ entity: ChannelEntity;
+ /** Unread channel notifications, newest first. */
+ unread: UnifiedNotification[];
+}
+
+/**
+ * Open a channel like the soup list would: an unread channel opens at its
+ * newest unread message, a read one opens at the latest message.
+ */
+function useOpenChannel() {
+ const layout = useSplitLayout();
+ return (channel: RecentChannel, newSplit: boolean) => {
+ const manager = globalSplitManager();
+ if (!manager) return;
+ const notification = channel.unread[0];
+ if (notification) {
+ openNotification(notification, manager, newSplit);
+ return;
+ }
+ layout.openWithSplit(
+ { type: 'channel', id: channel.entity.id },
+ { preferNewSplit: newSplit, referredFrom: 'sidebar' }
+ );
+ };
+}
+
+const HOVER_PREVIEW_COUNT = 3;
+
+// Unique thread roots (a reply previews its whole thread), newest first.
+function getPreviewThreadRoots(notifications: UnifiedNotification[]): string[] {
+ const roots: string[] = [];
+ const seen = new Set<string>();
+ for (const notification of notifications) {
+ const { messageId, threadId } = getChannelNotificationParams(notification);
+ const rootId = threadId ?? messageId;
+ if (!rootId || seen.has(rootId)) continue;
+ seen.add(rootId);
+ roots.push(rootId);
+ }
+ return roots;
+}
+
+function ChannelHoverPreview(props: { channel: RecentChannel }) {
+ const orchestrator = useGlobalBlockOrchestrator();
+ const roots = () => getPreviewThreadRoots(props.channel.unread);
+ // 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;
+
+ return (
+ <div 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
+ </span>
+ </Show>
+ <For each={visible()}>
+ {(rootMessageId) => (
+ <ReadonlyThread
+ channelId={props.channel.entity.id}
+ messageId={rootMessageId}
+ onClickMessage={(clickedMessageId, e) => {
+ e.stopPropagation();
+ const isReply = clickedMessageId !== rootMessageId;
+ navigateToChannelMessage(
+ orchestrator,
+ props.channel.entity.id,
+ clickedMessageId,
+ isReply ? rootMessageId : undefined
+ );
+ }}
+ />
+ )}
+ </For>
+ </div>
+ );
+}
+
+function UnreadHoverCard(
+ props: ParentProps<{
+ channel: RecentChannel;
+ disabled?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ }>
+) {
+ const [hovered, setHovered] = createSignal(false);
+ const open = () => hovered() && !props.disabled;
+
+ createEffect(() => props.onOpenChange?.(open()));
+
+ return (
+ <Show when={!isTouchDevice()} fallback={props.children}>
+ <KobalteTooltip
+ open={open()}
+ onOpenChange={setHovered}
+ 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"
+ >
+ {props.children}
+ </KobalteTooltip.Trigger>
+ <KobalteTooltip.Portal>
+ <KobalteTooltip.Content class="z-tool-tip max-w-[calc(100vw-32px)] menu-open-animation">
+ <Surface
+ depth={3}
+ hideBorder
+ class="shadow-menu ring ring-edge rounded-xl"
+ >
+ <ChannelHoverPreview channel={props.channel} />
+ </Surface>
+ </KobalteTooltip.Content>
+ </KobalteTooltip.Portal>
+ </KobalteTooltip>
+ </Show>
+ );
+}
+
+function ChannelRow(props: {
+ channel: RecentChannel;
+ isSlim?: boolean;
+ onFloatingOpenChange?: (open: boolean) => void;
+}) {
+ const notificationSource = useGlobalNotificationSource();
+ const openChannel = useOpenChannel();
+
+ const entity = () => props.channel.entity;
+ const isUnread = () => props.channel.unread.length > 0;
+ const isSlim = () => props.isSlim ?? false;
+
+ const canOpenInNewSplit = () =>
+ globalSplitManager()?.canAppendSplit() ?? false;
+
+ const openInCurrentSplit = () => openChannel(props.channel, false);
+
+ const openInNewSplit = () => {
+ if (!canOpenInNewSplit()) return;
+ openChannel(props.channel, true);
+ };
+
+ const markAllAsRead = () => {
+ void notificationSource.bulkMarkAsRead(props.channel.unread);
+ };
+
+ const ButtonContent = () => (
+ <NavRow
+ class="justify-start w-full h-7"
+ draggable={false}
+ onMouseDown={(e) => {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ openChannel(props.channel, e.shiftKey);
+ }}
+ >
+ <div class="relative flex items-center justify-center shrink-0 size-5">
+ <div class="size-3.5">
+ <EntityRowIcon entity={entity()} suppressClick showTooltip={false} />
+ </div>
+ <Show when={isSlim() && isUnread()}>
+ <div class="absolute -top-0.5 -right-0.5 size-1.5 bg-accent rounded-full ring-surface ring-2" />
+ </Show>
+ </div>
+
+ <Show when={!isSlim()}>
+ <span class="text-sm font-medium truncate flex-1 text-start">
+ {entity().name}
+ </span>
+ </Show>
+ <Show when={!isSlim() && isUnread()}>
+ <UnreadIndicator active />
+ </Show>
+ </NavRow>
+ );
+
+ const [contextMenuOpen, setContextMenuOpen] = createSignal(false);
+ const [hoverCardOpen, setHoverCardOpen] = createSignal(false);
+
+ createEffect(() => {
+ props.onFloatingOpenChange?.(contextMenuOpen() || hoverCardOpen());
+ });
+
+ return (
+ <ContextMenu onOpenChange={setContextMenuOpen}>
+ <ContextMenu.Trigger
+ class={cn(isSlim() ? 'flex justify-center' : 'w-full')}
+ >
+ <Show
+ when={!isSlim()}
+ fallback={
+ <Tooltip label={entity().name} placement="right">
+ <ButtonContent />
+ </Tooltip>
+ }
+ >
+ <UnreadHoverCard
+ channel={props.channel}
+ disabled={contextMenuOpen() || !isUnread()}
+ onOpenChange={setHoverCardOpen}
+ >
+ <ButtonContent />
+ </UnreadHoverCard>
+ </Show>
+ </ContextMenu.Trigger>
+
+ <ContextMenu.Portal>
+ <ContextMenuContent class="text-xs text-ink-muted">
+ <MenuGroup>
+ <MenuItem
+ text="Open in new split"
+ onClick={openInNewSplit}
+ disabled={!canOpenInNewSplit()}
+ />
+ <MenuItem
+ text="Open in current split"
+ onClick={openInCurrentSplit}
+ />
+ </MenuGroup>
+ <Show when={isUnread()}>
+ <MenuSeparator />
+ <MenuGroup>
+ <MenuItem text="Mark as read" onClick={markAllAsRead} />
+ </MenuGroup>
+ </Show>
+ </ContextMenuContent>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ );
+}
+
+export const ChannelsRecentWidget = (props: {
+ sidebarState: SidebarState;
+ /** Rows visible before the list scrolls. */
+ maxVisible?: number;
+ onSectionOpenChange?: () => void;
+ onDropdownOpenChange?: (open: boolean) => void;
+}) => {
+ const notificationSource = useGlobalNotificationSource();
+
+ const channelsQuery = useSoupAstItemsQuery(
+ () => ({
+ params: { limit: RECENT_CHANNELS_LIMIT, sort_method: 'updated_at' },
+ body: compileToAst(
+ queryStateFrom(
+ defineQueryFilters({
+ include: { channelImportance: true, channelIsParticipant: [true] },
+ })
+ )
+ ),
+ }),
+ () => ({ staleTime: RECENT_CHANNELS_STALE_MS })
+ );
+
+ const unreadByChannel = createMemo(() => {
+ const map = new Map<string, UnifiedNotification[]>();
+ for (const notification of notificationSource.notifications()) {
+ if (notification.entity_type !== 'channel') continue;
+ if (notificationIsRead(notification)) continue;
+ const list = map.get(notification.entity_id);
+ if (list) list.push(notification);
+ else map.set(notification.entity_id, [notification]);
+ }
+ // `unread[0]` must be the newest notification (it aims open-at-unread and
+ // the hover previews); don't rely on the source list's ordering.
+ for (const list of map.values()) {
+ list.sort((a, b) => compareDateDesc(a.created_at, b.created_at));
+ }
+ return map;
+ });
+
+ const recentChannels = createMemo<RecentChannel[]>(() => {
+ const unread = unreadByChannel();
+ const channels = (channelsQuery.data?.entities ?? [])
+ .filter(isChannelEntity)
+ .map((entity) => ({ entity, unread: unread.get(entity.id) ?? [] }));
+ // Same ordering as the channels soup view…
+ channels.sort((a, b) =>
+ compareDateDesc(
+ a.entity.sortTs ?? a.entity.updatedAt,
+ b.entity.sortTs ?? b.entity.updatedAt
+ )
+ );
+ // …but with unread channels sorted to the top.
+ return [
+ ...channels.filter((channel) => channel.unread.length > 0),
+ ...channels.filter((channel) => channel.unread.length === 0),
+ ];
+ });
+
+ const maxVisible = () => props.maxVisible ?? VISIBLE_CHANNEL_COUNT;
+ // The list shows `maxVisible` rows (h-7 rows, gap-0.5) and scrolls inside
+ // itself to reveal the rest.
+ const listMaxHeight = () =>
+ `calc(${maxVisible()} * 1.75rem + ${Math.max(0, maxVisible() - 1)} * 0.125rem)`;
+
+ // The slim rail keeps its "unread at a glance" role: unread channels only.
+ const slimChannels = () =>
+ recentChannels().filter((channel) => channel.unread.length > 0);
+ const slimVisible = () => slimChannels().slice(0, SLIM_MAX);
+ const slimOverflow = () => Math.max(0, slimChannels().length - SLIM_MAX);
+
+ const isSlim = () => props.sidebarState === 'slim';
+
+ let channelListRef: HTMLDivElement | undefined;
+ let lastUserScrollAt = 0;
+ let suppressNextScrollEvent = false;
+
+ const snapToTopIfIdle = () => {
+ const el = channelListRef;
+ if (!el || el.scrollTop === 0) return;
+ if (Date.now() - lastUserScrollAt < SCROLL_IDLE_SNAP_MS) return;
+ // The programmatic scroll fires a scroll event too; don't let it count
+ // as user scrolling.
+ suppressNextScrollEvent = true;
+ el.scrollTop = 0;
+ };
+
+ const unsubscribe = notificationSource.subscribe((notification) => {
+ if (!isChannelNotification(notification)) return;
+ snapToTopIfIdle();
+ });
+ onCleanup(unsubscribe);
+
+ const sectionItems = createMemo<CollapsibleSidebarSectionItem[]>(() => [
+ {
+ id: 'channels-list',
+ visible: () => (
+ <div
+ ref={channelListRef}
+ class="flex flex-col gap-0.5 overflow-y-auto overscroll-contain"
+ style={{ 'max-height': listMaxHeight() }}
+ onScroll={() => {
+ if (suppressNextScrollEvent) {
+ suppressNextScrollEvent = false;
+ return;
+ }
+ lastUserScrollAt = Date.now();
+ }}
+ >
+ <For each={recentChannels()}>
+ {(channel) => (
+ <ChannelRow
+ channel={channel}
+ onFloatingOpenChange={props.onDropdownOpenChange}
+ />
+ )}
+ </For>
+ </div>
+ ),
+ dropdown: () => null,
+ },
+ ]);
+
+ return (
+ <Show
+ when={!isSlim()}
+ fallback={
+ <Show when={slimVisible().length > 0}>
+ <section class="w-full py-1.5 flex flex-col items-start gap-0.5">
+ <For each={slimVisible()}>
+ {(channel) => <ChannelRow channel={channel} isSlim />}
+ </For>
+ <Show when={slimOverflow() > 0}>
+ <span class="w-full text-center text-xxs text-ink-muted mt-1">
+ +{slimOverflow()}
+ </span>
+ </Show>
+ </section>
+ </Show>
+ }
+ >
+ <Show when={recentChannels().length > 0}>
+ <CollapsibleSidebarSection
+ label="Channels"
+ persistKey="recent-channels"
+ items={sectionItems()}
+ onOpenChange={() => props.onSectionOpenChange?.()}
+ />
+ </Show>
+ </Show>
+ );
+};
diff --git a/apps/web/src/features/channel/sidebar/channels-unread-widget.tsx b/apps/web/src/features/channel/sidebar/channels-unread-widget.tsx
deleted file mode 100644
index 362d025a23..0000000000
--- a/apps/web/src/features/channel/sidebar/channels-unread-widget.tsx
+++ /dev/null
@@ -1,514 +0,0 @@
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { navigateToChannelMessage } from '@block-channel/utils/link';
-import { ReadonlyThread } from '@channel/StandaloneThread';
-import {
- CollapsibleSidebarSection,
- type CollapsibleSidebarSectionItem,
-} from '@components/app/app-sidebar/collapsible-sidebar-section';
-import type { SidebarState } from '@components/app/app-sidebar/sidebar';
-import { useSenderName } from '@components/app/app-sidebar/utils';
-import {
- useGlobalBlockOrchestrator,
- useGlobalNotificationSource,
-} from '@components/app/GlobalAppState';
-import { useSplitLayout } from '@components/app/split-layout/layout';
-import {
- ContextMenuContent,
- MenuGroup,
- MenuItem,
- MenuSeparator,
-} from '@core/component/ContextMenu';
-import { EntityIcon } from '@core/component/EntityIcon';
-import { UserIcon } from '@core/component/UserIcon';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { compareDateDesc } from '@core/util/date';
-import { ContextMenu } from '@kobalte/core/context-menu';
-import { Tooltip as KobalteTooltip } from '@kobalte/core/tooltip';
-import { openNotification } from '@notifications';
-import { isChannelNotification } from '@notifications/notification-helpers';
-import { getChannelNotificationParams } from '@notifications/notification-navigation';
-import type { UnifiedNotification } from '@notifications/types';
-import { cn, Dropdown, NavRow, Surface, Tooltip } from '@ui';
-import {
- createEffect,
- createMemo,
- createSignal,
- For,
- on,
- onMount,
- type ParentProps,
- Show,
-} from 'solid-js';
-
-function getChannelInfo(notification: UnifiedNotification): {
- channelName: string | null;
- channelType: string | null;
- isDM: boolean;
-} {
- if (!isChannelNotification(notification)) {
- return { channelName: null, channelType: null, isDM: false };
- }
-
- const meta = notification.notification_metadata;
- const channelType = meta.content.channelType;
- const isDM = channelType === 'directMessage';
- const channelName =
- 'channelName' in meta.content ? (meta.content.channelName ?? null) : null;
- return { channelName, channelType, isDM };
-}
-
-interface ChannelGroup {
- entityId: string;
- channelName: string | null;
- channelType: string | null;
- isDM: boolean;
- notifications: UnifiedNotification[];
- latestSenderId: string | null;
-}
-
-function groupByChannel(
- notifications: UnifiedNotification[]
-): Map<string, ChannelGroup> {
- const groups = new Map<string, ChannelGroup>();
-
- for (const notification of notifications) {
- if (!isChannelNotification(notification)) continue;
-
- const entityId = notification.entity_id;
- const info = getChannelInfo(notification);
-
- if (!groups.has(entityId)) {
- groups.set(entityId, {
- entityId,
- channelName: info.channelName,
- channelType: info.channelType,
- isDM: info.isDM,
- notifications: [],
- latestSenderId: null,
- });
- }
-
- const group = groups.get(entityId)!;
- group.notifications.push(notification);
-
- // Track latest sender for DMs
- if (info.isDM && notification.sender_id) {
- group.latestSenderId = notification.sender_id;
- }
- }
-
- return groups;
-}
-
-const HOVER_PREVIEW_COUNT = 3;
-
-// Unique thread roots (a reply previews its whole thread), newest first.
-function getPreviewThreadRoots(group: ChannelGroup): string[] {
- const roots: string[] = [];
- const seen = new Set<string>();
- for (const notification of group.notifications) {
- const { messageId, threadId } = getChannelNotificationParams(notification);
- const rootId = threadId ?? messageId;
- if (!rootId || seen.has(rootId)) continue;
- seen.add(rootId);
- roots.push(rootId);
- }
- return roots;
-}
-
-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;
-
- return (
- <div 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
- </span>
- </Show>
- <For each={visible()}>
- {(rootMessageId) => (
- <ReadonlyThread
- channelId={props.group.entityId}
- messageId={rootMessageId}
- onClickMessage={(clickedMessageId, e) => {
- e.stopPropagation();
- const isReply = clickedMessageId !== rootMessageId;
- navigateToChannelMessage(
- orchestrator,
- props.group.entityId,
- clickedMessageId,
- isReply ? rootMessageId : undefined
- );
- }}
- />
- )}
- </For>
- </div>
- );
-}
-
-function UnreadHoverCard(
- props: ParentProps<{
- group: ChannelGroup;
- disabled?: boolean;
- onOpenChange?: (open: boolean) => void;
- }>
-) {
- const [hovered, setHovered] = createSignal(false);
- const open = () => hovered() && !props.disabled;
-
- createEffect(() => props.onOpenChange?.(open()));
-
- return (
- <Show when={!isTouchDevice()} fallback={props.children}>
- <KobalteTooltip
- open={open()}
- onOpenChange={setHovered}
- 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"
- >
- {props.children}
- </KobalteTooltip.Trigger>
- <KobalteTooltip.Portal>
- <KobalteTooltip.Content class="z-tool-tip max-w-[calc(100vw-32px)] menu-open-animation">
- <Surface
- depth={3}
- hideBorder
- class="shadow-menu ring ring-edge rounded-xl"
- >
- <GroupHoverPreview group={props.group} />
- </Surface>
- </KobalteTooltip.Content>
- </KobalteTooltip.Portal>
- </KobalteTooltip>
- </Show>
- );
-}
-
-function ChannelGroupItem(props: {
- group: ChannelGroup;
- animate?: boolean;
- isSlim?: boolean;
- onFloatingOpenChange?: (open: boolean) => void;
-}) {
- const layout = useSplitLayout();
- const notificationSource = useGlobalNotificationSource();
- const [isVisible, setIsVisible] = createSignal(!props.animate);
-
- onMount(() => {
- if (props.animate) {
- requestAnimationFrame(() => {
- setIsVisible(true);
- });
- }
- });
-
- const senderName = useSenderName(props.group.latestSenderId);
- const count = () => props.group.notifications.length;
-
- const isDM = () => props.group.isDM;
- const senderId = () => props.group.latestSenderId;
-
- const displayName = () => {
- if (props.group.isDM) {
- return senderName() ?? 'Direct Message';
- }
- return props.group.channelName ?? 'Unknown Channel';
- };
-
- const latestNotification = () => props.group.notifications[0];
-
- const canOpenInNewSplit = () =>
- globalSplitManager()?.canAppendSplit() ?? false;
- const canOpenFullscreen = () => layout.getSplitCount() > 1;
-
- const navigateToLatestNotification = (newSplit = false) => {
- const manager = globalSplitManager();
- if (!manager) return;
- const notification = latestNotification();
- openNotification(notification, manager, newSplit);
- };
-
- const openInCurrentSplit = () => {
- navigateToLatestNotification(false);
- };
-
- const openInNewSplit = () => {
- if (!canOpenInNewSplit()) return;
- navigateToLatestNotification(true);
- };
-
- const markAllAsDone = () => {
- void notificationSource.bulkMarkAsDone(props.group.notifications);
- };
-
- const markAllAsRead = () => {
- void notificationSource.bulkMarkAsRead(props.group.notifications);
- };
-
- const openFullscreen = () => {
- const { params } = getChannelNotificationParams(latestNotification());
- const split = layout.replaceAllSplits(
- {
- type: 'channel',
- id: props.group.entityId,
- params,
- },
- { referredFrom: 'sidebar' }
- );
- globalSplitManager()?.returnFocus();
- return split;
- };
-
- const isSlim = () => props.isSlim ?? false;
-
- const ButtonContent = () => (
- <NavRow
- class="transition-[opacity,transform] justify-start w-full h-7"
- draggable={false}
- classList={{
- 'opacity-0 -translate-y-2': !isVisible(),
- 'opacity-100 translate-y-0': isVisible(),
- }}
- onMouseDown={(e) => {
- if (e.button !== 0) return;
- e.preventDefault();
- navigateToLatestNotification(e.shiftKey);
- }}
- >
- <div
- class={cn('relative flex items-center justify-center shrink-0 size-5')}
- >
- <Show
- when={isDM() && senderId()}
- fallback={
- <EntityIcon targetType="channel" size="xs" class="size-3.5" />
- }
- >
- <UserIcon
- id={senderId()!}
- size="sm"
- suppressClick
- showTooltip={false}
- class="size-3.5"
- />
- </Show>
- <Show when={isSlim()}>
- <div class="absolute -top-0.5 -right-0.5 size-1.5 bg-accent rounded-full ring-surface ring-2" />
- </Show>
- </div>
-
- <Show when={!isSlim()}>
- <span class="text-sm font-medium truncate">{displayName()}</span>
-
- <Show when={count() > 0}>
- <span class="shrink-0 min-w-5 h-5 px-1.5 flex items-center justify-center text-xs font-medium bg-ink/6 text-ink-muted rounded-md ml-auto">
- {count()}
- </span>
- </Show>
- </Show>
- </NavRow>
- );
-
- const [contextMenuOpen, setContextMenuOpen] = createSignal(false);
- const [hoverCardOpen, setHoverCardOpen] = createSignal(false);
-
- createEffect(() => {
- props.onFloatingOpenChange?.(contextMenuOpen() || hoverCardOpen());
- });
-
- return (
- <ContextMenu onOpenChange={setContextMenuOpen}>
- <ContextMenu.Trigger
- class={cn(isSlim() ? 'flex justify-center' : 'w-full')}
- >
- <Show
- when={!isSlim()}
- fallback={
- <Tooltip label={displayName()} placement="right">
- <ButtonContent />
- </Tooltip>
- }
- >
- <UnreadHoverCard
- group={props.group}
- disabled={contextMenuOpen()}
- onOpenChange={setHoverCardOpen}
- >
- <ButtonContent />
- </UnreadHoverCard>
- </Show>
- </ContextMenu.Trigger>
-
- <ContextMenu.Portal>
- <ContextMenuContent class="text-xs text-ink-muted">
- <MenuGroup>
- <MenuItem
- text="Open in new split"
- onClick={openInNewSplit}
- disabled={!canOpenInNewSplit()}
- />
- <Show when={canOpenFullscreen()}>
- <MenuItem text="Open fullscreen" onClick={openFullscreen} />
- </Show>
- <MenuItem
- text="Open in current split"
- onClick={openInCurrentSplit}
- />
- </MenuGroup>
- <MenuSeparator />
- <MenuGroup>
- <MenuItem text="Mark all as read" onClick={markAllAsRead} />
- <MenuItem text="Mark all as done" onClick={markAllAsDone} />
- </MenuGroup>
- </ContextMenuContent>
- </ContextMenu.Portal>
- </ContextMenu>
- );
-}
-
-function filterUnreadNotDone(notifications: UnifiedNotification[]) {
- return notifications.filter((n) => !n.viewed_at && !n.done);
-}
-
-function ChannelGroupDropdownItem(props: { group: ChannelGroup }) {
- const senderName = useSenderName(props.group.latestSenderId);
- const count = () => props.group.notifications.length;
- const displayName = () => {
- if (props.group.isDM) return senderName() ?? 'Direct Message';
- return props.group.channelName ?? 'Unknown Channel';
- };
- const latestNotification = () => props.group.notifications[0];
-
- return (
- <Dropdown.Item
- class="min-h-8 gap-2 px-2.5 text-[13px]"
- onSelect={() => {
- const manager = globalSplitManager();
- if (manager) openNotification(latestNotification(), manager, false);
- }}
- >
- <Show
- when={props.group.isDM && props.group.latestSenderId}
- fallback={
- <EntityIcon targetType="channel" size="xs" class="size-3.5" />
- }
- >
- <UserIcon
- id={props.group.latestSenderId!}
- size="md"
- suppressClick
- showTooltip={false}
- />
- </Show>
- <span class="min-w-0 flex-1 truncate text-ink">{displayName()}</span>
- <span class="shrink-0 min-w-5 h-5 px-1.5 flex items-center justify-center text-xs font-medium bg-ink/6 text-ink-muted rounded-md">
- {count()}
- </span>
- </Dropdown.Item>
- );
-}
-
-export const ChannelsUnreadWidget = (props: {
- sidebarState: SidebarState;
- onSectionOpenChange?: () => void;
- onDropdownOpenChange?: (open: boolean) => void;
-}) => {
- const notificationSource = useGlobalNotificationSource();
- const allNotifications = () => [...notificationSource.notifications()];
-
- const filteredNotifications = () => filterUnreadNotDone(allNotifications());
-
- const channelGroupsMap = createMemo(() =>
- groupByChannel(filteredNotifications())
- );
-
- const [orderedIds, setOrderedIds] = createSignal<string[]>([]);
-
- createEffect(
- on(channelGroupsMap, (groups) => {
- const currentIds = new Set(groups.keys());
- const prev = orderedIds();
- const kept = prev.filter((id) => currentIds.has(id));
- const keptSet = new Set(kept);
- const added = [...currentIds].filter((id) => !keptSet.has(id));
-
- if (added.length === 0 && kept.length === prev.length) return;
-
- added.sort((a, b) => {
- const aTime = groups.get(a)?.notifications[0]?.created_at;
- const bTime = groups.get(b)?.notifications[0]?.created_at;
- return compareDateDesc(aTime, bTime);
- });
-
- setOrderedIds([...added, ...kept]);
- })
- );
-
- const channelGroups = createMemo(() => {
- const groups = channelGroupsMap();
- return orderedIds()
- .map((id) => groups.get(id))
- .filter((g): g is ChannelGroup => g != null);
- });
-
- 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 sectionItems = createMemo<CollapsibleSidebarSectionItem[]>(() =>
- channelGroups().map((group) => ({
- id: group.entityId,
- visible: () => (
- <ChannelGroupItem
- group={group}
- animate={false}
- onFloatingOpenChange={props.onDropdownOpenChange}
- />
- ),
- dropdown: () => <ChannelGroupDropdownItem group={group} />,
- }))
- );
-
- 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 />
- )}
- </For>
- <Show when={slimOverflow() > 0}>
- <span class="w-full text-center text-xxs text-ink-muted mt-1">
- +{slimOverflow()}
- </span>
- </Show>
- </section>
- }
- >
- <CollapsibleSidebarSection
- label="Unread"
- items={sectionItems()}
- onOpenChange={() => props.onSectionOpenChange?.()}
- />
- </Show>
- </Show>
- );
-};
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
index 1ee541c10c..ec90293a36 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
@@ -11,7 +11,7 @@ import type { LayoutProps } from './shared';
export function NarrowCondensedLayout(props: LayoutProps) {
return (
<Entity.Layout
- class="w-full gap-x-2 items-center px-2 grid text-sm"
+ class="w-full gap-x-2 items-center pr-2 grid text-sm"
style={{
'grid-template-columns': 'auto 1fr',
'grid-template-rows': '36px',
@@ -37,7 +37,7 @@ export function NarrowCondensedLayout(props: LayoutProps) {
placement="title"
class="ph-no-capture flex min-w-0 items-center gap-2 truncate font-normal"
>
- <Show when={props.unread}>
+ <Show when={props.unread} fallback={<div class="size-2" />}>
<UnreadIndicator active />
</Show>
<div class="size-4 shrink-0">