SPB Git

Repository Public

shell.tsx 24.3 KB 460 lines tsx

1import { useEffect, useMemo, useState } from "react"2import type { Conv } from "../core/engine"3import { Admin } from "./admin"4import { Avatar, errText, I, Sheet, t, timeShort, toast, useApp, useCalls } from "./bits"5import { CallUI } from "./callui"6import { ChatView, sysText } from "./chat"7import { Details } from "./details"8import { SettingsMenu, SettingsPage, type Section } from "./settings"910type Tab = "chats" | "calls" | "contacts" | "settings" | "admin"1112export function Shell() {13  const { engine, signOut } = useApp()14  const calls = useCalls()15  const [tab, setTab] = useState<Tab>("chats")16  const [active, setActive] = useState<string | null>(null)17  const [jump, setJump] = useState<string | undefined>()18  const [side, setSide] = useState(false)19  const [section, setSection] = useState<Section | null>(null)20  const [adminOpen, setAdminOpen] = useState(false)21  const [newChat, setNewChat] = useState(false)22  const [shortcuts, setShortcuts] = useState(false)23  const conv = active ? engine.convs.get(active) : undefined24  const unread = [...engine.convs.values()].reduce((n, c) => n + (c.muted ? 0 : c.unread), 0)2526  // theme27  useEffect(() => {28    const apply = () => {29      const th = engine.prefs.theme === "system" ? (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark") : engine.prefs.theme30      document.documentElement.dataset.theme = th31    }32    apply()33    const mq = matchMedia("(prefers-color-scheme: light)")34    mq.addEventListener("change", apply)35    return () => mq.removeEventListener("change", apply)36  }, [engine.prefs.theme])3738  // window title, focus tracking, notifications39  useEffect(() => {40    document.title = unread ? `(${unread}) SP Message` : "SP Message"41  }, [unread])42  useEffect(() => {43    const f = () => {44      engine.focused = document.visibilityState === "visible" && document.hasFocus()45      if (engine.focused && engine.activeConv) void engine.markRead(engine.activeConv)46    }47    f()48    window.addEventListener("focus", f)49    window.addEventListener("blur", f)50    document.addEventListener("visibilitychange", f)51    engine.onNotify = (c, m) => {52      if (!engine.prefs.notify || engine.focused) return53      if ("Notification" in window && Notification.permission === "granted") {54        // The text shown by the system never contains the message itself.55        const n = new Notification(engine.convTitle(c), { body: t("New message", "Nouveau message"), tag: c.id, icon: "/icon.svg" })56        n.onclick = () => (window.focus(), setTab("chats"), setActive(c.id), n.close())57      }58      void m59    }60    return () => {61      window.removeEventListener("focus", f)62      window.removeEventListener("blur", f)63      document.removeEventListener("visibilitychange", f)64    }65  }, [engine])6667  // notices raised by the engine (key changes, new devices)68  const [seenNotices, setSeenNotices] = useState(0)69  useEffect(() => {70    for (const n of engine.notices.slice(seenNotices)) toast(n.text)71    if (engine.notices.length !== seenNotices) setSeenNotices(engine.notices.length)72  }, [engine.notices.length])7374  // welcome conversation with the person who invited this account75  useEffect(() => {76    const key = `spm-welcomed-${engine.me.id}`77    if (!engine.me.invited_by || localStorage.getItem(key) || !engine.online) return78    localStorage.setItem(key, "1")79    engine.createConversation("dm", [engine.me.invited_by]).then((id) => setActive(id)).catch(() => localStorage.removeItem(key))80  }, [engine, engine.online])8182  // keyboard shortcuts83  useEffect(() => {84    const onKey = (e: KeyboardEvent) => {85      const mod = e.metaKey || e.ctrlKey86      if (mod && e.key.toLowerCase() === "k") (e.preventDefault(), setTab("chats"), setTimeout(() => document.getElementById("search")?.focus()))87      else if (mod && e.shiftKey && e.key.toLowerCase() === "n") (e.preventDefault(), setNewChat(true))88      else if (mod && e.key === "/") (e.preventDefault(), setShortcuts(true))89      else if (mod && e.key.toLowerCase() === "i" && active) (e.preventDefault(), setSide((s) => !s))90      else if (e.key === "Escape" && !document.querySelector(".backdrop, .menu, .viewer")) {91        if (side) setSide(false)92        else if (matchMedia("(max-width: 820px)").matches) (setActive(null), setSection(null), setAdminOpen(false))93      }94    }95    window.addEventListener("keydown", onKey)96    return () => window.removeEventListener("keydown", onKey)97  }, [active, side])9899  if (engine.fatal)100    return (101      <main className="stage">102        <div className="stage-card">103          <div className="brand"><img src="/icon.svg" alt="" />SP Message</div>104          <h1 className="h1">{t("This device was signed out", "Cet appareil a été déconnecté")}</h1>105          <p className="muted">{t("Its session or its device key was revoked. Sign in again to continue.", "Sa session ou sa clé d’appareil a été révoquée. Reconnectez-vous pour continuer.")}</p>106          <button className="btn primary lg" onClick={() => signOut(false)}>{t("Sign in again", "Se reconnecter")}</button>107        </div>108      </main>109    )110111  const open = (id: string, msgId?: string) => {112    setActive(id)113    setJump(msgId)114    setSection(null)115    setAdminOpen(false)116  }117  const pick = (next: Tab) => {118    setTab(next)119    setSide(false)120    if (next === "admin") (setAdminOpen(true), setActive(null), setSection(null))121    else setAdminOpen(false)122    if (next === "settings") setActive(null)123    else setSection(null)124  }125  const mainOpen = !!conv || !!section || adminOpen126  const tabs: { id: Tab; icon: React.ReactNode; label: string; badge?: number }[] = [127    { id: "chats", icon: I.chat, label: t("Chats", "Discussions"), badge: unread },128    { id: "calls", icon: I.phone, label: t("Calls", "Appels") },129    { id: "contacts", icon: I.users, label: t("Contacts", "Contacts") },130    { id: "settings", icon: I.gear, label: t("Settings", "Réglages"), badge: engine.pendingDevices.length },131    ...(engine.me.role === "admin" ? [{ id: "admin" as Tab, icon: I.crown, label: "Admin" }] : []),132  ]133134  return (135    <div className={`app ${side && conv ? "with-side" : ""} ${mainOpen ? "open" : ""}`}>136      <nav className="rail" aria-label={t("Sections", "Sections")}>137        <img className="logo" src="/icon.svg" alt="SP Message" />138        {tabs.map((x) => (139          <button key={x.id} className="nav" aria-current={tab === x.id} aria-label={x.label} title={x.label} onClick={() => pick(x.id)}>140            {x.icon}141            {x.badge ? <span className="pill">{x.badge}</span> : null}142          </button>143        ))}144        <span className="grow" />145        <span className="tiny dim" title={engine.online ? t("Connected", "Connecté") : t("Reconnecting…", "Reconnexion…")} style={{ color: engine.online ? "var(--ok)" : "var(--warn)" }}>●</span>146      </nav>147148      <section className="pane" aria-label={tabs.find((x) => x.id === tab)?.label}>149        {tab === "chats" && <ConvList active={active} onOpen={open} onNew={() => setNewChat(true)} />}150        {tab === "calls" && <CallList onOpen={open} />}151        {tab === "contacts" && <Contacts onOpen={open} />}152        {tab === "settings" && <SettingsMenu current={section} onPick={setSection} />}153        {tab === "admin" && (154          <>155            <div className="pane-head"><h1 className="h1">Admin</h1></div>156            <div className="pane-body"><button className="list-row" onClick={() => setAdminOpen(true)}>{I.crown}<span className="grow">{t("Open the dashboard", "Ouvrir le tableau de bord")}</span></button></div>157          </>158        )}159      </section>160161      <main className="main">162        {!engine.online && <div className="banner warn" style={{ margin: "calc(8px + var(--sat)) 14px 0", position: "absolute", zIndex: 8, left: 0, right: 0 }} role="status">{I.warn}{t("Offline. Messages you write are kept and sent on reconnection.", "Hors ligne. Les messages que vous écrivez sont conservés et envoyés à la reconnexion.")}</div>}163        {adminOpen ? <Admin onBack={() => setAdminOpen(false)} />164          : section ? <SettingsPage section={section} onBack={() => setSection(null)} />165          : conv ? <ChatView key={conv.id} conv={conv} jumpTo={jump} onBack={() => (setActive(null), setSide(false))} onInfo={() => setSide((s) => !s)} />166          : (167            <div className="empty">168              <div>169                <div className="glyph">{I.chat}</div>170                <h2 className="h2">{t("Select a conversation", "Choisissez une conversation")}</h2>171                <p className="small">{t("Everything you send is encrypted on this device before it leaves.", "Tout ce que vous envoyez est chiffré sur cet appareil avant d’en sortir.")}</p>172                <button className="btn primary" onClick={() => setNewChat(true)}>{I.plus}{t("New conversation", "Nouvelle conversation")}</button>173              </div>174            </div>175          )}176      </main>177178      {side && conv && <Details conv={conv} onClose={() => setSide(false)} onOpen={open} onLeft={() => (setSide(false), setActive(null))} />}179180      <nav className="tabbar" aria-label={t("Sections", "Sections")}>181        {tabs.map((x) => (182          <button key={x.id} aria-current={tab === x.id} onClick={() => pick(x.id)}>183            {x.icon}184            {x.label}185            {x.badge ? <span className="pill">{x.badge}</span> : null}186          </button>187        ))}188      </nav>189190      {newChat && <NewChat onClose={() => setNewChat(false)} onOpen={(id) => (setNewChat(false), setTab("chats"), open(id))} />}191      {shortcuts && <Shortcuts onClose={() => setShortcuts(false)} />}192      {engine.pendingDevices.length > 0 && <DeviceApproval />}193      {(calls.current || calls.waiting) && <CallUI />}194      {calls.error && <Sheet title={t("Call", "Appel")} onClose={() => calls.clearError()}><p>{calls.error}</p></Sheet>}195    </div>196  )197}198199function preview(engine: ReturnType<typeof useApp>["engine"], c: Conv): string {200  if (engine.drafts[c.id]) return `${t("Draft", "Brouillon")} : ${engine.drafts[c.id]}`201  const last = [...c.messages].reverse().find((m) => m.kind !== "sys" || m.sys?.type !== "device")202  if (!last) return c.waitingForKeys && !c.state ? t("Waiting for keys…", "En attente des clés…") : t("No messages yet", "Aucun message")203  if (last.kind !== "text") return String(sysTextPlain(engine, last))204  const who = last.from === engine.me.id ? `${t("You", "Vous")} : ` : c.kind === "group" ? `${engine.userName(last.from).split(" ")[0]} : ` : ""205  if (last.deleted) return who + t("Message deleted", "Message supprimé")206  const f = last.files?.[0]207  const att = f ? (f.voice ? `🎙 ${t("Voice message", "Message vocal")}` : f.mime.startsWith("image/") ? `📷 ${t("Photo", "Photo")}` : f.mime.startsWith("video/") ? `🎬 ${t("Video", "Vidéo")}` : `📎 ${f.name}`) : ""208  return who + (last.body || att)209}210function sysTextPlain(engine: ReturnType<typeof useApp>["engine"], m: Parameters<typeof sysText>[1]) {211  const x = sysText(engine, m)212  return typeof x === "string" ? x : m.sys?.video ? t("Video call", "Appel vidéo") : t("Voice call", "Appel vocal")213}214215function ConvList({ active, onOpen, onNew }: { active: string | null; onOpen: (id: string, msg?: string) => void; onNew: () => void }) {216  const { engine } = useApp()217  const [q, setQ] = useState("")218  const convs = [...engine.convs.values()].filter((c) => !c.left || c.messages.length).sort((a, b) => b.lastTs - a.lastTs)219  const hits = useMemo(() => engine.search(q), [q, engine.version])220  const query = q.trim().toLowerCase()221  const convHits = query ? convs.filter((c) => engine.convTitle(c).toLowerCase().includes(query)) : convs222  return (223    <>224      <div className="pane-head">225        <div className="row">226          <h1 className="h1 grow">{t("Chats", "Discussions")}</h1>227          <button className="icon-btn on" onClick={onNew} aria-label={t("New conversation", "Nouvelle conversation")}>{I.plus}</button>228        </div>229        <div className="search">230          {I.search}231          <input id="search" className="input" type="search" placeholder={t("Search messages and people", "Chercher messages et personnes")} value={q} onChange={(e) => setQ(e.target.value)} aria-label={t("Search", "Recherche")} />232        </div>233      </div>234      <div className="pane-body">235        {convHits.map((c) => {236          const peer = engine.peerOf(c)237          return (238            <button key={c.id} className="conv" aria-current={active === c.id} onClick={() => onOpen(c.id)}>239              <Avatar id={peer ?? c.id} name={engine.convTitle(c)} size={48} online={peer ? engine.users.get(peer)?.online : null} />240              <span className="grow">241                <span className="row" style={{ gap: 6 }}>242                  <span className="name ell grow">{engine.convTitle(c)}</span>243                  {c.muted && <span className="dim" style={{ width: 14, display: "inline-flex" }}>{I.bellOff}</span>}244                  <span className="time">{timeShort(c.lastTs)}</span>245                </span>246                <span className="row" style={{ gap: 6 }}>247                  <span className="preview ell grow" style={Object.keys(c.typing).length ? { color: "var(--accent)" } : undefined}>248                    {Object.keys(c.typing).length ? t("typing…", "écrit…") : preview(engine, c)}249                  </span>250                  {c.warnings.length > 0 && <span style={{ color: "var(--warn)", width: 16, display: "inline-flex" }}>{I.warn}</span>}251                  {c.unread > 0 && <span className="count">{c.unread}</span>}252                </span>253              </span>254            </button>255          )256        })}257        {!convs.length && !query && (258          <div className="empty">259            <div>260              <div className="glyph">{I.sparkle}</div>261              <b>{t("No conversation yet", "Aucune conversation")}</b>262              <p className="small">{t("Start one with someone from your private network.", "Commencez-en une avec une personne de votre réseau privé.")}</p>263              <button className="btn primary" onClick={onNew}>{I.plus}{t("New conversation", "Nouvelle conversation")}</button>264            </div>265          </div>266        )}267        {query.length >= 2 && (268          <>269            <h3 className="h3" style={{ paddingLeft: 10 }}>{t("Messages", "Messages")} · {hits.length}</h3>270            {hits.map((m) => {271              const c = engine.convs.get(m.conv)!272              return (273                <button key={m.id} className="conv" onClick={() => onOpen(m.conv, m.id)}>274                  <Avatar id={m.from} name={engine.userName(m.from)} size={38} />275                  <span className="grow">276                    <span className="row"><span className="name ell grow small">{engine.userName(m.from)} · {engine.convTitle(c)}</span><span className="time">{timeShort(m.ts)}</span></span>277                    <span className="preview ell" style={{ display: "block" }}>{m.body || m.files?.[0]?.name}</span>278                  </span>279                </button>280              )281            })}282            {!hits.length && <p className="dim small" style={{ padding: "0 12px" }}>{t("Search runs on this device, over the messages it has decrypted.", "La recherche s’exécute sur cet appareil, dans les messages qu’il a déchiffrés.")}</p>}283          </>284        )}285      </div>286    </>287  )288}289290function CallList({ onOpen }: { onOpen: (id: string, msg?: string) => void }) {291  const { engine } = useApp()292  const calls = [...engine.convs.values()].flatMap((c) => c.messages.filter((m) => m.kind === "call").map((m) => ({ m, c }))).sort((a, b) => b.m.ts - a.m.ts).slice(0, 200)293  return (294    <>295      <div className="pane-head"><h1 className="h1">{t("Calls", "Appels")}</h1></div>296      <div className="pane-body">297        {calls.map(({ m, c }) => {298          const missed = m.sys?.text === "missed" && m.from !== engine.me.id299          return (300            <button key={m.id} className="conv" onClick={() => onOpen(c.id, m.id)}>301              <Avatar id={engine.peerOf(c) ?? c.id} name={engine.convTitle(c)} size={44} />302              <span className="grow">303                <span className="name ell" style={{ display: "block", color: missed ? "var(--danger)" : undefined }}>{engine.convTitle(c)}</span>304                <span className="preview ell" style={{ display: "block" }}>{m.from === engine.me.id ? "↗ " : "↙ "}{sysText(engine, m)}</span>305              </span>306              <span className="dim" style={{ width: 20, display: "inline-flex" }}>{m.sys?.video ? I.video : I.phone}</span>307            </button>308          )309        })}310        {!calls.length && <div className="empty"><div><div className="glyph">{I.phone}</div><b>{t("No calls yet", "Aucun appel")}</b><p className="small">{t("Start a voice or video call from any conversation. Calls connect device to device and are encrypted.", "Lancez un appel vocal ou vidéo depuis une conversation. Les appels relient les appareils entre eux et sont chiffrés.")}</p></div></div>}311      </div>312    </>313  )314}315316type DirEntry = { id: string; handle: string; display_name: string }317function useDirectory() {318  const { engine } = useApp()319  const [dir, setDir] = useState<DirEntry[] | null>(null)320  useEffect(() => {321    engine.t.request<DirEntry[]>("GET", "/api/directory").then((d) => setDir(d.filter((u) => u.id !== engine.me.id))).catch(() => setDir([]))322  }, [engine])323  return dir324}325326function Contacts({ onOpen }: { onOpen: (id: string) => void }) {327  const { engine } = useApp()328  const dir = useDirectory()329  const [busy, setBusy] = useState("")330  const start = async (id: string) => {331    setBusy(id)332    try {333      onOpen(await engine.createConversation("dm", [id]))334    } catch (e) {335      toast(errText(e))336    }337    setBusy("")338  }339  return (340    <>341      <div className="pane-head"><h1 className="h1">{t("Contacts", "Contacts")}</h1><span className="dim small">{t("Everyone invited to this private network.", "Toutes les personnes invitées dans ce réseau privé.")}</span></div>342      <div className="pane-body">343        {dir === null && <div className="row" style={{ padding: 16 }}><span className="spinner" /></div>}344        {dir?.map((u) => {345          const pin = engine.pins.get(u.id)346          return (347            <button key={u.id} className="conv" onClick={() => start(u.id)} disabled={busy === u.id}>348              <Avatar id={u.id} name={u.display_name} size={44} online={engine.users.get(u.id)?.online} />349              <span className="grow">350                <span className="name ell" style={{ display: "block" }}>{u.display_name}</span>351                <span className="preview ell" style={{ display: "block" }}>@{u.handle}</span>352              </span>353              {pin?.verified && <span className="badge ok">{I.shield}{t("Verified", "Vérifié")}</span>}354              {busy === u.id && <span className="spinner" />}355            </button>356          )357        })}358        {dir?.length === 0 && <div className="empty"><div><div className="glyph">{I.users}</div><b>{t("Nobody else yet", "Personne d’autre pour l’instant")}</b><p className="small">{t("People appear here once they accepted an invitation and set up their keys.", "Les personnes apparaissent ici après avoir accepté une invitation et créé leurs clés.")}</p></div></div>}359      </div>360    </>361  )362}363364function NewChat({ onClose, onOpen }: { onClose: () => void; onOpen: (id: string) => void }) {365  const { engine } = useApp()366  const dir = useDirectory()367  const [sel, setSel] = useState<string[]>([])368  const [name, setName] = useState("")369  const [q, setQ] = useState("")370  const [busy, setBusy] = useState(false)371  const [err, setErr] = useState("")372  const group = sel.length > 1373  const go = async () => {374    setBusy(true)375    setErr("")376    try {377      onOpen(await engine.createConversation(group ? "group" : "dm", sel, group ? name.trim() || undefined : undefined))378    } catch (e) {379      setErr(errText(e))380      setBusy(false)381    }382  }383  const list = (dir ?? []).filter((u) => !q || `${u.display_name} ${u.handle}`.toLowerCase().includes(q.toLowerCase()))384  return (385    <Sheet title={t("New conversation", "Nouvelle conversation")} onClose={onClose}>386      <div className="col">387        <div className="search">{I.search}<input className="input" placeholder={t("Search people", "Chercher une personne")} value={q} onChange={(e) => setQ(e.target.value)} autoFocus aria-label={t("Search people", "Chercher une personne")} /></div>388        {group && <input className="input" placeholder={t("Group name", "Nom du groupe")} value={name} maxLength={80} onChange={(e) => setName(e.target.value)} aria-label={t("Group name", "Nom du groupe")} />}389        <div className="col" style={{ gap: 2, maxHeight: "42dvh", overflowY: "auto" }}>390          {dir === null && <span className="spinner" />}391          {list.map((u) => {392            const on = sel.includes(u.id)393            return (394              <button key={u.id} className="list-row" role="checkbox" aria-checked={on} onClick={() => setSel((s) => (on ? s.filter((x) => x !== u.id) : [...s, u.id]))}>395                <Avatar id={u.id} name={u.display_name} size={38} />396                <span className="grow"><span style={{ display: "block", fontWeight: 600 }}>{u.display_name}</span><span className="dim small">@{u.handle}</span></span>397                <span className={`badge ${on ? "accent" : ""}`} style={{ width: 24, padding: 0, justifyContent: "center" }}>{on ? "✓" : ""}</span>398              </button>399            )400          })}401          {dir?.length === 0 && <p className="dim small">{t("Nobody else has joined this network yet. An administrator can invite people.", "Personne d’autre n’a encore rejoint ce réseau. Un administrateur peut inviter des personnes.")}</p>}402        </div>403        {err && <p className="err" role="alert">{err}</p>}404        <button className="btn primary lg" disabled={!sel.length || busy} onClick={go}>405          {busy && <span className="spinner" />}406          {group ? t(`Create a group of ${sel.length + 1}`, `Créer un groupe de ${sel.length + 1}`) : t("Start the conversation", "Commencer la conversation")}407        </button>408      </div>409    </Sheet>410  )411}412413function DeviceApproval() {414  const { engine } = useApp()415  const d = engine.pendingDevices[0]416  const [busy, setBusy] = useState(false)417  const act = async (approve: boolean) => {418    setBusy(true)419    try {420      await (approve ? engine.approveDevice(d.id) : engine.rejectDevice(d.id))421      if (approve) toast(t("Device approved. It is being added to your conversations.", "Appareil approuvé. Il est ajouté à vos conversations."))422    } catch (e) {423      toast(errText(e))424    }425    setBusy(false)426  }427  return (428    <Sheet title={t("A new device wants to join your account", "Un nouvel appareil veut rejoindre votre compte")} onClose={() => act(false)}>429      <div className="col">430        <p className="muted">{t("Someone signed in with your passkey on", "Quelqu’un s’est connecté avec votre clé d’accès sur")} <b>{d.label}</b>. {t("Approve only if it is you and if that device shows exactly this code:", "N’approuvez que s’il s’agit de vous et si cet appareil affiche exactement ce code :")}</p>431        <div className="code" data-testid="approve-code">{d.code.slice(0, 3)} {d.code.slice(3)}</div>432        <p className="dim small">{t("Approving gives that device your encryption identity and adds it to all your conversations.", "Approuver transmet à cet appareil votre identité de chiffrement et l’ajoute à toutes vos conversations.")}</p>433        <div className="row">434          <button className="btn grow danger" disabled={busy} onClick={() => act(false)}>{t("Refuse", "Refuser")}</button>435          <button className="btn grow primary" disabled={busy} onClick={() => act(true)}>{t("The codes match: approve", "Les codes concordent : approuver")}</button>436        </div>437      </div>438    </Sheet>439  )440}441442function Shortcuts({ onClose }: { onClose: () => void }) {443  const mod = /Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl"444  const rows: [string, string][] = [445    [`${mod} K`, t("Search", "Rechercher")],446    [`${mod} ⇧ N`, t("New conversation", "Nouvelle conversation")],447    [`${mod} I`, t("Conversation details", "Détails de la conversation")],448    [`${mod} /`, t("This list", "Cette liste")],449    ["Enter", t("Send", "Envoyer")],450    ["⇧ Enter", t("New line", "Nouvelle ligne")],451    ["↑", t("Edit your last message", "Modifier votre dernier message")],452    ["Esc", t("Close panel or cancel", "Fermer le panneau ou annuler")],453  ]454  return (455    <Sheet title={t("Keyboard shortcuts", "Raccourcis clavier")} onClose={onClose}>456      <table className="table"><tbody>{rows.map(([k, d]) => <tr key={k}><td className="mono">{k}</td><td>{d}</td></tr>)}</tbody></table>457    </Sheet>458  )459}460
Files main
Menu

Theme