Repository Public
1import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"2import type { Conv, Engine } from "../core/engine"3import { formatBytes, formatDuration, prepare, VoiceRecorder, type Prepared } from "../core/media"4import type { FileRef, Msg } from "../core/types"5import { Avatar, clock, dateTime, dayLabel, errText, haptic, I, Menu, Sheet, t, toast, ttlLabel, useApp, useCalls, type MenuItem } from "./bits"67const QUICK = ["👍", "❤️", "😂", "😮", "😢", "🙏"]8const URL_RE = /(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g910function Linkified({ text }: { text: string }) {11 const parts = text.split(URL_RE)12 return (13 <>14 {parts.map((p, i) =>15 i % 2 ? (16 <a key={i} href={p} target="_blank" rel="noopener noreferrer nofollow">{p}</a>17 ) : (18 p19 ),20 )}21 </>22 )23}2425// ---------------------------------------------------------------- attachments26function useBlobUrl(engine: Engine, ref: FileRef, load: boolean) {27 const [url, setUrl] = useState<string>()28 const [progress, setProgress] = useState(0)29 const [error, setError] = useState(false)30 useEffect(() => {31 if (!load) return32 let dead = false, made: string | undefined33 engine.download(ref, (f) => !dead && setProgress(f)).then(34 (b) => {35 if (dead) return36 made = URL.createObjectURL(b)37 setUrl(made)38 },39 () => !dead && setError(true),40 )41 return () => {42 dead = true43 if (made) URL.revokeObjectURL(made)44 }45 }, [engine, ref.id, load])46 return { url, progress, error }47}4849async function saveFile(engine: Engine, ref: FileRef) {50 try {51 const blob = await engine.download(ref)52 const a = document.createElement("a")53 a.href = URL.createObjectURL(blob)54 a.download = ref.name55 a.click()56 setTimeout(() => URL.revokeObjectURL(a.href), 30000)57 } catch {58 toast(t("This file could not be decrypted or is no longer available.", "Ce fichier n’a pas pu être déchiffré ou n’est plus disponible."))59 }60}6162export function Visual({ engine, f, onOpen, square }: { engine: Engine; f: FileRef; onOpen: () => void; square?: boolean }) {63 const isVideo = f.mime.startsWith("video/")64 // Photos load in full as soon as they are displayed; videos only when opened.65 const { url } = useBlobUrl(engine, f, !isVideo && f.size < 12 * 1024 * 1024)66 const ratio = f.w && f.h ? f.w / f.h : 167 const w = Math.min(320, Math.max(140, ratio >= 1 ? 320 : 320 * ratio))68 return (69 <button className="att-img" style={square ? undefined : { width: w, aspectRatio: String(Math.max(0.5, Math.min(2.2, ratio))) }} onClick={onOpen} aria-label={f.name}>70 {url ? <img src={url} alt={f.name} /> : f.thumb ? <img className="blur" src={`data:image/jpeg;base64,${f.thumb}`} alt="" /> : null}71 {isVideo && <span className="play"><i>{I.play}</i></span>}72 </button>73 )74}7576function Voice({ engine, f }: { engine: Engine; f: FileRef }) {77 const [want, setWant] = useState(false)78 const { url } = useBlobUrl(engine, f, want)79 const audio = useRef<HTMLAudioElement>(null)80 const [playing, setPlaying] = useState(false)81 const [pos, setPos] = useState(0)82 useEffect(() => {83 if (url && want) void audio.current?.play().catch(() => {})84 }, [url, want])85 const peaks = f.wave?.length ? f.wave : Array.from({ length: 40 }, (_, i) => 0.3 + 0.4 * Math.abs(Math.sin(i * 1.7)))86 const dur = f.dur ?? audio.current?.duration ?? 087 return (88 <div className="voice">89 <button className="pp" aria-label={playing ? t("Pause", "Pause") : t("Play", "Lire")} onClick={() => (!want ? setWant(true) : playing ? audio.current?.pause() : void audio.current?.play())}>90 {playing ? I.pause : I.play}91 </button>92 <div className="wave" onClick={(e) => {93 const r = e.currentTarget.getBoundingClientRect()94 if (audio.current && dur) audio.current.currentTime = ((e.clientX - r.left) / r.width) * dur95 }}>96 {peaks.map((p, i) => <i key={i} className={dur && i / peaks.length < pos / dur ? "played" : ""} style={{ height: `${Math.max(12, p * 100)}%` }} />)}97 </div>98 <span className="tiny mono">{formatDuration(playing || pos ? pos : dur)}</span>99 {url && <audio ref={audio} src={url} onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => (setPlaying(false), setPos(0))} onTimeUpdate={(e) => setPos(e.currentTarget.currentTime)} />}100 </div>101 )102}103104function FileRow({ engine, f }: { engine: Engine; f: FileRef }) {105 const [busy, setBusy] = useState(false)106 return (107 <button className="file" onClick={async () => (setBusy(true), await saveFile(engine, f), setBusy(false))}>108 <span className="ic">{busy ? <span className="spinner" /> : I.file}</span>109 <span className="grow">110 <span className="ell" style={{ display: "block", fontWeight: 600 }}>{f.name}</span>111 <span className="tiny" style={{ opacity: 0.7 }}>{formatBytes(f.size)}</span>112 </span>113 {I.download}114 </button>115 )116}117118export function Viewer({ engine, f, onClose }: { engine: Engine; f: FileRef; onClose: () => void }) {119 const { url, progress, error } = useBlobUrl(engine, f, true)120 useEffect(() => {121 const k = (e: KeyboardEvent) => e.key === "Escape" && onClose()122 window.addEventListener("keydown", k)123 return () => window.removeEventListener("keydown", k)124 }, [onClose])125 return (126 <div className="viewer" onClick={(e) => e.target === e.currentTarget && onClose()} role="dialog" aria-label={f.name}>127 {error ? <p>{t("This file could not be decrypted.", "Ce fichier n’a pas pu être déchiffré.")}</p>128 : !url ? <div className="col" style={{ alignItems: "center", color: "#fff" }}><span className="spinner" /><span className="tiny">{Math.round(progress * 100)} %</span></div>129 : f.mime.startsWith("video/") ? <video src={url} controls autoPlay playsInline /> : <img src={url} alt={f.name} />}130 <div className="bar">131 <button className="icon-btn" onClick={onClose} aria-label={t("Close", "Fermer")}>{I.x}</button>132 <button className="icon-btn" onClick={() => saveFile(engine, f)} aria-label={t("Download", "Télécharger")}>{I.download}</button>133 </div>134 </div>135 )136}137138const isVisual = (f: FileRef) => (f.mime.startsWith("image/") && !!f.thumb) || f.mime.startsWith("video/")139140// ---------------------------------------------------------------- one message141type RowProps = {142 m: Msg; rev: number; receipt: 0 | 1 | 2; conv: Conv; engine: Engine; first: boolean; highlight: boolean143 onMenu: (m: Msg, x: number, y: number) => void; onReply: (m: Msg) => void; onOpen: (f: FileRef) => void; onJump: (id: string) => void144}145const Row = memo(function Row({ m, receipt, conv, engine, first, highlight, onMenu, onReply, onOpen, onJump }: RowProps) {146 const me = m.from === engine.me.id147 const press = useRef<ReturnType<typeof setTimeout>>(undefined)148 const swipe = useRef<{ x: number; y: number; dx: number } | null>(null)149 const bubble = useRef<HTMLDivElement>(null)150151 if (m.kind === "sys" || m.kind === "call") return <div className="sysmsg" data-mid={m.id}>{sysText(engine, m)}</div>152153 const visuals = (m.files ?? []).filter(isVisual)154 const others = (m.files ?? []).filter((f) => !isVisual(f))155 const peerRead = receipt === 2, delivered = receipt >= 1156 const status = !me ? null : m.status === "failed" ? <span title={t("Not sent", "Non envoyé")}>{I.warn}</span> : !m.seq ? I.clock : peerRead ? <span style={{ color: "#0b3d91" }} title={t("Read", "Lu")}>{I.checks}</span> : delivered ? <span title={t("Delivered", "Distribué")}>{I.checks}</span> : <span title={t("Sent", "Envoyé")}>{I.check}</span>157158 return (159 <div160 className={`msg ${me ? "me" : ""} ${first ? "first" : ""} ${visuals.length ? "media" : ""} ${visuals.length && !m.body && !others.length ? "notext" : ""} ${highlight ? "hl" : ""}`}161 data-mid={m.id}162 onContextMenu={(e) => (e.preventDefault(), onMenu(m, e.clientX, e.clientY))}163 onTouchStart={(e) => {164 const p = e.touches[0]165 swipe.current = { x: p.clientX, y: p.clientY, dx: 0 }166 press.current = setTimeout(() => (haptic(12), onMenu(m, p.clientX, p.clientY), (swipe.current = null)), 480)167 }}168 onTouchMove={(e) => {169 const s = swipe.current170 if (!s) return171 const p = e.touches[0]172 const dx = p.clientX - s.x, dy = p.clientY - s.y173 if (Math.abs(dx) > 8 || Math.abs(dy) > 8) clearTimeout(press.current)174 if (Math.abs(dy) > 30 && s.dx < 12) return void (swipe.current = null)175 s.dx = Math.max(0, Math.min(72, dx))176 if (bubble.current && s.dx > 10) bubble.current.style.transform = `translateX(${s.dx}px)`177 }}178 onTouchEnd={() => {179 clearTimeout(press.current)180 if (bubble.current) {181 bubble.current.style.transition = "transform .25s cubic-bezier(.22,1,.36,1)"182 bubble.current.style.transform = ""183 setTimeout(() => bubble.current && (bubble.current.style.transition = ""), 260)184 }185 if ((swipe.current?.dx ?? 0) > 56 && !m.deleted) (haptic(), onReply(m))186 swipe.current = null187 }}188 >189 {!me && conv.kind === "group" && (first ? <Avatar id={m.from} name={engine.userName(m.from)} size={30} /> : <span style={{ width: 30, flex: "none" }} />)}190 <div className="grow" ref={bubble}>191 {!me && conv.kind === "group" && first && <div className="who dim">{engine.userName(m.from)}</div>}192 <div className="bubble">193 {m.fwd && <div className="fwd">{I.forward}{t("Forwarded from", "Transféré de")} {m.fwd.from}</div>}194 {m.reply && <button className="reply-ref" onClick={() => onJump(m.reply!.id)}><b>{engine.userName(m.reply.from)}</b> · {m.reply.excerpt}</button>}195 {m.deleted ? (196 <span className="deleted">{t("Message deleted", "Message supprimé")}</span>197 ) : (198 <>199 {visuals.length > 0 && (200 <div className={visuals.length > 1 ? "att-grid" : ""}>201 {visuals.map((f) => <Visual key={f.id} engine={engine} f={f} onOpen={() => onOpen(f)} square={visuals.length > 1} />)}202 </div>203 )}204 {others.map((f) => (f.voice || f.mime.startsWith("audio/") ? <Voice key={f.id} engine={engine} f={f} /> : <FileRow key={f.id} engine={engine} f={f} />))}205 {m.body && <span className="text"><Linkified text={m.body} /></span>}206 </>207 )}208 <span className="meta">209 {m.untrusted && <span title={t("Sent by a device whose identity key differs from the one you trusted", "Envoyé par un appareil dont la clé d’identité diffère de celle que vous aviez approuvée")}>{I.warn}</span>}210 {m.pinned && I.pin}211 {m.bookmarked && I.bookmark}212 {m.expiresAt && I.timer}213 {m.edited && !m.deleted && <span>{t("edited", "modifié")}</span>}214 <time dateTime={new Date(m.ts).toISOString()} title={dateTime(m.ts)}>{clock(m.ts)}</time>215 {status}216 </span>217 </div>218 {m.reactions && Object.keys(m.reactions).length > 0 && (219 <div className="reactions">220 {Object.entries(m.reactions).map(([emoji, users]) => (221 <button key={emoji} className={`react ${users.includes(engine.me.id) ? "mine" : ""}`} title={users.map((u) => engine.userName(u)).join(", ")}222 onClick={() => engine.send(conv.id, { t: "react", target: m.id, emoji, on: !users.includes(engine.me.id) })}>223 {emoji}{users.length > 1 && <span className="tiny">{users.length}</span>}224 </button>225 ))}226 </div>227 )}228 {!m.deleted && (229 <div className="msg-actions">230 <button aria-label={t("React", "Réagir")} onClick={() => engine.send(conv.id, { t: "react", target: m.id, emoji: "👍", on: !m.reactions?.["👍"]?.includes(engine.me.id) })}>👍</button>231 <button aria-label={t("Reply", "Répondre")} onClick={() => onReply(m)}>{I.reply}</button>232 <button aria-label={t("More", "Plus")} onClick={(e) => onMenu(m, e.clientX, e.clientY)}>{I.more}</button>233 </div>234 )}235 </div>236 </div>237 )238})239240export function sysText(engine: Engine, m: Msg): ReactNode {241 const who = m.from === engine.me.id ? t("You", "Vous") : engine.userName(m.from)242 const names = (m.sys?.users ?? []).map((u) => (u === engine.me.id ? t("you", "vous") : engine.userName(u))).join(", ")243 switch (m.sys?.type) {244 case "added": return `${who} ${t("added", "a ajouté")} ${names}`245 case "removed": return `${who} ${t("removed", "a retiré")} ${names}`246 case "device": return t(`A new device was added for ${names}`, `Un nouvel appareil a été ajouté pour ${names}`)247 case "renamed": return `${who} ${t("named the group", "a nommé le groupe")} « ${m.sys.text} »`248 case "ttl": return Number(m.sys.text) ? `${who} ${t("set messages to disappear after", "a réglé la disparition des messages après")} ${ttlLabel(Number(m.sys.text))}` : `${who} ${t("turned off disappearing messages", "a désactivé les messages éphémères")}`249 case "call": {250 const kind = m.sys.video ? t("Video call", "Appel vidéo") : t("Voice call", "Appel vocal")251 const s = m.sys.text ?? ""252 const detail = s.startsWith("duration:") ? formatDuration(Number(s.slice(9))) : s === "missed" ? t("missed", "manqué") : s === "declined" ? t("declined", "refusé") : s === "unanswered" ? t("no answer", "sans réponse") : ""253 return <>{m.sys.video ? "📹" : "📞"} {kind} · {clock(m.ts)}{detail && ` · ${detail}`}</>254 }255 default: return ""256 }257}258259// ---------------------------------------------------------------- conversation view260export function ChatView({ conv, onBack, onInfo, jumpTo }: { conv: Conv; onBack: () => void; onInfo: () => void; jumpTo?: string }) {261 const { engine } = useApp()262 const calls = useCalls()263 const list = useRef<HTMLDivElement>(null)264 const [menu, setMenu] = useState<{ m: Msg; x: number; y: number } | null>(null)265 const [reply, setReply] = useState<Msg | null>(null)266 const [editing, setEditing] = useState<Msg | null>(null)267 const [viewer, setViewer] = useState<FileRef | null>(null)268 const [forwarding, setForwarding] = useState<Msg | null>(null)269 const [limit, setLimit] = useState(200)270 const [hl, setHl] = useState<string | undefined>(jumpTo)271 const [away, setAway] = useState(false)272 const stick = useRef(true)273274 const all = conv.messages275 const shown = useMemo(() => all.slice(-limit), [all, all.length, limit, engine.version])276 const peer = engine.peerOf(conv)277 const peerUser = peer ? engine.users.get(peer) : undefined278 const typing = Object.keys(conv.typing).filter((u) => u !== engine.me.id)279280 useLayoutEffect(() => {281 stick.current = true282 setLimit(200)283 setReply(null)284 setEditing(null)285 }, [conv.id])286 useLayoutEffect(() => {287 const el = list.current288 if (el && stick.current && !hl) el.scrollTop = el.scrollHeight289 })290 useEffect(() => {291 if (!hl) return292 const el = list.current?.querySelector(`[data-mid="${CSS.escape(hl)}"]`)293 el?.scrollIntoView({ block: "center" })294 stick.current = false295 const timer = setTimeout(() => setHl(undefined), 2200)296 return () => clearTimeout(timer)297 }, [hl, conv.id])298 useEffect(() => setHl(jumpTo), [jumpTo])299 useEffect(() => {300 engine.activeConv = conv.id301 void engine.markRead(conv.id)302 return () => {303 if (engine.activeConv === conv.id) engine.activeConv = null304 }305 }, [engine, conv.id, all.length])306307 useEffect(() => {308 const onEdit = (e: Event) => {309 const m = conv.messages.find((x) => x.id === (e as CustomEvent).detail)310 if (m) (setEditing(m), setReply(null))311 }312 document.addEventListener("spm-edit", onEdit)313 return () => document.removeEventListener("spm-edit", onEdit)314 }, [conv])315316 const onMenu = useCallback((m: Msg, x: number, y: number) => !m.deleted && setMenu({ m, x, y }), [])317 const onJump = useCallback((id: string) => {318 const idx = all.findIndex((x) => x.id === id)319 if (idx < 0) return toast(t("The original message is not on this device.", "Le message d’origine n’est pas sur cet appareil."))320 setLimit((l) => Math.max(l, all.length - idx + 20))321 setHl(id)322 }, [all])323324 const menuItems = (m: Msg): MenuItem[] => {325 const mine = m.from === engine.me.id326 const items: MenuItem[] = [{ label: t("Reply", "Répondre"), icon: I.reply, onClick: () => setReply(m) }]327 if (m.body) items.push({ label: t("Copy", "Copier"), icon: I.copy, onClick: () => navigator.clipboard?.writeText(m.body) })328 items.push({ label: t("Forward", "Transférer"), icon: I.forward, onClick: () => setForwarding(m) })329 if (mine && m.body && !m.files?.some((f) => f.voice)) items.push({ label: t("Edit", "Modifier"), icon: I.edit, onClick: () => (setEditing(m), setReply(null)) })330 items.push({ label: m.pinned ? t("Unpin", "Désépingler") : t("Pin", "Épingler"), icon: I.pin, onClick: () => engine.send(conv.id, { t: "pin", target: m.id, on: !m.pinned }) })331 items.push({ label: m.bookmarked ? t("Remove bookmark", "Retirer le signet") : t("Bookmark", "Ajouter un signet"), icon: I.bookmark, onClick: () => engine.toggleBookmark(conv.id, m.id) })332 if (mine) items.push({ label: t("Delete for everyone", "Supprimer pour tous"), icon: I.trash, danger: true, onClick: () => engine.send(conv.id, { t: "del", target: m.id }) })333 return items334 }335336 const title = engine.convTitle(conv)337 const sub = typing.length338 ? null339 : conv.kind === "group" ? `${conv.serverMembers.length} ${t("members", "membres")}` : peerUser?.online ? t("online", "en ligne") : peerUser ? `@${peerUser.handle}` : ""340 const canCall = !!conv.state && !conv.left && !calls.current341342 const others = (rec: Record<string, number>) => Object.entries(rec).reduce((n, [u, s]) => (u === engine.me.id ? n : Math.max(n, s)), 0)343 const readUpTo = others(conv.read), deliveredUpTo = others(conv.delivered)344 const receiptOf = (m: Msg): 0 | 1 | 2 => (m.from !== engine.me.id || !m.seq ? 0 : m.seq <= readUpTo ? 2 : m.seq <= deliveredUpTo ? 1 : 0)345 let lastDay = "", lastFrom = "", lastTs = 0346 return (347 <>348 <header className="chat-head">349 <button className="icon-btn back" onClick={onBack} aria-label={t("Back", "Retour")}>{I.back}</button>350 <button className="row grow" style={{ textAlign: "left", minWidth: 0 }} onClick={onInfo} aria-label={t("Conversation details", "Détails de la conversation")}>351 <Avatar id={peer ?? conv.id} name={title} size={40} online={peerUser?.online} />352 <span className="grow">353 <span className="ell" style={{ display: "block", fontWeight: 650 }}>{title}</span>354 <span className="lock ell">{I.lock}{t("End-to-end encrypted", "Chiffré de bout en bout")}{sub ? ` · ${sub}` : ""}{conv.ttl ? ` · ⏱ ${ttlLabel(conv.ttl)}` : ""}</span>355 </span>356 </button>357 <button className="icon-btn" disabled={!canCall} onClick={() => calls.start(conv.id, false)} aria-label={t("Voice call", "Appel vocal")}>{I.phone}</button>358 <button className="icon-btn" disabled={!canCall} onClick={() => calls.start(conv.id, true)} aria-label={t("Video call", "Appel vidéo")}>{I.video}</button>359 <button className="icon-btn" onClick={onInfo} aria-label={t("Details", "Détails")}>{I.info}</button>360 </header>361362 {conv.warnings.map((u) => (363 <div key={u} className="banner warn" style={{ margin: "8px 14px 0" }} role="alert">364 {I.warn}365 <span className="grow">{t(`The security key of ${engine.userName(u)} has changed. This happens when someone re-installs their account, or if someone is intercepting. Verify with them before you continue.`, `La clé de sécurité de ${engine.userName(u)} a changé. Cela arrive lorsqu’une personne réinitialise son compte, ou en cas d’interception. Vérifiez avec elle avant de continuer.`)}</span>366 {engine.pins.get(u)?.changed && <button className="btn sm" onClick={() => engine.acceptIdentityChange(u)}>{t("Accept new key", "Accepter la nouvelle clé")}</button>}367 </div>368 ))}369 {conv.missing.map((u) => (370 <div key={`m-${u}`} className="banner info" style={{ margin: "8px 14px 0" }} role="status">371 {I.key}372 <span className="grow">{t(`${engine.userName(u)} currently holds no key for this conversation (their devices were reset) and cannot read it.`, `${engine.userName(u)} ne détient actuellement aucune clé pour cette conversation (ses appareils ont été réinitialisés) et ne peut pas la lire.`)}</span>373 {!engine.pins.get(u)?.changed && <button className="btn sm" onClick={() => engine.reAdd(conv.id, u).catch((e) => toast(errText(e)))}>{t("Add them back", "Les réintégrer")}</button>}374 </div>375 ))}376 {conv.strangers.map((u) => (377 <div key={`s-${u}`} className="banner warn" style={{ margin: "8px 14px 0" }} role="alert">{I.warn}<span>{t(`${engine.userName(u)} holds a key for this conversation without being listed as a member. Their access is being removed.`, `${engine.userName(u)} détient une clé pour cette conversation sans figurer parmi les membres. Son accès est en cours de retrait.`)}</span></div>378 ))}379 {conv.left ? (380 <div className="banner" style={{ margin: "8px 14px 0" }}>{t("You are no longer a member of this conversation.", "Vous ne faites plus partie de cette conversation.")}</div>381 ) : conv.waitingForKeys && !conv.state ? (382 <div className="banner info" style={{ margin: "8px 14px 0" }}><span className="spinner" />{t("Waiting for another member's device to share the encryption keys with this device…", "En attente qu’un appareil d’un autre membre partage les clés de chiffrement avec cet appareil…")}</div>383 ) : null}384385 <div className="msgs" ref={list} role="log" aria-live="polite" aria-label={t("Messages", "Messages")}386 onScroll={(e) => {387 const el = e.currentTarget388 const near = el.scrollHeight - el.scrollTop - el.clientHeight < 120389 stick.current = near390 if (away === near) setAway(!near)391 }}>392 {all.length > shown.length && <button className="btn sm ghost" style={{ alignSelf: "center" }} onClick={() => (stick.current = false, setLimit((l) => l + 300))}>{t("Earlier messages", "Messages précédents")}</button>}393 {all.length === 0 && (394 <div className="empty">395 <div>396 <div className="glyph">{I.lock}</div>397 <b>{t("This conversation is end-to-end encrypted", "Cette conversation est chiffrée de bout en bout")}</b>398 <p className="small">{t("Only the devices of its members hold the keys. Not even the server can read what you write here.", "Seuls les appareils de ses membres détiennent les clés. Même le serveur ne peut pas lire ce que vous écrivez ici.")}</p>399 </div>400 </div>401 )}402 {shown.map((m) => {403 const day = new Date(m.ts).toDateString()404 const showDay = day !== lastDay405 const first = showDay || m.from !== lastFrom || m.ts - lastTs > 5 * 60_000 || m.kind !== "text"406 lastDay = day407 lastFrom = m.kind === "text" ? m.from : ""408 lastTs = m.ts409 return (410 <FragmentRow key={m.id} day={showDay ? dayLabel(m.ts) : undefined}>411 <Row m={m} rev={m.rev ?? 0} receipt={receiptOf(m)} conv={conv} engine={engine} first={first} highlight={hl === m.id} onMenu={onMenu} onReply={setReply} onOpen={setViewer} onJump={onJump} />412 </FragmentRow>413 )414 })}415 </div>416 {away && <button className="jump" aria-label={t("Latest messages", "Derniers messages")} onClick={() => { const el = list.current!; el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }) }}>{I.down}</button>}417 <div className="typing" aria-live="polite">418 {typing.length > 0 && (<><span className="dots"><i /><i /><i /></span>{typing.map((u) => engine.userName(u)).join(", ")} {t("is typing", "écrit")}</>)}419 </div>420 {!conv.left && <Composer conv={conv} reply={reply} editing={editing} clear={() => (setReply(null), setEditing(null))} />}421422 {menu && (423 <Menu x={menu.x} y={menu.y} onClose={() => setMenu(null)} items={menuItems(menu.m)}424 quick={QUICK.map((emoji) => ({ emoji, onClick: () => void engine.send(conv.id, { t: "react", target: menu.m.id, emoji, on: !menu.m.reactions?.[emoji]?.includes(engine.me.id) }) }))} />425 )}426 {viewer && <Viewer engine={engine} f={viewer} onClose={() => setViewer(null)} />}427 {forwarding && <ForwardSheet msg={forwarding} onClose={() => setForwarding(null)} />}428 </>429 )430}431432function FragmentRow({ day, children }: { day?: string; children: ReactNode }) {433 return (434 <>435 {day && <div className="day">{day}</div>}436 {children}437 </>438 )439}440441function ForwardSheet({ msg, onClose }: { msg: Msg; onClose: () => void }) {442 const { engine } = useApp()443 const convs = [...engine.convs.values()].filter((c) => c.state && !c.left).sort((a, b) => b.lastTs - a.lastTs)444 return (445 <Sheet title={t("Forward to…", "Transférer à…")} onClose={onClose}>446 <div className="col" style={{ gap: 2 }}>447 {convs.map((c) => (448 <button key={c.id} className="list-row" onClick={async () => {449 try {450 await engine.forward(msg, c.id)451 toast(t("Forwarded", "Transféré"))452 } catch (e) {453 toast(errText(e))454 }455 onClose()456 }}>457 <Avatar id={engine.peerOf(c) ?? c.id} name={engine.convTitle(c)} size={38} />458 <span className="grow ell">{engine.convTitle(c)}</span>459 </button>460 ))}461 </div>462 </Sheet>463 )464}465466// ---------------------------------------------------------------- composer467type Pending = { id: string; prep: Prepared; progress: number; preview?: string; ref?: FileRef; error?: boolean }468469function Composer({ conv, reply, editing, clear }: { conv: Conv; reply: Msg | null; editing: Msg | null; clear: () => void }) {470 const { engine } = useApp()471 const [text, setText] = useState(engine.drafts[conv.id] ?? "")472 const [files, setFiles] = useState<Pending[]>([])473 const [busy, setBusy] = useState(false)474 const [drag, setDrag] = useState(false)475 const [rec, setRec] = useState<VoiceRecorder | null>(null)476 const [recTime, setRecTime] = useState(0)477 const [scheduling, setScheduling] = useState(false)478 const ta = useRef<HTMLTextAreaElement>(null)479 const fileInput = useRef<HTMLInputElement>(null)480 const camInput = useRef<HTMLInputElement>(null)481 const typingAt = useRef(0)482 const touch = matchMedia("(pointer: coarse)").matches483484 useEffect(() => {485 setText(editing ? editing.body : (engine.drafts[conv.id] ?? ""))486 setFiles([])487 if (!touch || editing) ta.current?.focus()488 }, [conv.id, editing])489 useEffect(() => {490 if (reply && !touch) ta.current?.focus()491 }, [reply])492 useLayoutEffect(() => {493 const el = ta.current494 if (!el) return495 el.style.height = "auto"496 el.style.height = `${Math.min(180, el.scrollHeight)}px`497 }, [text])498 useEffect(() => {499 if (!rec) return500 const timer = setInterval(() => setRecTime((Date.now() - rec.startedAt) / 1000), 200)501 return () => clearInterval(timer)502 }, [rec])503504 const add = useCallback(async (list: File[]) => {505 for (const file of list.slice(0, 20)) {506 const id = crypto.randomUUID()507 const prep = await prepare(file, engine.prefs.compress)508 setFiles((f) => [...f, { id, prep, progress: 0, preview: prep.thumb ? `data:image/jpeg;base64,${prep.thumb}` : undefined }])509 }510 }, [engine])511512 // drag and drop over the whole conversation pane513 useEffect(() => {514 const main = ta.current?.closest(".main")515 if (!main) return516 let depth = 0517 const enter = (e: Event) => ((e as DragEvent).dataTransfer?.types.includes("Files") && (depth++, setDrag(true)))518 const leave = () => (--depth <= 0 && ((depth = 0), setDrag(false)))519 const over = (e: Event) => e.preventDefault()520 const drop = (e: Event) => {521 e.preventDefault()522 depth = 0523 setDrag(false)524 const fl = [...((e as DragEvent).dataTransfer?.files ?? [])]525 if (fl.length) void add(fl)526 }527 main.addEventListener("dragenter", enter)528 main.addEventListener("dragleave", leave)529 main.addEventListener("dragover", over)530 main.addEventListener("drop", drop)531 return () => {532 main.removeEventListener("dragenter", enter)533 main.removeEventListener("dragleave", leave)534 main.removeEventListener("dragover", over)535 main.removeEventListener("drop", drop)536 }537 }, [add])538539 const onText = (v: string) => {540 setText(v)541 if (!editing) engine.setDraft(conv.id, v)542 if (Date.now() - typingAt.current > 3000 && v) {543 typingAt.current = Date.now()544 engine.typing(conv.id, true)545 }546 }547548 const uploadAll = async (list: Pending[]): Promise<FileRef[]> => {549 const refs: FileRef[] = []550 for (const p of list) {551 const { blob, ...info } = p.prep552 const ref = await engine.upload(conv.id, blob, info, (f) => setFiles((fs) => fs.map((x) => (x.id === p.id ? { ...x, progress: f } : x))))553 refs.push(ref)554 }555 return refs556 }557558 const submit = async (at?: number) => {559 const body = text.trim()560 if (busy || (!body && !files.length)) return561 if (editing) {562 if (body && body !== editing.body) await engine.send(conv.id, { t: "edit", target: editing.id, body })563 setText(engine.drafts[conv.id] ?? "")564 return clear()565 }566 setBusy(true)567 try {568 const refs = files.length ? await uploadAll(files) : undefined569 const content = { t: "text" as const, body, files: refs, reply: reply ? { id: reply.id, from: reply.from, excerpt: (reply.body || reply.files?.[0]?.name || "").slice(0, 120) } : undefined }570 if (at) {571 await engine.schedule(conv.id, content, at)572 toast(t("Scheduled. It will be sent from this device when the time comes.", "Programmé. Il sera envoyé depuis cet appareil le moment venu."))573 } else await engine.send(conv.id, content)574 haptic()575 setText("")576 setFiles([])577 engine.setDraft(conv.id, "")578 engine.typing(conv.id, false)579 typingAt.current = 0580 clear()581 } catch (e) {582 toast(errText(e))583 } finally {584 setBusy(false)585 }586 }587588 const startRec = async () => {589 try {590 const r = new VoiceRecorder()591 await r.start()592 setRecTime(0)593 setRec(r)594 haptic(15)595 } catch {596 toast(t("Microphone access was refused.", "L’accès au microphone a été refusé."))597 }598 }599 const stopRec = async (send: boolean) => {600 const r = rec601 if (!r) return602 setRec(null)603 if (!send) return r.cancel()604 setBusy(true)605 try {606 const file = await r.stop()607 const prep = await prepare(file, false)608 const { blob, ...info } = prep609 const ref = await engine.upload(conv.id, blob, { ...info, voice: true })610 await engine.send(conv.id, { t: "text", body: "", files: [ref] })611 } catch (e) {612 toast(errText(e))613 } finally {614 setBusy(false)615 }616 }617618 const disabled = !conv.state619 return (620 <div className="composer">621 {drag && <div className="drop">{t("Drop to encrypt and send", "Déposez pour chiffrer et envoyer")}</div>}622 {(reply || editing) && (623 <div className="ctx">624 {editing ? I.edit : I.reply}625 <span className="grow ell">{editing ? t("Editing message", "Modification du message") : <><b>{engine.userName(reply!.from)}</b> · {reply!.body || reply!.files?.[0]?.name}</>}</span>626 <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => (clear(), editing && setText(engine.drafts[conv.id] ?? ""))} aria-label={t("Cancel", "Annuler")}>{I.x}</button>627 </div>628 )}629 {files.length > 0 && (630 <div className="tray">631 {files.map((f) => (632 <div className="item" key={f.id}>633 {f.preview ? <img src={f.preview} alt="" /> : <span className="ell" style={{ width: "100%" }}>{f.prep.name}<br /><span className="dim">{formatBytes(f.prep.blob.size)}</span></span>}634 {!busy && <button className="x" onClick={() => setFiles((l) => l.filter((x) => x.id !== f.id))} aria-label={t("Remove", "Retirer")}>✕</button>}635 {busy && <div className="progress"><i style={{ width: `${f.progress * 100}%` }} /></div>}636 </div>637 ))}638 </div>639 )}640 <div className="composer-box">641 {rec ? (642 <>643 <button className="icon-btn" onClick={() => stopRec(false)} aria-label={t("Discard recording", "Abandonner l’enregistrement")}>{I.trash}</button>644 <div className="rec"><i />{formatDuration(recTime)}<span className="dim small grow">{t("Recording…", "Enregistrement…")}</span></div>645 <button className="send" onClick={() => stopRec(true)} aria-label={t("Send voice message", "Envoyer le message vocal")}>{I.send}</button>646 </>647 ) : (648 <>649 <button className="icon-btn" disabled={disabled || !!editing} onClick={() => fileInput.current?.click()} aria-label={t("Attach files", "Joindre des fichiers")}>{I.clip}</button>650 {touch && <button className="icon-btn" disabled={disabled || !!editing} onClick={() => camInput.current?.click()} aria-label={t("Take a photo", "Prendre une photo")}>{I.camera}</button>}651 <textarea ref={ta} rows={1} value={text} disabled={disabled} placeholder={disabled ? t("Waiting for keys…", "En attente des clés…") : t("Message", "Message")} aria-label={t("Message", "Message")}652 enterKeyHint={touch ? "enter" : "send"}653 onChange={(e) => onText(e.target.value)}654 onPaste={(e) => {655 const fl = [...e.clipboardData.files]656 if (fl.length) (e.preventDefault(), void add(fl))657 }}658 onKeyDown={(e) => {659 if (e.key === "Enter" && !e.shiftKey && !touch && engine.prefs.enterSends && !e.nativeEvent.isComposing) (e.preventDefault(), void submit())660 else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) (e.preventDefault(), void submit())661 else if (e.key === "Escape" && (reply || editing)) clear()662 else if (e.key === "ArrowUp" && !text && !editing) {663 const last = [...conv.messages].reverse().find((m) => m.from === engine.me.id && m.kind === "text" && !m.deleted && m.body)664 if (last) (e.preventDefault(), (document.dispatchEvent(new CustomEvent("spm-edit", { detail: last.id }))))665 }666 }} />667 {text.trim() || files.length ? (668 <>669 {!editing && <button className="icon-btn" disabled={busy} onClick={() => setScheduling(true)} aria-label={t("Schedule", "Programmer")}>{I.clock}</button>}670 <button className="send" disabled={busy || disabled} onClick={() => submit()} aria-label={editing ? t("Save", "Enregistrer") : t("Send", "Envoyer")}>{busy ? <span className="spinner" /> : editing ? I.check : I.send}</button>671 </>672 ) : (673 <button className="icon-btn" disabled={disabled || busy} onClick={startRec} aria-label={t("Record a voice message", "Enregistrer un message vocal")}>{busy ? <span className="spinner" /> : I.mic}</button>674 )}675 </>676 )}677 </div>678 <input ref={fileInput} type="file" multiple hidden onChange={(e) => (void add([...(e.target.files ?? [])]), (e.target.value = ""))} />679 <input ref={camInput} type="file" accept="image/*,video/*" capture="environment" hidden onChange={(e) => (void add([...(e.target.files ?? [])]), (e.target.value = ""))} />680 {scheduling && <ScheduleSheet onClose={() => setScheduling(false)} onPick={(at) => (setScheduling(false), void submit(at))} />}681 </div>682 )683}684685function ScheduleSheet({ onClose, onPick }: { onClose: () => void; onPick: (at: number) => void }) {686 const pad = (n: number) => String(n).padStart(2, "0")687 const d = new Date(Date.now() + 3600_000)688 const [v, setV] = useState(`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`)689 const at = new Date(v).getTime()690 return (691 <Sheet title={t("Send later", "Envoyer plus tard")} onClose={onClose}>692 <div className="col">693 <input className="input" type="datetime-local" value={v} onChange={(e) => setV(e.target.value)} aria-label={t("Date and time", "Date et heure")} />694 <p className="dim small">{t("The message stays encrypted on this device and is sent when the time comes, as long as SP Message is open on it. The server never holds a message waiting to be sent.", "Le message reste chiffré sur cet appareil et part le moment venu, à condition que SP Message y soit ouvert. Le serveur ne détient jamais de message en attente d’envoi.")}</p>695 <button className="btn primary" disabled={!(at > Date.now())} onClick={() => onPick(at)}>{t("Schedule", "Programmer")}</button>696 </div>697 </Sheet>698 )699}700