xonecas.io
8058
Ir

irvc / files

irvc / web / src / components / MessageList.tsx

10.3 KB
1import { Fragment, useEffect, useLayoutEffect, useRef } from "react";
2import { Heart, Laugh, MoreHorizontal, ThumbsDown, ThumbsUp } from "lucide-react";
3import { cn } from "cn";
4import { IconButton, TextArea } from "@/ui";
5import type { Message, Reaction } from "../lib/types";
6import { Time, dayKey, formatDay } from "../lib/time";
7import LinkPreview from "./LinkPreview";
8import Markdown from "./Markdown";
9import { userColor } from "../lib/scheme";
10
11export const reactions: { key: Reaction; label: string; Icon: typeof ThumbsUp }[] = [
12  { key: "+1", label: "+1", Icon: ThumbsUp },
13  { key: "-1", label: "-1", Icon: ThumbsDown },
14  { key: "heart", label: "like", Icon: Heart },
15  { key: "laugh", label: "laugh", Icon: Laugh },
16];
17
18// isMentioned reports whether body contains "@username" as a whole word.
19export function isMentioned(body: string, username: string) {
20  return new RegExp(`(^|[^\\w-])@${username}(?![\\w-])`, "i").test(body);
21}
22
23export default function MessageList({
24  messages,
25  username,
26  collapsed,
27  previewCollapsed,
28  hidePreviews,
29  editing,
30  activeId,
31  onSelect,
32  onToggleImages,
33  onTogglePreview,
34  onRemovePreview,
35  onEditBody,
36  onCancelEdit,
37  onSaveEdit,
38}: {
39  messages: Message[];
40  username: string;
41  collapsed: Set<number>;
42  previewCollapsed: (id: number) => boolean;
43  hidePreviews: boolean;
44  editing: { id: number; body: string } | null;
45  activeId: number | null;
46  onSelect: (msg: Message) => void;
47  onToggleImages: (id: number) => void;
48  onTogglePreview: (id: number) => void;
49  onRemovePreview: (msg: Message) => void;
50  onEditBody: (body: string) => void;
51  onCancelEdit: () => void;
52  onSaveEdit: () => void;
53}) {
54  const list = useRef<HTMLDivElement>(null);
55  const stick = useRef(true);
56  // The scrollTop we last set ourselves. Our scroll-to-bottom can queue a
57  // scroll event that is handled only after a lazy image grows the list, so
58  // the gap to the bottom reads large even though the reader never scrolled.
59  const pinned = useRef(0);
60
61  const pin = () => {
62    const el = list.current;
63    if (!el || !stick.current) return;
64    el.scrollTop = el.scrollHeight;
65    pinned.current = el.scrollTop;
66  };
67
68  // Follow new messages while the reader stays at the bottom. The channel is
69  // remounted on switch, so this also lands on the newest message.
70  useLayoutEffect(pin);
71
72  useEffect(() => {
73    const el = list.current;
74    if (!el) return;
75    // Images load after the effect above, so follow the bottom on resize too.
76    const ro = new ResizeObserver(pin);
77    ro.observe(el.firstElementChild ?? el);
78    const onScroll = () => {
79      // A scroll still sitting where we pinned is ours, so leave stick alone.
80      if (el.scrollTop === pinned.current) return;
81      stick.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 2;
82    };
83    el.addEventListener("scroll", onScroll, { passive: true });
84    return () => {
85      ro.disconnect();
86      el.removeEventListener("scroll", onScroll);
87    };
88  }, []);
89
90  return (
91    <div
92      ref={list}
93      className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-2 [scrollbar-gutter:stable]"
94    >
95      <div>
96        {messages.map((m, i) => {
97          const prev = messages[i - 1];
98          const action = m.body.startsWith("/me ") ? m.body.slice(4) : null;
99          const newDay = !prev || dayKey(prev.createdAt) !== dayKey(m.createdAt);
100          const grouped =
101            !action &&
102            !newDay &&
103            prev !== undefined &&
104            !prev.body.startsWith("/me ") &&
105            prev.username === m.username &&
106            m.createdAt - prev.createdAt < 300;
107          return (
108            <Fragment key={m.id}>
109              {newDay && <DaySeparator ts={m.createdAt} />}
110              <Row
111                message={m}
112                action={action}
113                grouped={grouped}
114                username={username}
115                mentioned={!action && isMentioned(m.body, username)}
116                active={activeId === m.id}
117                editing={editing?.id === m.id}
118                editBody={editing?.body ?? ""}
119                collapsed={collapsed.has(m.id)}
120                previewCollapsed={previewCollapsed(m.id)}
121                hidePreviews={hidePreviews}
122                onSelect={() => onSelect(m)}
123                onToggleImages={() => onToggleImages(m.id)}
124                onTogglePreview={() => onTogglePreview(m.id)}
125                onRemovePreview={m.username === username ? () => onRemovePreview(m) : undefined}
126                onEditBody={onEditBody}
127                onSaveEdit={onSaveEdit}
128                onCancelEdit={onCancelEdit}
129              />
130            </Fragment>
131          );
132        })}
133      </div>
134    </div>
135  );
136}
137
138function DaySeparator({ ts }: { ts: number }) {
139  return (
140    <div role="separator" className="flex items-center gap-3 px-3 py-2 md:px-4">
141      <div className="h-px flex-1 bg-line" />
142      <span className="text-[0.7rem] text-fg">{formatDay(ts)}</span>
143      <div className="h-px flex-1 bg-line" />
144    </div>
145  );
146}
147
148function Row({
149  message: m,
150  action,
151  grouped,
152  username,
153  mentioned,
154  active,
155  editing,
156  editBody,
157  collapsed,
158  previewCollapsed,
159  hidePreviews,
160  onSelect,
161  onToggleImages,
162  onTogglePreview,
163  onRemovePreview,
164  onEditBody,
165  onSaveEdit,
166  onCancelEdit,
167}: {
168  message: Message;
169  action: string | null;
170  grouped: boolean;
171  username: string;
172  mentioned: boolean;
173  active: boolean;
174  editing: boolean;
175  editBody: string;
176  collapsed: boolean;
177  previewCollapsed: boolean;
178  hidePreviews: boolean;
179  onSelect: () => void;
180  onToggleImages: () => void;
181  onTogglePreview: () => void;
182  onRemovePreview?: () => void;
183  onEditBody: (body: string) => void;
184  onSaveEdit: () => void;
185  onCancelEdit: () => void;
186}) {
187  const textarea = useRef<HTMLTextAreaElement>(null);
188
189  useEffect(() => {
190    const el = textarea.current;
191    if (!el) return;
192    el.style.height = "auto";
193    el.style.height = `${Math.min(el.scrollHeight, 200)}px`;
194    el.focus();
195  }, [editing]);
196
197  const menuButton = (hidden: boolean) => (
198    <IconButton
199      label="message actions"
200      size="sm"
201      data-actions-for={m.id}
202      className={cn(
203        "size-6 text-faint",
204        active && "bg-raised text-fg",
205        // Continuation rows keep the actions out of sight so the list stays
206        // calm, but the button remains in the accessibility tree and is
207        // revealed on keyboard focus. Tapping the row works too.
208        hidden && "pointer-events-none opacity-0 focus:pointer-events-auto focus:opacity-100",
209      )}
210      onClick={onSelect}
211    >
212      <MoreHorizontal size={14} />
213    </IconButton>
214  );
215
216  if (action) {
217    return (
218      <div className="flex items-baseline gap-2 px-3 py-1 text-sm italic md:px-4">
219        <span className="not-italic text-accent" style={{ color: userColor(m.username, "var(--accent)") }}>
220          * {m.username}
221        </span>
222        <span className="min-w-0 flex-1">{action}</span>
223        <Time ts={m.createdAt} className="text-[0.7rem] not-italic text-faint" />
224      </div>
225    );
226  }
227
228  const chips = [...chipsOf(m.reactions)].filter(([, who]) => who.length > 0);
229
230  return (
231    <div
232      // Tapping anywhere in the row selects it. Skipped while text is being
233      // selected, and when the tap lands on a link or the actions button.
234      onClick={(e) => {
235        if (!window.getSelection()?.isCollapsed) return;
236        if ((e.target as HTMLElement).closest("a,button,video")) return;
237        onSelect();
238      }}
239      className={cn(
240        "group relative flex gap-2 px-3 py-0.5 md:px-4",
241        mentioned ? "bg-accent/10" : active && "bg-raised",
242      )}
243    >
244      <div className="min-w-0 flex-1">
245        {!grouped && (
246          <div className="flex items-baseline gap-2">
247            <span
248              className="text-sm font-medium text-accent"
249              style={{ color: userColor(m.username, "var(--accent)") }}
250            >
251              {m.username}
252            </span>
253            <Time ts={m.createdAt} className="text-[0.7rem] text-faint" />
254            {!!m.editedAt && <span className="text-[0.7rem] text-faint">(edited)</span>}
255            <span className="ml-auto -my-0.5">{menuButton(false)}</span>
256          </div>
257        )}
258        {editing ? (
259          <div className="py-1 pl-5 md:pl-8">
260            <TextArea
261              ref={textarea}
262              rows={1}
263              value={editBody}
264              onChange={(e) => onEditBody(e.target.value)}
265              onKeyDown={(e) => {
266                if (e.key === "Escape") onCancelEdit();
267                else if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
268                  e.preventDefault();
269                  onSaveEdit();
270                }
271              }}
272            />
273            <div className="flex gap-1 pt-1">
274              <button type="button" className="btn btn-ghost btn-sm" onClick={onCancelEdit}>
275                cancel
276              </button>
277              <button type="button" className="btn btn-primary btn-sm" onClick={onSaveEdit}>
278                save
279              </button>
280            </div>
281          </div>
282        ) : (
283          <div className="md pl-5 md:pl-8">
284            <Markdown text={m.body} collapsed={collapsed} onToggle={onToggleImages} />
285          </div>
286        )}
287        {!editing && !hidePreviews && m.preview?.kind === "card" && (
288          <LinkPreview
289            preview={m.preview}
290            collapsed={previewCollapsed}
291            onToggle={onTogglePreview}
292            onRemove={onRemovePreview}
293            pinned={active}
294          />
295        )}
296        {grouped && <span className="absolute top-0 right-2 md:right-3">{menuButton(true)}</span>}
297        {chips.length > 0 && (
298          <div className="flex flex-wrap gap-1 pt-1 pl-5 md:pl-8">
299            {chips.map(([key, who]) => {
300              const Icon = reactions.find((r) => r.key === key)!.Icon;
301              return (
302                <button
303                  key={key}
304                  type="button"
305                  title={who.join(", ")}
306                  onClick={onSelect}
307                  className={cn("chip", who.includes(username) && "chip-active")}
308                >
309                  <Icon className="size-3" />
310                  {who.length}
311                </button>
312              );
313            })}
314          </div>
315        )}
316      </div>
317    </div>
318  );
319}
320
321function chipsOf(reactions?: Partial<Record<Reaction, string[]>>) {
322  return Object.entries(reactions ?? {}) as [Reaction, string[]][];
323}