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.

refactor(entity): create composable ui components for entities (#1368)

Seamus3d73048b7170
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 00e3a4e3da..293bc26f4f 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -137,6 +137,11 @@ if (LOCAL_ONLY) {
'properties-debug',
lazy(() => import('@core/component/Properties/debug/PropertiesDebug'))
);
+
+ registerComponent(
+ 'entity-debug',
+ lazy(() => import('@entity/src/debug/DebugEntityView'))
+ );
}
if (DEV_MODE_ENV) {
diff --git a/js/app/packages/core/component/UserGroup.tsx b/js/app/packages/core/component/UserGroup.tsx
new file mode 100644
index 0000000000..e3a18a5219
--- /dev/null
+++ b/js/app/packages/core/component/UserGroup.tsx
@@ -0,0 +1,98 @@
+import { createMemo, For, Show } from 'solid-js';
+import { UserIcon } from './UserIcon';
+import { cn } from '@ui/utils/classname';
+import { match } from 'ts-pattern';
+
+export type UserGroupProps = {
+ userIds: string[];
+ maxUsers?: number;
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
+ suppressClick?: boolean;
+ showTooltip?: boolean;
+};
+
+/**
+ * Displays a group of user avatars in an overlapping style with an overflow indicator
+ */
+export function UserGroup(props: UserGroupProps) {
+ const max = () => props.maxUsers ?? 3;
+ const size = () => props.size ?? 'xs';
+
+ const remaining = createMemo(() => {
+ if (props.userIds.length <= max()) return undefined;
+ return props.userIds.length - max();
+ });
+
+ const displayUserIds = () => props.userIds.slice(0, max());
+
+ const sizeClasses = () => {
+ return match(size())
+ .with('xs', () => ({
+ userIcon: 'size-4',
+ wrapper: 'p-[2px]',
+ overlap: '-mr-3',
+ counter: 'size-5 text-[10px] -mr-2 border-2',
+ }))
+ .with('sm', () => ({
+ userIcon: 'size-6',
+ wrapper: 'p-[2px]',
+ overlap: '-mr-4',
+ counter: 'size-6 text-xs -mr-3 border-2',
+ }))
+ .with('md', () => ({
+ userIcon: 'size-8',
+ wrapper: 'p-[3px]',
+ overlap: '-mr-5',
+ counter: 'size-8 text-sm -mr-4 border-2',
+ }))
+ .with('lg', () => ({
+ userIcon: 'size-10',
+ wrapper: 'p-[3px]',
+ overlap: '-mr-6',
+ counter: 'size-10 text-base -mr-5 border-2',
+ }))
+ .with('xl', () => ({
+ userIcon: 'size-25',
+ wrapper: 'p-1',
+ overlap: '-mr-16',
+ counter: 'size-20 text-2xl -mr-12 border-4',
+ }))
+ .exhaustive();
+ };
+
+ return (
+ <div class="flex items-center shrink-0 w-fit pr-3">
+ <For each={displayUserIds()}>
+ {(userId) => (
+ <div
+ class={cn(
+ 'bg-panel rounded-full',
+ sizeClasses().wrapper,
+ sizeClasses().overlap
+ )}
+ >
+ <UserIcon
+ id={userId}
+ isDeleted={false}
+ size={size()}
+ suppressClick={props.suppressClick}
+ showTooltip={props.showTooltip ?? false}
+ />
+ </div>
+ )}
+ </For>
+ <Show when={remaining()}>
+ <div class="z-4">
+ <div
+ class={cn(
+ 'bg-menu text-ink border-panel rounded-full flex flex-col justify-center items-center',
+ sizeClasses().counter
+ )}
+ >
+ <span>+{remaining()}</span>
+ </div>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/js/app/packages/core/user/displayName.ts b/js/app/packages/core/user/displayName.ts
index 4aac395033..b019d22680 100644
--- a/js/app/packages/core/user/displayName.ts
+++ b/js/app/packages/core/user/displayName.ts
@@ -195,3 +195,21 @@ export function useDisplayName(
return [accessor, { refetch, mutate }];
}
+
+/**
+ * Seeds the display name cache with mock user data.
+ * Useful for debug views and testing.
+ */
+export function seedMockDisplayNames(
+ users: Array<{ id: string; firstName?: string; lastName?: string }>
+) {
+ for (const user of users) {
+ setUserDisplayNames(user.id, {
+ _createdAt: new Date(),
+ id: user.id,
+ firstName: user.firstName,
+ lastName: user.lastName,
+ loading: false,
+ });
+ }
+}
diff --git a/js/app/packages/core/user/index.ts b/js/app/packages/core/user/index.ts
index 21da99a7e7..8191bfa362 100644
--- a/js/app/packages/core/user/index.ts
+++ b/js/app/packages/core/user/index.ts
@@ -10,6 +10,7 @@ export { useContacts } from './contactService';
export { useAugmentUserWithDmActivity } from './dmActivity';
export {
type DisplayNameParts,
+ seedMockDisplayNames,
useDisplayName,
useDisplayNameParts,
} from './displayName';
diff --git a/js/app/packages/entity/README.md b/js/app/packages/entity/README.md
new file mode 100644
index 0000000000..39742342b3
--- /dev/null
+++ b/js/app/packages/entity/README.md
@@ -0,0 +1,5 @@
+# Entity
+
+Composable entity component library for Macro.
+
+This package provides a flexible, composable API for rendering entities with various extractors for different contexts (search, notifications, etc.).
diff --git a/js/app/packages/entity/mocks/mockEntityData.ts b/js/app/packages/entity/mocks/mockEntityData.ts
new file mode 100644
index 0000000000..086e3e2111
--- /dev/null
+++ b/js/app/packages/entity/mocks/mockEntityData.ts
@@ -0,0 +1,747 @@
+import type { Property } from '@core/component/Properties/types';
+import type {
+ ChannelEntity,
+ ChatEntity,
+ DocumentEntity,
+ EmailEntity,
+ ProjectEntity,
+ TaskEntity,
+} from '../src/types/entity';
+import type { Notification, WithNotification } from '../src/types/notification';
+import type { WithSearch } from '../src/types/search';
+
+export const MOCK_USER_IDS = {
+ owner: 'macro|[email protected]',
+ sharedUser: 'macro|[email protected]',
+ teamMember1: 'macro|[email protected]',
+ teamMember2: 'macro|[email protected]',
+ currentUser: 'macro|[email protected]',
+} as const;
+
+export const MOCK_USERS = [
+ { id: MOCK_USER_IDS.owner, firstName: 'Alex', lastName: 'Owner' },
+ { id: MOCK_USER_IDS.sharedUser, firstName: 'Sam', lastName: 'Shared' },
+ { id: MOCK_USER_IDS.teamMember1, firstName: 'Jordan', lastName: 'Team' },
+ { id: MOCK_USER_IDS.teamMember2, firstName: 'Casey', lastName: 'Member' },
+ { id: MOCK_USER_IDS.currentUser, firstName: 'Current', lastName: 'User' },
+] as const;
+
+export const MOCK_TIMESTAMPS = {
+ now: Date.now(),
+ today: Date.now() - 1000 * 60 * 30, // 30 minutes ago
+ yesterday: Date.now() - 1000 * 60 * 60 * 24, // 1 day ago
+ lastWeek: Date.now() - 1000 * 60 * 60 * 24 * 7, // 7 days ago
+ lastMonth: Date.now() - 1000 * 60 * 60 * 24 * 30, // 30 days ago
+ lastYear: Date.now() - 1000 * 60 * 60 * 24 * 365, // 365 days ago
+} as const;
+
+export const MOCK_PROPERTIES: Property[] = [
+ {
+ propertyId: 'prop_priority_1',
+ propertyDefinitionId: 'def_priority',
+ displayName: 'Priority',
+ isMultiSelect: false,
+ valueType: 'SELECT_STRING',
+ value: ['opt_high'],
+ options: [
+ {
+ id: 'opt_high',
+ value: { type: 'string', value: 'High' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_priority',
+ display_order: 0,
+ },
+ {
+ id: 'opt_medium',
+ value: { type: 'string', value: 'Medium' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_priority',
+ display_order: 1,
+ },
+ {
+ id: 'opt_low',
+ value: { type: 'string', value: 'Low' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_priority',
+ display_order: 2,
+ },
+ ],
+ owner: { scope: 'organization', organization_id: 1 },
+ createdAt: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updatedAt: new Date(MOCK_TIMESTAMPS.today).toISOString(),
+ },
+ {
+ propertyId: 'prop_status_1',
+ propertyDefinitionId: 'def_status',
+ displayName: 'Status',
+ isMultiSelect: false,
+ valueType: 'SELECT_STRING',
+ value: ['opt_in_progress'],
+ options: [
+ {
+ id: 'opt_todo',
+ value: { type: 'string', value: 'To Do' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_status',
+ display_order: 0,
+ },
+ {
+ id: 'opt_in_progress',
+ value: { type: 'string', value: 'In Progress' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_status',
+ display_order: 1,
+ },
+ {
+ id: 'opt_done',
+ value: { type: 'string', value: 'Done' },
+ created_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updated_at: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ property_definition_id: 'def_status',
+ display_order: 2,
+ },
+ ],
+ owner: { scope: 'organization', organization_id: 1 },
+ createdAt: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updatedAt: new Date(MOCK_TIMESTAMPS.today).toISOString(),
+ },
+ {
+ propertyId: 'prop_due_date_1',
+ propertyDefinitionId: 'def_due_date',
+ displayName: 'Due Date',
+ isMultiSelect: false,
+ valueType: 'DATE',
+ value: new Date(MOCK_TIMESTAMPS.now + 1000 * 60 * 60 * 24 * 7), // 7 days from now
+ owner: { scope: 'organization', organization_id: 1 },
+ createdAt: new Date(MOCK_TIMESTAMPS.lastMonth).toISOString(),
+ updatedAt: new Date(MOCK_TIMESTAMPS.today).toISOString(),
+ },
+];
+
+export const createMockNotification = (
+ overrides?: Partial<Notification>
+): Notification => ({
+ id: 'notif_123',
+ done: false,
+ sent: true,
+ senderId: MOCK_USER_IDS.teamMember1,
+ notificationEventType: 'document_mention',
+ entity_id: 'doc_123',
+ entity_type: 'document',
+ createdAt: MOCK_TIMESTAMPS.today,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ deletedAt: null,
+ viewedAt: null,
+ notificationMetadata: { tag: 'document_mention', content: {} },
+ ...overrides,
+});
+
+export const MOCK_NOTIFICATIONS: Notification[] = [
+ createMockNotification({
+ id: 'notif_mention_1',
+ notificationEventType: 'document_mention',
+ senderId: MOCK_USER_IDS.teamMember1,
+ createdAt: MOCK_TIMESTAMPS.today,
+ }),
+ createMockNotification({
+ id: 'notif_task_1',
+ notificationEventType: 'task_assigned',
+ senderId: MOCK_USER_IDS.teamMember2,
+ createdAt: MOCK_TIMESTAMPS.yesterday,
+ }),
+ createMockNotification({
+ id: 'notif_channel_1',
+ notificationEventType: 'channel_message_document',
+ senderId: MOCK_USER_IDS.sharedUser,
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ entity_type: 'channel',
+ }),
+];
+
+export const MOCK_DOCUMENT_BASIC: DocumentEntity = {
+ type: 'document',
+ id: 'doc_basic_1',
+ name: 'Meeting Notes',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.85,
+};
+
+export const MOCK_DOCUMENT_WITH_PROJECT: DocumentEntity = {
+ type: 'document',
+ id: 'doc_project_1',
+ name: 'Project Roadmap Q1 2025',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ projectId: 'proj_1',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.92,
+};
+
+export const MOCK_DOCUMENT_PDF: DocumentEntity = {
+ type: 'document',
+ id: 'doc_pdf_1',
+ name: 'Design Specifications.pdf',
+ ownerId: MOCK_USER_IDS.sharedUser,
+ fileType: 'pdf',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.lastWeek,
+ frecencyScore: 0.65,
+};
+
+export const MOCK_DOCUMENT_LONG_NAME: DocumentEntity = {
+ type: 'document',
+ id: 'doc_long_1',
+ name: 'This is a very long document name that should test truncation behavior and how the UI handles overflow text in the entity component',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ createdAt: MOCK_TIMESTAMPS.lastYear,
+ updatedAt: MOCK_TIMESTAMPS.lastMonth,
+ frecencyScore: 0.45,
+};
+
+export const MOCK_DOCUMENT_SPECIAL_CHARS: DocumentEntity = {
+ type: 'document',
+ id: 'doc_special_1',
+ name: 'Test [Document] with "Special" & <Characters>!',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.75,
+};
+
+export const MOCK_TASK_TODO: TaskEntity = {
+ type: 'document',
+ id: 'task_todo_1',
+ name: 'Review Q1 Budget',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ subType: { type: 'task', is_completed: false },
+ projectId: 'proj_1',
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.88,
+};
+
+export const MOCK_TASK_COMPLETED: TaskEntity = {
+ type: 'document',
+ id: 'task_done_1',
+ name: 'Setup CI/CD Pipeline',
+ ownerId: MOCK_USER_IDS.currentUser,
+ fileType: 'md',
+ subType: { type: 'task', is_completed: true },
+ projectId: 'proj_2',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.95,
+};
+
+export const MOCK_TASK_HIGH_PRIORITY: TaskEntity = {
+ type: 'document',
+ id: 'task_urgent_1',
+ name: 'Fix Critical Security Bug',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ subType: { type: 'task', is_completed: false },
+ createdAt: MOCK_TIMESTAMPS.today,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.99,
+};
+
+export const MOCK_CHANNEL_PUBLIC: ChannelEntity = {
+ type: 'channel',
+ id: 'channel_public_1',
+ name: 'general',
+ ownerId: MOCK_USER_IDS.owner,
+ channelType: 'public',
+ createdAt: MOCK_TIMESTAMPS.lastYear,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ interactedAt: MOCK_TIMESTAMPS.today,
+ latestMessage: {
+ content: "Hey everyone! Don't forget about the team meeting at 2pm",
+ senderId: MOCK_USER_IDS.teamMember1,
+ createdAt: MOCK_TIMESTAMPS.today,
+ },
+ frecencyScore: 0.91,
+};
+
+export const MOCK_CHANNEL_PRIVATE: ChannelEntity = {
+ type: 'channel',
+ id: 'channel_private_1',
+ name: 'design-team',
+ ownerId: MOCK_USER_IDS.owner,
+ channelType: 'private',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ interactedAt: MOCK_TIMESTAMPS.yesterday,
+ latestMessage: {
+ content: 'Updated the mockups in Figma',
+ senderId: MOCK_USER_IDS.teamMember2,
+ createdAt: MOCK_TIMESTAMPS.yesterday,
+ },
+ frecencyScore: 0.83,
+};
+
+export const MOCK_CHANNEL_DIRECT_MESSAGE: ChannelEntity = {
+ type: 'channel',
+ id: 'channel_dm_1',
+ name: 'Direct Message',
+ ownerId: MOCK_USER_IDS.currentUser,
+ channelType: 'direct_message',
+ participantIds: [MOCK_USER_IDS.currentUser, MOCK_USER_IDS.teamMember1],
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ interactedAt: MOCK_TIMESTAMPS.today,
+ latestMessage: {
+ content: 'Can you review the PR?',
+ senderId: MOCK_USER_IDS.teamMember1,
+ createdAt: MOCK_TIMESTAMPS.today,
+ },
+ frecencyScore: 0.87,
+};
+
+export const MOCK_CHANNEL_ORGANIZATION: ChannelEntity = {
+ type: 'channel',
+ id: 'channel_org_1',
+ name: 'company-announcements',
+ ownerId: MOCK_USER_IDS.owner,
+ channelType: 'organization',
+ createdAt: MOCK_TIMESTAMPS.lastYear,
+ updatedAt: MOCK_TIMESTAMPS.lastWeek,
+ interactedAt: MOCK_TIMESTAMPS.lastWeek,
+ latestMessage: {
+ content: 'Q4 results are in!',
+ senderId: MOCK_USER_IDS.owner,
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ },
+ frecencyScore: 0.72,
+};
+
+export const MOCK_CHANNEL_EMPTY_MESSAGE: ChannelEntity = {
+ type: 'channel',
+ id: 'channel_attachment_1',
+ name: 'project-files',
+ ownerId: MOCK_USER_IDS.owner,
+ channelType: 'private',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ interactedAt: MOCK_TIMESTAMPS.today,
+ latestMessage: {
+ content: '',
+ senderId: MOCK_USER_IDS.teamMember2,
+ createdAt: MOCK_TIMESTAMPS.today,
+ },
+ frecencyScore: 0.68,
+};
+
+export const MOCK_EMAIL_UNREAD: EmailEntity = {
+ type: 'email',
+ id: 'email_unread_1',
+ name: 'Q1 Planning Session',
+ ownerId: MOCK_USER_IDS.currentUser,
+ isRead: false,
+ isDraft: false,
+ isImportant: false,
+ done: false,
+ senderEmail: '[email protected]',
+ senderName: 'Alice Johnson',
+ snippet: "Let's schedule a meeting to discuss our Q1 goals and objectives...",
+ participants: [
+ { email: '[email protected]', name: 'Alice Johnson' },
+ { email: '[email protected]', name: 'Bob Smith' },
+ ],
+ createdAt: MOCK_TIMESTAMPS.today,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.94,
+};
+
+export const MOCK_EMAIL_READ: EmailEntity = {
+ type: 'email',
+ id: 'email_read_1',
+ name: 'Re: Project Update',
+ ownerId: MOCK_USER_IDS.currentUser,
+ isRead: true,
+ isDraft: false,
+ isImportant: false,
+ done: true,
+ senderEmail: '[email protected]',
+ senderName: 'Charlie Davis',
+ snippet: 'Thanks for the update! Everything looks good to me.',
+ participants: [{ email: '[email protected]', name: 'Charlie Davis' }],
+ createdAt: MOCK_TIMESTAMPS.yesterday,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.76,
+};
+
+export const MOCK_EMAIL_DRAFT: EmailEntity = {
+ type: 'email',
+ id: 'email_draft_1',
+ name: 'Draft: Team Announcement',
+ ownerId: MOCK_USER_IDS.currentUser,
+ isRead: true,
+ isDraft: true,
+ isImportant: false,
+ done: false,
+ snippet: 'I wanted to share some exciting news with the team...',
+ participants: [],
+ createdAt: MOCK_TIMESTAMPS.today,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.81,
+};
+
+export const MOCK_EMAIL_THREAD: EmailEntity = {
+ type: 'email',
+ id: 'email_thread_1',
+ name: 'Re: Design Review [4 messages]',
+ ownerId: MOCK_USER_IDS.currentUser,
+ isRead: false,
+ isDraft: false,
+ isImportant: true,
+ done: false,
+ senderEmail: '[email protected]',
+ senderName: 'Diana Miller',
+ snippet: 'I have some feedback on the latest designs...',
+ participants: [
+ { email: '[email protected]', name: 'Diana Miller' },
+ { email: '[email protected]', name: 'Eve Wilson' },
+ { email: MOCK_USER_IDS.currentUser, name: 'Current User' },
+ ],
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.89,
+};
+
+export const MOCK_EMAIL_MULTIPLE_PARTICIPANTS: EmailEntity = {
+ type: 'email',
+ id: 'email_multi_1',
+ name: 'All Hands Meeting Next Week',
+ ownerId: MOCK_USER_IDS.currentUser,
+ isRead: false,
+ isDraft: false,
+ isImportant: false,
+ done: false,
+ senderEmail: '[email protected]',
+ senderName: 'Frank Anderson',
+ snippet:
+ 'Just a reminder that our all hands meeting is scheduled for next Monday...',
+ participants: [
+ { email: '[email protected]', name: 'Frank Anderson' },
+ { email: '[email protected]', name: 'Grace Lee' },
+ { email: '[email protected]', name: 'Henry Brown' },
+ { email: '[email protected]', name: 'Iris Taylor' },
+ { email: MOCK_USER_IDS.currentUser, name: 'Current User' },
+ ],
+ createdAt: MOCK_TIMESTAMPS.yesterday,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.78,
+};
+
+export const MOCK_PROJECT_1: ProjectEntity = {
+ type: 'project',
+ id: 'proj_1',
+ name: 'Website Redesign',
+ ownerId: MOCK_USER_IDS.owner,
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.91,
+};
+
+export const MOCK_PROJECT_2: ProjectEntity = {
+ type: 'project',
+ id: 'proj_2',
+ name: 'Mobile App Development',
+ ownerId: MOCK_USER_IDS.owner,
+ createdAt: MOCK_TIMESTAMPS.lastYear,
+ updatedAt: MOCK_TIMESTAMPS.lastWeek,
+ frecencyScore: 0.84,
+};
+
+export const MOCK_PROJECT_SHARED: ProjectEntity = {
+ type: 'project',
+ id: 'proj_shared_1',
+ name: 'Marketing Campaign 2025',
+ ownerId: MOCK_USER_IDS.sharedUser,
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.79,
+};
+
+export const MOCK_CHAT_BASIC: ChatEntity = {
+ type: 'chat',
+ id: 'chat_1',
+ name: 'Product Brainstorm',
+ ownerId: MOCK_USER_IDS.currentUser,
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.86,
+};
+
+export const MOCK_CHAT_WITH_PROJECT: ChatEntity = {
+ type: 'chat',
+ id: 'chat_project_1',
+ name: 'Design Discussion',
+ ownerId: MOCK_USER_IDS.owner,
+ projectId: 'proj_1',
+ createdAt: MOCK_TIMESTAMPS.lastMonth,
+ updatedAt: MOCK_TIMESTAMPS.yesterday,
+ frecencyScore: 0.82,
+};
+
+export const MOCK_SEARCH_DOCUMENT: WithSearch<DocumentEntity> = {
+ ...MOCK_DOCUMENT_BASIC,
+ search: {
+ nameHighlight: 'Meeting **Notes**',
+ contentHitData: [
+ {
+ type: 'md',
+ content: 'Discussed the **Q1 budget** and resource allocation',
+ location: { type: 'md', nodeId: 'node_1' },
+ },
+ {
+ type: 'md',
+ content: 'Action items: Review the **budget proposal** by Friday',
+ location: { type: 'md', nodeId: 'node_2' },
+ },
+ ],
+ source: 'service',
+ },
+};
+
+export const MOCK_SEARCH_CHANNEL: WithSearch<ChannelEntity> = {
+ ...MOCK_CHANNEL_PUBLIC,
+ search: {
+ nameHighlight: '**general**',
+ contentHitData: [
+ {
+ type: 'channel',
+ id: 'msg_1',
+ content: 'Has anyone seen the **budget report**?',
+ senderId: MOCK_USER_IDS.teamMember1,
+ sentAt: MOCK_TIMESTAMPS.today,
+ location: {
+ type: 'channel',
+ messageId: 'msg_1',
+ },
+ },
+ {
+ type: 'channel',
+ id: 'msg_2',
+ content: 'I uploaded it to the **shared drive**',
+ senderId: MOCK_USER_IDS.teamMember2,
+ sentAt: MOCK_TIMESTAMPS.today,
+ location: {
+ type: 'channel',
+ messageId: 'msg_2',
+ },
+ },
+ ],
+ source: 'service',
+ },
+};
+
+export const MOCK_SEARCH_EMAIL: WithSearch<EmailEntity> = {
+ ...MOCK_EMAIL_THREAD,
+ search: {
+ nameHighlight: '**Design** Review',
+ contentHitData: [
+ {
+ type: 'email',
+ content: 'The **design mockups** look great!',
+ sender: 'Diana Miller',
+ senderId: '[email protected]',
+ sentAt: MOCK_TIMESTAMPS.yesterday,
+ location: {
+ type: 'email',
+ messageId: 'email_msg_1',
+ },
+ },
+ {
+ type: 'email',
+ content: 'I agree, but we should adjust the **color scheme**',
+ sender: 'Eve Wilson',
+ senderId: '[email protected]',
+ sentAt: MOCK_TIMESTAMPS.today,
+ location: {
+ type: 'email',
+ messageId: 'email_msg_2',
+ },
+ },
+ ],
+ source: 'service',
+ },
+};
+
+export const MOCK_SEARCH_PDF: WithSearch<DocumentEntity> = {
+ ...MOCK_DOCUMENT_PDF,
+ search: {
+ nameHighlight: '**Design** Specifications.pdf',
+ contentHitData: [
+ {
+ type: 'pdf',
+ content: 'Section 3.2: **Color Palette** and Typography',
+ location: {
+ type: 'pdf',
+ searchPage: 5,
+ highlightTerms: ['Color', 'Palette'],
+ searchSnippet: 'Color Palette and Typography',
+ searchRawQuery: 'color palette',
+ },
+ },
+ ],
+ source: 'service',
+ },
+};
+
+export const createEntityWithNotifications = <T extends object>(
+ entity: T,
+ notifications: Notification[]
+): WithNotification<T> => ({
+ ...entity,
+ notifications: () => notifications,
+});
+
+export const MOCK_DOCUMENT_WITH_NOTIFICATIONS = createEntityWithNotifications(
+ MOCK_DOCUMENT_BASIC,
+ [MOCK_NOTIFICATIONS[0]]
+);
+
+export const MOCK_TASK_WITH_NOTIFICATIONS = createEntityWithNotifications(
+ MOCK_TASK_TODO,
+ [MOCK_NOTIFICATIONS[1]]
+);
+
+export const MOCK_CHANNEL_WITH_NOTIFICATIONS = createEntityWithNotifications(
+ MOCK_CHANNEL_PUBLIC,
+ [MOCK_NOTIFICATIONS[2]]
+);
+
+export const MOCK_SHARED_DOCUMENT: DocumentEntity = {
+ ...MOCK_DOCUMENT_BASIC,
+ id: 'doc_shared_1',
+ name: 'Shared Project Plan',
+ ownerId: MOCK_USER_IDS.sharedUser,
+};
+
+export const MOCK_SHARED_TASK: TaskEntity = {
+ ...MOCK_TASK_TODO,
+ id: 'task_shared_1',
+ name: 'Shared Task',
+ ownerId: MOCK_USER_IDS.teamMember1,
+};
+
+export const MOCK_TASK_WITH_PROPERTIES = MOCK_TASK_TODO;
+export const MOCK_TASK_PROPERTIES = MOCK_PROPERTIES;
+
+export const MOCK_ENTITY_MISSING_FIELDS: DocumentEntity = {
+ type: 'document',
+ id: 'doc_minimal_1',
+ name: 'Minimal Document',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ // Missing optional fields like createdAt, updatedAt, frecencyScore
+};
+
+export const MOCK_ENTITY_VERY_OLD: DocumentEntity = {
+ type: 'document',
+ id: 'doc_old_1',
+ name: 'Archive Document 2020',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ createdAt: new Date('2020-01-01').getTime(),
+ updatedAt: new Date('2020-06-15').getTime(),
+ frecencyScore: 0.12,
+};
+
+export const MOCK_ENTITY_UNICODE: DocumentEntity = {
+ type: 'document',
+ id: 'doc_unicode_1',
+ name: '🚀 Product Launch 2025 💡 Ideas & Notes ✨',
+ ownerId: MOCK_USER_IDS.owner,
+ fileType: 'md',
+ createdAt: MOCK_TIMESTAMPS.lastWeek,
+ updatedAt: MOCK_TIMESTAMPS.today,
+ frecencyScore: 0.88,
+};
+
+export const ALL_DOCUMENT_ENTITIES = [
+ MOCK_DOCUMENT_BASIC,
+ MOCK_DOCUMENT_WITH_PROJECT,
+ MOCK_DOCUMENT_PDF,
+ MOCK_DOCUMENT_LONG_NAME,
+ MOCK_DOCUMENT_SPECIAL_CHARS,
+ MOCK_SHARED_DOCUMENT,
+ MOCK_ENTITY_MISSING_FIELDS,
+ MOCK_ENTITY_VERY_OLD,
+ MOCK_ENTITY_UNICODE,
+];
+
+export const ALL_TASK_ENTITIES = [
+ MOCK_TASK_TODO,
+ MOCK_TASK_COMPLETED,
+ MOCK_TASK_HIGH_PRIORITY,
+ MOCK_SHARED_TASK,
+];
+
+export const ALL_CHANNEL_ENTITIES = [
+ MOCK_CHANNEL_PUBLIC,
+ MOCK_CHANNEL_PRIVATE,
+ MOCK_CHANNEL_DIRECT_MESSAGE,
+ MOCK_CHANNEL_ORGANIZATION,
+ MOCK_CHANNEL_EMPTY_MESSAGE,
+];
+
+export const ALL_EMAIL_ENTITIES = [
+ MOCK_EMAIL_UNREAD,
+ MOCK_EMAIL_READ,
+ MOCK_EMAIL_DRAFT,
+ MOCK_EMAIL_THREAD,
+ MOCK_EMAIL_MULTIPLE_PARTICIPANTS,
+];
+
+export const ALL_PROJECT_ENTITIES = [
+ MOCK_PROJECT_1,
+ MOCK_PROJECT_2,
+ MOCK_PROJECT_SHARED,
+];
+
+export const ALL_CHAT_ENTITIES = [MOCK_CHAT_BASIC, MOCK_CHAT_WITH_PROJECT];
+
+export const ALL_SEARCH_ENTITIES = [
+ MOCK_SEARCH_DOCUMENT,
+ MOCK_SEARCH_CHANNEL,
+ MOCK_SEARCH_EMAIL,
+ MOCK_SEARCH_PDF,
+];
+
+export const ALL_ENTITIES_WITH_NOTIFICATIONS = [
+ MOCK_DOCUMENT_WITH_NOTIFICATIONS,
+ MOCK_TASK_WITH_NOTIFICATIONS,
+ MOCK_CHANNEL_WITH_NOTIFICATIONS,
+];
+
+export const ALL_SHARED_ENTITIES = [
+ MOCK_SHARED_DOCUMENT,
+ MOCK_SHARED_TASK,
+ MOCK_PROJECT_SHARED,
+];
+
+/**
+ * Comprehensive collection of all mock entities for testing
+ */
+export const ALL_MOCK_ENTITIES = [
+ ...ALL_DOCUMENT_ENTITIES,
+ ...ALL_TASK_ENTITIES,
+ ...ALL_CHANNEL_ENTITIES,
+ ...ALL_EMAIL_ENTITIES,
+ ...ALL_PROJECT_ENTITIES,
+ ...ALL_CHAT_ENTITIES,
+];
diff --git a/js/app/packages/entity/src/components/Badges.tsx b/js/app/packages/entity/src/components/Badges.tsx
new file mode 100644
index 0000000000..acc369f09f
--- /dev/null
+++ b/js/app/packages/entity/src/components/Badges.tsx
@@ -0,0 +1,38 @@
+import type { ParentProps } from 'solid-js';
+import { UserIcon } from '@core/component/UserIcon';
+import { cn } from '@ui/utils/classname';
+
+function Badge(props: ParentProps<{ class?: string }>) {
+ return (
+ <div
+ class={cn(
+ 'font-mono font-medium user-select-none uppercase flex items-center p-0.5 gap-1 text-[0.625rem] rounded-full border',
+ props.class
+ )}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+// TODO (seamus) : tool tip for now, better shared context later
+export function SharedBadge(props: { ownerId: string }) {
+ return (
+ <Badge class="text-ink-extra-muted border-edge-muted pr-2">
+ <UserIcon id={props.ownerId} size="xs" />
+ shared
+ </Badge>
+ );
+}
+
+export function DraftBadge() {
+ return <Badge class="text-accent-30 border-edge-muted px-2">draft</Badge>;
+}
+
+export function ImportantBadge() {
+ return (
+ <Badge class="text-accent bg-accent/10 px-2 border-accent/10">
+ important
+ </Badge>
+ );
+}
diff --git a/js/app/packages/entity/src/components/CollapsibleList.tsx b/js/app/packages/entity/src/components/CollapsibleList.tsx
new file mode 100644
index 0000000000..05e4bc7cb7
--- /dev/null
+++ b/js/app/packages/entity/src/components/CollapsibleList.tsx
@@ -0,0 +1,65 @@
+import { For, Show, createSignal, type JSX } from 'solid-js';
+import ChevronDownIcon from '@icon/regular/caret-down.svg?component-solid';
+import { cn } from '@ui/utils/classname';
+
+interface CollapsibleListProps<T> {
+ items: T[];
+ visibleCount?: number;
+ children: (item: T, index?: number, count?: number) => JSX.Element;
+}
+
+/**
+ * Generic collapsible list component
+ * - Shows a limited number of items initially
+ * - Provides "Show N more" / "Collapse" buttons
+ * - Supports thread border for visual hierarchy
+ *
+ * NOTE: This component uses <For> which compares items by referential equality.
+ * If items array is recreated with new object references on every render,
+ * all children will remount. To prevent this, ensure stable object references
+ * in the parent component using reconcile() or proper memoization.
+ */
+export function CollapsibleList<T>(props: CollapsibleListProps<T>) {
+ const [showAll, setShowAll] = createSignal(false);
+ const visibleCount = () => props.visibleCount ?? 3;
+
+ const visibleItems = () => {
+ if (props.items.length <= visibleCount() || showAll()) {
+ return props.items;
+ }
+ return props.items.slice(0, visibleCount());
+ };
+
+ const count = () => props.items.length;
+ const hasMore = () => props.items.length > visibleCount();
+
+ return (
+ <>
+ <For each={visibleItems()}>
+ {(child, index) => props.children(child, index(), count())}
+ </For>
+ <Show when={hasMore()}>
+ <div class="w-full flex items-center gap-2 my-2">
+ <button
+ type="button"
+ class="flex items-center gap-1 text-xs bracket-never"
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowAll((prev) => !prev);
+ }}
+ >
+ <ChevronDownIcon
+ class={cn('w-3 h-3 transition-transform duration-100', {
+ 'rotate-180': showAll(),
+ })}
+ />
+ <Show when={!showAll()} fallback="Collapse">
+ Show {props.items.length - visibleCount()} More
+ </Show>
+ </button>
+ <div class="border-t border-edge-muted/50 grow"></div>
+ </div>
+ </Show>
+ </>
+ );
+}
diff --git a/js/app/packages/entity/src/components/DisplayName.tsx b/js/app/packages/entity/src/components/DisplayName.tsx
new file mode 100644
index 0000000000..a101738dfb
--- /dev/null
+++ b/js/app/packages/entity/src/components/DisplayName.tsx
@@ -0,0 +1,22 @@
+import { tryMacroId, useDisplayNameParts } from '@core/user';
+
+export function DisplayName(props: {
+ id: string;
+ format?: 'firstName' | 'lastName' | 'fullName';
+}) {
+ const parts = useDisplayNameParts(tryMacroId(props.id));
+
+ const name = () => {
+ const format = props.format ?? 'fullName';
+
+ if (format === 'fullName') {
+ return parts.fullName();
+ }
+
+ // For firstName or lastName, fall back to fullName if empty
+ const requestedPart = parts[format]();
+ return requestedPart || parts.fullName();
+ };
+
+ return <>{name()}</>;
+}
diff --git a/js/app/packages/entity/src/components/MultiSelectCheckbox.tsx b/js/app/packages/entity/src/components/MultiSelectCheckbox.tsx
new file mode 100644
index 0000000000..4817faf82f
--- /dev/null
+++ b/js/app/packages/entity/src/components/MultiSelectCheckbox.tsx
@@ -0,0 +1,44 @@
+import CheckIcon from '@icon/regular/check.svg';
+import { cn } from '@ui/utils/classname';
+import { Show } from 'solid-js';
+
+export interface MultiSelectCheckboxProps {
+ checked?: boolean;
+ onChecked?: (checked: boolean, shiftKey: boolean) => void;
+}
+
+/**
+ * Multi-select checkbox component with responsive behavior:
+ * - Desktop: Always visible checkbox in left column
+ * - Mobile/narrow: Icon by default, checkbox on hover or when checked
+ * - Shows unread indicator when not checked
+ */
+export function MultiSelectCheckbox(props: MultiSelectCheckboxProps) {
+ return (
+ <button
+ type="button"
+ class="size-full relative group/button flex items-center justify-center bracket-never"
+ onMouseDown={(e) => {
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onChecked?.(!props.checked, e.shiftKey);
+ }}
+ data-blocks-navigation
+ >
+ <div
+ class={cn(
+ 'size-4 p-0.5 flex items-center justify-center rounded-xs group-hover/button:border-accent group-hover/button:border pointer-events-none',
+ {
+ 'bg-accent border border-accent': props.checked,
+ }
+ )}
+ >
+ <Show when={props.checked}>
+ <CheckIcon class="w-full h-full text-panel" />
+ </Show>
+ </div>
+ </button>
+ );
+}
diff --git a/js/app/packages/entity/src/components/ProjectBreadCrumb.tsx b/js/app/packages/entity/src/components/ProjectBreadCrumb.tsx
new file mode 100644
index 0000000000..4a9691091e
--- /dev/null
+++ b/js/app/packages/entity/src/components/ProjectBreadCrumb.tsx
@@ -0,0 +1,65 @@
+import { Show, Suspense } from 'solid-js';
+import { Tooltip } from '@core/component/Tooltip';
+import type { ProjectEntity, ProjectContainedEntity } from '../types/entity';
+import { useProjectPreviewQuery } from '@queries/storage/project-preview';
+import { truncatedPath } from '../utils/path';
+import FolderIcon from '@icon/regular/folder-simple.svg';
+import { cn } from '@ui/utils/classname';
+
+const MAX_PATH_LENGTH = 30;
+
+function Path(props: { path: string[] }) {
+ const fullPath = () => props.path.join('/');
+ const displayPath = () => {
+ return truncatedPath(props.path, MAX_PATH_LENGTH);
+ };
+ const truncated = () => displayPath().length < fullPath().length;
+
+ return (
+ <Tooltip tooltip={fullPath()} hide={!truncated()}>
+ <div class="truncate">{displayPath()}</div>
+ </Tooltip>
+ );
+}
+
+export function ProjectBreadCrumb(props: {
+ entity: ProjectContainedEntity;
+ onClick?: (entity: ProjectEntity, event: MouseEvent) => void;
+}) {
+ const projectQuery = useProjectPreviewQuery(() => props.entity.projectId);
+
+ const handleClick = (e: MouseEvent) => {
+ e.preventDefault();
+ if (!projectQuery.isSuccess) return;
+ e.stopPropagation();
+
+ const data = projectQuery.data;
+ const projectEntity: ProjectEntity = {
+ type: 'project',
+ id: data.id,
+ name: data.name,
+ ownerId: data.owner,
+ updatedAt: data.updatedAt,
+ };
+
+ props.onClick?.(projectEntity, e);
+ };
+
+ return (
+ <a
+ onClick={handleClick}
+ class={cn('flex gap-1 items-center min-w-0 cursor-default', {
+ 'hover:text-accent': projectQuery.isSuccess,
+ })}
+ >
+ <FolderIcon class="size-[1em]" />
+ <Suspense
+ fallback={<div class="h-1 w-10 bg-ink-placeholder/20 animate-pulse" />}
+ >
+ <Show when={projectQuery.data}>
+ {(data) => <Path path={data().path} />}
+ </Show>
+ </Suspense>
+ </a>
+ );
+}
diff --git a/js/app/packages/entity/src/components/UnreadIndicator.tsx b/js/app/packages/entity/src/components/UnreadIndicator.tsx
new file mode 100644
index 0000000000..b4d9b945d7
--- /dev/null
+++ b/js/app/packages/entity/src/components/UnreadIndicator.tsx
@@ -0,0 +1,12 @@
+import { cn } from '@ui/utils/classname';
+
+export function UnreadIndicator(props: { active?: boolean }) {
+ return (
+ <div
+ class={cn({
+ 'bg-accent rounded-full size-2': true,
+ 'opacity-0': !props.active,
+ })}
+ />
+ );
+}
diff --git a/js/app/packages/entity/src/composed/InlineEntity.tsx b/js/app/packages/entity/src/composed/InlineEntity.tsx
new file mode 100644
index 0000000000..883080aa6d
--- /dev/null
+++ b/js/app/packages/entity/src/composed/InlineEntity.tsx
@@ -0,0 +1,14 @@
+import type { EntityData } from '../types/entity';
+import { EntityIcon } from '../extractors/entity-icon';
+import { EntityTitle } from '../extractors/entity-title';
+
+export function InlineEntity(props: { entity: EntityData }) {
+ return (
+ <div class="flex items-center gap-1 min-w-0">
+ <span class="w-[1.25em]">
+ <EntityIcon entity={props.entity} />
+ </span>
+ <EntityTitle entity={props.entity} />
+ </div>
+ );
+}
diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsx
new file mode 100644
index 0000000000..39bd511a5f
--- /dev/null
+++ b/js/app/packages/entity/src/composed/ListEntity.tsx
@@ -0,0 +1,396 @@
+import { Entity } from '../entity';
+import {
+ isChannelEntity,
+ isEmailEntity,
+ isProjectContainedEntity,
+ type ProjectEntity,
+ type EntityData,
+} from '../types/entity';
+import { Match, Show, Switch, type Ref } from 'solid-js';
+import {
+ isWithNotification,
+ type WithNotification,
+} from '../types/notification';
+import { unreadFilterFn } from '../utils/filter';
+import { cn } from '@ui/utils/classname';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import type { SearchLocation } from '../types/search';
+import { isSearchEntity } from '../types/search';
+import { createEntityDraggable } from '../utils/draggable';
+import { UnreadIndicator } from '../components/UnreadIndicator';
+import { MultiSelectCheckbox } from '../components/MultiSelectCheckbox';
+import { DraftBadge, SharedBadge } from '../components/Badges';
+import { DisplayName } from '../components/DisplayName';
+import { useIsShared } from '../utils/shared';
+import { ProjectBreadCrumb } from '../components/ProjectBreadCrumb';
+import {
+ filterNotDoneNotifications,
+ filterValidNotifications,
+} from '../utils/notification';
+import { useSplitPanel } from '@app/component/split-layout/layoutUtils';
+import { mergeRefs } from '@solid-primitives/refs';
+
+interface ListEntityProps {
+ entity: WithNotification<EntityData>;
+ onClick?: (event: MouseEvent) => void;
+ timestamp?: number;
+ ref?: Ref<HTMLDivElement>;
+ checked?: boolean;
+ highlighted?: boolean;
+ onChecked?: (checked: boolean, shiftKey: boolean) => void;
+ onMouseOver?: () => void;
+ onMouseLeave?: () => void;
+ showUnrollNotifications?: boolean;
+ onProjectClick?: (
+ entity: ProjectEntity,
+ e: PointerEvent | MouseEvent
+ ) => void;
+ onContentHitClick?: (location?: SearchLocation) => void;
+}
+
+interface LayoutProps {
+ entity: WithNotification<EntityData>;
+ checked?: boolean;
+ onChecked?: (checked: boolean, shiftKey: boolean) => void;
+ unread: boolean;
+ isShared: boolean;
+ hasNotifications: boolean;
+ onProjectClick?: (
+ entity: ProjectEntity,
+ e: PointerEvent | MouseEvent
+ ) => void;
+}
+
+function NarrowLayout(props: LayoutProps) {
+ return (
+ <Entity.Layout
+ class="w-full gap-x-2 items-center text-sm pl-0 px-2 grid @lg/entity:hidden"
+ style={{
+ 'grid-template-columns': 'auto 1fr 8ch',
+ 'grid-template-rows': '2.5rem auto',
+ 'grid-template-areas':
+ '"indicator title timestamp" "indicator body body"',
+ }}
+ >
+ <Entity.Slot placement="indicator" class="relative self-start pt-3">
+ <div
+ class={cn('w-0 opacity-0 overflow-hidden', {
+ 'w-6 opacity-100': props.checked,
+ })}
+ >
+ <MultiSelectCheckbox
+ checked={props.checked}
+ onChecked={props.onChecked}
+ />
+ </div>
+ </Entity.Slot>
+
+ <Entity.Slot
+ placement="title"
+ class="flex items-center gap-2 truncate font-semibold"
+ >
+ <Show when={props.unread}>
+ <UnreadIndicator active />
+ </Show>
+ <div class="size-4">
+ <Entity.Icon entity={props.entity} />
+ </div>
+ <Switch>
+ <Match when={isEmailEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <>
+ <Show when={entity().isDraft}>
+ <DraftBadge />
+ </Show>
+ <span class="truncate">
+ <Entity.EmailParticipants entity={entity()} />
+ </span>
+ </>
+ )}
+ </Match>
+ <Match when={props.entity}>
+ {(entity) => <Entity.Title entity={entity()} />}
+ </Match>
+ </Switch>
+ </Entity.Slot>
+
+ <Entity.Slot
+ placement="timestamp"
+ class="text-xs font-mono text-right text-ink-extra-muted uppercase font-light"
+ >
+ <Show when={!props.hasNotifications}>
+ <Entity.Timestamp entity={props.entity} />
+ </Show>
+ </Entity.Slot>
+
+ <Show
+ when={
+ (isEmailEntity(props.entity) || isChannelEntity(props.entity)) &&
+ !props.hasNotifications &&
+ !isSearchEntity(props.entity)
+ }
+ >
+ <Entity.Slot placement="body" class="flex flex-col gap-1 pb-3 -mt-1">
+ <Switch>
+ <Match when={isEmailEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <>
+ <div class="flex items-center gap-2 font-semibold truncate">
+ <span class="truncate">
+ <Entity.Title entity={entity()} />
+ </span>
+ </div>
+ <div class="text-ink/50 font-medium w-full truncate">
+ <span class="truncate">{entity().snippet}</span>
+ </div>
+ </>
+ )}
+ </Match>
+ <Match when={isChannelEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <Show when={entity().latestMessage}>
+ {(msg) => (
+ <div class="flex items-center gap-2 w-full truncate">
+ <span class="font-semibold truncate">
+ <DisplayName id={msg().senderId} format="firstName" />
+ </span>
+ <span class="text-ink/50 font-medium truncate inline-flex items-center">
+ <StaticMarkdown
+ theme={unifiedListMarkdownTheme}
+ markdown={msg().content}
+ singleLine
+ />
+ </span>
+ </div>
+ )}
+ </Show>
+ )}
+ </Match>
+ </Switch>
+ </Entity.Slot>
+ </Show>
+ </Entity.Layout>
+ );
+}
+
+function WideLayout(props: LayoutProps) {
+ return (
+ <Entity.Layout
+ class={cn(
+ 'w-full min-h-[inherit] items-center text-sm px-2',
+ 'gap-2 grid grid-cols-[1rem_1fr_auto_8ch] grid-rows-[1fr]',
+ '[--title-width:clamp(6rem,20%,16rem)]',
+ 'hidden @lg/entity:grid'
+ )}
+ style={{
+ 'grid-template-areas': '"indicator content meta timestamp"',
+ }}
+ >
+ <Entity.Slot placement="indicator" class="relative size-full group">
+ <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">
+ <UnreadIndicator active={props.unread} />
+ </div>
+ <div
+ class={cn(
+ 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100 transition-opacity',
+ {
+ 'opacity-100': props.checked,
+ }
+ )}
+ >
+ <MultiSelectCheckbox
+ checked={props.checked}
+ onChecked={props.onChecked}
+ />
+ </div>
+ </Entity.Slot>
+
+ <Entity.Slot
+ placement="content"
+ class="font-semibold truncate items-center gap-2 flex"
+ >
+ <div class="size-4">
+ <Entity.Icon entity={props.entity} />
+ </div>
+ <Switch>
+ <Match when={isEmailEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <>
+ <Show
+ when={!isSearchEntity(entity())}
+ fallback={
+ <>
+ <span class="truncate">
+ <Entity.Title entity={entity()} />
+ </span>
+ <span class="text-ink/50 font-medium truncate flex-1">
+ {entity().snippet}
+ </span>
+ </>
+ }
+ >
+ <span class="w-(--title-width) truncate shrink-0 flex gap-2">
+ <Show when={entity().isDraft}>
+ <DraftBadge />
+ </Show>
+ <span class="truncate">
+ <Entity.EmailParticipants entity={entity()} />
+ </span>
+ </span>
+ <span class="truncate">
+ <Entity.Title entity={entity()} />
+ </span>
+ <span class="text-ink/50 font-medium truncate flex-1">
+ {entity().snippet}
+ </span>
+ </Show>
+ </>
+ )}
+ </Match>
+ <Match when={isChannelEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <>
+ <span class="w-(--title-width) shrink-0 truncate flex gap-2">
+ <Entity.Title entity={entity()} />
+ </span>
+ <Show when={!props.hasNotifications && entity().latestMessage}>
+ {(msg) => (
+ <>
+ <DisplayName id={msg().senderId} format="firstName" />
+ <span class="text-ink/50 font-medium truncate inline-flex items-center">
+ <StaticMarkdown
+ theme={unifiedListMarkdownTheme}
+ markdown={msg().content}
+ singleLine
+ />
+ </span>
+ </>
+ )}
+ </Show>
+ </>
+ )}
+ </Match>
+ <Match when={props.entity}>
+ {(entity) => <Entity.Title entity={entity()} />}
+ </Match>
+ </Switch>
+ </Entity.Slot>
+
+ <Entity.Slot placement="meta" class="flex items-center gap-2">
+ <Show when={isProjectContainedEntity(props.entity) && props.entity}>
+ {(entity) => (
+ <span class="text-ink-extra-muted text-xs">
+ <ProjectBreadCrumb
+ entity={entity()}
+ onClick={props.onProjectClick}
+ />
+ </span>
+ )}
+ </Show>
+ <Show when={props.isShared}>
+ <SharedBadge ownerId={props.entity.ownerId} />
+ </Show>
+ </Entity.Slot>
+
+ <Entity.Slot
+ placement="timestamp"
+ class="text-xs font-mono text-right text-ink-extra-muted uppercase font-light"
+ >
+ <Show when={!props.hasNotifications}>
+ <Entity.Timestamp entity={props.entity} />
+ </Show>
+ </Entity.Slot>
+ </Entity.Layout>
+ );
+}
+
+export function ListEntity(props: ListEntityProps) {
+ const unread = () => unreadFilterFn(props.entity);
+ const isShared = useIsShared(props.entity);
+
+ const hasNotifications = () => {
+ if (!props.showUnrollNotifications) return false;
+ if (!isWithNotification(props.entity)) return false;
+ return (
+ filterNotDoneNotifications(
+ filterValidNotifications(props.entity.notifications?.())
+ ).length > 0
+ );
+ };
+
+ const layoutProps = (): LayoutProps => ({
+ entity: props.entity,
+ checked: props.checked,
+ onChecked: props.onChecked,
+ unread: unread(),
+ isShared: isShared(),
+ hasNotifications: hasNotifications(),
+ onProjectClick: props.onProjectClick,
+ });
+
+ const draggable = createEntityDraggable({
+ entity: props.entity,
+ splitId: useSplitPanel()?.handle?.id,
+ });
+
+ return (
+ <Entity.Root
+ entity={props.entity}
+ onClick={(e) => {
+ if (e.metaKey && props.onChecked) {
+ props.onChecked(!props.checked, e.shiftKey);
+ return;
+ }
+ props.onClick?.(e);
+ }}
+ ref={mergeRefs(props.ref, draggable)}
+ class={cn('@container/entity w-full min-h-10 relative group/narrow', {
+ 'bg-accent/5': props.checked,
+ 'bg-accent/5 outline-1 outline-accent/20 outline-offset-[-1px]':
+ props.highlighted,
+ })}
+ onMouseOver={props.onMouseOver}
+ onMouseLeave={props.onMouseLeave}
+ >
+ <div
+ class={cn('absolute h-full w-[3px] left-0 top-0 bg-accent opacity-0', {
+ 'opacity-100': props.highlighted,
+ })}
+ />
+
+ <NarrowLayout {...layoutProps()} />
+ <WideLayout {...layoutProps()} />
+
+ <Show when={hasNotifications()}>
+ <div class="flex gap-2 w-full h-full items-center text-sm px-2 pb-1 -mt-2 min-w-0 overflow-hidden">
+ <div class={cn('min-w-0 flex-1 truncate ml-2 @lg/entity:ml-6')}>
+ <Show
+ when={
+ isWithNotification(props.entity) &&
+ !isSearchEntity(props.entity)
+ }
+ >
+ <Entity.Notification.Stacks
+ entity={props.entity}
+ visibleCount={3}
+ />
+ </Show>
+ </div>
+ </div>
+ </Show>
+
+ <Show when={isSearchEntity(props.entity)}>
+ <div class="flex gap-2 w-full h-full items-center text-sm px-2 pb-1 -mt-2 min-w-0 overflow-hidden">
+ <div class={cn('min-w-0 flex-1 truncate ml-4 @lg/entity:ml-6')}>
+ <Entity.Search.ContentHits
+ entity={props.entity}
+ onClick={props.onContentHitClick}
+ visibleCount={1}
+ />
+ </div>
+ </div>
+ </Show>
+ </Entity.Root>
+ );
+}
diff --git a/js/app/packages/entity/src/core/Layout.tsx b/js/app/packages/entity/src/core/Layout.tsx
new file mode 100644
index 0000000000..e3e0c10a5f
--- /dev/null
+++ b/js/app/packages/entity/src/core/Layout.tsx
@@ -0,0 +1,12 @@
+import { cn } from '@ui/utils/classname';
+import { type JSX, splitProps } from 'solid-js';
+
+export function Layout(props: JSX.HTMLAttributes<HTMLDivElement>) {
+ const [local, rest] = splitProps(props, ['class', 'children']);
+
+ return (
+ <div class={cn('entity-layout', local.class)} {...rest}>
+ {local.children}
+ </div>
+ );
+}
diff --git a/js/app/packages/entity/src/core/Root.tsx b/js/app/packages/entity/src/core/Root.tsx
new file mode 100644
index 0000000000..5e130b361c
--- /dev/null
+++ b/js/app/packages/entity/src/core/Root.tsx
@@ -0,0 +1,20 @@
+import { type JSX, splitProps } from 'solid-js';
+import { cn } from '@ui/utils/classname';
+import type { EntityData } from '../types/entity';
+
+export function Root(
+ props: JSX.HTMLAttributes<HTMLDivElement> & { entity: EntityData }
+) {
+ const [local, rest] = splitProps(props, ['children', 'class', 'entity']);
+
+ return (
+ <div
+ class={cn('entity-root group/entity', local.class)}
+ data-entity
+ data-entity-id={local.entity.id}
+ {...rest}
+ >
+ {local.children}
+ </div>
+ );
+}
diff --git a/js/app/packages/entity/src/core/Slot.tsx b/js/app/packages/entity/src/core/Slot.tsx
new file mode 100644
index 0000000000..207eeca2e4
--- /dev/null
+++ b/js/app/packages/entity/src/core/Slot.tsx
@@ -0,0 +1,59 @@
+import { cn } from '@ui/utils/classname';
+import {
+ type JSX,
+ type ComponentProps,
+ type ValidComponent,
+ splitProps,
+} from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+
+type SlotElement = 'div' | 'span' | 'button';
+
+const placeGrid = (
+ area: string | [string, string] | undefined
+): Partial<JSX.CSSProperties> => {
+ if (area === undefined) return {};
+ if (typeof area === 'string') {
+ return { 'grid-area': area };
+ }
+ return {
+ 'grid-column-start': area[0],
+ 'grid-column-end': area[1],
+ };
+};
+
+type CommonProps = {
+ children?: JSX.Element;
+ placement?: string | [string, string];
+ class?: string;
+ style?: JSX.CSSProperties | string;
+};
+
+type SlotProps<T extends ValidComponent = 'div'> = { as?: T } & CommonProps &
+ Omit<ComponentProps<T>, keyof CommonProps | 'component'>;
+
+export function Slot<T extends SlotElement = 'div'>(props: SlotProps<T>) {
+ const [local, rest] = splitProps(props, [
+ 'as',
+ 'class',
+ 'children',
+ 'placement',
+ 'style',
+ ]);
+
+ const gridArea = () => placeGrid(local.placement);
+
+ return (
+ <Dynamic
+ class={cn('entity-slot', local.class)}
+ component={local.as ?? ('div' as SlotElement)}
+ style={{
+ ...gridArea(),
+ ...(typeof local.style === 'object' ? local.style : {}),
+ }}
+ {...rest}
+ >
+ {local.children}
+ </Dynamic>
+ );
+}
diff --git a/js/app/packages/entity/src/debug/DebugEntityView.tsx b/js/app/packages/entity/src/debug/DebugEntityView.tsx
new file mode 100644
index 0000000000..10ffb1d639
--- /dev/null
+++ b/js/app/packages/entity/src/debug/DebugEntityView.tsx
@@ -0,0 +1,86 @@
+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
+import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';
+import { seedMockDisplayNames } from '@core/user';
+import { For, createSignal } from 'solid-js';
+import { ListEntity } from '../composed/ListEntity';
+import {
+ ALL_MOCK_ENTITIES,
+ createEntityWithNotifications,
+ MOCK_NOTIFICATIONS,
+ MOCK_USERS,
+} from '../../mocks/mockEntityData';
+import type { EntityData } from '../types/entity';
+import type { WithNotification } from '../types/notification';
+
+// Seed mock display names so user names render correctly
+seedMockDisplayNames([...MOCK_USERS]);
+
+export default function DebugEntityView() {
+ const [selectedIds, setSelectedIds] = createSignal<Set<string>>(new Set());
+ const [lastSelectedIndex, setLastSelectedIndex] = createSignal<number | null>(
+ null
+ );
+
+ const entitiesWithNotifications: WithNotification<EntityData>[] =
+ ALL_MOCK_ENTITIES.map((entity, ndx) => {
+ if (ndx % 6 === 0) {
+ return createEntityWithNotifications(entity, MOCK_NOTIFICATIONS);
+ }
+ return entity;
+ });
+
+ const handleEntityClick = (entity: EntityData, index: number) => {
+ console.log('Entity clicked:', entity);
+ setLastSelectedIndex(index);
+ };
+
+ const handleEntityChecked = (
+ entity: EntityData,
+ index: number,
+ checked: boolean,
+ shiftKey: boolean
+ ) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (checked) {
+ if (shiftKey && lastSelectedIndex() !== null) {
+ const start = Math.min(lastSelectedIndex()!, index);
+ const end = Math.max(lastSelectedIndex()!, index);
+ for (let i = start; i <= end; i++) {
+ next.add(entitiesWithNotifications[i].id);
+ }
+ } else {
+ next.add(entity.id);
+ }
+ } else {
+ next.delete(entity.id);
+ }
+ return next;
+ });
+ setLastSelectedIndex(index);
+ };
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <StaticSplitLabel label="Enity Component Demo (mock data)" />
+ jk
+ </SplitHeaderLeft>
+ <div class="w-full h-full overflow-auto">
+ <For each={entitiesWithNotifications}>
+ {(entity, index) => (
+ <ListEntity
+ entity={entity}
+ onClick={() => handleEntityClick(entity, index())}
+ checked={selectedIds().has(entity.id)}
+ onChecked={(checked, shiftKey) =>
+ handleEntityChecked(entity, index(), checked, shiftKey)
+ }
+ showUnrollNotifications={true}
+ />
+ )}
+ </For>
+ </div>
+ </>
+ );
+}
diff --git a/js/app/packages/entity/src/entity.ts b/js/app/packages/entity/src/entity.ts
new file mode 100644
index 0000000000..743c05b97a
--- /dev/null
+++ b/js/app/packages/entity/src/entity.ts
@@ -0,0 +1,50 @@
+// Core components
+import { Root } from './core/Root';
+import { Layout } from './core/Layout';
+import { Slot } from './core/Slot';
+
+import { EntityIcon } from './extractors/entity-icon';
+import { EntityTitle } from './extractors/entity-title';
+import { EntityTimestamp } from './extractors/entity-timestamp';
+import { EntityEmailParticipants } from './extractors/entity-email-participants';
+import { EntityOwner } from './extractors/entity-owner';
+
+// Search components
+import { ContentHits } from './extractors-search';
+
+// Notification components
+import {
+ NotificationStacks,
+ NotificationIcon,
+ NotificationSender,
+ NotificationContent,
+ NotificationTimestamp,
+ NotificationDescription,
+ NotificationCount,
+} from './extractors-notification';
+
+/**
+ * Entity composable component namespace.
+ */
+export const Entity = {
+ Root,
+ Layout,
+ Slot,
+ Icon: EntityIcon,
+ Title: EntityTitle,
+ Timestamp: EntityTimestamp,
+ EmailParticipants: EntityEmailParticipants,
+ Owner: EntityOwner,
+ Search: {
+ ContentHits: ContentHits,
+ },
+ Notification: {
+ Stacks: NotificationStacks,
+ Icon: NotificationIcon,
+ Sender: NotificationSender,
+ Content: NotificationContent,
+ Timestamp: NotificationTimestamp,
+ Description: NotificationDescription,
+ Count: NotificationCount,
+ },
+};
diff --git a/js/app/packages/entity/src/extractors-notification/index.ts b/js/app/packages/entity/src/extractors-notification/index.ts
new file mode 100644
index 0000000000..e65bbcf392
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/index.ts
@@ -0,0 +1,8 @@
+export { NotificationStacks } from './notification-stacks';
+export { NotificationIcon } from './notification-icon';
+export { NotificationSender } from './notification-sender';
+export { NotificationSenderIcon } from './notification-sender-icon';
+export { NotificationContent } from './notification-content';
+export { NotificationTimestamp } from './notification-timestamp';
+export { NotificationDescription } from './notification-description';
+export { NotificationCount } from './notification-count';
diff --git a/js/app/packages/entity/src/extractors-notification/notification-actions.tsx b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
new file mode 100644
index 0000000000..bc1c908343
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
@@ -0,0 +1,50 @@
+import type { NotificationStack } from '@notifications';
+import type { UnifiedNotification } from '@notifications';
+import { getAllNotificationsFromGroup } from '@notifications';
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+
+interface NotificationActionsProps {
+ stack: NotificationStack;
+ onMarkAsDone?: () => void;
+ onMarkAsRead?: () => void;
+}
+
+interface SingleNotificationActionsProps {
+ notification: UnifiedNotification;
+ onMarkAsDone?: () => void;
+ onMarkAsRead?: () => void;
+}
+
+export function useNotificationStackActions(props: NotificationActionsProps) {
+ const notificationSource = useGlobalNotificationSource();
+
+ const markStackAsDone = async () => {
+ const notifications = getAllNotificationsFromGroup(props.stack);
+ await notificationSource.bulkMarkAsDone(notifications);
+ props.onMarkAsDone?.();
+ };
+
+ const markStackAsRead = async () => {
+ const notifications = getAllNotificationsFromGroup(props.stack);
+ await notificationSource.bulkMarkAsRead(notifications);
+ props.onMarkAsRead?.();
+ };
+
+ return { markStackAsDone, markStackAsRead };
+}
+
+export function useNotificationActions(props: SingleNotificationActionsProps) {
+ const notificationSource = useGlobalNotificationSource();
+
+ const markAsDone = async () => {
+ await notificationSource.markAsDone(props.notification);
+ props.onMarkAsDone?.();
+ };
+
+ const markAsRead = async () => {
+ await notificationSource.markAsRead(props.notification);
+ props.onMarkAsRead?.();
+ };
+
+ return { markAsDone, markAsRead };
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-content.tsx b/js/app/packages/entity/src/extractors-notification/notification-content.tsx
new file mode 100644
index 0000000000..fd4138c8b0
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-content.tsx
@@ -0,0 +1,50 @@
+import { Show } from 'solid-js';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import { extractMessageContent } from '../utils/notification';
+
+interface NotificationContentProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+ singleLine?: boolean;
+}
+
+/**
+ * Displays the content/preview of a notification
+ * For single notifications, shows the message content
+ * For stacks, shows the most recent notification's content
+ */
+export function NotificationContent(props: NotificationContentProps) {
+ const content = () => {
+ if (props.notification) {
+ return extractMessageContent(props.notification);
+ }
+ if (props.stack && props.stack.notifications.length > 0) {
+ return extractMessageContent(props.stack.notifications[0]);
+ }
+ return '';
+ };
+
+ return (
+ <Show when={content()}>
+ {(text) => (
+ <Show
+ when={text().trim()}
+ fallback={
+ <span class="italic text-ink-disabled">Attached items</span>
+ }
+ >
+ {(trimmedContent) => (
+ <StaticMarkdown
+ markdown={trimmedContent()}
+ theme={unifiedListMarkdownTheme}
+ singleLine={props.singleLine ?? true}
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-count.tsx b/js/app/packages/entity/src/extractors-notification/notification-count.tsx
new file mode 100644
index 0000000000..17a491a10d
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-count.tsx
@@ -0,0 +1,31 @@
+import { Show, createMemo } from 'solid-js';
+import type { EntityData } from '../types/entity';
+import { isWithNotification } from '../types/notification';
+import {
+ filterNotDoneNotifications,
+ filterValidNotifications,
+} from '../utils/notification';
+
+interface NotificationCountProps {
+ entity: EntityData;
+}
+
+/**
+ * Displays the count of not-done notifications for an entity
+ * Returns empty fragment if entity has no notifications or all are done
+ */
+export function NotificationCount(props: NotificationCountProps) {
+ const count = createMemo(() => {
+ if (!isWithNotification(props.entity)) return 0;
+
+ const notifications = props.entity.notifications?.();
+ if (!notifications) return 0;
+
+ const validNotifications = filterValidNotifications(notifications);
+ const notDoneNotifications = filterNotDoneNotifications(validNotifications);
+
+ return notDoneNotifications.length;
+ });
+
+ return <Show when={count() > 0}>{count()}</Show>;
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
new file mode 100644
index 0000000000..9d2cfb7535
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
@@ -0,0 +1,53 @@
+import { match } from 'ts-pattern';
+import type { Notification } from '../types/notification';
+
+/**
+ * Gets unique sender IDs from a notification stack
+ * @internal
+ */
+export function getUniqueSenderIds(notifications: Notification[]): string[] {
+ const senderIds = new Set<string>();
+ for (const notification of notifications) {
+ if (notification.senderId) {
+ senderIds.add(notification.senderId);
+ }
+ }
+ return Array.from(senderIds);
+}
+
+/**
+ * Gets the action verb for a notification type
+ * @internal
+ */
+export function getActionVerb(
+ type: Notification['notificationEventType']
+): string {
+ return match(type)
+ .with('channel_mention', () => 'mentioned you')
+ .with('document_mention', () => 'mentioned you')
+ .with('channel_message_reply', () => 'replied')
+ .with('channel_message_send', () => 'sent a message')
+ .with('item_shared_user', () => 'shared')
+ .with('item_shared_organization', () => 'shared')
+ .with('new_email', () => 'sent an email')
+ .otherwise(() => 'notified you');
+}
+
+/**
+ * Gets a noun for the notification type (for multi-notification descriptions)
+ * @internal
+ */
+export function getTypeNoun(
+ type: Notification['notificationEventType'],
+ count: number
+): string {
+ return match(type)
+ .with('channel_message_reply', () => (count === 1 ? 'reply' : 'replies'))
+ .with('channel_message_send', () => (count === 1 ? 'message' : 'messages'))
+ .with('channel_mention', () => (count === 1 ? 'mention' : 'mentions'))
+ .with('document_mention', () => (count === 1 ? 'mention' : 'mentions'))
+ .with('item_shared_user', () => (count === 1 ? 'share' : 'shares'))
+ .with('item_shared_organization', () => (count === 1 ? 'share' : 'shares'))
+ .with('new_email', () => (count === 1 ? 'email' : 'emails'))
+ .otherwise(() => (count === 1 ? 'notification' : 'notifications'));
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-description.tsx b/js/app/packages/entity/src/extractors-notification/notification-description.tsx
new file mode 100644
index 0000000000..e4a0a8ce2c
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-description.tsx
@@ -0,0 +1,122 @@
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import { tryMacroId, useDisplayNameParts } from '@core/user';
+import {
+ getUniqueSenderIds,
+ getActionVerb,
+ getTypeNoun,
+} from './notification-description-helpers';
+
+// Re-export helpers for backward compatibility and testing
+export { getUniqueSenderIds, getActionVerb, getTypeNoun };
+
+interface NotificationDescriptionProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+}
+
+/**
+ * Displays a complete description of the notification including sender(s) and action
+ *
+ * Formats:
+ * - Single notification: "Peter mentioned you"
+ * - Stack with one sender: "Peter: 13 messages"
+ * - Stack with multiple senders: "13 messages from Peter +5"
+ */
+export function NotificationDescription(props: NotificationDescriptionProps) {
+ const isSingleNotification = () => {
+ return Boolean(
+ props.notification ||
+ (props.stack && props.stack.notifications.length === 1)
+ );
+ };
+
+ const notificationType = () => {
+ if (props.notification) return props.notification.notificationEventType;
+ if (props.stack) return props.stack.type;
+ return undefined;
+ };
+
+ const count = () => {
+ if (props.stack) return props.stack.notifications.length;
+ return 1;
+ };
+
+ const primarySenderId = () => {
+ if (props.notification?.senderId) {
+ return props.notification.senderId;
+ }
+ if (props.stack) {
+ const senderIds = getUniqueSenderIds(props.stack.notifications);
+ return senderIds[0];
+ }
+ return undefined;
+ };
+
+ const senderIds = () => {
+ if (!props.stack) return [];
+ return getUniqueSenderIds(props.stack.notifications);
+ };
+
+ const additionalSenderCount = () => {
+ if (!props.stack) return 0;
+ return Math.max(0, senderIds().length - 1);
+ };
+
+ const hasMultipleSenders = () => additionalSenderCount() > 0;
+
+ const primarySenderNameParts = useDisplayNameParts(
+ tryMacroId(primarySenderId() ?? '')
+ );
+
+ const primarySenderFirstName = () => {
+ const firstName = primarySenderNameParts.firstName();
+ return firstName || primarySenderNameParts.fullName();
+ };
+
+ const secondarySenderNameParts = useDisplayNameParts(
+ tryMacroId(senderIds()[1] ?? '')
+ );
+
+ const secondarySenderFirstName = () => {
+ const firstName = secondarySenderNameParts.firstName();
+ return firstName || secondarySenderNameParts.fullName();
+ };
+
+ const description = () => {
+ const type = notificationType();
+ const senderId = primarySenderId();
+
+ if (!type) return '';
+
+ // Single notification: "Peter mentioned you"
+ if (isSingleNotification()) {
+ if (senderId) {
+ return `${primarySenderFirstName()} ${getActionVerb(type)}`;
+ }
+ return getActionVerb(type);
+ }
+
+ // Stack with multiple senders
+ if (hasMultipleSenders()) {
+ if (senderId) {
+ const senderCount = senderIds().length;
+ // Two senders: "13 messages from Peter and Jane"
+ if (senderCount === 2) {
+ return `${count()} ${getTypeNoun(type, count())} from ${primarySenderFirstName()} and ${secondarySenderFirstName()}`;
+ }
+ // Three or more senders: "13 messages from Peter and 5 others"
+ return `${count()} ${getTypeNoun(type, count())} from ${primarySenderFirstName()} and ${additionalSenderCount()} ${additionalSenderCount() === 1 ? 'other' : 'others'}`;
+ }
+ return `${count()} ${getTypeNoun(type, count())}`;
+ }
+
+ // Stack with single sender: "Peter: 13 messages"
+ if (senderId) {
+ return `${primarySenderFirstName()}: ${count()} ${getTypeNoun(type, count())}`;
+ }
+ return `${count()} ${getTypeNoun(type, count())}`;
+ };
+
+ return <>{description()}</>;
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
new file mode 100644
index 0000000000..d8a4a31b08
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
@@ -0,0 +1,53 @@
+import { Dynamic } from 'solid-js/web';
+import type { JSX } from 'solid-js';
+import { match } from 'ts-pattern';
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import ChatIcon from '@icon/regular/chat.svg';
+import ArrowBendUpLeftIcon from '@icon/regular/arrow-bend-up-left.svg';
+import AtIcon from '@icon/regular/at.svg';
+import ShareIcon from '@icon/regular/share.svg';
+import EnvelopeIcon from '@icon/regular/envelope.svg';
+import { cn } from '@ui/utils/classname';
+
+interface NotificationIconProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+ class?: string;
+}
+
+/**
+ * Gets the appropriate icon for a notification type
+ */
+function getNotificationIcon(
+ type: Notification['notificationEventType']
+): (props: { class?: string }) => JSX.Element {
+ return match(type)
+ .with('channel_mention', () => AtIcon)
+ .with('document_mention', () => AtIcon)
+ .with('channel_message_reply', () => ArrowBendUpLeftIcon)
+ .with('channel_message_send', () => ChatIcon)
+ .with('item_shared_user', () => ShareIcon)
+ .with('item_shared_organization', () => ShareIcon)
+ .with('new_email', () => EnvelopeIcon)
+ .otherwise(() => ChatIcon);
+}
+
+/**
+ * Displays the appropriate icon for a notification or stack
+ */
+export function NotificationIcon(props: NotificationIconProps) {
+ const notificationType = () => {
+ if (props.stack) return props.stack.type;
+ if (props.notification) return props.notification.notificationEventType;
+ return undefined;
+ };
+
+ const icon = () => {
+ const type = notificationType();
+ if (!type) return ChatIcon;
+ return getNotificationIcon(type);
+ };
+
+ return <Dynamic component={icon()} class={cn('size-4', props.class)} />;
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-sender-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-sender-icon.tsx
new file mode 100644
index 0000000000..314454af3a
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-sender-icon.tsx
@@ -0,0 +1,69 @@
+import { Show } from 'solid-js';
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import { UserIcon } from '@core/component/UserIcon';
+import { UserGroup } from '@core/component/UserGroup';
+
+interface NotificationSenderIconProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
+}
+
+/**
+ * Gets unique sender IDs from a notification stack
+ */
+function getUniqueSenderIds(notifications: Notification[]): string[] {
+ const senderIds = new Set<string>();
+ for (const notification of notifications) {
+ if (notification.senderId) {
+ senderIds.add(notification.senderId);
+ }
+ }
+ return Array.from(senderIds);
+}
+
+/**
+ * Displays the sender icon(s) for a notification
+ * - Single sender: shows UserIcon
+ * - Multiple senders: shows UserGroup with overlapping avatars
+ */
+export function NotificationSenderIcon(props: NotificationSenderIconProps) {
+ const size = () => props.size ?? 'sm';
+
+ const senderIds = () => {
+ if (props.notification?.senderId) {
+ return [props.notification.senderId];
+ }
+ if (props.stack) {
+ return getUniqueSenderIds(props.stack.notifications);
+ }
+ return [];
+ };
+
+ const hasMultipleSenders = () => senderIds().length > 1;
+
+ return (
+ <Show when={senderIds().length > 0}>
+ <Show
+ when={hasMultipleSenders()}
+ fallback={
+ <UserIcon
+ id={senderIds()[0]}
+ size={size()}
+ suppressClick
+ showTooltip={false}
+ />
+ }
+ >
+ <UserGroup
+ userIds={senderIds()}
+ maxUsers={senderIds().length === 2 ? 2 : 1}
+ size={size()}
+ suppressClick
+ showTooltip={false}
+ />
+ </Show>
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-sender.tsx b/js/app/packages/entity/src/extractors-notification/notification-sender.tsx
new file mode 100644
index 0000000000..fee33f9359
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-sender.tsx
@@ -0,0 +1,60 @@
+import { Show } from 'solid-js';
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import { DisplayName } from '../components/DisplayName';
+
+interface NotificationSenderProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+}
+
+/**
+ * Gets unique sender IDs from a notification stack
+ */
+function getUniqueSenderIds(notifications: Notification[]): string[] {
+ const senderIds = new Set<string>();
+ for (const notification of notifications) {
+ if (notification.senderId) {
+ senderIds.add(notification.senderId);
+ }
+ }
+ return Array.from(senderIds);
+}
+
+/**
+ * Displays the sender(s) of a notification
+ * For single notifications, shows "FirstName"
+ * For stacks with one sender, shows "FirstName"
+ * For stacks with multiple senders, shows "FirstName +N"
+ */
+export function NotificationSender(props: NotificationSenderProps) {
+ const senderId = () => {
+ if (props.notification?.senderId) {
+ return props.notification.senderId;
+ }
+ if (props.stack) {
+ const senderIds = getUniqueSenderIds(props.stack.notifications);
+ return senderIds[0];
+ }
+ return undefined;
+ };
+
+ const additionalSenderCount = () => {
+ if (!props.stack) return 0;
+ const senderIds = getUniqueSenderIds(props.stack.notifications);
+ return Math.max(0, senderIds.length - 1);
+ };
+
+ return (
+ <Show when={senderId()}>
+ {(id) => (
+ <>
+ <DisplayName id={id()} format="firstName" />
+ <Show when={additionalSenderCount() > 0}>
+ <span class="ml-1">+{additionalSenderCount()}</span>
+ </Show>
+ </>
+ )}
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx
new file mode 100644
index 0000000000..610537788a
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx
@@ -0,0 +1,149 @@
+import { Show, createEffect } from 'solid-js';
+import { reconcile, createStore } from 'solid-js/store';
+import {
+ stackNotifications,
+ type NotificationStack,
+ getMostRecentNotification,
+ openNotification,
+ tryToTypedNotification,
+} from '@notifications';
+import type { WithNotification } from '../types/notification';
+import type { EntityData } from '../types/entity';
+import { CollapsibleList } from '../components/CollapsibleList';
+import {
+ filterValidNotifications,
+ filterNotDoneNotifications,
+ isNotificationUnread,
+} from '../utils/notification';
+import { NotificationContent } from './notification-content';
+import { NotificationIcon } from './notification-icon';
+import { NotificationDescription } from './notification-description';
+import { NotificationSenderIcon } from './notification-sender-icon';
+import { NotificationTimestamp } from './notification-timestamp';
+import { UnreadIndicator } from '../components/UnreadIndicator';
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { cn } from '@ui/utils/classname';
+import { useNotificationStackActions } from './notification-actions';
+import { Button } from '@ui/components/Button';
+import CheckIcon from '@icon/regular/check.svg';
+
+const DEFAULT_VISIBLE_COUNT = 3;
+
+interface NotificationStacksProps {
+ entity: WithNotification<EntityData>;
+ onClick?: (e: PointerEvent | MouseEvent) => void;
+ visibleCount?: number;
+}
+
+function NotificationStackRow(props: {
+ stack: NotificationStack;
+ onClick?: (e: PointerEvent | MouseEvent) => void;
+}) {
+ const notificationSource = useGlobalNotificationSource();
+ const unread = () => isNotificationUnread(props.stack);
+
+ const { markStackAsDone } = useNotificationStackActions({
+ stack: props.stack,
+ });
+
+ const handleClick = async (e: PointerEvent | MouseEvent) => {
+ const mostRecent = getMostRecentNotification(props.stack);
+ const typed = tryToTypedNotification(mostRecent);
+ const splitManager = globalSplitManager();
+ if (!typed || !splitManager) return;
+
+ e.stopPropagation();
+ await openNotification(typed, splitManager);
+ await notificationSource.markAsRead(mostRecent);
+ props.onClick?.(e);
+ };
+
+ const handleMarkAsDone = async (e: PointerEvent | MouseEvent) => {
+ e.stopPropagation();
+ await markStackAsDone();
+ };
+
+ return (
+ <div
+ class={cn(
+ 'flex p-2 pr-0 my-1 border-l-2 border-edge-muted bg-edge/10 gap-4 hover:bg-edge/20 min-w-0 overflow-hidden'
+ )}
+ onClick={handleClick}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ handleClick(e as unknown as MouseEvent);
+ }
+ }}
+ >
+ <div class="pt-1 flex-shrink-0">
+ <NotificationIcon stack={props.stack} class="size-4" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="flex items-center gap-1 text-xs min-w-0 overflow-hidden">
+ <span
+ class={cn(
+ 'w-0 transition-[width] overflow-hidden duration-500 ease flex-shrink-0',
+ {
+ 'w-4': unread(),
+ }
+ )}
+ >
+ <UnreadIndicator active />
+ </span>
+ <div class="flex-shrink-0">
+ <NotificationSenderIcon stack={props.stack} size="xs" />
+ </div>
+ <span class="truncate min-w-0">
+ <NotificationDescription stack={props.stack} />
+ </span>
+ <span class="text-ink-extra-muted/50 flex-shrink-0">
+ {' - '}
+ <NotificationTimestamp stack={props.stack} />
+ </span>
+ <div class="ml-auto flex items-center gap-1 pr-2 flex-shrink-0">
+ <Button
+ onClick={handleMarkAsDone}
+ tooltip={'Mark notification stack done'}
+ class="border border-edge-muted text-xs text-ink-muted grid p-0 place-items-center size-6"
+ >
+ <CheckIcon class="size-3" />
+ </Button>
+ </div>
+ </div>
+ <div class="mt-1 truncate min-w-0 overflow-hidden">
+ <NotificationContent stack={props.stack} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function NotificationStacks(props: NotificationStacksProps) {
+ const notifications = () => props.entity.notifications?.() ?? [];
+ const validNotifications = () =>
+ filterNotDoneNotifications(filterValidNotifications(notifications()));
+
+ const [stacks, setStacks] = createStore<NotificationStack[]>([]);
+
+ createEffect(() => {
+ const newStacks = stackNotifications(validNotifications());
+ setStacks(reconcile(newStacks, { key: 'id', merge: false }));
+ });
+
+ return (
+ <Show when={stacks.length > 0}>
+ <CollapsibleList
+ items={stacks}
+ visibleCount={props.visibleCount ?? DEFAULT_VISIBLE_COUNT}
+ >
+ {(stack) => (
+ <NotificationStackRow stack={stack} onClick={props.onClick} />
+ )}
+ </CollapsibleList>
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-timestamp.tsx b/js/app/packages/entity/src/extractors-notification/notification-timestamp.tsx
new file mode 100644
index 0000000000..ca320af6c9
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-notification/notification-timestamp.tsx
@@ -0,0 +1,32 @@
+import type { Notification } from '../types/notification';
+import type { NotificationStack } from '@notifications';
+import { formatRelativeTimestamp } from '../utils/timestamp';
+
+interface NotificationTimestampProps {
+ notification?: Notification;
+ stack?: NotificationStack;
+}
+
+/**
+ * Displays the timestamp of a notification
+ * For single notifications, shows that notification's timestamp
+ * For stacks, shows the most recent notification's timestamp
+ */
+export function NotificationTimestamp(props: NotificationTimestampProps) {
+ const timestamp = () => {
+ if (props.notification) {
+ return props.notification.createdAt;
+ }
+ if (props.stack && props.stack.notifications.length > 0) {
+ return props.stack.notifications[0].createdAt;
+ }
+ return undefined;
+ };
+
+ const formattedTimestamp = () => {
+ const ts = timestamp();
+ return ts ? formatRelativeTimestamp(ts) : '';
+ };
+
+ return <>{formattedTimestamp()}</>;
+}
diff --git a/js/app/packages/entity/src/extractors-search/content-hits.tsx b/js/app/packages/entity/src/extractors-search/content-hits.tsx
new file mode 100644
index 0000000000..19dd686db0
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/content-hits.tsx
@@ -0,0 +1,40 @@
+import { Show } from 'solid-js';
+import type { EntityData } from '../types/entity';
+import type { SearchLocation } from '../types/search';
+import { isSearchEntity } from '../types/search';
+import { CollapsibleList } from '../components/CollapsibleList';
+import { SearchContentHitRow } from './search-content-hit-row';
+
+interface ExtractorContentHitsProps {
+ entity: EntityData;
+ onClick?: (location?: SearchLocation) => void;
+ visibleCount?: number;
+}
+
+/**
+ * Renders collapsible list of content hit rows
+ */
+export function ContentHits(props: ExtractorContentHitsProps) {
+ const contentHits = () => {
+ if (!isSearchEntity(props.entity)) return [];
+ return props.entity.search.contentHitData ?? [];
+ };
+
+ return (
+ <Show when={contentHits().length > 0}>
+ <CollapsibleList
+ items={contentHits()}
+ visibleCount={props.visibleCount ?? 1}
+ >
+ {(hit, index, count) => (
+ <SearchContentHitRow
+ hit={hit}
+ onClick={props.onClick}
+ index={index}
+ count={count}
+ />
+ )}
+ </CollapsibleList>
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-search/index.ts b/js/app/packages/entity/src/extractors-search/index.ts
new file mode 100644
index 0000000000..b617d32733
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/index.ts
@@ -0,0 +1,7 @@
+export { ContentHits } from './content-hits';
+export { SearchIcon } from './search-icon';
+export { SearchContent } from './search-content';
+export { SearchSender } from './search-sender';
+export { SearchTimestamp } from './search-timestamp';
+export { SearchLocation } from './search-location';
+export { SearchContentHitRow } from './search-content-hit-row';
diff --git a/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx b/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx
new file mode 100644
index 0000000000..7dcad53b42
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-content-hit-row.tsx
@@ -0,0 +1,68 @@
+import { Show } from 'solid-js';
+import type { ContentHitData, SearchLocation } from '../types/search';
+import { SearchContent } from './search-content';
+import { SearchSender } from './search-sender';
+import { SearchTimestamp } from './search-timestamp';
+import { cn } from '@ui/utils/classname';
+import { UserIcon } from '@core/component/UserIcon';
+import { SearchLocation as SearchLoc } from './search-location';
+import { getSenderId } from './search-helpers';
+
+// Re-export helper for backward compatibility and testing
+export { getSenderId };
+
+interface SearchContentHitRowProps {
+ hit: ContentHitData;
+ onClick?: (location?: SearchLocation) => void;
+ index?: number;
+ count?: number;
+}
+
+export function SearchContentHitRow(props: SearchContentHitRowProps) {
+ const senderId = () => getSenderId(props.hit);
+ const handleClick = () => {
+ if (props.hit.location) {
+ props.onClick?.(props.hit.location);
+ } else {
+ props.onClick?.();
+ }
+ };
+
+ return (
+ <div
+ class={cn(
+ 'flex p-2 pr-0 my-1 border-l-2 border-edge-muted bg-edge/10 gap-4 hover:bg-edge/20'
+ )}
+ onClick={handleClick}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ handleClick();
+ }
+ }}
+ >
+ <div class="flex flex-col gap-3">
+ <Show when={props.hit.type === 'channel' || props.hit.type === 'email'}>
+ <div class="flex items-center gap-1">
+ <Show when={senderId()}>
+ {(id) => <UserIcon id={id()} size="xs" />}
+ </Show>
+ <span class="text-xs text-ink-muted">
+ <SearchSender hit={props.hit} />
+ <span class="text-ink-extra-muted/50">
+ {' - '}
+ <SearchTimestamp hit={props.hit} />
+ </span>
+ </span>
+ </div>
+ </Show>
+ <Show when={props.hit.type === 'pdf'}>
+ <SearchLoc hit={props.hit} />
+ </Show>
+ <SearchContent hit={props.hit} />
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-content.tsx b/js/app/packages/entity/src/extractors-search/search-content.tsx
new file mode 100644
index 0000000000..e1e02276f1
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-content.tsx
@@ -0,0 +1,35 @@
+import { Show } from 'solid-js';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import type { ContentHitData } from '../types/search';
+
+interface SearchContentProps {
+ hit?: ContentHitData;
+ singleLine?: boolean;
+}
+
+/**
+ * Displays the content/snippet of a search hit
+ */
+export function SearchContent(props: SearchContentProps) {
+ const content = () => props.hit?.content ?? '';
+
+ return (
+ <Show when={content()}>
+ {(text) => (
+ <Show
+ when={text().trim()}
+ fallback={<span class="italic text-ink-disabled">No content</span>}
+ >
+ {(trimmedContent) => (
+ <StaticMarkdown
+ markdown={trimmedContent()}
+ theme={unifiedListMarkdownTheme}
+ singleLine={props.singleLine ?? true}
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-helpers.ts b/js/app/packages/entity/src/extractors-search/search-helpers.ts
new file mode 100644
index 0000000000..64d6d11c82
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-helpers.ts
@@ -0,0 +1,29 @@
+import { match } from 'ts-pattern';
+import type { ContentHitData } from '../types/search';
+import FileTextIcon from '@icon/regular/file-text.svg';
+import FilePdfIcon from '@icon/regular/file-pdf.svg';
+import HashIcon from '@icon/regular/hash.svg';
+import EnvelopeIcon from '@icon/regular/envelope.svg';
+
+/**
+ * Gets the sender ID from a content hit, if applicable
+ * @internal
+ */
+export function getSenderId(hit: ContentHitData): string | undefined {
+ if (hit.type === 'channel' || hit.type === 'email') {
+ return hit.senderId;
+ }
+}
+
+/**
+ * Gets the appropriate icon for a content hit type
+ * @internal
+ */
+export function getSearchIcon(hit: ContentHitData) {
+ return match(hit)
+ .with({ type: 'md' }, () => FileTextIcon)
+ .with({ type: 'pdf' }, () => FilePdfIcon)
+ .with({ type: 'channel' }, () => HashIcon)
+ .with({ type: 'email' }, () => EnvelopeIcon)
+ .otherwise(() => FileTextIcon);
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-icon.tsx b/js/app/packages/entity/src/extractors-search/search-icon.tsx
new file mode 100644
index 0000000000..d6c00c581b
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-icon.tsx
@@ -0,0 +1,22 @@
+import { Dynamic } from 'solid-js/web';
+import type { ContentHitData } from '../types/search';
+import FileTextIcon from '@icon/regular/file-text.svg';
+import { cn } from '@ui/utils/classname';
+import { getSearchIcon } from './search-helpers';
+
+interface SearchIconProps {
+ hit?: ContentHitData;
+ class?: string;
+}
+
+/**
+ * Displays the appropriate icon for a search content hit
+ */
+export function SearchIcon(props: SearchIconProps) {
+ const icon = () => {
+ if (!props.hit) return FileTextIcon;
+ return getSearchIcon(props.hit);
+ };
+
+ return <Dynamic component={icon()} class={cn('size-4', props.class)} />;
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-location.tsx b/js/app/packages/entity/src/extractors-search/search-location.tsx
new file mode 100644
index 0000000000..fe97ad0d97
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-location.tsx
@@ -0,0 +1,30 @@
+import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import type { ContentHitData } from '../types/search';
+
+interface SearchLocationProps {
+ hit?: ContentHitData;
+}
+
+/**
+ * Gets location description for a content hit
+ */
+function getLocationDescription(hit: ContentHitData): string | undefined {
+ return match(hit)
+ .with({ type: 'pdf' }, (h) => `Page ${h.location.searchPage}`)
+ .otherwise(() => undefined);
+}
+
+/**
+ * Displays the location information for a search hit
+ */
+export function SearchLocation(props: SearchLocationProps) {
+ const locationText = () =>
+ props.hit ? getLocationDescription(props.hit) : undefined;
+
+ return (
+ <Show when={locationText()}>
+ {(text) => <span class="text-ink-muted text-xs">{text()}</span>}
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-sender.tsx b/js/app/packages/entity/src/extractors-search/search-sender.tsx
new file mode 100644
index 0000000000..0f35beb040
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-sender.tsx
@@ -0,0 +1,37 @@
+import { Show } from 'solid-js';
+import type {
+ ContentHitData,
+ ChannelContentHitData,
+ EmailContentHitData,
+} from '../types/search';
+import { DisplayName } from '../components/DisplayName';
+
+interface SearchSenderProps {
+ hit?: ContentHitData;
+}
+
+/**
+ * Gets sender ID from content hit if available
+ */
+function getSenderId(hit: ContentHitData): string | undefined {
+ if (hit.type === 'channel') {
+ return (hit as ChannelContentHitData).senderId;
+ }
+ if (hit.type === 'email') {
+ return (hit as EmailContentHitData).senderId;
+ }
+ return undefined;
+}
+
+/**
+ * Displays the sender of a search hit (for channel/email)
+ */
+export function SearchSender(props: SearchSenderProps) {
+ const senderId = () => (props.hit ? getSenderId(props.hit) : undefined);
+
+ return (
+ <Show when={senderId()}>
+ {(id) => <DisplayName id={id()} format="firstName" />}
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors-search/search-timestamp.tsx b/js/app/packages/entity/src/extractors-search/search-timestamp.tsx
new file mode 100644
index 0000000000..82fb89d9e3
--- /dev/null
+++ b/js/app/packages/entity/src/extractors-search/search-timestamp.tsx
@@ -0,0 +1,37 @@
+import type {
+ ContentHitData,
+ ChannelContentHitData,
+ EmailContentHitData,
+} from '../types/search';
+import { formatRelativeTimestamp } from '../utils/timestamp';
+
+interface SearchTimestampProps {
+ hit?: ContentHitData;
+}
+
+/**
+ * Gets timestamp from content hit if available
+ */
+function getTimestamp(hit: ContentHitData): number | undefined {
+ if (hit.type === 'channel') {
+ return (hit as ChannelContentHitData).sentAt;
+ }
+ if (hit.type === 'email') {
+ return (hit as EmailContentHitData).sentAt;
+ }
+ return undefined;
+}
+
+/**
+ * Displays the timestamp of a search hit (for channel/email)
+ */
+export function SearchTimestamp(props: SearchTimestampProps) {
+ const timestamp = () => (props.hit ? getTimestamp(props.hit) : undefined);
+
+ const formattedTimestamp = () => {
+ const ts = timestamp();
+ return ts ? formatRelativeTimestamp(ts) : '';
+ };
+
+ return <>{formattedTimestamp()}</>;
+}
diff --git a/js/app/packages/entity/src/extractors/entity-email-participants.tsx b/js/app/packages/entity/src/extractors/entity-email-participants.tsx
new file mode 100644
index 0000000000..8bbdf1d1c8
--- /dev/null
+++ b/js/app/packages/entity/src/extractors/entity-email-participants.tsx
@@ -0,0 +1,112 @@
+import { useEmail } from '@core/context/user';
+import { emailToMacroId, useDisplayName } from '@core/user';
+import type { EmailEntity } from '../types/entity';
+
+/** Checks if a value is likely an email address */
+export function isLikelyEmail(value?: string): boolean {
+ return typeof value === 'string' && value.includes('@');
+}
+
+/** Extracts the local part of an email address (before @) */
+export function getEmailLocalPart(email: string): string {
+ return email.split('@')[0];
+}
+
+/**
+ * Resolves the best display name for a participant
+ * Priority: macroDisplayName > participant.name > email local part
+ */
+export function resolveParticipantName(
+ participant: { email: string; name: string },
+ macroDisplayName?: string
+): string {
+ if (macroDisplayName && !isLikelyEmail(macroDisplayName)) {
+ return macroDisplayName;
+ }
+ const participantFullName = participant.name ?? '';
+ if (participantFullName && !isLikelyEmail(participantFullName)) {
+ return participantFullName;
+ }
+ return getEmailLocalPart(participant.email);
+}
+
+/**
+ * Combines participant names into a list, handling the "me" case
+ * Returns an array of display names (possibly ["me"] if single participant is userEmail)
+ */
+export function combineParticipantNames(
+ participants: Array<{ email: string; name: string }> | undefined,
+ userEmail: string | undefined,
+ getMacroDisplayName: (email: string) => string | undefined
+): string[] {
+ if (!participants || participants.length === 0) {
+ return [];
+ }
+
+ if (
+ participants.length === 1 &&
+ userEmail &&
+ participants[0].email === userEmail
+ ) {
+ return ['me'];
+ }
+
+ const namesSet = new Set<string>();
+
+ for (const participant of participants) {
+ if (!participant.email) continue;
+
+ if (userEmail && participant.email === userEmail) continue;
+
+ const macroDisplayName = getMacroDisplayName(participant.email);
+ const displayName = resolveParticipantName(participant, macroDisplayName);
+
+ namesSet.add(displayName);
+ }
+
+ return Array.from(namesSet);
+}
+
+/**
+ * Formats display names into a string suitable for UI display
+ * - Single name: returns as-is
+ * - 2-3 names: comma-separated with first names only
+ * - 4+ names: "First .. SecondLast, Last" format with first names
+ */
+export function formatDisplayNames(names: string[]): string | undefined {
+ if (!names || names.length === 0) return undefined;
+ if (names.length === 1) return names[0];
+
+ // For multiple participants, use first names only
+ const firstNames = names.map((name) => name.split(' ')[0]);
+
+ if (firstNames.length <= 3) {
+ return firstNames.join(', ');
+ }
+
+ // For 4+ participants: "First .. SecondLast, Last"
+ return `${firstNames[0]} .. ${firstNames[firstNames.length - 2]}, ${firstNames[firstNames.length - 1]}`;
+}
+
+/**
+ * Get a nicely formatted list of participants from an email entity.
+ * @param props
+ * @returns
+ */
+export function EntityEmailParticipants(props: { entity: EmailEntity }) {
+ const userEmail = useEmail();
+ const fetchDisplayName = (email: string) =>
+ useDisplayName(emailToMacroId(email))[0]();
+
+ const displayNames = () => {
+ return formatDisplayNames(
+ combineParticipantNames(
+ props.entity.participants,
+ userEmail(),
+ fetchDisplayName
+ )
+ );
+ };
+
+ return <>{displayNames()}</>;
+}
diff --git a/js/app/packages/entity/src/extractors/entity-icon.tsx b/js/app/packages/entity/src/extractors/entity-icon.tsx
new file mode 100644
index 0000000000..01f051bf84
--- /dev/null
+++ b/js/app/packages/entity/src/extractors/entity-icon.tsx
@@ -0,0 +1,71 @@
+import {
+ EntityIcon as CoreEntityIcon,
+ type EntityIconProps as CoreEntityIconProps,
+ getIconConfig,
+} from '@core/component/EntityIcon';
+import { UserIcon } from '@core/component/UserIcon';
+import { useUserId } from '@core/context/user';
+import { Show } from 'solid-js';
+import type { ChannelEntity, EntityData } from '../types/entity';
+import { isChannelEntity, isTaskEntity } from '../types/entity';
+import { match } from 'ts-pattern';
+
+interface EntityIconProps {
+ entity: EntityData;
+}
+
+function DirectMessageIcon(props: { entity: ChannelEntity }) {
+ const userId = useUserId();
+ const participantId = () => {
+ const participants = props.entity.participantIds ?? [];
+ return participants.find((id) => id !== userId());
+ };
+
+ return (
+ <div class="bg-panel size-full rounded-full">
+ <Show
+ when={participantId()}
+ fallback={<CoreEntityIcon targetType="directMessage" size="fill" />}
+ >
+ {(id) => <UserIcon id={id()} isDeleted={false} size="fill" />}
+ </Show>
+ </div>
+ );
+}
+
+export function EntityIcon(props: EntityIconProps) {
+ const iconType = () => {
+ return match(props.entity)
+ .when(isChannelEntity, ({ channelType }) =>
+ match(channelType)
+ .with('direct_message', () => 'directMessage' as const)
+ .with('organization', () => 'company' as const)
+ .otherwise(() => 'channel')
+ )
+ .when(isTaskEntity, () => 'task')
+ .with({ type: 'document' }, ({ fileType }) => {
+ return fileType ?? 'default';
+ })
+ .with({ type: 'chat' }, () => 'chat')
+ .with({ type: 'project' }, () => 'project')
+ .with({ type: 'email' }, ({ isRead }) => (isRead ? 'emailRead' : 'email'))
+ .otherwise(() => 'default');
+ };
+
+ const validIconType = () => {
+ const type = iconType();
+ if (getIconConfig(type)) return type as CoreEntityIconProps['targetType'];
+ else return 'default' as const;
+ };
+
+ const isDirectMessage = () => iconType() === 'directMessage';
+
+ return (
+ <Show
+ when={isDirectMessage()}
+ fallback={<CoreEntityIcon targetType={validIconType()} size="fill" />}
+ >
+ <DirectMessageIcon entity={props.entity as ChannelEntity} />
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/extractors/entity-owner.tsx b/js/app/packages/entity/src/extractors/entity-owner.tsx
new file mode 100644
index 0000000000..ff1fc1475b
--- /dev/null
+++ b/js/app/packages/entity/src/extractors/entity-owner.tsx
@@ -0,0 +1,29 @@
+import { tryMacroId, useDisplayName } from '@core/user';
+import { useUserId } from '@core/context/user';
+import type { EntityData } from '../types/entity';
+
+export function EntityOwner(props: { entity: EntityData }) {
+ const userId = useUserId();
+ const ownerId = () => props.entity.ownerId;
+
+ const ownerDisplayName = () => {
+ const owner = ownerId();
+ if (!owner) return undefined;
+ return useDisplayName(tryMacroId(owner))[0]();
+ };
+
+ const displayText = () => {
+ const owner = ownerId();
+ const currentUser = userId();
+
+ if (!owner) return undefined;
+
+ if (currentUser && owner === currentUser) {
+ return 'me';
+ }
+
+ return ownerDisplayName();
+ };
+
+ return <>{displayText()}</>;
+}
diff --git a/js/app/packages/entity/src/extractors/entity-timestamp.tsx b/js/app/packages/entity/src/extractors/entity-timestamp.tsx
new file mode 100644
index 0000000000..30c489632c
--- /dev/null
+++ b/js/app/packages/entity/src/extractors/entity-timestamp.tsx
@@ -0,0 +1,11 @@
+import type { EntityData } from '../types/entity';
+import { formatTimestamp } from '../utils/timestamp';
+
+export function EntityTimestamp(props: {
+ entity: EntityData;
+ overrideTimeStamp?: number;
+}) {
+ const timestamp = () =>
+ props.overrideTimeStamp ?? props.entity.updatedAt ?? Date.now();
+ return <>{formatTimestamp(timestamp())}</>;
+}
diff --git a/js/app/packages/entity/src/extractors/entity-title.tsx b/js/app/packages/entity/src/extractors/entity-title.tsx
new file mode 100644
index 0000000000..1439629ef9
--- /dev/null
+++ b/js/app/packages/entity/src/extractors/entity-title.tsx
@@ -0,0 +1,52 @@
+import { formatDocumentName } from '@service-storage/util/filename';
+import { match } from 'ts-pattern';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import { Show } from 'solid-js';
+import type { EntityData } from '../types/entity';
+import { isSearchEntity } from '../types/search';
+
+function extractRawTitle(entity: EntityData): string {
+ return match(entity)
+ .with({ type: 'document' }, (e) => formatDocumentName(e.name))
+ .with({ type: 'project' }, (e) => e.name)
+ .with({ type: 'channel' }, (e) => e.name)
+ .with({ type: 'email' }, (e) => e.name || '(No Subject)')
+ .with({ type: 'chat' }, (e) => e.name)
+ .otherwise(() => 'Unknown');
+}
+
+function extractSearchHighlight(entity: EntityData): string | undefined {
+ if (!isSearchEntity(entity)) return undefined;
+ return entity.search.nameHighlight ?? undefined;
+}
+
+export function EntityTitle(props: { entity: EntityData }) {
+ const titleData = () => {
+ const searchHighlight = extractSearchHighlight(props.entity);
+ if (searchHighlight) {
+ return {
+ text: searchHighlight,
+ isMarkdown: true,
+ };
+ }
+
+ return {
+ text: extractRawTitle(props.entity),
+ isMarkdown: false,
+ };
+ };
+
+ return (
+ <Show
+ when={titleData().isMarkdown}
+ fallback={<span class="truncate">{titleData().text}</span>}
+ >
+ <StaticMarkdown
+ markdown={titleData().text}
+ theme={unifiedListMarkdownTheme}
+ singleLine={true}
+ />
+ </Show>
+ );
+}
diff --git a/js/app/packages/entity/src/index.ts b/js/app/packages/entity/src/index.ts
new file mode 100644
index 0000000000..1be3824966
--- /dev/null
+++ b/js/app/packages/entity/src/index.ts
@@ -0,0 +1,26 @@
+// Export types
+export * from './types/entity';
+export * from './types/search';
+export * from './types/drag';
+export * from './types/notification';
+
+export { Entity } from './entity';
+
+export { createEntityDraggable } from './utils/draggable';
+
+export { InlineEntity } from './composed/InlineEntity';
+export { ListEntity } from './composed/ListEntity';
+
+export { UnreadIndicator } from './components/UnreadIndicator';
+export { MultiSelectCheckbox } from './components/MultiSelectCheckbox';
+export { DraftBadge, SharedBadge } from './components/Badges';
+export { DisplayName } from './components/DisplayName';
+export { ProjectBreadCrumb } from './components/ProjectBreadCrumb';
+
+export { useIsShared } from './utils/shared';
+export {
+ filterNotDoneNotifications,
+ filterValidNotifications,
+} from './utils/notification';
+
+export { default as DebugEntityView } from './debug/DebugEntityView';
diff --git a/js/app/packages/entity/src/types/drag.ts b/js/app/packages/entity/src/types/drag.ts
new file mode 100644
index 0000000000..765ae16d4d
--- /dev/null
+++ b/js/app/packages/entity/src/types/drag.ts
@@ -0,0 +1,17 @@
+import type { DragEvent } from '@thisbeyond/solid-dnd';
+import type { EntityData } from './entity';
+import type { Accessor } from 'solid-js';
+
+export type EntityDragOperation = 'move' | 'copy';
+
+export type EntityDragData = EntityData & {
+ dragType: 'entity';
+ operation: Accessor<EntityDragOperation>;
+ splitId?: string;
+};
+
+export type EntityDragEvent = DragEvent & {
+ draggable: {
+ data: EntityDragData;
+ };
+};
diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.ts
new file mode 100644
index 0000000000..37084db05a
--- /dev/null
+++ b/js/app/packages/entity/src/types/entity.ts
@@ -0,0 +1,198 @@
+import { isEntityType } from '@core/types/utils';
+import type { ApiLabel } from '@service-email/generated/schemas';
+import type {
+ SoupLabel,
+ SoupProperty,
+} from '@service-storage/generated/schemas';
+import type { JSX } from 'solid-js';
+
+export type EntityBase = {
+ id: string;
+ name: string;
+ ownerId: string;
+ frecencyScore?: number;
+ createdAt?: number;
+ updatedAt?: number;
+ viewedAt?: number;
+};
+
+export type ChannelEntity = EntityBase & {
+ type: 'channel';
+ channelType: 'direct_message' | 'private' | 'organization' | 'public';
+ interactedAt?: number;
+ participantIds?: string[];
+ latestMessage?: {
+ content: string;
+ senderId: string;
+ createdAt: number;
+ };
+};
+
+export type ChatEntity = EntityBase & {
+ type: 'chat';
+ projectId?: string;
+};
+
+/** Named sub types - currently only 'task' */
+export type NamedSubType = 'task';
+
+/** SubType for documents - currently only tasks */
+export type SubType = {
+ type: NamedSubType;
+ is_completed?: boolean;
+} | null;
+
+export type BaseDocumentEntity = EntityBase & {
+ type: 'document';
+ fileType?: string;
+ projectId?: string;
+ subType?: SubType;
+};
+
+export type TaskEntity = EntityBase & {
+ type: 'document';
+ fileType: 'md';
+ subType: { type: 'task'; is_completed?: boolean };
+ projectId?: string;
+};
+
+export type MarkdownEntity = EntityBase & {
+ type: 'document';
+ fileType: 'md';
+ subType?: null;
+ projectId?: string;
+};
+
+export type DocumentEntity = BaseDocumentEntity | MarkdownEntity;
+
+export const getEntityProjectId = (e: EntityData): string | false => {
+ return 'projectId' in e ? (e.projectId ?? false) : false;
+};
+
+// We spread ApiThreadPreviewCursor into the email entity, should we explcitly include all those fields here, or only add them as needed?
+export type EmailEntity = EntityBase & {
+ type: 'email';
+ isRead: boolean;
+ isDraft: boolean;
+ snippet?: string;
+ isImportant: boolean;
+ done: boolean;
+ participants?: Array<{ email: string; name: string }>;
+ senderEmail?: string;
+ senderName?: string;
+ labels?: SoupLabel[] | ApiLabel[];
+};
+
+export type ProjectEntity = EntityBase & {
+ type: 'project';
+ projectId?: string;
+};
+
+export type EntityData =
+ | ChannelEntity
+ | ChatEntity
+ | DocumentEntity
+ | TaskEntity
+ | EmailEntity
+ | ProjectEntity;
+
+export const isEntityData = (item: unknown): item is EntityData => {
+ if (typeof item !== 'object') return false;
+
+ if (!item) return false;
+
+ if (!('type' in item)) return false;
+
+ if (typeof item.type !== 'string') return false;
+
+ return isEntityType(item.type);
+};
+
+export const isTaskEntity = (entity: EntityData): entity is TaskEntity => {
+ return (
+ entity.type === 'document' &&
+ entity.fileType === 'md' &&
+ entity.subType?.type === 'task'
+ );
+};
+
+export const isChannelEntity = (
+ entity: EntityData
+): entity is ChannelEntity => {
+ return entity.type === 'channel';
+};
+
+export const isChatEntity = (entity: EntityData): entity is ChatEntity => {
+ return entity.type === 'chat';
+};
+
+export const isEmailEntity = (entity: EntityData): entity is EmailEntity => {
+ return entity.type === 'email';
+};
+
+export const isProjectEntity = (
+ entity: EntityData
+): entity is ProjectEntity => {
+ return entity.type === 'project';
+};
+
+export const isDocumentEntity = (
+ entity: EntityData
+): entity is DocumentEntity => {
+ return entity.type === 'document';
+};
+
+export const isMarkdownEntity = (
+ entity: EntityData
+): entity is MarkdownEntity => {
+ return (
+ entity.type === 'document' && entity.fileType === 'md' && !entity.subType
+ );
+};
+
+export const isPureDocumentEntity = (
+ entity: EntityData
+): entity is DocumentEntity => {
+ return entity.type === 'document' && entity.subType?.type !== 'task';
+};
+
+export type EntityType = EntityData['type'];
+
+export type ExpandedEntityType = EntityType | 'task';
+
+export type EntityWithProperties<T extends EntityData> = T & {
+ properties?: SoupProperty[];
+};
+
+export type TaskEntityWithProperties = EntityWithProperties<TaskEntity>;
+
+export type EntityOf<K extends EntityType> = Extract<EntityData, { type: K }>;
+
+export type EntityMapper<T extends EntityData> = (entity: EntityData) => T;
+
+export type EntityEnhancer<T extends EntityData> = (
+ entity: EntityData,
+ index?: number,
+ array?: EntityData[]
+) => T;
+
+export type EntityFilter<T extends EntityData> = (entity: T) => boolean;
+
+export type EntitiesFilter<T extends EntityData> = (entities: T[]) => T[];
+
+export type EntityComparator<T extends EntityData> = (a: T, b: T) => number;
+
+export type EntityRenderer<T extends EntityData> = (props: {
+ entity: T;
+ index: number;
+}) => JSX.Element;
+
+export type ProjectContainedEntity<T extends EntityData = EntityData> = T & {
+ projectId: string;
+};
+
+export const isProjectContainedEntity = <T extends EntityData>(
+ entity: T
+): entity is ProjectContainedEntity<T> => {
+ return getEntityProjectId(entity) !== false;
+};
diff --git a/js/app/packages/entity/src/types/notification.ts b/js/app/packages/entity/src/types/notification.ts
new file mode 100644
index 0000000000..2653868373
--- /dev/null
+++ b/js/app/packages/entity/src/types/notification.ts
@@ -0,0 +1,32 @@
+// Temporarily use the generated types for now
+import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';
+import type { Accessor } from 'solid-js';
+
+export type Notification = Omit<ApiUserNotification, 'ownerId'>;
+
+export type WithNotification<T> = T & {
+ notifications?: Accessor<Notification[]>;
+};
+
+/**
+ * Extended notification type that includes stacked notifications for bulk operations.
+ * When clicking a stacked notification row, this array contains all notifications in the stack
+ * so they can be bulk-marked as done.
+ */
+export type WithStackedNotifications<T> = T & {
+ stackedNotifications?: Notification[];
+};
+
+export const isWithNotification = <T extends {} = {}>(
+ item: T
+): item is WithNotification<T> => {
+ return 'notifications' in item && typeof item.notifications === 'function';
+};
+
+export const isWithStackedNotifications = <T extends {} = {}>(
+ item: T
+): item is WithStackedNotifications<T> => {
+ return (
+ 'stackedNotifications' in item && Array.isArray(item.stackedNotifications)
+ );
+};
diff --git a/js/app/packages/entity/src/types/search.ts b/js/app/packages/entity/src/types/search.ts
new file mode 100644
index 0000000000..d47672f09d
--- /dev/null
+++ b/js/app/packages/entity/src/types/search.ts
@@ -0,0 +1,92 @@
+import type { EntityData } from './entity';
+
+type MarkdownHighlightLocation = {
+ type: 'md';
+ nodeId: string;
+};
+
+type PdfHighlightLocation = {
+ type: 'pdf';
+ searchPage: number;
+ highlightTerms: string[];
+ searchSnippet: string;
+ searchRawQuery: string;
+};
+
+type ChannelMessageHighlightLocation = {
+ type: 'channel';
+ threadId?: string;
+ messageId: string;
+};
+
+type EmailMessageHighlightLocation = {
+ type: 'email';
+ messageId: string;
+};
+
+export type SearchLocation =
+ | MarkdownHighlightLocation
+ | PdfHighlightLocation
+ | ChannelMessageHighlightLocation
+ | EmailMessageHighlightLocation;
+
+export type ChannelContentHitData = {
+ type: 'channel';
+ id: string;
+ content: string;
+ senderId: string;
+ sentAt: number;
+ location: ChannelMessageHighlightLocation;
+};
+
+type MdContentHitData = {
+ type: 'md';
+ content: string;
+ location: MarkdownHighlightLocation;
+};
+
+type PdfContentHitData = {
+ type: 'pdf';
+ content: string;
+ location: PdfHighlightLocation;
+};
+
+type GenericContentHitData = {
+ type?: undefined;
+ content: string;
+ location?: never;
+};
+
+export type EmailContentHitData = {
+ type: 'email';
+ content: string;
+ sender: string;
+ senderId: string;
+ sentAt: number;
+ location: EmailMessageHighlightLocation;
+};
+
+export type DocumentContentHitData =
+ | MdContentHitData
+ | PdfContentHitData
+ | GenericContentHitData;
+
+export type ContentHitData =
+ | DocumentContentHitData
+ | ChannelContentHitData
+ | EmailContentHitData
+ | GenericContentHitData;
+
+export type SearchData = {
+ nameHighlight: string | null;
+ contentHitData: ContentHitData[] | null;
+ source: 'local' | 'service';
+};
+
+export type WithSearch<T extends EntityData> = T & {
+ search: SearchData;
+};
+
+export const isSearchEntity = <T extends EntityData>(
+ entity: T
+): entity is WithSearch<T> => 'search' in entity;
diff --git a/js/app/packages/entity/src/utils/draggable.ts b/js/app/packages/entity/src/utils/draggable.ts
new file mode 100644
index 0000000000..9ae9de72fc
--- /dev/null
+++ b/js/app/packages/entity/src/utils/draggable.ts
@@ -0,0 +1,22 @@
+import { createDraggable } from '@thisbeyond/solid-dnd';
+import { createUniqueId } from 'solid-js';
+import type { EntityData } from '../types/entity';
+import type { EntityDragData } from '../types/drag';
+import { useDragOperation } from '@app/component/ItemDragAndDrop';
+
+export function createEntityDraggable(options: {
+ entity: EntityData;
+ splitId?: string;
+}): ReturnType<typeof createDraggable> {
+ const { isAltKey } = useDragOperation();
+ const draggableId = `${options.entity.id}-${options.splitId ?? createUniqueId()}`;
+
+ const dragData: EntityDragData = {
+ dragType: 'entity',
+ splitId: options.splitId,
+ ...options.entity,
+ operation: () => (isAltKey() ? 'copy' : 'move'),
+ };
+
+ return createDraggable(draggableId, dragData);
+}
diff --git a/js/app/packages/entity/src/utils/filter.ts b/js/app/packages/entity/src/utils/filter.ts
new file mode 100644
index 0000000000..822805d231
--- /dev/null
+++ b/js/app/packages/entity/src/utils/filter.ts
@@ -0,0 +1,7 @@
+import type { EntityData } from '../types/entity';
+import type { WithNotification } from '../types/notification';
+
+export function unreadFilterFn(entity: WithNotification<EntityData>) {
+ if (entity.type === 'email') return !entity.isRead;
+ return entity.notifications?.()?.some(({ viewedAt }) => !viewedAt) ?? false;
+}
diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.ts
new file mode 100644
index 0000000000..9634f328ce
--- /dev/null
+++ b/js/app/packages/entity/src/utils/notification.ts
@@ -0,0 +1,148 @@
+import {
+ isChannelMention,
+ isChannelMessageReply,
+ isChannelMessageSend,
+ isDocumentMention,
+ isItemSharedOrganization,
+ isItemSharedUser,
+ isNewEmail,
+ getMetadata,
+ type UnifiedNotificationWithMetadata,
+ type TypedNotification,
+} from '@notifications/notification-metadata';
+import type { NotificationStack } from '@notifications/notification-stacking';
+import type { Notification } from '../types/notification';
+import { match } from 'ts-pattern';
+
+/**
+ * Filters out invalid notification types that shouldn't be displayed
+ * Currently filters out 'channel_message_document' notifications.
+ */
+export function filterValidNotifications(
+ notifications: Notification[] | undefined
+): Notification[] {
+ if (!notifications) return [];
+
+ return notifications.filter((n) => {
+ return (
+ n.notificationEventType !== 'channel_message_document' &&
+ n.notificationEventType !== undefined
+ );
+ });
+}
+
+/** filters out notifications that are marked as done */
+export function filterNotDoneNotifications(
+ notifications: Notification[]
+): Notification[] {
+ return notifications.filter((n) => !n.done);
+}
+
+export function extractNotificationSenderIds(
+ notifications: TypedNotification[],
+ maxCount: number = 3,
+ reverse = false
+): string[] {
+ const senderIds = new Set<string>();
+
+ for (const notification of notifications) {
+ if (senderIds.size >= maxCount) break;
+
+ const metadata = notification.notificationMetadata;
+ if (
+ metadata &&
+ 'senderId' in metadata &&
+ typeof metadata.senderId === 'string' &&
+ metadata.senderId
+ ) {
+ senderIds.add(metadata.senderId);
+ }
+ }
+
+ const arr = Array.from(senderIds);
+ if (reverse) arr.reverse();
+ return arr;
+}
+
+/**
+ * Gets a human-readable action text for a notification based on its type
+ * Returns a short verb phrase like "mentioned", "replied", "shared", etc.
+ */
+export function getNotificationActionText(notification: Notification): string {
+ const type = notification.notificationEventType;
+
+ return match(type)
+ .with('channel_mention', () => 'mentioned')
+ .with('channel_message_send', () => 'sent')
+ .with('channel_message_reply', () => 'replied')
+ .with('document_mention', () => 'mentioned')
+ .with('item_shared_user', () => 'shared')
+ .with('item_shared_organization', () => 'shared')
+ .with('channel_invite', () => 'invited')
+ .with('new_email', () => 'emailed')
+ .with('invite_to_team', () => 'invited')
+ .with('reject_team_invite', () => 'declined')
+ .with('task_assigned', () => 'assigned')
+ .with('channel_message_document', () => 'notified')
+ .otherwise(() => 'notified');
+}
+
+export function extractMessageContent(notification: Notification): string {
+ const typed = notification as UnifiedNotificationWithMetadata;
+
+ if (isChannelMention(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.messageContent || '';
+ }
+
+ if (isChannelMessageSend(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.messageContent || '';
+ }
+
+ if (isChannelMessageReply(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.messageContent || '';
+ }
+
+ if (isDocumentMention(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.documentName || '';
+ }
+
+ if (isItemSharedUser(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.itemName || '';
+ }
+
+ if (isItemSharedOrganization(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.itemName || '';
+ }
+
+ if (isNewEmail(typed)) {
+ const metadata = getMetadata(typed);
+ return metadata.subject || '';
+ }
+
+ return '';
+}
+
+/**
+ * Checks if a notification or notification stack is unread
+ * A notification is unread if it hasn't been viewed (!viewedAt) and isn't done (!done)
+ * A notification stack is unread if ANY notification in the stack is unread
+ */
+export function isNotificationUnread(
+ item: Notification | NotificationStack
+): boolean {
+ if ('notifications' in item && Array.isArray(item.notifications)) {
+ const stack = item as NotificationStack;
+ return stack.notifications.some(
+ (notification) => !notification.viewedAt && !notification.done
+ );
+ }
+
+ const notification = item as Notification;
+ return !notification.viewedAt && !notification.done;
+}
diff --git a/js/app/packages/entity/src/utils/path.ts b/js/app/packages/entity/src/utils/path.ts
new file mode 100644
index 0000000000..88c134c947
--- /dev/null
+++ b/js/app/packages/entity/src/utils/path.ts
@@ -0,0 +1,57 @@
+const SEP = ' / ';
+const ELLIPSIS = '…';
+
+/**
+ * path: ["root", "a", "b", "parent", "terminal"]
+ * - keeps "/" separators
+ * - prefers: root + file; collapses middle dirs to "…"
+ */
+export function truncatedPath(path: string[], maxChars: number): string {
+ const segments = (path ?? []).filter((s) => s && s.trim().length > 0);
+
+ if (maxChars <= 0) return '';
+ if (segments.length === 0) return '';
+
+ const full = segments.join(SEP);
+ if (full.length <= maxChars) return full;
+
+ const root = segments[0];
+ const file = segments[segments.length - 1];
+
+ const hasMiddle = segments.length > 2;
+
+ // root/…/file (or root/file if no middle)
+ const collapsed = hasMiddle
+ ? [root, ELLIPSIS, file].join(SEP)
+ : [root, file].join(SEP);
+ if (collapsed.length <= maxChars) return collapsed;
+
+ // …/file
+ const min = [ELLIPSIS, file].join(SEP);
+ if (min.length <= maxChars) return min;
+
+ // truncate filename (preserve extension when possible)
+ const truncate = (s: string, n: number) =>
+ s.length <= n ? s : s.slice(0, Math.max(1, n - 1)) + ELLIPSIS;
+
+ const lastDot = file.lastIndexOf('.');
+ const hasExt = lastDot > 0 && lastDot < file.length - 1;
+ const ext = hasExt ? file.slice(lastDot) : '';
+ const base = hasExt ? file.slice(0, lastDot) : file;
+
+ // space for "…/" + filename
+ const prefixLen = (ELLIPSIS + SEP).length;
+ const nameBudget = maxChars - prefixLen;
+
+ if (nameBudget <= 0) return ELLIPSIS.slice(0, maxChars);
+
+ if (!ext) return [ELLIPSIS, truncate(base, nameBudget)].join(SEP);
+
+ // try to keep full ext
+ if (ext.length >= nameBudget) {
+ return [ELLIPSIS, truncate(file, nameBudget)].join(SEP);
+ }
+
+ const baseBudget = nameBudget - ext.length;
+ return [ELLIPSIS, truncate(base, baseBudget) + ext].join(SEP);
+}
diff --git a/js/app/packages/entity/src/utils/shared.ts b/js/app/packages/entity/src/utils/shared.ts
new file mode 100644
index 0000000000..693232fea8
--- /dev/null
+++ b/js/app/packages/entity/src/utils/shared.ts
@@ -0,0 +1,11 @@
+import type { EntityData } from '../types/entity';
+import { useUserContext } from '@core/context/user';
+
+export function useIsShared(entity: EntityData) {
+ const { userId } = useUserContext();
+ return () => {
+ if (entity.type === 'channel') return false;
+ if (entity.ownerId === userId()) return false;
+ return true;
+ };
+}
diff --git a/js/app/packages/entity/src/utils/timestamp.ts b/js/app/packages/entity/src/utils/timestamp.ts
new file mode 100644
index 0000000000..a00722924d
--- /dev/null
+++ b/js/app/packages/entity/src/utils/timestamp.ts
@@ -0,0 +1,72 @@
+import {
+ format,
+ isToday,
+ isYesterday,
+ isSameYear,
+ fromUnixTime,
+ differenceInMinutes,
+ differenceInHours,
+} from 'date-fns';
+
+/**
+ * Formats a timestamp into a human-readable string.
+ * - Today: Shows time (e.g., "2:30 PM")
+ * - Same year: Shows month and day (e.g., "Jan 27")
+ * - Older: Shows full date (e.g., "1/27/24")
+ */
+export function formatTimestamp(timestamp: number): string {
+ const date = timestamp < 1e12 ? fromUnixTime(timestamp) : new Date(timestamp);
+
+ if (isToday(date)) {
+ return format(date, 'h:mm a');
+ }
+
+ if (isSameYear(date, new Date())) {
+ return format(date, 'MMM d');
+ }
+
+ return format(date, 'M/d/yy');
+}
+
+/**
+ * Formats a timestamp into a relative human-readable string.
+ * - Under 60 minutes: "X minutes ago"
+ * - Under 24 hours: "X hours ago"
+ * - Yesterday: "3:45pm yesterday"
+ * - Older: Shows date (e.g., "Jan 27" or "1/27/24")
+ */
+export function formatRelativeTimestamp(timestamp: number): string {
+ const date = timestamp < 1e12 ? fromUnixTime(timestamp) : new Date(timestamp);
+ const now = new Date();
+
+ const minutesAgo = differenceInMinutes(now, date);
+
+ if (minutesAgo < 1) {
+ return 'just now';
+ }
+
+ if (minutesAgo < 60) {
+ return `${minutesAgo} ${minutesAgo === 1 ? 'minute' : 'minutes'} ago`;
+ }
+
+ const hoursAgo = differenceInHours(now, date);
+
+ if (hoursAgo < 24) {
+ return `${hoursAgo} ${hoursAgo === 1 ? 'hour' : 'hours'} ago`;
+ }
+
+ if (isYesterday(date)) {
+ return `${format(date, 'h:mma')} yesterday`;
+ }
+
+ if (isSameYear(date, now)) {
+ return format(date, 'MMM d');
+ }
+
+ return format(date, 'M/d/yy');
+}
+
+export interface TimestampData {
+ formatted: string;
+ raw: number;
+}
diff --git a/js/app/packages/entity/tests/filter.test.ts b/js/app/packages/entity/tests/filter.test.ts
new file mode 100644
index 0000000000..6e3e6ff02b
--- /dev/null
+++ b/js/app/packages/entity/tests/filter.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it } from 'vitest';
+import { unreadFilterFn } from '../src/utils/filter';
+import type { EntityData } from '../src/types/entity';
+import type { WithNotification } from '../src/types/notification';
+
+describe('unreadFilterFn', () => {
+ describe('email entities', () => {
+ it('returns true for unread emails', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'email',
+ isRead: false,
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('returns false for read emails', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'email',
+ isRead: true,
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+ });
+
+ describe('non-email entities with notifications', () => {
+ it('returns true when entity has unviewed notifications', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [
+ { viewedAt: null } as any,
+ { viewedAt: 1234567890 } as any,
+ ],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('returns false when all notifications are viewed', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [
+ { viewedAt: 1234567890 } as any,
+ { viewedAt: 9876543210 } as any,
+ ],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+
+ it('returns false when notifications array is empty', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+
+ it('returns false when notifications function returns undefined', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => undefined,
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+
+ it('returns false when notifications function returns null', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => null,
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+
+ it('returns false when notifications property is undefined', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(false);
+ });
+ });
+
+ describe('mixed scenarios', () => {
+ it('handles entity with multiple unviewed notifications', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'channel',
+ notifications: () => [
+ { viewedAt: null } as any,
+ { viewedAt: null } as any,
+ { viewedAt: null } as any,
+ ],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('handles entity with one unviewed among many viewed', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'channel',
+ notifications: () => [
+ { viewedAt: 1234567890 } as any,
+ { viewedAt: 1234567890 } as any,
+ { viewedAt: null } as any,
+ { viewedAt: 1234567890 } as any,
+ ],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('handles different entity types correctly', () => {
+ const documentEntity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [{ viewedAt: null } as any],
+ } as any;
+
+ const channelEntity: WithNotification<EntityData> = {
+ type: 'channel',
+ notifications: () => [{ viewedAt: null } as any],
+ } as any;
+
+ expect(unreadFilterFn(documentEntity)).toBe(true);
+ expect(unreadFilterFn(channelEntity)).toBe(true);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('handles notifications with viewedAt as 0', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [{ viewedAt: 0 } as any],
+ } as any;
+
+ // viewedAt: 0 is falsy and treated as unread by the filter
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('handles notifications with undefined viewedAt', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'document',
+ notifications: () => [{ viewedAt: undefined } as any],
+ } as any;
+
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+
+ it('handles email type even with notifications property present', () => {
+ const entity: WithNotification<EntityData> = {
+ type: 'email',
+ isRead: false,
+ notifications: () => [{ viewedAt: 1234567890 } as any],
+ } as any;
+
+ // For email type, should only check isRead
+ expect(unreadFilterFn(entity)).toBe(true);
+ });
+ });
+});
diff --git a/js/app/packages/entity/tests/notification-description.test.ts b/js/app/packages/entity/tests/notification-description.test.ts
new file mode 100644
index 0000000000..f69755f20c
--- /dev/null
+++ b/js/app/packages/entity/tests/notification-description.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getUniqueSenderIds,
+ getActionVerb,
+ getTypeNoun,
+} from '../src/extractors-notification/notification-description-helpers';
+import type { Notification } from '../src/types/notification';
+
+describe('notification-description helpers', () => {
+ describe('getUniqueSenderIds', () => {
+ it('extracts unique sender IDs from notifications', () => {
+ const notifications: Notification[] = [
+ { senderId: 'user1' } as Notification,
+ { senderId: 'user2' } as Notification,
+ { senderId: 'user3' } as Notification,
+ ];
+
+ const result = getUniqueSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2', 'user3']);
+ });
+
+ it('deduplicates sender IDs', () => {
+ const notifications: Notification[] = [
+ { senderId: 'user1' } as Notification,
+ { senderId: 'user2' } as Notification,
+ { senderId: 'user1' } as Notification,
+ { senderId: 'user3' } as Notification,
+ { senderId: 'user2' } as Notification,
+ ];
+
+ const result = getUniqueSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2', 'user3']);
+ });
+
+ it('skips notifications without senderId', () => {
+ const notifications: Notification[] = [
+ { senderId: 'user1' } as Notification,
+ {} as Notification,
+ { senderId: 'user2' } as Notification,
+ { senderId: undefined } as any,
+ ];
+
+ const result = getUniqueSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2']);
+ });
+
+ it('returns empty array for notifications with no senders', () => {
+ const notifications: Notification[] = [
+ {} as Notification,
+ {} as Notification,
+ ];
+
+ const result = getUniqueSenderIds(notifications);
+ expect(result).toEqual([]);
+ });
+
+ it('returns empty array for empty input', () => {
+ const result = getUniqueSenderIds([]);
+ expect(result).toEqual([]);
+ });
+
+ it('maintains insertion order of unique sender IDs', () => {
+ const notifications: Notification[] = [
+ { senderId: 'user3' } as Notification,
+ { senderId: 'user1' } as Notification,
+ { senderId: 'user2' } as Notification,
+ { senderId: 'user3' } as Notification,
+ ];
+
+ const result = getUniqueSenderIds(notifications);
+ expect(result).toEqual(['user3', 'user1', 'user2']);
+ });
+ });
+
+ describe('getActionVerb', () => {
+ it('returns correct verb for channel_mention', () => {
+ expect(getActionVerb('channel_mention')).toBe('mentioned you');
+ });
+
+ it('returns correct verb for document_mention', () => {
+ expect(getActionVerb('document_mention')).toBe('mentioned you');
+ });
+
+ it('returns correct verb for channel_message_reply', () => {
+ expect(getActionVerb('channel_message_reply')).toBe('replied');
+ });
+
+ it('returns correct verb for channel_message_send', () => {
+ expect(getActionVerb('channel_message_send')).toBe('sent a message');
+ });
+
+ it('returns correct verb for item_shared_user', () => {
+ expect(getActionVerb('item_shared_user')).toBe('shared');
+ });
+
+ it('returns correct verb for item_shared_organization', () => {
+ expect(getActionVerb('item_shared_organization')).toBe('shared');
+ });
+
+ it('returns correct verb for new_email', () => {
+ expect(getActionVerb('new_email')).toBe('sent an email');
+ });
+
+ it('returns default verb for unknown types', () => {
+ expect(getActionVerb('channel_invite' as any)).toBe('notified you');
+ expect(getActionVerb('task_assigned' as any)).toBe('notified you');
+ });
+ });
+
+ describe('getTypeNoun', () => {
+ describe('channel_message_reply', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('channel_message_reply', 1)).toBe('reply');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('channel_message_reply', 2)).toBe('replies');
+ expect(getTypeNoun('channel_message_reply', 10)).toBe('replies');
+ });
+ });
+
+ describe('channel_message_send', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('channel_message_send', 1)).toBe('message');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('channel_message_send', 2)).toBe('messages');
+ expect(getTypeNoun('channel_message_send', 5)).toBe('messages');
+ });
+ });
+
+ describe('channel_mention', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('channel_mention', 1)).toBe('mention');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('channel_mention', 3)).toBe('mentions');
+ });
+ });
+
+ describe('document_mention', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('document_mention', 1)).toBe('mention');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('document_mention', 4)).toBe('mentions');
+ });
+ });
+
+ describe('item_shared_user', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('item_shared_user', 1)).toBe('share');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('item_shared_user', 2)).toBe('shares');
+ });
+ });
+
+ describe('item_shared_organization', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('item_shared_organization', 1)).toBe('share');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('item_shared_organization', 3)).toBe('shares');
+ });
+ });
+
+ describe('new_email', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('new_email', 1)).toBe('email');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('new_email', 2)).toBe('emails');
+ });
+ });
+
+ describe('unknown types', () => {
+ it('returns generic singular for count of 1', () => {
+ expect(getTypeNoun('channel_invite' as any, 1)).toBe('notification');
+ expect(getTypeNoun('task_assigned' as any, 1)).toBe('notification');
+ });
+
+ it('returns generic plural for count greater than 1', () => {
+ expect(getTypeNoun('channel_invite' as any, 2)).toBe('notifications');
+ expect(getTypeNoun('task_assigned' as any, 5)).toBe('notifications');
+ });
+ });
+
+ describe('edge cases', () => {
+ it('handles count of 0 as plural', () => {
+ expect(getTypeNoun('channel_message_send', 0)).toBe('messages');
+ });
+
+ it('handles large counts', () => {
+ expect(getTypeNoun('channel_message_reply', 1000)).toBe('replies');
+ });
+ });
+ });
+});
diff --git a/js/app/packages/entity/tests/notification.test.ts b/js/app/packages/entity/tests/notification.test.ts
new file mode 100644
index 0000000000..bb615a3065
--- /dev/null
+++ b/js/app/packages/entity/tests/notification.test.ts
@@ -0,0 +1,459 @@
+import { describe, expect, it } from 'vitest';
+import type { Notification } from '../src/types/notification';
+import {
+ filterValidNotifications,
+ filterNotDoneNotifications,
+ extractNotificationSenderIds,
+ getNotificationActionText,
+ extractMessageContent,
+ isNotificationUnread,
+} from '../src/utils/notification';
+
+describe('notification utils', () => {
+ describe('filterValidNotifications', () => {
+ it('returns empty array for undefined input', () => {
+ expect(filterValidNotifications(undefined)).toEqual([]);
+ });
+
+ it('filters out channel_message_document notifications', () => {
+ const notifications: Notification[] = [
+ {
+ id: '1',
+ notificationEventType: 'channel_mention',
+ } as Notification,
+ {
+ id: '2',
+ notificationEventType: 'channel_message_document',
+ } as Notification,
+ {
+ id: '3',
+ notificationEventType: 'channel_message_send',
+ } as Notification,
+ ];
+
+ const result = filterValidNotifications(notifications);
+ expect(result).toHaveLength(2);
+ expect(result.map((n) => n.id)).toEqual(['1', '3']);
+ });
+
+ it('filters out notifications with undefined type', () => {
+ const notifications = [
+ {
+ id: '1',
+ notificationEventType: 'channel_mention',
+ } as Notification,
+ {
+ id: '2',
+ notificationEventType: undefined,
+ } as any,
+ ];
+
+ const result = filterValidNotifications(notifications);
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('1');
+ });
+
+ it('keeps all valid notification types', () => {
+ const notifications: Notification[] = [
+ {
+ id: '1',
+ notificationEventType: 'channel_mention',
+ } as Notification,
+ {
+ id: '2',
+ notificationEventType: 'document_mention',
+ } as Notification,
+ { id: '3', notificationEventType: 'item_shared_user' } as Notification,
+ { id: '4', notificationEventType: 'new_email' } as Notification,
+ ];
+
+ const result = filterValidNotifications(notifications);
+ expect(result).toHaveLength(4);
+ });
+ });
+
+ describe('filterNotDoneNotifications', () => {
+ it('filters out notifications marked as done', () => {
+ const notifications: Notification[] = [
+ { id: '1', done: false } as Notification,
+ { id: '2', done: true } as Notification,
+ { id: '3', done: false } as Notification,
+ ];
+
+ const result = filterNotDoneNotifications(notifications);
+ expect(result).toHaveLength(2);
+ expect(result.map((n) => n.id)).toEqual(['1', '3']);
+ });
+
+ it('keeps notifications with undefined done property', () => {
+ const notifications = [
+ { id: '1', done: false } as Notification,
+ { id: '2' } as Notification,
+ ];
+
+ const result = filterNotDoneNotifications(notifications);
+ expect(result).toHaveLength(2);
+ });
+
+ it('returns empty array for empty input', () => {
+ expect(filterNotDoneNotifications([])).toEqual([]);
+ });
+ });
+
+ describe('extractNotificationSenderIds', () => {
+ it('extracts sender IDs from notification metadata', () => {
+ const notifications = [
+ {
+ notificationMetadata: { senderId: 'user1' },
+ },
+ {
+ notificationMetadata: { senderId: 'user2' },
+ },
+ {
+ notificationMetadata: { senderId: 'user3' },
+ },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2', 'user3']);
+ });
+
+ it('limits results to maxCount', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: { senderId: 'user2' } },
+ { notificationMetadata: { senderId: 'user3' } },
+ { notificationMetadata: { senderId: 'user4' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications, 2);
+ expect(result).toHaveLength(2);
+ expect(result).toEqual(['user1', 'user2']);
+ });
+
+ it('defaults to maxCount of 3', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: { senderId: 'user2' } },
+ { notificationMetadata: { senderId: 'user3' } },
+ { notificationMetadata: { senderId: 'user4' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications);
+ expect(result).toHaveLength(3);
+ });
+
+ it('deduplicates sender IDs', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: { senderId: 'user2' } },
+ { notificationMetadata: { senderId: 'user1' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2']);
+ });
+
+ it('skips notifications without senderId', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: {} },
+ { notificationMetadata: { senderId: 'user2' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2']);
+ });
+
+ it('skips notifications with empty senderId', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: { senderId: '' } },
+ { notificationMetadata: { senderId: 'user2' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications);
+ expect(result).toEqual(['user1', 'user2']);
+ });
+
+ it('reverses result when reverse is true', () => {
+ const notifications = [
+ { notificationMetadata: { senderId: 'user1' } },
+ { notificationMetadata: { senderId: 'user2' } },
+ { notificationMetadata: { senderId: 'user3' } },
+ ] as any[];
+
+ const result = extractNotificationSenderIds(notifications, 3, true);
+ expect(result).toEqual(['user3', 'user2', 'user1']);
+ });
+ });
+
+ describe('getNotificationActionText', () => {
+ it('returns correct action text for channel_mention', () => {
+ const notification = {
+ notificationEventType: 'channel_mention',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('mentioned');
+ });
+
+ it('returns correct action text for channel_message_send', () => {
+ const notification = {
+ notificationEventType: 'channel_message_send',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('sent');
+ });
+
+ it('returns correct action text for channel_message_reply', () => {
+ const notification = {
+ notificationEventType: 'channel_message_reply',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('replied');
+ });
+
+ it('returns correct action text for document_mention', () => {
+ const notification = {
+ notificationEventType: 'document_mention',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('mentioned');
+ });
+
+ it('returns correct action text for item_shared_user', () => {
+ const notification = {
+ notificationEventType: 'item_shared_user',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('shared');
+ });
+
+ it('returns correct action text for item_shared_organization', () => {
+ const notification = {
+ notificationEventType: 'item_shared_organization',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('shared');
+ });
+
+ it('returns correct action text for channel_invite', () => {
+ const notification = {
+ notificationEventType: 'channel_invite',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('invited');
+ });
+
+ it('returns correct action text for new_email', () => {
+ const notification = {
+ notificationEventType: 'new_email',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('emailed');
+ });
+
+ it('returns correct action text for invite_to_team', () => {
+ const notification = {
+ notificationEventType: 'invite_to_team',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('invited');
+ });
+
+ it('returns correct action text for reject_team_invite', () => {
+ const notification = {
+ notificationEventType: 'reject_team_invite',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('declined');
+ });
+
+ it('returns correct action text for task_assigned', () => {
+ const notification = {
+ notificationEventType: 'task_assigned',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('assigned');
+ });
+
+ it('returns correct action text for channel_message_document', () => {
+ const notification = {
+ notificationEventType: 'channel_message_document',
+ } as Notification;
+ expect(getNotificationActionText(notification)).toBe('notified');
+ });
+ });
+
+ describe('extractMessageContent', () => {
+ it('extracts messageContent for channel_mention', () => {
+ const notification = {
+ notificationEventType: 'channel_mention',
+ notificationMetadata: {
+ messageContent: 'Hey @user, check this out',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe(
+ 'Hey @user, check this out'
+ );
+ });
+
+ it('extracts messageContent for channel_message_send', () => {
+ const notification = {
+ notificationEventType: 'channel_message_send',
+ notificationMetadata: {
+ messageContent: 'Hello everyone',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Hello everyone');
+ });
+
+ it('extracts messageContent for channel_message_reply', () => {
+ const notification = {
+ notificationEventType: 'channel_message_reply',
+ notificationMetadata: {
+ messageContent: 'Great point!',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Great point!');
+ });
+
+ it('extracts documentName for document_mention', () => {
+ const notification = {
+ notificationEventType: 'document_mention',
+ notificationMetadata: {
+ documentName: 'Project Plan.doc',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Project Plan.doc');
+ });
+
+ it('extracts itemName for item_shared_user', () => {
+ const notification = {
+ notificationEventType: 'item_shared_user',
+ notificationMetadata: {
+ itemName: 'Shared Folder',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Shared Folder');
+ });
+
+ it('extracts itemName for item_shared_organization', () => {
+ const notification = {
+ notificationEventType: 'item_shared_organization',
+ notificationMetadata: {
+ itemName: 'Company Docs',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Company Docs');
+ });
+
+ it('extracts subject for new_email', () => {
+ const notification = {
+ notificationEventType: 'new_email',
+ notificationMetadata: {
+ subject: 'Important Update',
+ },
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('Important Update');
+ });
+
+ it('returns empty string for unsupported notification type', () => {
+ const notification = {
+ notificationEventType: 'channel_invite',
+ notificationMetadata: {},
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('');
+ });
+
+ it('returns empty string when content is missing', () => {
+ const notification = {
+ notificationEventType: 'channel_mention',
+ notificationMetadata: {},
+ } as any;
+
+ expect(extractMessageContent(notification)).toBe('');
+ });
+ });
+
+ describe('isNotificationUnread', () => {
+ describe('single notification', () => {
+ it('returns true for unviewed notification', () => {
+ const notification = {
+ viewedAt: null,
+ done: false,
+ } as Notification;
+
+ expect(isNotificationUnread(notification)).toBe(true);
+ });
+
+ it('returns false for viewed notification', () => {
+ const notification = {
+ viewedAt: 1234567890,
+ done: false,
+ } as Notification;
+
+ expect(isNotificationUnread(notification)).toBe(false);
+ });
+
+ it('returns false for done notification', () => {
+ const notification = {
+ viewedAt: null,
+ done: true,
+ } as Notification;
+
+ expect(isNotificationUnread(notification)).toBe(false);
+ });
+
+ it('returns false for viewed and done notification', () => {
+ const notification = {
+ viewedAt: 1234567890,
+ done: true,
+ } as Notification;
+
+ expect(isNotificationUnread(notification)).toBe(false);
+ });
+ });
+
+ describe('notification stack', () => {
+ it('returns true if any notification in stack is unread', () => {
+ const stack = {
+ notifications: [
+ { viewedAt: 1234567890, done: false } as Notification,
+ { viewedAt: null, done: false } as Notification,
+ { viewedAt: 1234567890, done: false } as Notification,
+ ],
+ } as any;
+
+ expect(isNotificationUnread(stack)).toBe(true);
+ });
+
+ it('returns false if all notifications are viewed', () => {
+ const stack = {
+ notifications: [
+ { viewedAt: 1234567890, done: false } as Notification,
+ { viewedAt: 1234567890, done: false } as Notification,
+ ],
+ } as any;
+
+ expect(isNotificationUnread(stack)).toBe(false);
+ });
+
+ it('returns false if all notifications are done', () => {
+ const stack = {
+ notifications: [
+ { viewedAt: null, done: true } as Notification,
+ { viewedAt: null, done: true } as Notification,
+ ],
+ } as any;
+
+ expect(isNotificationUnread(stack)).toBe(false);
+ });
+
+ it('returns false for empty stack', () => {
+ const stack = {
+ notifications: [],
+ } as any;
+
+ expect(isNotificationUnread(stack)).toBe(false);
+ });
+ });
+ });
+});
diff --git a/js/app/packages/entity/tests/path.test.ts b/js/app/packages/entity/tests/path.test.ts
new file mode 100644
index 0000000000..47b2fa8c72
--- /dev/null
+++ b/js/app/packages/entity/tests/path.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from 'vitest';
+import { truncatedPath } from '../src/utils/path';
+
+describe('truncatedPath', () => {
+ describe('basic functionality', () => {
+ it('returns empty string for empty path', () => {
+ expect(truncatedPath([], 100)).toBe('');
+ });
+
+ it('returns empty string when maxChars is 0', () => {
+ expect(truncatedPath(['root', 'file.txt'], 0)).toBe('');
+ });
+
+ it('returns empty string when maxChars is negative', () => {
+ expect(truncatedPath(['root', 'file.txt'], -5)).toBe('');
+ });
+
+ it('filters out empty and whitespace-only segments', () => {
+ expect(truncatedPath(['root', '', ' ', 'file.txt'], 100)).toBe(
+ 'root / file.txt'
+ );
+ });
+
+ it('returns full path when it fits within maxChars', () => {
+ const path = ['root', 'folder', 'file.txt'];
+ const full = 'root / folder / file.txt';
+ expect(truncatedPath(path, full.length)).toBe(full);
+ expect(truncatedPath(path, full.length + 10)).toBe(full);
+ });
+ });
+
+ describe('path collapsing', () => {
+ it('collapses middle segments when path is too long', () => {
+ const path = ['root', 'very', 'long', 'nested', 'path', 'file.txt'];
+ // Should collapse to: root / … / file.txt
+ expect(truncatedPath(path, 25)).toBe('root / … / file.txt');
+ });
+
+ it('handles two-segment path (no middle to collapse)', () => {
+ const path = ['root', 'file.txt'];
+ expect(truncatedPath(path, 20)).toBe('root / file.txt');
+ });
+
+ it('collapses to ellipsis and filename when root does not fit', () => {
+ const path = ['very-long-root-name', 'file.txt'];
+ // Should show: … / file.txt
+ expect(truncatedPath(path, 15)).toBe('… / file.txt');
+ });
+ });
+
+ describe('filename truncation', () => {
+ it('truncates filename when even minimal path is too long', () => {
+ const path = ['root', 'very-long-filename-that-needs-truncation.txt'];
+ // With maxChars=15, should truncate filename
+ const result = truncatedPath(path, 15);
+ expect(result).toContain('…');
+ expect(result.length).toBeLessThanOrEqual(15);
+ });
+
+ it('preserves file extension when truncating filename', () => {
+ const path = ['root', 'very-long-filename.txt'];
+ // Should try to keep .txt extension
+ const result = truncatedPath(path, 18);
+ expect(result).toContain('.txt');
+ expect(result).toMatch(/… \/ .*\.txt/);
+ });
+
+ it('handles filename without extension', () => {
+ const path = ['root', 'verylongfilenamewithoutextension'];
+ const result = truncatedPath(path, 15);
+ expect(result).toContain('…');
+ expect(result.length).toBeLessThanOrEqual(15);
+ });
+
+ it('handles filename with multiple dots', () => {
+ const path = ['root', 'file.name.with.dots.txt'];
+ const result = truncatedPath(path, 20);
+ // Should preserve the last extension (.txt)
+ expect(result).toContain('.txt');
+ });
+
+ it('truncates when extension is longer than budget', () => {
+ const path = ['root', 'file.verylongextension'];
+ const result = truncatedPath(path, 10);
+ expect(result.length).toBeLessThanOrEqual(10);
+ expect(result).toContain('…');
+ });
+
+ it('handles extreme truncation to just ellipsis', () => {
+ const path = ['root', 'file.txt'];
+ // maxChars=1 should return just one character of ellipsis
+ expect(truncatedPath(path, 1)).toBe('…');
+ });
+ });
+
+ describe('edge cases', () => {
+ it('handles single-segment path', () => {
+ expect(truncatedPath(['file.txt'], 100)).toBe('file.txt');
+ // Single segment still uses the root/file pattern, so it becomes "… / f…"
+ expect(truncatedPath(['file.txt'], 5)).toBe('… / f…');
+ });
+
+ it('handles path with special characters', () => {
+ const path = ['root', 'folder@2024', 'file (1).txt'];
+ const result = truncatedPath(path, 100);
+ expect(result).toBe('root / folder@2024 / file (1).txt');
+ });
+
+ it('handles very long single segment', () => {
+ const longName = 'a'.repeat(100);
+ const path = [longName];
+ const result = truncatedPath(path, 10);
+ expect(result.length).toBeLessThanOrEqual(10);
+ expect(result).toContain('…');
+ });
+
+ it('handles path with unicode characters', () => {
+ const path = ['root', 'folder', 'файл.txt'];
+ expect(truncatedPath(path, 100)).toContain('файл.txt');
+ });
+ });
+
+ describe('separator handling', () => {
+ it('uses " / " as separator', () => {
+ const path = ['root', 'folder', 'file.txt'];
+ const result = truncatedPath(path, 100);
+ expect(result).toMatch(/root \/ folder \/ file\.txt/);
+ });
+
+ it('accounts for separator length in truncation', () => {
+ const path = ['a', 'b', 'c'];
+ // "a / b / c" = 9 characters
+ expect(truncatedPath(path, 9)).toBe('a / b / c');
+ // With maxChars=8, "a / … / c" (9 chars) doesn't fit, so it returns "… / c" (5 chars)
+ expect(truncatedPath(path, 8)).toBe('… / c');
+ });
+ });
+});
diff --git a/js/app/packages/entity/tests/search-helpers.test.ts b/js/app/packages/entity/tests/search-helpers.test.ts
new file mode 100644
index 0000000000..c5ba01d836
--- /dev/null
+++ b/js/app/packages/entity/tests/search-helpers.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getSenderId,
+ getSearchIcon,
+} from '../src/extractors-search/search-helpers';
+import type { ContentHitData } from '../src/types/search';
+import FileTextIcon from '@icon/regular/file-text.svg';
+import FilePdfIcon from '@icon/regular/file-pdf.svg';
+import HashIcon from '@icon/regular/hash.svg';
+import EnvelopeIcon from '@icon/regular/envelope.svg';
+
+describe('search-helpers', () => {
+ describe('getSenderId', () => {
+ it('returns senderId for channel type hits', () => {
+ const hit: ContentHitData = {
+ type: 'channel',
+ senderId: 'user123',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBe('user123');
+ });
+
+ it('returns senderId for email type hits', () => {
+ const hit: ContentHitData = {
+ type: 'email',
+ senderId: 'user456',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBe('user456');
+ });
+
+ it('returns undefined for md type hits', () => {
+ const hit: ContentHitData = {
+ type: 'md',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBeUndefined();
+ });
+
+ it('returns undefined for pdf type hits', () => {
+ const hit: ContentHitData = {
+ type: 'pdf',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBeUndefined();
+ });
+
+ it('handles channel hits without senderId', () => {
+ const hit: ContentHitData = {
+ type: 'channel',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBeUndefined();
+ });
+
+ it('handles email hits without senderId', () => {
+ const hit: ContentHitData = {
+ type: 'email',
+ } as ContentHitData;
+
+ expect(getSenderId(hit)).toBeUndefined();
+ });
+ });
+
+ describe('getSearchIcon', () => {
+ it('returns FileTextIcon for md type', () => {
+ const hit: ContentHitData = {
+ type: 'md',
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(FileTextIcon);
+ });
+
+ it('returns FilePdfIcon for pdf type', () => {
+ const hit: ContentHitData = {
+ type: 'pdf',
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(FilePdfIcon);
+ });
+
+ it('returns HashIcon for channel type', () => {
+ const hit: ContentHitData = {
+ type: 'channel',
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(HashIcon);
+ });
+
+ it('returns EnvelopeIcon for email type', () => {
+ const hit: ContentHitData = {
+ type: 'email',
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(EnvelopeIcon);
+ });
+
+ it('returns FileTextIcon for unknown types', () => {
+ const hit: ContentHitData = {
+ type: 'unknown' as any,
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(FileTextIcon);
+ });
+
+ it('handles hits with additional properties', () => {
+ const hit: ContentHitData = {
+ type: 'channel',
+ senderId: 'user123',
+ content: 'some content',
+ } as ContentHitData;
+
+ expect(getSearchIcon(hit)).toBe(HashIcon);
+ });
+ });
+});
diff --git a/js/app/packages/entity/tests/timestamp.test.ts b/js/app/packages/entity/tests/timestamp.test.ts
new file mode 100644
index 0000000000..2e2d5d7625
--- /dev/null
+++ b/js/app/packages/entity/tests/timestamp.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest';
+import {
+ formatTimestamp,
+ formatRelativeTimestamp,
+} from '../src/utils/timestamp';
+
+describe('formatTimestamp', () => {
+ describe('timestamp format handling', () => {
+ it('handles Unix timestamp (seconds)', () => {
+ // January 1, 2025 at 12:00 PM
+ const unixSeconds = 1735732800;
+ const result = formatTimestamp(unixSeconds);
+ // Should format based on when test runs, but should not throw
+ expect(typeof result).toBe('string');
+ expect(result.length).toBeGreaterThan(0);
+ });
+
+ it('handles millisecond timestamp', () => {
+ // January 1, 2025 at 12:00 PM
+ const milliseconds = 1735732800000;
+ const result = formatTimestamp(milliseconds);
+ expect(typeof result).toBe('string');
+ expect(result.length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('time formatting for today', () => {
+ it("formats today's timestamp with time only", () => {
+ const now = Date.now();
+ const result = formatTimestamp(now);
+ // Should be in format like "2:30 PM"
+ expect(result).toMatch(/\d{1,2}:\d{2}\s?(AM|PM)/i);
+ });
+ });
+
+ describe('date formatting for same year', () => {
+ it('formats same year date as "MMM d"', () => {
+ // Create a date in the current year but not today
+ const currentYear = new Date().getFullYear();
+ const date = new Date(currentYear, 0, 15); // January 15
+ const result = formatTimestamp(date.getTime());
+
+ // Should be format like "Jan 15"
+ expect(result).toMatch(/^[A-Z][a-z]{2}\s\d{1,2}$/);
+ });
+ });
+
+ describe('date formatting for previous years', () => {
+ it('formats old dates with full date', () => {
+ // January 15, 2020
+ const oldDate = new Date(2020, 0, 15);
+ const result = formatTimestamp(oldDate.getTime());
+
+ // Should be format like "1/15/20"
+ expect(result).toMatch(/^\d{1,2}\/\d{1,2}\/\d{2}$/);
+ });
+ });
+});
+
+describe('formatRelativeTimestamp', () => {
+ describe('timestamp format handling', () => {
+ it('handles Unix timestamp (seconds)', () => {
+ const unixSeconds = Math.floor(Date.now() / 1000) - 300; // 5 minutes ago
+ const result = formatRelativeTimestamp(unixSeconds);
+ expect(result).toContain('minute');
+ });
+
+ it('handles millisecond timestamp', () => {
+ const milliseconds = Date.now() - 300000; // 5 minutes ago
+ const result = formatRelativeTimestamp(milliseconds);
+ expect(result).toContain('minute');
+ });
+ });
+
+ describe('just now', () => {
+ it('returns "just now" for very recent timestamps', () => {
+ const now = Date.now();
+ expect(formatRelativeTimestamp(now)).toBe('just now');
+ expect(formatRelativeTimestamp(now - 30000)).toBe('just now'); // 30 seconds ago
+ });
+ });
+
+ describe('minutes ago', () => {
+ it('formats timestamps within last hour as minutes', () => {
+ const oneMinuteAgo = Date.now() - 60000;
+ expect(formatRelativeTimestamp(oneMinuteAgo)).toBe('1 minute ago');
+ });
+
+ it('uses plural for multiple minutes', () => {
+ const fiveMinutesAgo = Date.now() - 300000;
+ expect(formatRelativeTimestamp(fiveMinutesAgo)).toBe('5 minutes ago');
+ });
+
+ it('handles 59 minutes correctly', () => {
+ const fiftyNineMinutesAgo = Date.now() - 59 * 60000;
+ expect(formatRelativeTimestamp(fiftyNineMinutesAgo)).toBe(
+ '59 minutes ago'
+ );
+ });
+ });
+
+ describe('hours ago', () => {
+ it('formats timestamps within 24 hours as hours', () => {
+ const oneHourAgo = Date.now() - 3600000;
+ expect(formatRelativeTimestamp(oneHourAgo)).toBe('1 hour ago');
+ });
+
+ it('uses plural for multiple hours', () => {
+ const threeHoursAgo = Date.now() - 3 * 3600000;
+ expect(formatRelativeTimestamp(threeHoursAgo)).toBe('3 hours ago');
+ });
+
+ it('handles 23 hours correctly', () => {
+ const twentyThreeHoursAgo = Date.now() - 23 * 3600000;
+ expect(formatRelativeTimestamp(twentyThreeHoursAgo)).toBe('23 hours ago');
+ });
+ });
+
+ describe('yesterday', () => {
+ it('formats yesterday with time', () => {
+ // Create yesterday's date
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ yesterday.setHours(14, 30, 0, 0); // 2:30 PM
+
+ const result = formatRelativeTimestamp(yesterday.getTime());
+ expect(result).toContain('yesterday');
+ expect(result).toMatch(/\d{1,2}:\d{2}(am|pm)/i);
+ });
+ });
+
+ describe('same year older dates', () => {
+ it('formats dates in same year as "MMM d"', () => {
+ // Create a date 30 days ago in current year
+ const date = new Date();
+ date.setDate(date.getDate() - 30);
+
+ const result = formatRelativeTimestamp(date.getTime());
+ // Should be format like "Jan 15"
+ expect(result).toMatch(/^[A-Z][a-z]{2}\s\d{1,2}$/);
+ });
+ });
+
+ describe('previous years', () => {
+ it('formats old dates with full date', () => {
+ // January 15, 2020
+ const oldDate = new Date(2020, 0, 15);
+ const result = formatRelativeTimestamp(oldDate.getTime());
+
+ // Should be format like "1/15/20"
+ expect(result).toMatch(/^\d{1,2}\/\d{1,2}\/\d{2}$/);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('handles future timestamps gracefully', () => {
+ const future = Date.now() + 3600000; // 1 hour in future
+ const result = formatRelativeTimestamp(future);
+ // Should return "just now" since difference is < 1 minute
+ expect(result).toBe('just now');
+ });
+
+ it('handles very old timestamps', () => {
+ const veryOld = new Date(1990, 0, 1).getTime();
+ const result = formatRelativeTimestamp(veryOld);
+ expect(typeof result).toBe('string');
+ expect(result.length).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/js/app/packages/entity/tsconfig.json b/js/app/packages/entity/tsconfig.json
new file mode 100644
index 0000000000..4f9992d657
--- /dev/null
+++ b/js/app/packages/entity/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "allowSyntheticDefaultImports": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "composite": true,
+ "isolatedModules": true,
+ "skipLibCheck": true,
+ "moduleResolution": "bundler"
+ },
+}
diff --git a/js/app/packages/entity/vitest.config.ts b/js/app/packages/entity/vitest.config.ts
new file mode 100644
index 0000000000..70485d572f
--- /dev/null
+++ b/js/app/packages/entity/vitest.config.ts
@@ -0,0 +1,13 @@
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ plugins: [
+ tsconfigPaths({
+ root: '../../',
+ }),
+ ],
+ test: {
+ globals: true,
+ },
+} as any);
diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.ts
index 54fb63f145..32955c0823 100644
--- a/js/app/packages/queries/storage/keys.ts
+++ b/js/app/packages/queries/storage/keys.ts
@@ -2,6 +2,9 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const projectsKeys = createQueryKeys('projects', {
list: null,
+ preview: (projectId: string) => ({
+ queryKey: [projectId],
+ }),
});
export const deletedKeys = createQueryKeys('deleted', {
diff --git a/js/app/packages/queries/storage/project-preview.ts b/js/app/packages/queries/storage/project-preview.ts
new file mode 100644
index 0000000000..87aee1aa67
--- /dev/null
+++ b/js/app/packages/queries/storage/project-preview.ts
@@ -0,0 +1,124 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+import {
+ catchToResult,
+ isErr,
+ ok,
+ type MaybeResult,
+} from '@core/util/maybeResult';
+import type {
+ GetBatchProjectPreviewResponse,
+ ProjectPreviewData,
+} from '@service-storage/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { projectsKeys } from './keys';
+
+const PROJECT_PREVIEW_STALE_TIME = 5 * 60 * 1000; // 5 minutes
+const PROJECT_PREVIEW_GC_TIME = 10 * 60 * 1000; // 10 minutes
+
+/**
+ * Fetch project preview data from the storage service
+ */
+async function fetchProjectPreview(
+ projectId: string
+): Promise<ProjectPreviewData> {
+ const dssHost = SERVER_HOSTS['document-storage-service'];
+ const apiVersion = 'v2';
+ const url = `${dssHost}/${apiVersion}/projects/preview`;
+
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ credentials: 'include',
+ body: JSON.stringify({
+ projectIds: [projectId],
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch project preview: ${response.statusText}`);
+ }
+
+ const json = (await response.json()) as GetBatchProjectPreviewResponse;
+
+ const projectPreview = json.previews.find(
+ (preview) => preview.id === projectId
+ );
+
+ if (!projectPreview) {
+ throw new Error(`Project ${projectId} not found in preview response`);
+ }
+
+ if (projectPreview.access === 'no_access') {
+ throw new Error(`No access to folder ${projectId}`);
+ }
+
+ if (projectPreview.access === 'does_not_exist') {
+ throw new Error(`Project ${projectId} does not exist`);
+ }
+
+ return projectPreview;
+}
+
+/**
+ * Create query options for a project preview
+ */
+function projectPreviewQueryOptions(projectId: string) {
+ return {
+ queryKey: projectsKeys.preview(projectId).queryKey,
+ queryFn: () => fetchProjectPreview(projectId),
+ staleTime: PROJECT_PREVIEW_STALE_TIME,
+ gcTime: PROJECT_PREVIEW_GC_TIME,
+ enabled: !!projectId,
+ };
+}
+
+/**
+ * Hook to fetch project preview data
+ */
+export function useProjectPreviewQuery(projectId: Accessor<string>) {
+ return useQuery(() => projectPreviewQueryOptions(projectId()));
+}
+
+/**
+ * Fetch and cache project preview data
+ * Useful for prefetching or ensuring data is available
+ */
+export async function fetchAndCacheProjectPreview(
+ projectId: string
+): Promise<MaybeResult<string, { project: ProjectPreviewData }>> {
+ const result = await catchToResult(async () =>
+ queryClient.ensureQueryData(projectPreviewQueryOptions(projectId))
+ );
+
+ if (isErr(result)) {
+ return result;
+ }
+
+ return ok({ project: result[1] });
+}
+
+/**
+ * Invalidate project preview cache
+ */
+export function invalidateProjectPreview(projectId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: projectsKeys.preview(projectId).queryKey,
+ });
+}
+
+/**
+ * Set project preview data directly in cache
+ */
+export function setProjectPreviewData(
+ projectId: string,
+ data: ProjectPreviewData
+) {
+ return queryClient.setQueryData<ProjectPreviewData>(
+ projectsKeys.preview(projectId).queryKey,
+ data
+ );
+}
diff --git a/js/app/tsconfig.json b/js/app/tsconfig.json
index 9dd9ae1c4b..29d40595ec 100644
--- a/js/app/tsconfig.json
+++ b/js/app/tsconfig.json
@@ -198,7 +198,10 @@
],
"@block-theme/*": [
"./packages/block-theme/*"
- ]
+ ],
+ "@entity/*": [
+ "./packages/entity/*"
+ ],
},
"rootDir": ".",
"outDir": "./dist"
@@ -230,6 +233,9 @@
},
{
"path": "./packages/service-clients"
+ },
+ {
+ "path": "./packages/entity"
}
]
}