@marktiderman/genesis-chat 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/web/inbox.tsx CHANGED
@@ -3,16 +3,16 @@
3
3
  * The inbox: your conversations, newest first, each a button with an avatar,
4
4
  * the title (the other person's name in a two-person conversation), a one-line
5
5
  * preview, the time, an unread count, an @ when you were mentioned, and muted
6
- * and pinned marks. Arrow keys move between rows.
6
+ * and pinned marks. Arrow keys, j and k, Home and End move between rows.
7
7
  *
8
- * Moving onto genesis-ui (feature `inbox-thread`): its scrolling, list and composer are the same
9
- * behaviour as genesis-ui's `InboxPage`, which were promoted from here. This screen keeps its data
10
- * wiring (the chat client, realtime, read state) and moves its rendering onto `InboxPage` with chat's
11
- * builder; until then fix behaviour in both places.
8
+ * On genesis-ui's `InboxPage`, which owns the list, its keyboard and its loading, empty and error
9
+ * states. This screen keeps its data wiring (the chat client, realtime, read state) and draws chat's
10
+ * row in the `row` slot.
12
11
  */
13
- import { useRef, type KeyboardEvent } from "react";
12
+ import { useMemo, type ComponentProps } from "react";
14
13
  import { AtSign, BellOff, MessageSquare, Pin } from "lucide-react";
15
- import { Badge, Button, EmptyState, Skeleton, UserAvatar, cn } from "@marktiderman/genesis-ui";
14
+ import { Badge, Button, EmptyState, InboxPage, UserAvatar, cn, type InboxPageSlotMap } from "@marktiderman/genesis-ui";
15
+ import type { InboxItem } from "@marktiderman/genesis-core/conversation";
16
16
  import { renderSlot, type SlotOverride } from "@marktiderman/genesis-core/slots";
17
17
  import type { ChatInboxItem } from "../core/types";
18
18
  import { useChat, useInbox, type ChatAttachmentKind } from "../react/index";
@@ -59,94 +59,83 @@ export function inboxTitle(item: ChatInboxItem, resolveUser: ResolveUser, fallba
59
59
  return fallback?.(item) ?? "Conversation";
60
60
  }
61
61
 
62
+ const formatTime = (date: Date) => relativeTime(date.toISOString());
63
+
62
64
  export function ChatInbox({ resolveUser, onSelect, selectedId, kind, archived = false, fallbackTitle, slots, className, ...rest }: ChatInboxProps) {
63
65
  const { userId: me, attachmentKinds } = useChat();
64
66
  const { items, isLoading, error, refetch } = useInbox({ kind, archived });
65
- const list = useRef<HTMLUListElement>(null);
66
-
67
- // Rows are native buttons (Tab reaches each); the arrows are added here
68
- // because no Radix primitive is a list of buttons with vertical roving focus.
69
- const onKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
70
- const buttons = Array.from(list.current?.querySelectorAll<HTMLButtonElement>("button[data-inbox-row]") ?? []);
71
- const at = buttons.indexOf(document.activeElement as HTMLButtonElement);
72
- const to =
73
- e.key === "ArrowDown" ? Math.min(buttons.length - 1, at + 1) : e.key === "ArrowUp" ? Math.max(0, at - 1) : e.key === "Home" ? 0 : e.key === "End" ? buttons.length - 1 : -2;
74
- if (to === -2 || buttons.length === 0) return;
75
- e.preventDefault();
76
- buttons[to < 0 ? 0 : to]?.focus();
77
- };
78
-
79
- if (isLoading) {
80
- return (
81
- <div className={cn("flex flex-col", className)} aria-busy aria-label="Loading conversations" data-testid="genesis-chat-inbox-loading">
82
- {Array.from({ length: 6 }, (_, i) => (
83
- <div key={i} className="flex items-center gap-3 px-3 py-3">
84
- <Skeleton className="size-10 shrink-0 rounded-full" />
85
- <div className="flex-1 space-y-2">
86
- <Skeleton className="h-3.5 w-2/5" />
87
- <Skeleton className="h-3 w-4/5" />
88
- </div>
89
- </div>
90
- ))}
91
- </div>
92
- );
93
- }
94
-
95
- if (error) {
96
- return (
97
- <div className={className}>
98
- <EmptyState
99
- icon={MessageSquare}
100
- title="Couldn't load your conversations"
101
- description="Check your connection and try again."
102
- action={
103
- <Button type="button" variant="outline" onClick={() => void refetch()}>
104
- Try again
105
- </Button>
106
- }
107
- />
108
- </div>
109
- );
110
- }
111
-
112
- if (items.length === 0) {
113
- return <div className={className}>{renderSlot(DefaultEmpty, slots?.empty, { archived })}</div>;
114
- }
67
+ const rows = useMemo<ChatInboxRow[]>(
68
+ () =>
69
+ items.map((item) => {
70
+ const title = inboxTitle(item, resolveUser, fallbackTitle);
71
+ const last = item.lastMessage;
72
+ let preview = last ? attachmentPreview(last.body, last.attachment, attachmentKinds, last.deleted) : "";
73
+ if (last && last.kind !== "system" && !last.deleted && last.senderId) {
74
+ if (last.senderId === me) preview = `You: ${preview}`;
75
+ else if (!item.otherUserId && item.memberCount > 2) preview = `${resolveUser(last.senderId).name}: ${preview}`;
76
+ }
77
+ const timestamp = item.lastMessageAt ?? last?.createdAt;
78
+ return {
79
+ id: item.conversationId,
80
+ title,
81
+ preview,
82
+ unreadCount: item.unread,
83
+ ...(timestamp ? { timestamp } : {}),
84
+ chat: item,
85
+ avatarUrl: item.otherUserId ? resolveUser(item.otherUserId).avatarUrl : undefined,
86
+ };
87
+ }),
88
+ [items, me, resolveUser, fallbackTitle, attachmentKinds],
89
+ );
90
+ const label = rest["aria-label"] ?? "Conversations";
115
91
 
116
92
  return (
117
- <nav aria-label={rest["aria-label"] ?? "Conversations"} className={cn("min-h-0", className)} data-testid="genesis-chat-inbox">
118
- <ul ref={list} className="flex flex-col" onKeyDown={onKeyDown}>
119
- {items.map((item) => (
120
- <li key={item.conversationId}>
121
- <InboxRow item={item} me={me} kinds={attachmentKinds} resolveUser={resolveUser} fallbackTitle={fallbackTitle} selected={item.conversationId === selectedId} onSelect={onSelect} />
122
- </li>
123
- ))}
124
- </ul>
93
+ <nav aria-label={label} className={cn("flex min-h-0 flex-col", className)}>
94
+ <InboxPage
95
+ testID="genesis-chat-inbox"
96
+ items={rows}
97
+ selectedId={selectedId}
98
+ onSelect={onSelect}
99
+ loading={isLoading}
100
+ error={Boolean(error) && rows.length === 0}
101
+ label={label}
102
+ loadingLabel="Loading conversations"
103
+ formatTime={formatTime}
104
+ slots={INBOX_SLOTS}
105
+ slotProps={{ empty: { override: slots?.empty, archived, onRetry: () => void refetch(), failed: Boolean(error) } as Partial<InboxPageSlotMap["empty"]> }}
106
+ />
125
107
  </nav>
126
108
  );
127
109
  }
