xonecas.io
8058
Ir

irvc / files

irvc / web / src / components / Markdown.tsx

4.2 KB
1import { Component, createContext, useContext, useEffect, useState, type ReactNode } from "react";
2import ReactMarkdown from "react-markdown";
3import remarkBreaks from "remark-breaks";
4import remarkGfm from "remark-gfm";
5import { ChevronDown, ChevronRight } from "lucide-react";
6import { attachmentNames, isVideo } from "../lib/media";
7
8const Collapsed = createContext(false);
9
10// Media renders images inline and video as a player capped to the image size.
11// Clicking an image opens it in a full-window focus dialog. When the message's
12// header is collapsed, both are hidden and their names show as chips beside the
13// header toggle.
14function Media({ src, alt }: { src?: string; alt?: string }) {
15  const [open, setOpen] = useState(false);
16  const collapsed = useContext(Collapsed);
17  // Esc closes the viewer. Capture phase + stopPropagation so it doesn't also
18  // dismiss whatever else listens for Escape (e.g. the message actions pane).
19  useEffect(() => {
20    if (!open) return;
21    const onKey = (e: KeyboardEvent) => {
22      if (e.key !== "Escape") return;
23      e.stopPropagation();
24      setOpen(false);
25    };
26    window.addEventListener("keydown", onKey, true);
27    return () => window.removeEventListener("keydown", onKey, true);
28  }, [open]);
29  if (!src) return alt ? <span>{alt}</span> : null;
30  if (collapsed) return null; // names are shown in the header row instead
31  if (isVideo(src)) {
32    // preload=metadata with the #t=0.1 fragment asks the browser for the first
33    // frame as a thumbnail, so no poster and no full download are needed.
34    return (
35      <video src={`${src}#t=0.1`} controls playsInline preload="metadata">
36        <a href={src}>{alt || "video"}</a>
37      </video>
38    );
39  }
40  return (
41    <>
42      <img
43        src={src}
44        alt={alt ?? ""}
45        loading="lazy"
46        onClick={() => setOpen(true)}
47        className="cursor-zoom-in"
48      />
49      {open && (
50        <div
51          className="fixed inset-0 z-50 grid cursor-zoom-out place-items-center bg-scrim p-4"
52          onClick={() => setOpen(false)}
53        >
54          <img src={src} alt={alt ?? ""} className="max-h-full max-w-full rounded" />
55        </div>
56      )}
57    </>
58  );
59}
60
61const components = {
62  a: ({ href, children }: { href?: string; children?: ReactNode }) => (
63    <a href={href} target="_blank" rel="noopener noreferrer">
64      {children}
65    </a>
66  ),
67  img: Media,
68};
69
70class Fallback extends Component<{ text: string; children: ReactNode }, { failed: boolean }> {
71  state = { failed: false };
72
73  static getDerivedStateFromError() {
74    return { failed: true };
75  }
76
77  render() {
78    if (this.state.failed) {
79      return <span className="whitespace-pre-wrap break-words">{this.props.text}</span>;
80    }
81    return this.props.children;
82  }
83}
84
85// Markdown renders a message body as GFM. Single newlines become hard breaks so
86// multiline input shows as typed. If rendering ever throws, the raw text is
87// shown instead. Messages containing media get a header to collapse them; the
88// header lines up with the username column.
89export default function Markdown({
90  text,
91  collapsed,
92  onToggle,
93}: {
94  text: string;
95  collapsed: boolean;
96  onToggle: () => void;
97}) {
98  const names = attachmentNames(text);
99  const count = names.length;
100  return (
101    <Fallback text={text}>
102      {count > 0 && (
103        <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
104          <button
105            type="button"
106            onClick={onToggle}
107            title={collapsed ? "show media" : "hide media"}
108            className="flex items-center gap-1 text-xs leading-6 text-faint hover:text-muted"
109          >
110            {collapsed ? <ChevronRight className="size-3" /> : <ChevronDown className="size-3" />}
111            {count} attachment{count > 1 ? "s" : ""}
112          </button>
113          {collapsed &&
114            names.map((name, i) => (
115              <span
116                key={i}
117                className="rounded-md border border-line bg-surface px-2 py-0.5 text-xs text-muted"
118              >
119                {name}
120              </span>
121            ))}
122        </div>
123      )}
124      <Collapsed.Provider value={collapsed}>
125        <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={components}>
126          {text}
127        </ReactMarkdown>
128      </Collapsed.Provider>
129    </Fallback>
130  );
131}