128
110
 
129
- interface InboxRowProps {
130
- item: ChatInboxItem;
131
- me: string;
132
- kinds?: Record<string, ChatAttachmentKind>;
133
- resolveUser: ResolveUser;
134
- fallbackTitle?: (item: ChatInboxItem) => string;
135
- selected: boolean;
136
- onSelect: (id: string) => void;
111
+ /** What chat adds to InboxPage's row, carried on the row itself. */
112
+ interface ChatInboxRow extends InboxItem {
113
+ preview: string;
114
+ chat: ChatInboxItem;
115
+ avatarUrl: string | null | undefined;
137
116
  }
138
117
 
139
- function InboxRow({ item, me, kinds, resolveUser, fallbackTitle, selected, onSelect }: InboxRowProps) {
140
- const title = inboxTitle(item, resolveUser, fallbackTitle);
141
- const other = item.otherUserId ? resolveUser(item.otherUserId) : null;
142
- const last = item.lastMessage;
143
- const unread = item.unread > 0;
144
- let preview = last ? attachmentPreview(last.body, last.attachment, kinds, last.deleted) : "";
145
- if (last && last.kind !== "system" && !last.deleted && last.senderId) {
146
- if (last.senderId === me) preview = `You: ${preview}`;
147
- else if (!item.otherUserId && item.memberCount > 2) preview = `${resolveUser(last.senderId).name}: ${preview}`;
118
+ function InboxEmpty({ override, archived, onRetry, failed }: InboxPageSlotMap["empty"] & { override?: SlotOverride<ChatInboxEmptyProps>; archived: boolean; onRetry: () => void; failed: boolean }) {
119
+ if (failed) {
120
+ return (
121
+ <EmptyState
122
+ icon={MessageSquare}
123
+ title="Couldn't load your conversations"
124
+ description="Check your connection and try again."
125
+ action={
126
+ <Button type="button" variant="outline" onClick={onRetry}>
127
+ Try again
128
+ </Button>
129
+ }
130
+ />
131
+ );
148
132
  }
149
- const time = relativeTime(item.lastMessageAt ?? last?.createdAt);
133
+ return <>{renderSlot(DefaultEmpty, override, { archived })}</>;
134
+ }
135
+
136
+ function InboxRow(row: InboxPageSlotMap["row"] & ChatInboxRow) {
137
+ const { chat: item, title, preview, timeLabel, selected, onPress, rowProps, testID, avatarUrl } = row;
138
+ const unread = item.unread > 0;
150
139
  const count = item.unread >= 99 ? "99+" : String(item.unread);
151
140
  const label = [
152
141
  title,
@@ -155,7 +144,7 @@ function InboxRow({ item, me, kinds, resolveUser, fallbackTitle, selected, onSel
155
144
  item.muted ? "muted" : null,
156
145
  item.pinned ? "pinned" : null,
157
146
  preview || null,
158
- time || null,
147
+ timeLabel || null,
159
148
  ]
160
149
  .filter(Boolean)
161
150
  .join(", ");
@@ -163,24 +152,24 @@ function InboxRow({ item, me, kinds, resolveUser, fallbackTitle, selected, onSel
163
152
  return (
164
153
  <button
165
154
  type="button"
166
- data-inbox-row
155
+ {...rowProps}
167
156
  aria-current={selected ? "true" : undefined}
168
157
  aria-label={label}
169
- onClick={() => onSelect(item.conversationId)}
158
+ onClick={onPress}
170
159
  className={cn(
171
160
  "flex w-full items-center gap-3 px-3 py-2.5 text-left transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
172
161
  selected && "bg-accent",
173
162
  )}
174
- data-testid={`genesis-chat-inbox-row-${item.conversationId}`}
163
+ data-testid={testID}
175
164
  >
176
- <UserAvatar name={title} src={other?.avatarUrl} className="shrink-0" />
165
+ <UserAvatar name={title} src={avatarUrl} className="shrink-0" />
177
166
  <span className="flex min-w-0 flex-1 flex-col gap-0.5" aria-hidden>
178
167
  <span className="flex items-center gap-2">
179
168
  <span className={cn("min-w-0 flex-1 truncate text-sm", unread ? "font-semibold text-foreground" : "font-medium text-foreground")}>{title}</span>
180
- <span className={cn("shrink-0 text-xs tabular-nums", unread && !item.muted ? "font-medium text-primary" : "text-muted-foreground")}>{time}</span>
169
+ <span className={cn("shrink-0 text-xs tabular-nums", unread && !item.muted ? "font-medium text-primary-text" : "text-muted-foreground")}>{timeLabel}</span>
181
170
  </span>
182
171
  <span className="flex items-center gap-1.5">
183
- <span className={cn("min-w-0 flex-1 truncate text-sm", unread ? "text-foreground" : "text-muted-foreground")}>{preview || " "}</span>
172
+ <span className={cn("min-w-0 flex-1 truncate text-sm", unread ? "text-foreground" : "text-muted-foreground")}>{preview || " "}</span>
184
173
  {item.pinned ? <Pin className="size-3.5 shrink-0 text-muted-foreground" /> : null}
185
174
  {item.muted ? <BellOff className="size-3.5 shrink-0 text-muted-foreground" /> : null}
186
175
  {item.mentioned ? (
@@ -199,3 +188,6 @@ function InboxRow({ item, me, kinds, resolveUser, fallbackTitle, selected, onSel
199
188
  );
200
189
  }
201
190
 
191
+ // Module scope: a new slot each render would remount every row. The row carries chat's fields
192
+ // itself, which InboxPage hands on; its own types don't know them.
193
+ const INBOX_SLOTS = { row: InboxRow, empty: InboxEmpty } as unknown as NonNullable<ComponentProps<typeof InboxPage>["slots"]>;
@@ -215,7 +215,7 @@ function renderNodes(nodes: MarkdownNode[], opts: RenderOptions): ReactNode[] {
215
215
  href={n.href}
216
216
  target="_blank"
217
217
  rel="noopener noreferrer"
218
- className={cn("underline underline-offset-2", opts.tone === "primary" ? "text-primary-foreground" : "text-primary")}
218
+ className={cn("underline underline-offset-2", opts.tone === "primary" ? "text-primary-foreground" : "text-primary-text")}
219
219
  >
220
220
  {renderNodes(n.children, opts)}
221
221
  </a>
@@ -232,8 +232,8 @@ function renderNodes(nodes: MarkdownNode[], opts: RenderOptions): ReactNode[] {
232
232
  opts.tone === "primary"
233
233
  ? "bg-primary-foreground/20 text-primary-foreground"
234
234
  : mine
235
- ? "bg-primary/20 text-primary"
236
- : "bg-primary/10 text-primary",
235
+ ? "bg-primary/20 text-primary-text"
236
+ : "bg-primary/10 text-primary-text",
237
237
  )}
238
238
  >
239
239
  @{n.name}