Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7bcd1a2a2d | |||
| efd31d9293 | |||
| a2a7e71f59 | |||
| 28907acf0e | |||
| 54add81187 | |||
| 4ad0decad0 | |||
| 0b433790a5 | |||
| 7982c243c0 | |||
| 1490fa3460 | |||
| 36f43d7d2a | |||
| 46aa7a767c | |||
| 4b50d682e6 | |||
| adb5a6bb7b | |||
| 2056592d51 |
@@ -437,7 +437,7 @@
|
|||||||
.dash-root .ds-modal-ic { width: 38px; height: 38px; border-radius: 11px; flex: 0 0 auto; display: grid; place-items: center; color: var(--orange); background: color-mix(in srgb, var(--orange) 14%, transparent); }
|
.dash-root .ds-modal-ic { width: 38px; height: 38px; border-radius: 11px; flex: 0 0 auto; display: grid; place-items: center; color: var(--orange); background: color-mix(in srgb, var(--orange) 14%, transparent); }
|
||||||
.dash-root .ds-modal-head h3 { font-size: 16px; font-weight: 700; }
|
.dash-root .ds-modal-head h3 { font-size: 16px; font-weight: 700; }
|
||||||
.dash-root .ds-modal-head p { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
|
.dash-root .ds-modal-head p { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
|
||||||
.dash-root .ds-modal-body { padding: 18px 20px; overflow-y: auto; }
|
.dash-root .ds-modal-body { padding: 18px 20px; overflow-y: auto; flex: 1 1 auto; min-height: 0; }
|
||||||
.dash-root .ds-modal-foot { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 20px; border-top: 1px solid var(--border); }
|
.dash-root .ds-modal-foot { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 20px; border-top: 1px solid var(--border); }
|
||||||
|
|
||||||
/* ---- Toasts ---- */
|
/* ---- Toasts ---- */
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Inbox — a personalized work/awareness feed IIOS projects from
|
// Inbox — the ONE unified communication surface. It lists everything
|
||||||
// events (mentions, needs-reply, support updates, …), surfaced via
|
// IIOS surfaces for you (mentions, needs-reply, system alerts, support
|
||||||
// the be-crm data door (crm.inbox.*). List + filter by state, and
|
// updates, …) AND the mail behind them: click an item tied to a thread
|
||||||
// mark items done / snoozed / archived. Items are created by IIOS's
|
// and its conversation opens on the right to read + reply. Compose new
|
||||||
// projector, never here. Mock when the Shell isn't configured.
|
// mail from here too. Items come from crm.inbox.*; threads from crm.mail.*.
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { Btn, Icon, PageHead, Pill } from "./ui";
|
import { Btn, Icon, PageHead, Pill, useToast } from "./ui";
|
||||||
import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api";
|
import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api";
|
||||||
|
import { MailReader, NewMailModal } from "./mail";
|
||||||
|
|
||||||
const KIND_LABEL: Record<string, string> = {
|
const KIND_LABEL: Record<string, string> = {
|
||||||
|
MAIL: "Mail",
|
||||||
MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval",
|
MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval",
|
||||||
SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner",
|
SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner",
|
||||||
};
|
};
|
||||||
@@ -23,10 +25,22 @@ const FILTERS: { value: InboxState; label: string }[] = [
|
|||||||
export function Inbox() {
|
export function Inbox() {
|
||||||
const [filter, setFilter] = useState<InboxState>("OPEN");
|
const [filter, setFilter] = useState<InboxState>("OPEN");
|
||||||
const inbox = useInboxData(filter);
|
const inbox = useInboxData(filter);
|
||||||
|
const toast = useToast();
|
||||||
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
|
const [newOpen, setNewOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if ((!selectedId || !inbox.items.some((i) => i.id === selectedId)) && inbox.items[0]) setSelectedId(inbox.items[0].id);
|
||||||
|
}, [inbox.items, selectedId]);
|
||||||
|
|
||||||
|
const selected = inbox.items.find((i) => i.id === selectedId) ?? null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="view">
|
<div className="view">
|
||||||
<PageHead eyebrow="Communication" title="Inbox" subtitle="Mentions, replies and updates that need your attention" icon="bell" />
|
<PageHead
|
||||||
|
eyebrow="Communication" title="Inbox" subtitle="Mentions, messages, system alerts and mail — all in one place" icon="bell"
|
||||||
|
actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New mail</Btn>}
|
||||||
|
/>
|
||||||
{!inbox.live && (
|
{!inbox.live && (
|
||||||
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
|
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
|
||||||
Demo mode — running on mock data. It goes live once the Shell + be-crm are connected.
|
Demo mode — running on mock data. It goes live once the Shell + be-crm are connected.
|
||||||
@@ -39,47 +53,100 @@ export function Inbox() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="card" style={{ padding: 0, overflow: "hidden" }}>
|
<div className="card" style={{ display: "flex", height: 620, padding: 0, overflow: "hidden" }}>
|
||||||
|
{/* Left — the unified item list */}
|
||||||
|
<aside style={{ width: 360, borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--panel)" }}>
|
||||||
{inbox.loading && <div style={{ padding: 20, color: "var(--muted)" }}>Loading…</div>}
|
{inbox.loading && <div style={{ padding: 20, color: "var(--muted)" }}>Loading…</div>}
|
||||||
{!inbox.loading && inbox.items.length === 0 && (
|
{!inbox.loading && inbox.items.length === 0 && (
|
||||||
<div style={{ padding: 28, color: "var(--muted)", textAlign: "center" }}>Nothing here — you're all caught up 🎉</div>
|
<div style={{ padding: 28, color: "var(--muted)", textAlign: "center" }}>Nothing here — you're all caught up 🎉</div>
|
||||||
)}
|
)}
|
||||||
{inbox.items.map((it) => (
|
{inbox.items.map((it) => (
|
||||||
<InboxRow
|
<ItemRow key={it.id} it={it} active={it.id === selectedId} onClick={() => setSelectedId(it.id)} />
|
||||||
key={it.id} it={it}
|
|
||||||
onDone={() => inbox.transition(it.id, "DONE")}
|
|
||||||
onSnooze={() => inbox.transition(it.id, "SNOOZED")}
|
|
||||||
onArchive={() => inbox.transition(it.id, "ARCHIVED")}
|
|
||||||
/>
|
|
||||||
))}
|
))}
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* Right — read the mail behind the item, or the item detail */}
|
||||||
|
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "var(--bg)" }}>
|
||||||
|
{selected ? (
|
||||||
|
<Detail
|
||||||
|
it={selected}
|
||||||
|
onError={(m) => toast.push({ tone: "error", title: "Failed", desc: m })}
|
||||||
|
onDone={() => inbox.transition(selected.id, "DONE")}
|
||||||
|
onSnooze={() => inbox.transition(selected.id, "SNOOZED")}
|
||||||
|
onArchive={() => inbox.transition(selected.id, "ARCHIVED")}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
|
||||||
|
<Icon name="bell" size={38} /><p>Select an item to read</p>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<NewMailModal
|
||||||
|
open={newOpen} onClose={() => setNewOpen(false)}
|
||||||
|
onSent={() => { setNewOpen(false); inbox.refetch(); toast.push({ tone: "success", title: "Sent" }); }}
|
||||||
|
onError={(m) => toast.push({ tone: "error", title: "Couldn't send", desc: m })}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function InboxRow({ it, onDone, onSnooze, onArchive }: { it: UiInboxItem; onDone: () => void; onSnooze: () => void; onArchive: () => void }) {
|
function ItemRow({ it, active, onClick }: { it: UiInboxItem; active: boolean; onClick: () => void }) {
|
||||||
const isMention = it.kind === "MENTION";
|
const isMention = it.kind === "MENTION";
|
||||||
return (
|
return (
|
||||||
<div style={{ display: "flex", gap: 12, alignItems: "flex-start", padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
|
<button
|
||||||
<span style={{ marginTop: 2, color: isMention ? "var(--orange)" : "var(--text-2)" }}>
|
onClick={onClick}
|
||||||
<Icon name={isMention ? "chat" : "bell"} size={18} />
|
style={{
|
||||||
|
display: "flex", gap: 10, alignItems: "flex-start", width: "100%", textAlign: "left",
|
||||||
|
padding: "13px 16px", border: "none", borderBottom: "1px solid var(--border)", cursor: "pointer",
|
||||||
|
background: active ? "var(--panel-2)" : "transparent", color: "var(--text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ marginTop: 2, color: isMention ? "var(--orange)" : "var(--text-2)", flexShrink: 0 }}>
|
||||||
|
<Icon name={it.kind === "MAIL" ? "mail" : it.threadId ? "chat" : isMention ? "chat" : "bell"} size={18} />
|
||||||
</span>
|
</span>
|
||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
|
<div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
|
||||||
<Pill tone={isMention ? "warn" : "muted"}>{KIND_LABEL[it.kind] ?? it.kind}</Pill>
|
<Pill tone={isMention ? "warn" : "muted"}>{KIND_LABEL[it.kind] ?? it.kind}</Pill>
|
||||||
<span style={{ fontWeight: 600 }}>{it.title}</span>
|
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.title}</span>
|
||||||
</div>
|
</div>
|
||||||
{it.summary && <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3 }}>{it.summary}</div>}
|
{it.summary && <div style={{ color: "var(--muted)", fontSize: 12.5, marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.summary}</div>}
|
||||||
</div>
|
</div>
|
||||||
{it.state === "OPEN" ? (
|
{it.state !== "OPEN" && <Pill tone="muted">{it.state.toLowerCase()}</Pill>}
|
||||||
<div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Detail({ it, onError, onDone, onSnooze, onArchive }: {
|
||||||
|
it: UiInboxItem; onError: (m: string) => void; onDone: () => void; onSnooze: () => void; onArchive: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Item actions bar — only for real inbox work-items. Mail isn't an inbox item
|
||||||
|
(no crm.inbox.transition), so it gets read/reply only, no Done/Snooze/Archive. */}
|
||||||
|
{it.state === "OPEN" && it.kind !== "MAIL" && (
|
||||||
|
<div style={{ display: "flex", gap: 6, padding: "10px 16px", borderBottom: "1px solid var(--border)", justifyContent: "flex-end" }}>
|
||||||
<Btn variant="ghost" icon="clock" onClick={onSnooze}>Snooze</Btn>
|
<Btn variant="ghost" icon="clock" onClick={onSnooze}>Snooze</Btn>
|
||||||
<Btn variant="outline" icon="check" onClick={onDone}>Done</Btn>
|
<Btn variant="outline" icon="check" onClick={onDone}>Done</Btn>
|
||||||
<Btn variant="ghost" icon="x" onClick={onArchive}>Archive</Btn>
|
<Btn variant="ghost" icon="x" onClick={onArchive}>Archive</Btn>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
|
||||||
<Pill tone="muted">{it.state.toLowerCase()}</Pill>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{it.threadId ? (
|
||||||
|
// A message/mail item → open the conversation to read + reply.
|
||||||
|
// key by threadId: the SDK's useQuery only refetches when the ACTION changes, not the
|
||||||
|
// variables — so switching items must remount MailReader to load the new thread's history.
|
||||||
|
<div style={{ flex: 1, minHeight: 0 }}>
|
||||||
|
<MailReader key={it.threadId} threadId={it.threadId} subject={it.title} onError={onError} />
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
// A non-threaded item (e.g. a system alert) → show its detail.
|
||||||
|
<div style={{ flex: 1, overflowY: "auto", padding: 22 }}>
|
||||||
|
<div style={{ fontWeight: 700, fontSize: 16, marginBottom: 6 }}>{it.title}</div>
|
||||||
|
{it.summary && <div style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.55 }}>{it.summary}</div>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Mail components used INSIDE the Inbox (not a separate tab).
|
||||||
|
// The Inbox is the one unified surface — mentions, system messages
|
||||||
|
// and mail all live there. These render the mail body + reply, and
|
||||||
|
// compose a new message. HTML bodies render in a sandboxed iframe.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { type CSSProperties, useEffect, useRef, useState } from "react";
|
||||||
|
import { Avatar, Btn, Field, Icon, Modal, Pill } from "./ui";
|
||||||
|
import { useMailThread, useMailCompose, type MailAttachment, type MailPerson } from "@/lib/mail-api";
|
||||||
|
import { useUploadAttachment, useDownloadUrl, isImage, type UploadedAttachment } from "@/lib/media-api";
|
||||||
|
|
||||||
|
const timeOf = (iso?: string) => {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
return Number.isNaN(+d) ? "" : d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||||
|
};
|
||||||
|
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
|
||||||
|
const inputStyle: CSSProperties = {
|
||||||
|
width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)",
|
||||||
|
background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none",
|
||||||
|
};
|
||||||
|
|
||||||
|
function fmtBytes(n: number): string {
|
||||||
|
if (!n) return "";
|
||||||
|
if (n < 1024) return `${n} B`;
|
||||||
|
if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
|
||||||
|
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolves a signed URL for a stored attachment and renders it inline (image) or as a file chip. */
|
||||||
|
function MailAttachmentView({ att }: { att: MailAttachment }) {
|
||||||
|
const getUrl = useDownloadUrl();
|
||||||
|
const [url, setUrl] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
getUrl(att.contentRef, att.mimeType).then((u) => { if (alive) setUrl(u); }).catch(() => {});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [att.contentRef, att.mimeType, getUrl]);
|
||||||
|
|
||||||
|
const label = att.filename || "Attachment";
|
||||||
|
if (isImage(att.mimeType)) {
|
||||||
|
return url
|
||||||
|
? <a href={url} target="_blank" rel="noreferrer" style={{ display: "inline-block" }}><img src={url} alt={label} style={{ maxWidth: 320, maxHeight: 240, borderRadius: 8, border: "1px solid var(--border)" }} /></a>
|
||||||
|
: <div style={{ color: "var(--muted)", fontSize: 13 }}>Loading image…</div>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<a href={url ?? "#"} target="_blank" rel="noreferrer"
|
||||||
|
style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 12px", borderRadius: 10, border: "1px solid var(--border)", background: "var(--panel-2)", color: "var(--text)", textDecoration: "none", maxWidth: 320 }}>
|
||||||
|
<Icon name="paperclip" size={18} />
|
||||||
|
<span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{label}</span>
|
||||||
|
{att.sizeBytes > 0 && <span style={{ color: "var(--muted)", fontSize: 12 }}>{fmtBytes(att.sizeBytes)}</span>}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A small staged-file chip shown in a composer before send, with a remove button. */
|
||||||
|
function StagedChip({ file, onRemove }: { file: UploadedAttachment; onRemove: () => void }) {
|
||||||
|
return (
|
||||||
|
<div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "5px 10px", borderRadius: 999, background: "var(--panel-2)", border: "1px solid var(--border)", fontSize: 13 }}>
|
||||||
|
<Icon name="paperclip" size={14} />
|
||||||
|
<span style={{ maxWidth: 160, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.filename}</span>
|
||||||
|
<span style={{ color: "var(--muted)" }}>{fmtBytes(file.sizeBytes)}</span>
|
||||||
|
<button onClick={onRemove} title="Remove" style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", padding: 0, lineHeight: 1 }}>✕</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reader + reply for one mail thread. Used in the Inbox detail pane when an item has a threadId. */
|
||||||
|
export function MailReader({ threadId, subject, onError }: { threadId: string; subject: string; onError: (m: string) => void }) {
|
||||||
|
const t = useMailThread(threadId);
|
||||||
|
const upload = useUploadAttachment();
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [staged, setStaged] = useState<UploadedAttachment | null>(null);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
e.target.value = "";
|
||||||
|
if (!file) return;
|
||||||
|
setUploading(true);
|
||||||
|
try { setStaged(await upload(file)); }
|
||||||
|
catch (err) { onError((err as Error).message); }
|
||||||
|
finally { setUploading(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reply() {
|
||||||
|
const text = draft.trim();
|
||||||
|
if ((!text && !staged) || sending) return;
|
||||||
|
const att = staged ?? undefined;
|
||||||
|
setDraft(""); setStaged(null); setSending(true);
|
||||||
|
try { await t.reply(text, att); }
|
||||||
|
catch (e) { setDraft(text); setStaged(att ?? null); onError((e as Error).message); }
|
||||||
|
finally { setSending(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0 }}>
|
||||||
|
<header style={{ padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||||
|
<div style={{ fontWeight: 700, fontSize: 15 }}>{subject || "(no subject)"}</div>
|
||||||
|
</header>
|
||||||
|
<div style={{ flex: 1, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
|
||||||
|
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading…</div>}
|
||||||
|
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages.</div>}
|
||||||
|
{t.messages.map((m) => (
|
||||||
|
<div key={m.interactionId} style={{ border: "1px solid var(--border)", borderRadius: 12, background: "var(--panel)", overflow: "hidden" }}>
|
||||||
|
<div style={{ padding: "7px 12px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--muted)" }}>
|
||||||
|
<span>{m.kind === "EMAIL" ? "Email" : "Reply"}{m.actorId ? ` · ${m.actorId.replace(/^(pp_|cust_)/, "").slice(0, 8)}` : ""}</span>
|
||||||
|
<span>{timeOf(m.occurredAt)}</span>
|
||||||
|
</div>
|
||||||
|
{m.html
|
||||||
|
? <iframe sandbox="" srcDoc={m.html} title="mail body" style={{ width: "100%", height: 200, border: "none", background: "#fff" }} />
|
||||||
|
: m.text
|
||||||
|
? <div style={{ padding: 12, whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14 }}>{m.text}</div>
|
||||||
|
: null}
|
||||||
|
{m.attachment && <div style={{ padding: 12, paddingTop: m.html || m.text ? 0 : 12 }}><MailAttachmentView att={m.attachment} /></div>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<footer style={{ display: "flex", flexDirection: "column", gap: 8, padding: 12, borderTop: "1px solid var(--border)" }}>
|
||||||
|
{staged && <div><StagedChip file={staged} onRemove={() => setStaged(null)} /></div>}
|
||||||
|
<div style={{ display: "flex", gap: 8 }}>
|
||||||
|
<input ref={fileRef} type="file" style={{ display: "none" }} onChange={onPickFile} />
|
||||||
|
<Btn variant="ghost" icon="paperclip" onClick={() => fileRef.current?.click()} disabled={uploading}>{uploading ? "…" : ""}</Btn>
|
||||||
|
<input
|
||||||
|
value={draft} onChange={(e) => setDraft(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void reply(); } }}
|
||||||
|
placeholder="Reply…" style={inputStyle}
|
||||||
|
/>
|
||||||
|
<Btn icon="send" onClick={() => void reply()} disabled={sending || (!draft.trim() && !staged)}>Reply</Btn>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compose a new message — in-app (to a person) or external (to an email). */
|
||||||
|
export function NewMailModal({ open, onClose, onSent, onError }: { open: boolean; onClose: () => void; onSent: () => void; onError: (m: string) => void }) {
|
||||||
|
const compose = useMailCompose(onSent);
|
||||||
|
const upload = useUploadAttachment();
|
||||||
|
const [mode, setMode] = useState<"internal" | "external">("internal");
|
||||||
|
const [recipient, setRecipient] = useState("");
|
||||||
|
const [subject, setSubject] = useState("");
|
||||||
|
const [body, setBody] = useState("");
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [staged, setStaged] = useState<UploadedAttachment[]>([]);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => { if (!open) { setMode("internal"); setRecipient(""); setSubject(""); setBody(""); setQ(""); setBusy(false); setStaged([]); setUploading(false); } }, [open]);
|
||||||
|
|
||||||
|
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const files = Array.from(e.target.files ?? []);
|
||||||
|
e.target.value = "";
|
||||||
|
if (!files.length) return;
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const uploaded = await Promise.all(files.map((f) => upload(f)));
|
||||||
|
setStaged((s) => [...s, ...uploaded].slice(0, 10));
|
||||||
|
} catch (err) { onError((err as Error).message); }
|
||||||
|
finally { setUploading(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const filtered = compose.directory.filter((p) => p.name.toLowerCase().includes(q.trim().toLowerCase()));
|
||||||
|
const canSend = !!recipient && !!subject.trim() && !!body.trim() && !busy && !uploading;
|
||||||
|
|
||||||
|
async function send() {
|
||||||
|
if (!canSend) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
if (mode === "internal") await compose.sendInternal(recipient, subject.trim(), body.trim(), staged.length ? staged : undefined);
|
||||||
|
else await compose.sendExternal(recipient.trim(), subject.trim(), body.trim(), staged.length ? { attachments: staged } : undefined);
|
||||||
|
} catch (e) { onError((e as Error).message); }
|
||||||
|
finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open} onClose={onClose} title="New message" subtitle={mode === "internal" ? "To a team member or client (in-app)" : "To an email address"} icon="chat"
|
||||||
|
footer={<>
|
||||||
|
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
|
||||||
|
<Btn icon="send" onClick={() => void send()} disabled={!canSend}>{busy ? "Sending…" : "Send"}</Btn>
|
||||||
|
</>}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", gap: 6, marginBottom: 12 }}>
|
||||||
|
<Btn variant={mode === "internal" ? "primary" : "outline"} onClick={() => { setMode("internal"); setRecipient(""); }}>In-app</Btn>
|
||||||
|
<Btn variant={mode === "external" ? "primary" : "outline"} onClick={() => { setMode("external"); setRecipient(""); }}>Email</Btn>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{mode === "internal" ? (
|
||||||
|
<Field label="To (person)">
|
||||||
|
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people…" style={{ ...inputStyle, marginBottom: 8 }} />
|
||||||
|
<div style={{ maxHeight: 180, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
|
{filtered.length === 0 && <div style={{ color: "var(--muted)", padding: 8 }}>No people found.</div>}
|
||||||
|
{filtered.map((p: MailPerson) => (
|
||||||
|
<label key={p.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 10px", borderRadius: 10, cursor: "pointer", background: recipient === p.id ? "var(--panel-2)" : "transparent" }}>
|
||||||
|
<input type="radio" checked={recipient === p.id} onChange={() => setRecipient(p.id)} />
|
||||||
|
<Avatar initials={(p.name.split(/\s+/).map((s) => s[0]).join("").slice(0, 2) || "?").toUpperCase()} size={26} gradient={p.kind === "customer" ? CUSTOMER_GRAD : undefined} />
|
||||||
|
<span style={{ flex: 1 }}>{p.name}</span>
|
||||||
|
<Pill tone="muted">{p.kind}</Pill>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
) : (
|
||||||
|
<Field label="To (email)">
|
||||||
|
<input value={recipient} onChange={(e) => setRecipient(e.target.value)} placeholder="name@company.com" style={inputStyle} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Field label="Subject"><input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Subject" style={inputStyle} /></Field>
|
||||||
|
<Field label="Message"><textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write your message…" rows={6} style={{ ...inputStyle, resize: "vertical" }} /></Field>
|
||||||
|
|
||||||
|
{/* NOT a <Field> (which is a <label>): a label wrapping the file input would hijack the
|
||||||
|
Attach button's click via label→input association and open the picker erratically. */}
|
||||||
|
<div className="ds-field">
|
||||||
|
<span className="ds-field-lbl">Attachments</span>
|
||||||
|
<input ref={fileRef} type="file" multiple style={{ display: "none" }} onChange={onPickFile} />
|
||||||
|
<div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>
|
||||||
|
<Btn variant="outline" icon="paperclip" onClick={() => fileRef.current?.click()} disabled={uploading || staged.length >= 10}>{uploading ? "Uploading…" : "Attach"}</Btn>
|
||||||
|
{staged.map((f, i) => <StagedChip key={`${f.contentRef}_${i}`} file={f} onRemove={() => setStaged((s) => s.filter((_, j) => j !== i))} />)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,14 +6,43 @@
|
|||||||
// thread view + composer, with a "new chat" people picker that
|
// thread view + composer, with a "new chat" people picker that
|
||||||
// creates a DM (1 person) or group (2+). DM-vs-group and who-can-
|
// creates a DM (1 person) or group (2+). DM-vs-group and who-can-
|
||||||
// chat are enforced server-side by IIOS/OPA; this is just UI.
|
// chat are enforced server-side by IIOS/OPA; this is just UI.
|
||||||
// Data comes from useMessengerData()/useThread(): local mock when
|
// Live messages, typing, read receipts and reactions come over the
|
||||||
// the Shell isn't configured, live be-crm when it is.
|
// IIOS socket (Shell mode); mock keeps the demo working offline.
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
import { type CSSProperties, useEffect, useRef, useState } from "react";
|
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, useToast } from "./ui";
|
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, useToast } from "./ui";
|
||||||
import { useMessengerData, useThread, type Membership, type UiConversation, type UiPerson } from "@/lib/messenger-api";
|
import { useMessengerData, useThread, useGroupSettings, type Membership, type UiAttachment, type UiConversation, type UiMember, type UiMessage, type UiPerson } from "@/lib/messenger-api";
|
||||||
import { MessengerSocketProvider } from "@/lib/messenger-socket";
|
import { MessengerSocketProvider, useMessengerSocket } from "@/lib/messenger-socket";
|
||||||
|
import { useUploadAttachment, useDownloadUrl, isImage, type UploadedAttachment } from "@/lib/media-api";
|
||||||
|
|
||||||
|
const fmtBytes = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(0)} KB` : `${(n / 1048576).toFixed(1)} MB`);
|
||||||
|
|
||||||
|
/** Renders a message attachment — an inline image thumbnail, or a downloadable file chip. */
|
||||||
|
function AttachmentView({ att }: { att: UiAttachment }) {
|
||||||
|
const getUrl = useDownloadUrl();
|
||||||
|
const [url, setUrl] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
getUrl(att.contentRef, att.mimeType).then((u) => { if (alive) setUrl(u); }).catch(() => {});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [att.contentRef, att.mimeType, getUrl]);
|
||||||
|
|
||||||
|
if (isImage(att.mimeType)) {
|
||||||
|
return url ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<a href={url} target="_blank" rel="noreferrer"><img src={url} alt="attachment" style={{ maxWidth: 240, maxHeight: 240, borderRadius: 10, display: "block", marginTop: 6, border: "1px solid var(--border)" }} /></a>
|
||||||
|
) : <div style={{ marginTop: 6, color: "var(--muted)", fontSize: 12 }}>Loading image…</div>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<a href={url ?? "#"} target={url ? "_blank" : undefined} rel="noreferrer"
|
||||||
|
style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6, padding: "8px 12px", borderRadius: 10, background: "var(--panel-2)", border: "1px solid var(--border)", textDecoration: "none", color: "var(--text)", maxWidth: 240 }}>
|
||||||
|
<Icon name="paperclip" size={18} />
|
||||||
|
<span style={{ flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", fontSize: 13 }}>Attachment</span>
|
||||||
|
<span style={{ color: "var(--muted)", fontSize: 12, flexShrink: 0 }}>{fmtBytes(att.sizeBytes)}</span>
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const initialsOf = (name: string) =>
|
const initialsOf = (name: string) =>
|
||||||
name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
|
name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
|
||||||
@@ -24,6 +53,7 @@ const timeOf = (iso?: string) => {
|
|||||||
};
|
};
|
||||||
const GROUP_GRAD = "linear-gradient(135deg,#6366f1,#8b5cf6)";
|
const GROUP_GRAD = "linear-gradient(135deg,#6366f1,#8b5cf6)";
|
||||||
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
|
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
|
||||||
|
const REACTION_EMOJIS = ["👍", "❤️", "😂", "😮", "😢", "🎉"];
|
||||||
const inputStyle: CSSProperties = {
|
const inputStyle: CSSProperties = {
|
||||||
width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)",
|
width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)",
|
||||||
background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none",
|
background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none",
|
||||||
@@ -77,7 +107,7 @@ function MessengerPanel() {
|
|||||||
|
|
||||||
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
|
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
|
||||||
{current ? (
|
{current ? (
|
||||||
<ThreadView key={current.threadId} conv={current} onError={(msg) => toast.push({ tone: "error", title: "Message failed", desc: msg })} />
|
<ThreadView key={current.threadId} conv={current} nameOf={m.nameOf} directory={m.directory} onError={(msg) => toast.push({ tone: "error", title: "Message failed", desc: msg })} />
|
||||||
) : (
|
) : (
|
||||||
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
|
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
|
||||||
<Icon name="send" size={38} />
|
<Icon name="send" size={38} />
|
||||||
@@ -117,79 +147,264 @@ function ConversationRow({ c, active, onClick }: { c: UiConversation; active: bo
|
|||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
||||||
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.title}</span>
|
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.title}</span>
|
||||||
{c.membership === "group" && <Pill tone="muted">group</Pill>}
|
<span style={{ color: "var(--muted)", fontSize: 11, flexShrink: 0 }}>{timeOf(c.lastAt)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div style={{ color: "var(--muted)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
||||||
|
<span style={{ color: "var(--muted)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||||
{c.lastMessage ?? "No messages yet"}
|
{c.lastMessage ?? "No messages yet"}
|
||||||
</div>
|
</span>
|
||||||
</div>
|
|
||||||
{c.unread > 0 && (
|
{c.unread > 0 && (
|
||||||
<span style={{ background: "var(--orange)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px" }}>{c.unread}</span>
|
<span style={{ background: "var(--orange)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px", flexShrink: 0 }}>{c.unread}</span>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function ThreadView({ conv, onError }: { conv: UiConversation; onError: (m: string) => void }) {
|
function ThreadView({ conv, nameOf, directory, onError }: { conv: UiConversation; nameOf: (id: string) => string; directory: UiPerson[]; onError: (m: string) => void }) {
|
||||||
const t = useThread(conv.threadId);
|
const t = useThread(conv.threadId);
|
||||||
|
const socket = useMessengerSocket();
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
const [sending, setSending] = useState(false);
|
const [sending, setSending] = useState(false);
|
||||||
|
const [replyTo, setReplyTo] = useState<UiMessage | null>(null);
|
||||||
|
const [flashId, setFlashId] = useState<string | null>(null);
|
||||||
const endRef = useRef<HTMLDivElement>(null);
|
const endRef = useRef<HTMLDivElement>(null);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const msgRefs = useRef<Map<string, HTMLElement>>(new Map());
|
||||||
|
const typingSentAt = useRef(0);
|
||||||
|
|
||||||
useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [t.messages.length]);
|
useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [t.messages.length]);
|
||||||
|
|
||||||
|
const byId = useMemo(() => Object.fromEntries(t.messages.map((m) => [m.id, m])), [t.messages]);
|
||||||
|
const lastMineId = useMemo(() => [...t.messages].reverse().find((m) => m.mine)?.id ?? null, [t.messages]);
|
||||||
|
|
||||||
|
// Reply → focus the composer (bug: it didn't focus, forcing a manual click).
|
||||||
|
function startReply(msg: UiMessage) {
|
||||||
|
setReplyTo(msg);
|
||||||
|
requestAnimationFrame(() => inputRef.current?.focus());
|
||||||
|
}
|
||||||
|
// Click a quoted message → scroll to the original and flash it.
|
||||||
|
function jumpTo(id: string) {
|
||||||
|
const el = msgRefs.current.get(id);
|
||||||
|
if (!el) return;
|
||||||
|
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||||
|
setFlashId(id);
|
||||||
|
setTimeout(() => setFlashId((f) => (f === id ? null : f)), 1200);
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadAttachment = useUploadAttachment();
|
||||||
|
const [staged, setStaged] = useState<UploadedAttachment | null>(null);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
function onDraftChange(v: string) {
|
||||||
|
setDraft(v);
|
||||||
|
const now = Date.now();
|
||||||
|
if (socket && now - typingSentAt.current > 2000) { socket.sendTyping(conv.threadId); typingSentAt.current = now; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onPickFile(file: File | undefined) {
|
||||||
|
if (!file) return;
|
||||||
|
setUploading(true);
|
||||||
|
try { setStaged(await uploadAttachment(file)); }
|
||||||
|
catch (e) { onError((e as Error).message); }
|
||||||
|
finally { setUploading(false); if (fileRef.current) fileRef.current.value = ""; }
|
||||||
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
const text = draft.trim();
|
const text = draft.trim();
|
||||||
if (!text || sending) return;
|
if ((!text && !staged) || sending) return; // allow an attachment with no text
|
||||||
setDraft(""); setSending(true);
|
const parent = replyTo?.id;
|
||||||
try { await t.send(text); }
|
const att = staged;
|
||||||
catch (e) { setDraft(text); onError((e as Error).message); }
|
setDraft(""); setReplyTo(null); setStaged(null); setSending(true);
|
||||||
|
try {
|
||||||
|
await t.send(text, {
|
||||||
|
...(parent ? { parentInteractionId: parent } : {}),
|
||||||
|
...(att ? { attachment: { contentRef: att.contentRef, mimeType: att.mimeType, sizeBytes: att.sizeBytes } } : {}),
|
||||||
|
});
|
||||||
|
} catch (e) { setDraft(text); setStaged(att); onError((e as Error).message); }
|
||||||
finally { setSending(false); }
|
finally { setSending(false); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||||
|
|
||||||
|
const typingLabel = t.typingUserIds.length === 1
|
||||||
|
? `${nameOf(t.typingUserIds[0])} is typing…`
|
||||||
|
: t.typingUserIds.length > 1 ? "Several people are typing…" : "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<header style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
|
<header style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||||
<Avatar initials={initialsOf(conv.title)} size={34} gradient={conv.membership === "group" ? GROUP_GRAD : undefined} />
|
<Avatar initials={initialsOf(conv.title)} size={34} gradient={conv.membership === "group" ? GROUP_GRAD : undefined} />
|
||||||
<div>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
<div style={{ fontWeight: 600 }}>{conv.title}</div>
|
<div style={{ fontWeight: 600 }}>{conv.title}</div>
|
||||||
<div style={{ color: "var(--muted)", fontSize: 12 }}>
|
<div style={{ color: "var(--muted)", fontSize: 12 }}>
|
||||||
{conv.membership === "group" ? `${conv.participants.length} people` : "Direct message"}
|
{conv.membership === "group" ? `${conv.participants.length} people` : "Direct message"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{conv.membership === "group" && (
|
||||||
|
<button onClick={() => setSettingsOpen(true)} title="Group settings" style={{ ...actionBtnStyle, width: 34, height: 34 }}>
|
||||||
|
<Icon name="settings" size={18} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</header>
|
</header>
|
||||||
|
{conv.membership === "group" && settingsOpen && (
|
||||||
|
<GroupSettingsModal conv={conv} directory={directory} onClose={() => setSettingsOpen(false)} onError={onError} />
|
||||||
|
)}
|
||||||
|
|
||||||
<div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 8, background: "var(--bg)" }}>
|
<div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 10, background: "var(--bg)" }}>
|
||||||
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading messages…</div>}
|
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading messages…</div>}
|
||||||
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages yet — say hello 👋</div>}
|
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages yet — say hello 👋</div>}
|
||||||
{t.messages.map((msg) => (
|
{t.messages.map((msg) => (
|
||||||
<div key={msg.id} style={{ alignSelf: msg.mine ? "flex-end" : "flex-start", maxWidth: "72%" }}>
|
<MessageBubble
|
||||||
<div style={{
|
key={msg.id} msg={msg}
|
||||||
background: msg.mine ? "var(--grad-brand)" : "var(--panel-2)", color: msg.mine ? "#fff" : "var(--text)",
|
parent={msg.parentInteractionId ? byId[msg.parentInteractionId] : undefined}
|
||||||
padding: "8px 12px", borderRadius: 14,
|
seen={msg.id === lastMineId && t.seenIds.has(msg.id)}
|
||||||
borderBottomRightRadius: msg.mine ? 4 : 14, borderBottomLeftRadius: msg.mine ? 14 : 4,
|
showStatus={msg.id === lastMineId}
|
||||||
whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14,
|
flash={flashId === msg.id}
|
||||||
}}>
|
registerRef={(el) => { if (el) msgRefs.current.set(msg.id, el); else msgRefs.current.delete(msg.id); }}
|
||||||
{msg.text}
|
onReact={(emoji) => t.react(msg.id, emoji)}
|
||||||
</div>
|
onReply={() => startReply(msg)}
|
||||||
<div style={{ fontSize: 10.5, color: "var(--muted)", textAlign: msg.mine ? "right" : "left", marginTop: 2 }}>{timeOf(msg.at)}</div>
|
onQuoteClick={jumpTo}
|
||||||
</div>
|
/>
|
||||||
))}
|
))}
|
||||||
<div ref={endRef} />
|
<div ref={endRef} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
|
<div style={{ minHeight: 18, padding: "0 18px", color: "var(--muted)", fontSize: 12, fontStyle: "italic" }}>{typingLabel}</div>
|
||||||
|
|
||||||
|
{replyTo && (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 10, margin: "0 14px", padding: "8px 12px", borderRadius: 10, background: "var(--panel-2)", borderLeft: "3px solid var(--orange)" }}>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<div style={{ fontSize: 11, color: "var(--orange)", fontWeight: 600 }}>Replying to {replyTo.mine ? "yourself" : nameOf(replyTo.senderId ?? "")}</div>
|
||||||
|
<div style={{ fontSize: 12.5, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{replyTo.text}</div>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setReplyTo(null)} style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", fontSize: 16 }} aria-label="Cancel reply">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{staged && (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8, margin: "0 14px", padding: "8px 12px", borderRadius: 10, background: "var(--panel-2)", border: "1px solid var(--border)" }}>
|
||||||
|
<Icon name={isImage(staged.mimeType) ? "image" : "file"} size={16} />
|
||||||
|
<span style={{ flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", fontSize: 13 }}>{staged.filename}</span>
|
||||||
|
<span style={{ color: "var(--muted)", fontSize: 12 }}>{fmtBytes(staged.sizeBytes)}</span>
|
||||||
|
<button onClick={() => setStaged(null)} style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", fontSize: 16 }} aria-label="Remove attachment">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)", alignItems: "center" }}>
|
||||||
|
<input ref={fileRef} type="file" hidden onChange={(e) => void onPickFile(e.target.files?.[0])} />
|
||||||
|
<button onClick={() => fileRef.current?.click()} disabled={uploading} title="Attach a file" style={{ ...actionBtnStyle, width: 38, height: 38, flexShrink: 0, opacity: uploading ? 0.5 : 1 }}>
|
||||||
|
{uploading ? "…" : "📎"}
|
||||||
|
</button>
|
||||||
<input
|
<input
|
||||||
value={draft} onChange={(e) => setDraft(e.target.value)}
|
ref={inputRef}
|
||||||
|
value={draft} onChange={(e) => onDraftChange(e.target.value)}
|
||||||
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void submit(); } }}
|
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void submit(); } }}
|
||||||
placeholder="Type a message…" style={inputStyle}
|
placeholder="Type a message…" style={inputStyle}
|
||||||
/>
|
/>
|
||||||
<Btn icon="send" onClick={() => void submit()} disabled={sending || !draft.trim()}>Send</Btn>
|
<Btn icon="send" onClick={() => void submit()} disabled={sending || (!draft.trim() && !staged)}>Send</Btn>
|
||||||
</footer>
|
</footer>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function MessageBubble({
|
||||||
|
msg, parent, seen, showStatus, flash, registerRef, onReact, onReply, onQuoteClick,
|
||||||
|
}: {
|
||||||
|
msg: UiMessage; parent?: UiMessage; seen: boolean; showStatus: boolean; flash?: boolean;
|
||||||
|
registerRef?: (el: HTMLElement | null) => void;
|
||||||
|
onReact: (emoji: string) => void; onReply: () => void; onQuoteClick?: (id: string) => void;
|
||||||
|
}) {
|
||||||
|
const [hover, setHover] = useState(false);
|
||||||
|
const [picker, setPicker] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={registerRef}
|
||||||
|
onMouseEnter={() => setHover(true)}
|
||||||
|
onMouseLeave={() => { setHover(false); setPicker(false); }}
|
||||||
|
style={{
|
||||||
|
alignSelf: msg.mine ? "flex-end" : "flex-start", maxWidth: "72%", display: "flex", flexDirection: "column",
|
||||||
|
alignItems: msg.mine ? "flex-end" : "flex-start", position: "relative",
|
||||||
|
borderRadius: 14, padding: 2, transition: "background 0.4s",
|
||||||
|
background: flash ? "rgba(253,169,19,0.22)" : "transparent",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{parent && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => parent.id && onQuoteClick?.(parent.id)}
|
||||||
|
title="Go to message"
|
||||||
|
style={{ maxWidth: "100%", padding: "4px 10px", marginBottom: 3, borderRadius: 8, background: "var(--panel-2)", borderLeft: "3px solid var(--orange)", border: "none", borderLeftWidth: 3, fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", cursor: "pointer", textAlign: "left" }}
|
||||||
|
>
|
||||||
|
<span style={{ opacity: 0.8 }}>↩ {parent.text}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6, flexDirection: msg.mine ? "row-reverse" : "row" }}>
|
||||||
|
{(msg.text || !msg.attachment) && (
|
||||||
|
<div style={{
|
||||||
|
background: msg.mine ? "var(--grad-brand)" : "var(--panel)", color: msg.mine ? "#fff" : "var(--text)",
|
||||||
|
padding: "8px 12px", borderRadius: 14,
|
||||||
|
borderBottomRightRadius: msg.mine ? 4 : 14, borderBottomLeftRadius: msg.mine ? 14 : 4,
|
||||||
|
border: msg.mine ? "none" : "1px solid var(--border)",
|
||||||
|
whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14,
|
||||||
|
}}>
|
||||||
|
{msg.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{hover && (
|
||||||
|
<div style={{ display: "flex", gap: 2, position: "relative" }}>
|
||||||
|
<button onClick={() => setPicker((p) => !p)} title="React" style={actionBtnStyle}>🙂</button>
|
||||||
|
<button onClick={onReply} title="Reply" style={actionBtnStyle}>↩</button>
|
||||||
|
{picker && (
|
||||||
|
<div style={{ position: "absolute", bottom: "100%", [msg.mine ? "right" : "left"]: 0, marginBottom: 4, display: "flex", gap: 2, padding: 4, borderRadius: 999, background: "var(--panel)", border: "1px solid var(--border)", boxShadow: "0 6px 20px rgba(0,0,0,0.35)", zIndex: 5 }}>
|
||||||
|
{REACTION_EMOJIS.map((e) => (
|
||||||
|
<button key={e} onClick={() => { onReact(e); setPicker(false); }} style={{ ...actionBtnStyle, fontSize: 16 }}>{e}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{msg.attachment && (
|
||||||
|
<div style={{ marginTop: 4, display: "flex", justifyContent: msg.mine ? "flex-end" : "flex-start" }}>
|
||||||
|
<AttachmentView att={msg.attachment} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{msg.reactions && msg.reactions.length > 0 && (
|
||||||
|
<div style={{ display: "flex", gap: 4, marginTop: 3, flexWrap: "wrap" }}>
|
||||||
|
{msg.reactions.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.emoji} onClick={() => onReact(r.emoji)}
|
||||||
|
style={{
|
||||||
|
display: "inline-flex", alignItems: "center", gap: 3, padding: "1px 7px", borderRadius: 999, fontSize: 12, cursor: "pointer",
|
||||||
|
background: r.mine ? "rgba(253,169,19,0.18)" : "var(--panel-2)",
|
||||||
|
border: `1px solid ${r.mine ? "var(--orange)" : "var(--border)"}`, color: "var(--text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>{r.emoji}</span><span style={{ color: "var(--muted)" }}>{r.count}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>
|
||||||
|
{timeOf(msg.at)}{showStatus && msg.mine ? ` · ${seen ? "Seen" : "Sent"}` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const actionBtnStyle: CSSProperties = {
|
||||||
|
background: "var(--panel-2)", border: "1px solid var(--border)", borderRadius: 8,
|
||||||
|
width: 26, height: 26, display: "grid", placeItems: "center", cursor: "pointer", fontSize: 13, color: "var(--text)", padding: 0,
|
||||||
|
};
|
||||||
|
|
||||||
function NewChatModal({
|
function NewChatModal({
|
||||||
open, onClose, directory, onCreate,
|
open, onClose, directory, onCreate,
|
||||||
}: {
|
}: {
|
||||||
@@ -246,3 +461,90 @@ function NewChatModal({
|
|||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Group settings: rename, member list with roles, add/remove — admin-gated (IIOS/OPA re-enforces). */
|
||||||
|
function GroupSettingsModal({ conv, directory, onClose, onError }: {
|
||||||
|
conv: UiConversation; directory: UiPerson[]; onClose: () => void; onError: (m: string) => void;
|
||||||
|
}) {
|
||||||
|
const g = useGroupSettings(conv.threadId);
|
||||||
|
const [name, setName] = useState(conv.subject ?? "");
|
||||||
|
const [savingName, setSavingName] = useState(false);
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [pendingId, setPendingId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => { setName(conv.subject ?? ""); }, [conv.subject]);
|
||||||
|
|
||||||
|
const memberIds = useMemo(() => new Set(g.members.map((m) => m.userId)), [g.members]);
|
||||||
|
const nameChanged = name.trim() && name.trim() !== (conv.subject ?? "").trim();
|
||||||
|
const addable = directory.filter((p) => !memberIds.has(p.id) && p.name.toLowerCase().includes(q.trim().toLowerCase()));
|
||||||
|
|
||||||
|
async function saveName() {
|
||||||
|
if (!nameChanged || savingName) return;
|
||||||
|
setSavingName(true);
|
||||||
|
try { await g.rename(name.trim()); }
|
||||||
|
catch (e) { onError((e as Error).message); }
|
||||||
|
finally { setSavingName(false); }
|
||||||
|
}
|
||||||
|
async function add(userId: string) {
|
||||||
|
setPendingId(userId);
|
||||||
|
try { await g.addMember(userId); }
|
||||||
|
catch (e) { onError((e as Error).message); }
|
||||||
|
finally { setPendingId(null); }
|
||||||
|
}
|
||||||
|
async function remove(userId: string) {
|
||||||
|
setPendingId(userId);
|
||||||
|
try { await g.removeMember(userId); }
|
||||||
|
catch (e) { onError((e as Error).message); }
|
||||||
|
finally { setPendingId(null); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open onClose={onClose} title="Group settings" subtitle={conv.title} icon="settings"
|
||||||
|
footer={<Btn variant="ghost" onClick={onClose}>Done</Btn>}
|
||||||
|
>
|
||||||
|
<Field label="Group name">
|
||||||
|
<div style={{ display: "flex", gap: 8 }}>
|
||||||
|
<input value={name} onChange={(e) => setName(e.target.value)} disabled={!g.isAdmin}
|
||||||
|
placeholder="Group name" style={{ ...inputStyle, opacity: g.isAdmin ? 1 : 0.6 }} />
|
||||||
|
{g.isAdmin && <Btn onClick={() => void saveName()} disabled={!nameChanged || savingName}>{savingName ? "…" : "Save"}</Btn>}
|
||||||
|
</div>
|
||||||
|
{!g.isAdmin && <div style={{ color: "var(--muted)", fontSize: 12, marginTop: 4 }}>Only a group admin can rename the group.</div>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field label={`Members (${g.members.length})`}>
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 2, maxHeight: 200, overflowY: "auto" }}>
|
||||||
|
{g.loading && g.members.length === 0 && <div style={{ color: "var(--muted)", padding: 8 }}>Loading…</div>}
|
||||||
|
{g.members.map((mem: UiMember) => (
|
||||||
|
<div key={mem.userId} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 10px", borderRadius: 10 }}>
|
||||||
|
<Avatar initials={initialsOf(mem.displayName)} size={28} gradient={GROUP_GRAD} />
|
||||||
|
<span style={{ flex: 1 }}>{mem.displayName}</span>
|
||||||
|
{mem.role === "ADMIN" && <Pill tone="purple">admin</Pill>}
|
||||||
|
{g.isAdmin && mem.role !== "ADMIN" && (
|
||||||
|
<button onClick={() => void remove(mem.userId)} disabled={pendingId === mem.userId} title="Remove"
|
||||||
|
style={{ ...actionBtnStyle, width: 28, height: 28 }}><Icon name="trash" size={15} /></button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
{g.isAdmin && (
|
||||||
|
<Field label="Add member">
|
||||||
|
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people…" style={{ ...inputStyle, marginBottom: 8 }} />
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 2, maxHeight: 180, overflowY: "auto" }}>
|
||||||
|
{addable.length === 0 && <div style={{ color: "var(--muted)", padding: 8 }}>No one to add.</div>}
|
||||||
|
{addable.map((p) => (
|
||||||
|
<button key={p.id} onClick={() => void add(p.id)} disabled={pendingId === p.id}
|
||||||
|
style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 10px", borderRadius: 10, cursor: "pointer", background: "transparent", border: "none", color: "var(--text)", textAlign: "left" }}>
|
||||||
|
<Avatar initials={initialsOf(p.name)} size={28} gradient={p.kind === "customer" ? CUSTOMER_GRAD : undefined} />
|
||||||
|
<span style={{ flex: 1 }}>{p.name}</span>
|
||||||
|
<Icon name="plus" size={16} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export const NAV_GROUPS: NavGroup[] = [
|
|||||||
title: "Communication",
|
title: "Communication",
|
||||||
items: [
|
items: [
|
||||||
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
|
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
|
||||||
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, replies and updates for you" },
|
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, messages, alerts and mail — all in one" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
createContext, useCallback, useContext, useEffect, useId,
|
createContext, useCallback, useContext, useEffect, useId,
|
||||||
useRef, useState, type ReactNode,
|
useRef, useState, type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
import {
|
import {
|
||||||
MessageCircle, Ticket, Phone, Mail, BookOpen, Rocket, Shield, ShieldCheck,
|
MessageCircle, Ticket, Phone, Mail, BookOpen, Rocket, Shield, ShieldCheck,
|
||||||
Lock, CreditCard, User, Bell, Eye, EyeOff, Camera, Upload, Plus, Star, Send,
|
Lock, CreditCard, User, Bell, Eye, EyeOff, Camera, Upload, Plus, Star, Send,
|
||||||
@@ -221,6 +222,11 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
|||||||
children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg";
|
children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg";
|
||||||
}) {
|
}) {
|
||||||
const titleId = useId();
|
const titleId = useId();
|
||||||
|
// Portal the overlay up to `.dash-root` so its position:fixed anchors to the viewport,
|
||||||
|
// not to a transformed/overflow panel ancestor (which would clip or offset the modal).
|
||||||
|
const [host, setHost] = useState<Element | null>(null);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
useEffect(() => { setHost(document.querySelector(".dash-root")); setMounted(true); }, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||||
@@ -228,8 +234,8 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
|||||||
return () => document.removeEventListener("keydown", onKey);
|
return () => document.removeEventListener("keydown", onKey);
|
||||||
}, [open, onClose]);
|
}, [open, onClose]);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open || !mounted) return null;
|
||||||
return (
|
const overlay = (
|
||||||
<div className="ds-modal-overlay" onMouseDown={onClose}>
|
<div className="ds-modal-overlay" onMouseDown={onClose}>
|
||||||
<div className={`ds-modal size-${size}`} role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={(e) => e.stopPropagation()}>
|
<div className={`ds-modal size-${size}`} role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={(e) => e.stopPropagation()}>
|
||||||
<div className="ds-modal-head">
|
<div className="ds-modal-head">
|
||||||
@@ -247,6 +253,7 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
return host ? createPortal(overlay, host) : overlay;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------------------------------------------------- */
|
/* ---------------------------------------------------------- */
|
||||||
|
|||||||
+40
-2
@@ -8,9 +8,10 @@
|
|||||||
// query crm.inbox.list { state? } -> InboxItem[]
|
// query crm.inbox.list { state? } -> InboxItem[]
|
||||||
// cmd crm.inbox.transition { id, state, reason? } -> InboxItem
|
// cmd crm.inbox.transition { id, state, reason? } -> InboxItem
|
||||||
|
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
import { isShellConfigured } from "./appshell";
|
import { isShellConfigured } from "./appshell";
|
||||||
|
import type { MailThread } from "./mail-api";
|
||||||
|
|
||||||
export type InboxState = "OPEN" | "SNOOZED" | "DONE" | "ARCHIVED" | "CANCELLED" | "STALE";
|
export type InboxState = "OPEN" | "SNOOZED" | "DONE" | "ARCHIVED" | "CANCELLED" | "STALE";
|
||||||
export interface UiInboxItem {
|
export interface UiInboxItem {
|
||||||
@@ -34,11 +35,48 @@ export function useInboxData(state?: InboxState): InboxData {
|
|||||||
function useLiveInbox(state?: InboxState): InboxData {
|
function useLiveInbox(state?: InboxState): InboxData {
|
||||||
const { sdk } = useAppShell();
|
const { sdk } = useAppShell();
|
||||||
const q = useQuery<UiInboxItem[]>("crm.inbox.list", state ? { state } : {});
|
const q = useQuery<UiInboxItem[]>("crm.inbox.list", state ? { state } : {});
|
||||||
|
// Mail lives in crm-mail threads, NOT the inbox projection — fold it into the one unified
|
||||||
|
// surface. Mail has no inbox work-item state, so it only shows in the Open (or unfiltered) view.
|
||||||
|
const showMail = !state || state === "OPEN";
|
||||||
|
const mq = useQuery<MailThread[]>("crm.mail.list", {});
|
||||||
|
|
||||||
|
// The SDK's useQuery only refetches when the ACTION changes, not the variables — so a filter
|
||||||
|
// change (same action, new { state }) wouldn't reload. Force a refetch when the filter changes.
|
||||||
|
const refetchInbox = q.refetch;
|
||||||
|
useEffect(() => { refetchInbox(); }, [state, refetchInbox]);
|
||||||
|
|
||||||
|
const items = useMemo<UiInboxItem[]>(() => {
|
||||||
|
const inboxItems = q.data ?? [];
|
||||||
|
const mailItems: UiInboxItem[] = showMail
|
||||||
|
? (mq.data ?? []).map((t) => ({
|
||||||
|
id: `mail:${t.threadId}`,
|
||||||
|
kind: "MAIL",
|
||||||
|
state: "OPEN" as InboxState,
|
||||||
|
title: t.subject || "(no subject)",
|
||||||
|
...(t.lastMessage ? { summary: t.lastMessage } : {}),
|
||||||
|
priority: t.unread > 0 ? "HIGH" : "LOW",
|
||||||
|
threadId: t.threadId,
|
||||||
|
createdAt: t.lastAt ?? "",
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
// Newest first; mail and inbox items interleave by time.
|
||||||
|
return [...mailItems, ...inboxItems].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
|
||||||
|
}, [q.data, mq.data, showMail]);
|
||||||
|
|
||||||
const transition = useCallback(async (id: string, next: InboxState) => {
|
const transition = useCallback(async (id: string, next: InboxState) => {
|
||||||
await sdk.command("crm.inbox.transition", { id, state: next });
|
await sdk.command("crm.inbox.transition", { id, state: next });
|
||||||
q.refetch();
|
q.refetch();
|
||||||
}, [sdk, q]);
|
}, [sdk, q]);
|
||||||
return { live: true, loading: q.loading, error: q.error?.message ?? null, items: q.data ?? [], transition, refetch: q.refetch };
|
|
||||||
|
return {
|
||||||
|
live: true,
|
||||||
|
loading: q.loading || (showMail && mq.loading),
|
||||||
|
// Don't let a mail-list hiccup blank the whole inbox — surface only the inbox error.
|
||||||
|
error: q.error?.message ?? null,
|
||||||
|
items,
|
||||||
|
transition,
|
||||||
|
refetch: () => { q.refetch(); mq.refetch(); },
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const MOCK_ITEMS: UiInboxItem[] = [
|
const MOCK_ITEMS: UiInboxItem[] = [
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Mail data layer. A dedicated Mail reader over the be-crm data door (crm.mail.*), distinct from
|
||||||
|
// the Messenger chat and from the work-item Inbox. Live via the AppShell SDK; a small mock keeps the
|
||||||
|
// demo working before the Shell + be-crm are connected.
|
||||||
|
//
|
||||||
|
// Live contract (be-crm):
|
||||||
|
// query crm.mail.list {} -> MailThread[]
|
||||||
|
// query crm.mail.history { threadId } -> MailMessage[]
|
||||||
|
// cmd crm.mail.reply { threadId, content } -> { interactionId, threadId }
|
||||||
|
// cmd crm.mail.internal { recipientUserId, subject?, text?, html? } -> { threadId }
|
||||||
|
// cmd crm.mail.send { target, subject?, text?, html?, mirrorToUserId? } -> { commandId }
|
||||||
|
// query crm.messenger.directory { kind, limit } -> people to compose to (reused)
|
||||||
|
|
||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
|
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import { isShellConfigured } from "./appshell";
|
||||||
|
|
||||||
|
export interface MailThread {
|
||||||
|
threadId: string; subject: string | null; participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||||
|
}
|
||||||
|
export interface MailAttachment { contentRef: string; mimeType: string; sizeBytes: number; filename: string | null }
|
||||||
|
export interface MailMessage {
|
||||||
|
interactionId: string; actorId: string | null; kind: string; occurredAt: string; html: string | null; text: string | null; attachment: MailAttachment | null;
|
||||||
|
}
|
||||||
|
export interface MailPerson { id: string; name: string; kind: "staff" | "customer" }
|
||||||
|
|
||||||
|
/** Shape produced by media-api's useUploadAttachment, passed into a reply/compose. */
|
||||||
|
export interface OutgoingAttachment { contentRef: string; mimeType: string; sizeBytes: number; filename: string }
|
||||||
|
|
||||||
|
const SHELL = isShellConfigured();
|
||||||
|
|
||||||
|
/* ============================ Thread list ============================ */
|
||||||
|
|
||||||
|
export interface MailListData {
|
||||||
|
live: boolean; loading: boolean; error: string | null; threads: MailThread[]; refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMailThreads(): MailListData {
|
||||||
|
if (SHELL) {
|
||||||
|
const q = useQuery<MailThread[]>("crm.mail.list", {});
|
||||||
|
return { live: true, loading: q.loading, error: q.error?.message ?? null, threads: q.data ?? [], refetch: q.refetch };
|
||||||
|
}
|
||||||
|
return { live: false, loading: false, error: null, threads: MOCK_THREADS, refetch: () => {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ One thread ============================ */
|
||||||
|
|
||||||
|
export interface MailThreadData {
|
||||||
|
loading: boolean; error: string | null; messages: MailMessage[]; reply: (content: string, attachment?: OutgoingAttachment) => Promise<void>; refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMailThread(threadId: string | null): MailThreadData {
|
||||||
|
if (SHELL) return useLiveThread(threadId);
|
||||||
|
return useMockThread(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useLiveThread(threadId: string | null): MailThreadData {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const q = useQuery<MailMessage[]>("crm.mail.history", threadId ? { threadId } : { threadId: "" });
|
||||||
|
const reply = useCallback(async (content: string, attachment?: OutgoingAttachment) => {
|
||||||
|
if (!threadId) return;
|
||||||
|
await sdk.command("crm.mail.reply", { threadId, content, ...(attachment ? { attachment } : {}) });
|
||||||
|
q.refetch();
|
||||||
|
}, [sdk, threadId, q]);
|
||||||
|
return { loading: q.loading, error: q.error?.message ?? null, messages: threadId ? (q.data ?? []) : [], reply, refetch: q.refetch };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ Compose ============================ */
|
||||||
|
|
||||||
|
export interface ComposeData {
|
||||||
|
directory: MailPerson[];
|
||||||
|
sendInternal: (recipientUserId: string, subject: string, text: string, attachments?: OutgoingAttachment[]) => Promise<void>;
|
||||||
|
sendExternal: (target: string, subject: string, text: string, opts?: { mirrorToUserId?: string; attachments?: OutgoingAttachment[] }) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMailCompose(onSent: () => void): ComposeData {
|
||||||
|
if (SHELL) {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const dirQ = useQuery<MailPerson[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||||
|
const directory = useMemo(() => (dirQ.data ?? []).map((d) => ({ id: (d as unknown as { id: string }).id, name: (d as unknown as { displayName?: string; name?: string }).displayName ?? (d as unknown as { name?: string }).name ?? "", kind: (d as MailPerson).kind })), [dirQ.data]);
|
||||||
|
const sendInternal = useCallback(async (recipientUserId: string, subject: string, text: string, attachments?: OutgoingAttachment[]) => {
|
||||||
|
await sdk.command("crm.mail.internal", { recipientUserId, subject, text, html: `<p>${escapeHtml(text)}</p>`, ...(attachments && attachments.length ? { attachments } : {}) });
|
||||||
|
onSent();
|
||||||
|
}, [sdk, onSent]);
|
||||||
|
const sendExternal = useCallback(async (target: string, subject: string, text: string, opts?: { mirrorToUserId?: string; attachments?: OutgoingAttachment[] }) => {
|
||||||
|
await sdk.command("crm.mail.send", { target, subject, text, html: `<p>${escapeHtml(text)}</p>`, ...(opts?.mirrorToUserId ? { mirrorToUserId: opts.mirrorToUserId } : {}), ...(opts?.attachments && opts.attachments.length ? { attachments: opts.attachments } : {}) });
|
||||||
|
onSent();
|
||||||
|
}, [sdk, onSent]);
|
||||||
|
return { directory, sendInternal, sendExternal };
|
||||||
|
}
|
||||||
|
return { directory: MOCK_PEOPLE, sendInternal: async () => onSent(), sendExternal: async () => onSent() };
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s: string): string {
|
||||||
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ Mock (demo mode) ============================ */
|
||||||
|
|
||||||
|
const now = () => new Date().toISOString();
|
||||||
|
const MOCK_PEOPLE: MailPerson[] = [
|
||||||
|
{ id: "pp_sofia", name: "Sofia Ramirez", kind: "staff" },
|
||||||
|
{ id: "cust_acme", name: "Acme Roofing (Client)", kind: "customer" },
|
||||||
|
];
|
||||||
|
const MOCK_THREADS: MailThread[] = [
|
||||||
|
{ threadId: "mt_1", subject: "Welcome to the Founders Club", participants: ["you", "system"], unread: 1, lastMessage: "Thanks for joining…", lastAt: now() },
|
||||||
|
{ threadId: "mt_2", subject: "Storm response — East side", participants: ["you", "pp_sofia"], unread: 0, lastMessage: "Crew rolling out at 7", lastAt: now() },
|
||||||
|
];
|
||||||
|
function useMockThread(threadId: string | null): MailThreadData {
|
||||||
|
const [extra, setExtra] = useState<MailMessage[]>([]);
|
||||||
|
const base: MailMessage[] = threadId === "mt_1"
|
||||||
|
? [{ interactionId: "m1", actorId: "system", kind: "EMAIL", occurredAt: now(), html: "<p>Thanks for joining the <b>Founders Club</b>. Set up your account to get started.</p>", text: "Thanks for joining the Founders Club.", attachment: null }]
|
||||||
|
: threadId === "mt_2"
|
||||||
|
? [{ interactionId: "m2", actorId: "pp_sofia", kind: "EMAIL", occurredAt: now(), html: "<p>Crew is rolling out at 7. Confirm the Henderson scope?</p>", text: "Crew rolling out at 7.", attachment: null }]
|
||||||
|
: [];
|
||||||
|
const reply = useCallback(async (content: string, attachment?: OutgoingAttachment) => {
|
||||||
|
setExtra((l) => [...l, { interactionId: `r_${l.length}`, actorId: "you", kind: "MESSAGE", occurredAt: now(), html: null, text: content, attachment: attachment ? { contentRef: attachment.contentRef, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, filename: attachment.filename } : null }]);
|
||||||
|
}, []);
|
||||||
|
return { loading: false, error: null, messages: threadId ? [...base, ...extra] : [], reply, refetch: () => {} };
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Media (attachment) helpers over the be-crm data door (crm.media.*). The browser transfers bytes
|
||||||
|
// DIRECTLY to IIOS storage via the signed URLs — be-crm only mints them. Used by Messenger + Mail.
|
||||||
|
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||||
|
|
||||||
|
export interface UploadedAttachment { contentRef: string; mimeType: string; sizeBytes: number; filename: string }
|
||||||
|
|
||||||
|
export const MAX_ATTACHMENT_BYTES = 26 * 1024 * 1024; // matches IIOS's cap
|
||||||
|
|
||||||
|
export function isImage(mime?: string | null): boolean {
|
||||||
|
return !!mime && mime.startsWith("image/");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upload a File → { contentRef, mimeType, sizeBytes, filename }. Throws on oversize / failure. */
|
||||||
|
export function useUploadAttachment() {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
return useCallback(async (file: File): Promise<UploadedAttachment> => {
|
||||||
|
if (file.size > MAX_ATTACHMENT_BYTES) throw new Error("File is too large (max 25 MB).");
|
||||||
|
const mime = file.type || "application/octet-stream";
|
||||||
|
const { objectKey, uploadUrl } = (await sdk.command("crm.media.presignUpload", { mime, sizeBytes: file.size })) as { objectKey: string; uploadUrl: string };
|
||||||
|
const res = await fetch(uploadUrl, { method: "PUT", body: file });
|
||||||
|
if (!res.ok) throw new Error(`Upload failed (${res.status}).`);
|
||||||
|
return { contentRef: objectKey, mimeType: mime, sizeBytes: file.size, filename: file.name };
|
||||||
|
}, [sdk]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mint a short-lived signed URL to display/download an attachment by its contentRef. */
|
||||||
|
export function useDownloadUrl() {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
return useCallback(async (contentRef: string, mime?: string): Promise<string> => {
|
||||||
|
const { url } = (await sdk.command("crm.media.presignDownload", { contentRef, ...(mime ? { mime } : {}) })) as { url: string };
|
||||||
|
return url;
|
||||||
|
}, [sdk]);
|
||||||
|
}
|
||||||
+225
-28
@@ -12,10 +12,12 @@
|
|||||||
// cmd crm.messenger.send { threadId, content } -> MessengerMessage
|
// cmd crm.messenger.send { threadId, content } -> MessengerMessage
|
||||||
// cmd crm.messenger.participant.add { threadId, userId }
|
// cmd crm.messenger.participant.add { threadId, userId }
|
||||||
//
|
//
|
||||||
// v1 uses REST + polling for the live stream; v2 swaps in the IIOS MessageSocket (see messenger-socket.ts).
|
// v1 uses REST + polling for the live stream; v2 layers the IIOS MessageSocket (messenger-socket.tsx)
|
||||||
|
// on top for live messages, typing, read receipts, and reactions.
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
import { useAppShell, useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import type { AnnotationEvent, AnnotationGroup } from "@insignia/iios-kernel-client";
|
||||||
import { isShellConfigured } from "./appshell";
|
import { isShellConfigured } from "./appshell";
|
||||||
import { useMessengerSocket } from "./messenger-socket";
|
import { useMessengerSocket } from "./messenger-socket";
|
||||||
|
|
||||||
@@ -25,7 +27,14 @@ export interface UiConversation {
|
|||||||
threadId: string; title: string; subject: string | null; membership: Membership | null;
|
threadId: string; title: string; subject: string | null; membership: Membership | null;
|
||||||
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||||
}
|
}
|
||||||
export interface UiMessage { id: string; actorId: string | null; text: string; at: string; mine: boolean }
|
export interface UiReaction { emoji: string; count: number; mine: boolean }
|
||||||
|
export interface UiAttachment { contentRef: string; mimeType: string; sizeBytes: number }
|
||||||
|
export interface UiMessage {
|
||||||
|
id: string; actorId: string | null; senderId?: string | null; text: string; at: string; mine: boolean;
|
||||||
|
parentInteractionId?: string | null;
|
||||||
|
attachment?: UiAttachment;
|
||||||
|
reactions?: UiReaction[];
|
||||||
|
}
|
||||||
|
|
||||||
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
||||||
interface ConversationDTO {
|
interface ConversationDTO {
|
||||||
@@ -36,9 +45,25 @@ interface MessageDTO { interactionId: string; actorId: string | null; kind: stri
|
|||||||
|
|
||||||
const SHELL = isShellConfigured();
|
const SHELL = isShellConfigured();
|
||||||
const POLL_MS = 4000;
|
const POLL_MS = 4000;
|
||||||
|
const TYPING_TTL_MS = 3500;
|
||||||
|
|
||||||
const shortId = (id: string) => id.replace(/^(pp_|cust_)/, "").slice(0, 6);
|
const shortId = (id: string) => id.replace(/^(pp_|cust_)/, "").slice(0, 6);
|
||||||
|
|
||||||
|
/** Turn the kernel's generic annotation aggregates into reaction chips. `users` may hold user or
|
||||||
|
* actor ids depending on the source, so `mine` is best-effort; a fresh annotation event corrects it. */
|
||||||
|
export function toReactions(annotations: AnnotationGroup[] | undefined, myId?: string): UiReaction[] {
|
||||||
|
if (!annotations) return [];
|
||||||
|
return annotations
|
||||||
|
.filter((a) => a.type === "reaction" && a.users.length > 0)
|
||||||
|
.map((a) => ({ emoji: a.value, count: a.users.length, mine: !!myId && a.users.includes(myId) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyAnnotation(prev: UiReaction[] | undefined, e: AnnotationEvent, myId?: string): UiReaction[] {
|
||||||
|
const base = (prev ?? []).filter((r) => r.emoji !== e.value);
|
||||||
|
if (e.type !== "reaction" || e.users.length === 0) return base;
|
||||||
|
return [...base, { emoji: e.value, count: e.users.length, mine: !!myId && e.users.includes(myId) }];
|
||||||
|
}
|
||||||
|
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
/* Public hooks */
|
/* Public hooks */
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
@@ -55,7 +80,21 @@ export interface MessengerData {
|
|||||||
export interface ThreadData {
|
export interface ThreadData {
|
||||||
loading: boolean; error: string | null;
|
loading: boolean; error: string | null;
|
||||||
messages: UiMessage[];
|
messages: UiMessage[];
|
||||||
send: (content: string) => Promise<void>;
|
send: (content: string, opts?: { parentInteractionId?: string; attachment?: UiAttachment }) => Promise<void>;
|
||||||
|
react: (interactionId: string, emoji: string) => void;
|
||||||
|
typingUserIds: string[];
|
||||||
|
seenIds: Set<string>;
|
||||||
|
refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UiMember { userId: string; displayName: string; role: string }
|
||||||
|
export interface GroupSettingsData {
|
||||||
|
loading: boolean; error: string | null;
|
||||||
|
members: UiMember[];
|
||||||
|
isAdmin: boolean;
|
||||||
|
rename: (subject: string) => Promise<void>;
|
||||||
|
addMember: (userId: string) => Promise<void>;
|
||||||
|
removeMember: (userId: string) => Promise<void>;
|
||||||
refetch: () => void;
|
refetch: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,13 +104,19 @@ export function useMessengerData(): MessengerData {
|
|||||||
export function useThread(threadId: string): ThreadData {
|
export function useThread(threadId: string): ThreadData {
|
||||||
return SHELL ? useLiveThread(threadId) : useMockThread(threadId);
|
return SHELL ? useLiveThread(threadId) : useMockThread(threadId);
|
||||||
}
|
}
|
||||||
|
export function useGroupSettings(threadId: string): GroupSettingsData {
|
||||||
|
return SHELL ? useLiveGroupSettings(threadId) : useMockGroupSettings(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
/* Live implementation (be-crm data door) */
|
/* Live implementation (be-crm data door + IIOS socket) */
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
|
|
||||||
function useLiveMessenger(): MessengerData {
|
function useLiveMessenger(): MessengerData {
|
||||||
const { sdk } = useAppShell();
|
const { sdk } = useAppShell();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const socket = useMessengerSocket();
|
||||||
|
const myId = user?.id;
|
||||||
const dirQ = useQuery<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
const dirQ = useQuery<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||||
const convQ = useQuery<ConversationDTO[]>("crm.messenger.conversation.list", {});
|
const convQ = useQuery<ConversationDTO[]>("crm.messenger.conversation.list", {});
|
||||||
|
|
||||||
@@ -82,9 +127,25 @@ function useLiveMessenger(): MessengerData {
|
|||||||
const nameById = useMemo(() => Object.fromEntries(directory.map((p) => [p.id, p.name])), [directory]);
|
const nameById = useMemo(() => Object.fromEntries(directory.map((p) => [p.id, p.name])), [directory]);
|
||||||
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
||||||
|
|
||||||
|
// Live sidebar previews: patch lastMessage/lastAt the instant a message arrives on any thread,
|
||||||
|
// then reconcile authoritative unread/order with a debounced refetch.
|
||||||
|
const [previews, setPreviews] = useState<Record<string, { lastMessage: string; lastAt: string }>>({});
|
||||||
|
const refetchRef = useRef(convQ.refetch);
|
||||||
|
refetchRef.current = convQ.refetch;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket) return;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const off = socket.onAnyMessage((threadId, m) => {
|
||||||
|
setPreviews((p) => ({ ...p, [threadId]: { lastMessage: m.text, lastAt: m.at } }));
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => refetchRef.current(), 600);
|
||||||
|
});
|
||||||
|
return () => { off(); if (timer) clearTimeout(timer); };
|
||||||
|
}, [socket]);
|
||||||
|
|
||||||
const conversations: UiConversation[] = useMemo(
|
const conversations: UiConversation[] = useMemo(
|
||||||
() => (convQ.data ?? []).map((c) => shape(c, nameOf)),
|
() => (convQ.data ?? []).map((c) => shape(c, nameOf, myId, previews[c.threadId])),
|
||||||
[convQ.data, nameOf],
|
[convQ.data, nameOf, myId, previews],
|
||||||
);
|
);
|
||||||
|
|
||||||
const refetch = useCallback(() => { dirQ.refetch(); convQ.refetch(); }, [dirQ, convQ]);
|
const refetch = useCallback(() => { dirQ.refetch(); convQ.refetch(); }, [dirQ, convQ]);
|
||||||
@@ -111,6 +172,11 @@ function useLiveThread(threadId: string): ThreadData {
|
|||||||
const q = useQuery<MessageDTO[]>("crm.messenger.history", { threadId });
|
const q = useQuery<MessageDTO[]>("crm.messenger.history", { threadId });
|
||||||
const [socketMsgs, setSocketMsgs] = useState<UiMessage[]>([]);
|
const [socketMsgs, setSocketMsgs] = useState<UiMessage[]>([]);
|
||||||
const [myActorId, setMyActorId] = useState<string | null>(null);
|
const [myActorId, setMyActorId] = useState<string | null>(null);
|
||||||
|
const myActorIdRef = useRef<string | null>(null);
|
||||||
|
myActorIdRef.current = myActorId;
|
||||||
|
const [typing, setTyping] = useState<Record<string, number>>({}); // userId -> expiry ts
|
||||||
|
const [seenIds, setSeenIds] = useState<Set<string>>(new Set());
|
||||||
|
const myId = socket?.myUserId;
|
||||||
|
|
||||||
// REST poll — the fallback whenever the live socket isn't connected.
|
// REST poll — the fallback whenever the live socket isn't connected.
|
||||||
const refetchRef = useRef(q.refetch);
|
const refetchRef = useRef(q.refetch);
|
||||||
@@ -121,46 +187,134 @@ function useLiveThread(threadId: string): ThreadData {
|
|||||||
return () => clearInterval(t);
|
return () => clearInterval(t);
|
||||||
}, [socketReady, threadId]);
|
}, [socketReady, threadId]);
|
||||||
|
|
||||||
// Socket (primary): load history + subscribe to live messages once connected.
|
// Socket (primary): load history + subscribe to live messages, typing, receipts, reactions.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!socket || !socketReady) return;
|
if (!socket || !socketReady) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
setSocketMsgs([]);
|
setSocketMsgs([]); setSeenIds(new Set()); setTyping({});
|
||||||
void socket.openThread(threadId).then((hist) => { if (alive) setSocketMsgs(hist); }).catch(() => {});
|
void socket.openThread(threadId).then((hist) => { if (alive) setSocketMsgs(hist); }).catch(() => {});
|
||||||
const unsub = socket.subscribe(threadId, (m) => setSocketMsgs((l) => (l.some((x) => x.id === m.id) ? l : [...l, m])));
|
|
||||||
return () => { alive = false; unsub(); };
|
const offMsg = socket.subscribe(threadId, (m) =>
|
||||||
}, [socket, socketReady, threadId]);
|
setSocketMsgs((l) => (l.some((x) => x.id === m.id) ? l : [...l, m])),
|
||||||
|
);
|
||||||
|
const offTyping = socket.onTyping(threadId, (userId) =>
|
||||||
|
setTyping((t) => ({ ...t, [userId]: Date.now() + TYPING_TTL_MS })),
|
||||||
|
);
|
||||||
|
// Receipts are a global stream (no threadId). Count only reads by the OTHER side; seenMine then
|
||||||
|
// narrows to my messages in this thread.
|
||||||
|
const offReceipt = socket.onReceipt((e) => {
|
||||||
|
if (e.actorId === myActorIdRef.current) return;
|
||||||
|
setSeenIds((s) => (s.has(e.interactionId) ? s : new Set(s).add(e.interactionId)));
|
||||||
|
});
|
||||||
|
const offAnn = socket.onAnnotation(threadId, (e) =>
|
||||||
|
setSocketMsgs((l) => l.map((m) => (m.id === e.interactionId ? { ...m, reactions: applyAnnotation(m.reactions, e, myId) } : m))),
|
||||||
|
);
|
||||||
|
return () => { alive = false; offMsg(); offTyping(); offReceipt(); offAnn(); };
|
||||||
|
}, [socket, socketReady, threadId, myId]);
|
||||||
|
|
||||||
|
// Learn my own actor id from a message I sent, so receipts from OTHER actors read as "seen".
|
||||||
|
useEffect(() => {
|
||||||
|
const mine = socketMsgs.find((m) => m.mine && m.actorId);
|
||||||
|
if (mine?.actorId && mine.actorId !== myActorId) setMyActorId(mine.actorId);
|
||||||
|
}, [socketMsgs, myActorId]);
|
||||||
|
|
||||||
|
// Tell the server I've read the latest message (drives the other side's "seen" tick).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket || !socketReady || socketMsgs.length === 0) return;
|
||||||
|
socket.markRead(threadId, socketMsgs[socketMsgs.length - 1].id);
|
||||||
|
}, [socket, socketReady, threadId, socketMsgs]);
|
||||||
|
|
||||||
|
// Expire stale typing entries.
|
||||||
|
const typingUserIds = useMemo(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
return Object.entries(typing).filter(([, exp]) => exp > now).map(([u]) => u);
|
||||||
|
}, [typing]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (typingUserIds.length === 0) return;
|
||||||
|
const t = setTimeout(() => setTyping((p) => ({ ...p })), TYPING_TTL_MS);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [typingUserIds.length, typing]);
|
||||||
|
|
||||||
const restMsgs: UiMessage[] = useMemo(
|
const restMsgs: UiMessage[] = useMemo(
|
||||||
() => (q.data ?? []).map((m) => ({
|
() => (q.data ?? []).map((m) => ({
|
||||||
id: m.interactionId, actorId: m.actorId, text: m.text ?? "", at: m.occurredAt,
|
id: m.interactionId, actorId: m.actorId, senderId: null, text: m.text ?? "", at: m.occurredAt,
|
||||||
mine: !!myActorId && m.actorId === myActorId,
|
mine: !!myActorId && m.actorId === myActorId, reactions: [],
|
||||||
})),
|
})),
|
||||||
[q.data, myActorId],
|
[q.data, myActorId],
|
||||||
);
|
);
|
||||||
|
|
||||||
const messages = socketReady ? socketMsgs : restMsgs;
|
const messages = socketReady ? socketMsgs : restMsgs;
|
||||||
|
|
||||||
const send = useCallback(async (content: string) => {
|
// My messages the other side has read (receipts carry the other actor's id).
|
||||||
|
const seenMine = useMemo(() => {
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const id of seenIds) if (messages.some((m) => m.id === id && m.mine)) out.add(id);
|
||||||
|
return out;
|
||||||
|
}, [seenIds, messages]);
|
||||||
|
|
||||||
|
const send = useCallback(async (content: string, opts?: { parentInteractionId?: string; attachment?: UiAttachment }) => {
|
||||||
if (socket && socketReady) {
|
if (socket && socketReady) {
|
||||||
await socket.send(threadId, content); // echoes back over the socket as a 'message' event
|
await socket.send(threadId, content, opts); // echoes back over the socket as a 'message' event
|
||||||
} else {
|
} else {
|
||||||
const m = (await sdk.command("crm.messenger.send", { threadId, content })) as MessageDTO;
|
// REST fallback carries the attachment ref too; a socket reconnect will replace with the live copy.
|
||||||
|
const m = (await sdk.command("crm.messenger.send", { threadId, content, ...(opts?.attachment ? { attachment: opts.attachment } : {}) })) as MessageDTO;
|
||||||
if (m.actorId) setMyActorId(m.actorId);
|
if (m.actorId) setMyActorId(m.actorId);
|
||||||
q.refetch();
|
q.refetch();
|
||||||
}
|
}
|
||||||
}, [socket, socketReady, threadId, sdk, q]);
|
}, [socket, socketReady, threadId, sdk, q]);
|
||||||
|
|
||||||
return { loading: q.loading && !socketReady, error: q.error?.message ?? null, messages, send, refetch: q.refetch };
|
const react = useCallback((interactionId: string, emoji: string) => {
|
||||||
|
if (socket && socketReady) socket.react(threadId, interactionId, emoji);
|
||||||
|
}, [socket, socketReady, threadId]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
loading: q.loading && !socketReady, error: q.error?.message ?? null,
|
||||||
|
messages, send, react, typingUserIds, seenIds: seenMine, refetch: q.refetch,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function shape(c: ConversationDTO, nameOf: (id: string) => string): UiConversation {
|
function useLiveGroupSettings(threadId: string): GroupSettingsData {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const q = useQuery<UiMember[]>("crm.messenger.members", { threadId });
|
||||||
|
const members = useMemo(() => q.data ?? [], [q.data]);
|
||||||
|
const isAdmin = useMemo(() => members.some((m) => m.userId === user?.id && m.role === "ADMIN"), [members, user?.id]);
|
||||||
|
|
||||||
|
const rename = useCallback(async (subject: string) => {
|
||||||
|
await sdk.command("crm.messenger.group.rename", { threadId, subject });
|
||||||
|
q.refetch();
|
||||||
|
}, [sdk, threadId, q]);
|
||||||
|
const addMember = useCallback(async (userId: string) => {
|
||||||
|
await sdk.command("crm.messenger.participant.add", { threadId, userId });
|
||||||
|
q.refetch();
|
||||||
|
}, [sdk, threadId, q]);
|
||||||
|
const removeMember = useCallback(async (userId: string) => {
|
||||||
|
await sdk.command("crm.messenger.participant.remove", { threadId, userId });
|
||||||
|
q.refetch();
|
||||||
|
}, [sdk, threadId, q]);
|
||||||
|
|
||||||
|
return { loading: q.loading, error: q.error?.message ?? null, members, isAdmin, rename, addMember, removeMember, refetch: q.refetch };
|
||||||
|
}
|
||||||
|
|
||||||
|
function shape(
|
||||||
|
c: ConversationDTO,
|
||||||
|
nameOf: (id: string) => string,
|
||||||
|
myId: string | undefined,
|
||||||
|
overlay?: { lastMessage: string; lastAt: string },
|
||||||
|
): UiConversation {
|
||||||
|
// A DM's title is the OTHER person — never yourself, and never the raw unknown-id fallback for both.
|
||||||
|
const others = myId ? c.participants.filter((p) => p !== myId) : c.participants;
|
||||||
const title = c.subject?.trim()
|
const title = c.subject?.trim()
|
||||||
|| (c.membership === "group"
|
|| (c.membership === "group"
|
||||||
? "Group"
|
? `Group · ${c.participants.length}`
|
||||||
: c.participants.map(nameOf).join(", ") || "Conversation");
|
: (others.map(nameOf).join(", ") || nameOf(c.participants[0] ?? "") || "Conversation"));
|
||||||
return { threadId: c.threadId, title, subject: c.subject, membership: c.membership,
|
const lastMessage = overlay?.lastMessage ?? c.lastMessage;
|
||||||
participants: c.participants, unread: c.unread, ...(c.lastMessage ? { lastMessage: c.lastMessage } : {}), ...(c.lastAt ? { lastAt: c.lastAt } : {}) };
|
const lastAt = overlay?.lastAt ?? c.lastAt;
|
||||||
|
return {
|
||||||
|
threadId: c.threadId, title, subject: c.subject, membership: c.membership,
|
||||||
|
participants: c.participants, unread: c.unread,
|
||||||
|
...(lastMessage ? { lastMessage } : {}), ...(lastAt ? { lastAt } : {}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
@@ -183,9 +337,9 @@ let MOCK_SEQ = 100;
|
|||||||
// conversation list and the open thread stay in sync (no globalThis, no render writes).
|
// conversation list and the open thread stay in sync (no globalThis, no render writes).
|
||||||
const MOCK_STORE = new Map<string, MockThread>([
|
const MOCK_STORE = new Map<string, MockThread>([
|
||||||
["th_mock_1", { threadId: "th_mock_1", membership: "dm", subject: null, participants: ["me", "pp_sofia"],
|
["th_mock_1", { threadId: "th_mock_1", membership: "dm", subject: null, participants: ["me", "pp_sofia"],
|
||||||
messages: [{ id: "m1", actorId: "pp_sofia", text: "Can you review the Henderson estimate?", at: now(), mine: false }] }],
|
messages: [{ id: "m1", actorId: "pp_sofia", text: "Can you review the Henderson estimate?", at: now(), mine: false, reactions: [] }] }],
|
||||||
["th_mock_2", { threadId: "th_mock_2", membership: "group", subject: "Storm response — East side", participants: ["me", "pp_dan", "pp_priya"],
|
["th_mock_2", { threadId: "th_mock_2", membership: "group", subject: "Storm response — East side", participants: ["me", "pp_dan", "pp_priya"],
|
||||||
messages: [{ id: "m2", actorId: "pp_dan", text: "Crew is rolling out at 7.", at: now(), mine: false }] }],
|
messages: [{ id: "m2", actorId: "pp_dan", text: "Crew is rolling out at 7.", at: now(), mine: false, reactions: [] }] }],
|
||||||
]);
|
]);
|
||||||
const mockListeners = new Set<() => void>();
|
const mockListeners = new Set<() => void>();
|
||||||
const notifyMock = () => mockListeners.forEach((l) => l());
|
const notifyMock = () => mockListeners.forEach((l) => l());
|
||||||
@@ -227,12 +381,55 @@ function useMockMessenger(): MessengerData {
|
|||||||
function useMockThread(threadId: string): ThreadData {
|
function useMockThread(threadId: string): ThreadData {
|
||||||
useMockSubscription();
|
useMockSubscription();
|
||||||
const thread = MOCK_STORE.get(threadId);
|
const thread = MOCK_STORE.get(threadId);
|
||||||
const send = useCallback(async (content: string) => {
|
const send = useCallback(async (content: string, opts?: { parentInteractionId?: string }) => {
|
||||||
const t = MOCK_STORE.get(threadId);
|
const t = MOCK_STORE.get(threadId);
|
||||||
if (t) {
|
if (t) {
|
||||||
t.messages = [...t.messages, { id: `m_${MOCK_SEQ++}`, actorId: "me", text: content, at: now(), mine: true }];
|
t.messages = [...t.messages, {
|
||||||
|
id: `m_${MOCK_SEQ++}`, actorId: "me", text: content, at: now(), mine: true, reactions: [],
|
||||||
|
...(opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : {}),
|
||||||
|
}];
|
||||||
notifyMock();
|
notifyMock();
|
||||||
}
|
}
|
||||||
}, [threadId]);
|
}, [threadId]);
|
||||||
return { loading: false, error: null, messages: thread?.messages ?? [], send, refetch: notifyMock };
|
const react = useCallback((interactionId: string, emoji: string) => {
|
||||||
|
const t = MOCK_STORE.get(threadId);
|
||||||
|
if (!t) return;
|
||||||
|
t.messages = t.messages.map((m) => {
|
||||||
|
if (m.id !== interactionId) return m;
|
||||||
|
const has = (m.reactions ?? []).find((r) => r.emoji === emoji);
|
||||||
|
const reactions = has
|
||||||
|
? (m.reactions ?? []).filter((r) => r.emoji !== emoji)
|
||||||
|
: [...(m.reactions ?? []), { emoji, count: 1, mine: true }];
|
||||||
|
return { ...m, reactions };
|
||||||
|
});
|
||||||
|
notifyMock();
|
||||||
|
}, [threadId]);
|
||||||
|
return {
|
||||||
|
loading: false, error: null, messages: thread?.messages ?? [], send, react,
|
||||||
|
typingUserIds: [], seenIds: new Set(), refetch: notifyMock,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function useMockGroupSettings(threadId: string): GroupSettingsData {
|
||||||
|
useMockSubscription();
|
||||||
|
const nameById = useMemo(() => Object.fromEntries(MOCK_PEOPLE.map((p) => [p.id, p.name])), []);
|
||||||
|
const t = MOCK_STORE.get(threadId);
|
||||||
|
const members: UiMember[] = (t?.participants ?? []).map((id) => ({
|
||||||
|
userId: id,
|
||||||
|
displayName: id === "me" ? "You" : (nameById[id] ?? `User ${shortId(id)}`),
|
||||||
|
role: id === "me" ? "ADMIN" : "MEMBER",
|
||||||
|
}));
|
||||||
|
const rename = useCallback(async (subject: string) => {
|
||||||
|
const th = MOCK_STORE.get(threadId);
|
||||||
|
if (th) { th.subject = subject; notifyMock(); }
|
||||||
|
}, [threadId]);
|
||||||
|
const addMember = useCallback(async (userId: string) => {
|
||||||
|
const th = MOCK_STORE.get(threadId);
|
||||||
|
if (th && !th.participants.includes(userId)) { th.participants = [...th.participants, userId]; notifyMock(); }
|
||||||
|
}, [threadId]);
|
||||||
|
const removeMember = useCallback(async (userId: string) => {
|
||||||
|
const th = MOCK_STORE.get(threadId);
|
||||||
|
if (th) { th.participants = th.participants.filter((p) => p !== userId); notifyMock(); }
|
||||||
|
}, [threadId]);
|
||||||
|
return { loading: false, error: null, members, isAdmin: true, rename, addMember, removeMember, refetch: notifyMock };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,20 +5,37 @@
|
|||||||
// the be-crm data door (crm.messenger.realtime). Threads subscribe through a context; the socket
|
// the be-crm data door (crm.messenger.realtime). Threads subscribe through a context; the socket
|
||||||
// re-opens every joined thread on reconnect (handled inside the SDK). In mock mode this is a no-op
|
// re-opens every joined thread on reconnect (handled inside the SDK). In mock mode this is a no-op
|
||||||
// passthrough and the thread hook falls back to the REST poll.
|
// passthrough and the thread hook falls back to the REST poll.
|
||||||
|
//
|
||||||
|
// Beyond plain messages, the kernel exposes typing, read receipts, and reactions (generic
|
||||||
|
// annotations). This provider fans each server event out to per-thread listeners so the UI can
|
||||||
|
// render typing indicators, "seen" ticks, and emoji reactions live.
|
||||||
|
|
||||||
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
|
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
|
||||||
import { MessageSocket, type Message } from "@insignia/iios-kernel-client";
|
import { MessageSocket, type Message, type AnnotationEvent } from "@insignia/iios-kernel-client";
|
||||||
import { useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
import { useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
import { isShellConfigured } from "./appshell";
|
import { isShellConfigured } from "./appshell";
|
||||||
import type { UiMessage } from "./messenger-api";
|
import { toReactions, type UiMessage } from "./messenger-api";
|
||||||
|
|
||||||
interface RealtimeDTO { url: string; audience: string; token?: string }
|
interface RealtimeDTO { url: string; audience: string; token?: string }
|
||||||
|
|
||||||
|
export interface ReceiptHit { interactionId: string; actorId: string }
|
||||||
|
|
||||||
export interface MessengerSocket {
|
export interface MessengerSocket {
|
||||||
ready: boolean;
|
ready: boolean;
|
||||||
|
myUserId?: string;
|
||||||
openThread: (threadId: string) => Promise<UiMessage[]>;
|
openThread: (threadId: string) => Promise<UiMessage[]>;
|
||||||
send: (threadId: string, content: string) => Promise<void>;
|
send: (threadId: string, content: string, opts?: { parentInteractionId?: string; attachment?: { contentRef: string; mimeType: string; sizeBytes: number } }) => Promise<void>;
|
||||||
subscribe: (threadId: string, cb: (m: UiMessage) => void) => () => void;
|
subscribe: (threadId: string, cb: (m: UiMessage) => void) => () => void;
|
||||||
|
/** Fires for EVERY inbound message regardless of thread — drives live sidebar previews. */
|
||||||
|
onAnyMessage: (cb: (threadId: string, m: UiMessage) => void) => () => void;
|
||||||
|
sendTyping: (threadId: string) => void;
|
||||||
|
onTyping: (threadId: string, cb: (userId: string) => void) => () => void;
|
||||||
|
markRead: (threadId: string, interactionId: string) => void;
|
||||||
|
/** The kernel's receipt event carries no threadId, so this is a global stream; the thread hook
|
||||||
|
* filters to receipts for its own (mine) messages. */
|
||||||
|
onReceipt: (cb: (e: ReceiptHit) => void) => () => void;
|
||||||
|
react: (threadId: string, interactionId: string, emoji: string) => void;
|
||||||
|
onAnnotation: (threadId: string, cb: (e: AnnotationEvent) => void) => () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Ctx = createContext<MessengerSocket | null>(null);
|
const Ctx = createContext<MessengerSocket | null>(null);
|
||||||
@@ -27,8 +44,11 @@ export function useMessengerSocket(): MessengerSocket | null { return useContext
|
|||||||
const SHELL = isShellConfigured();
|
const SHELL = isShellConfigured();
|
||||||
|
|
||||||
const toUi = (m: Message, myUserId?: string): UiMessage => ({
|
const toUi = (m: Message, myUserId?: string): UiMessage => ({
|
||||||
id: m.id, actorId: m.senderActorId ?? null, text: m.content ?? "", at: m.createdAt,
|
id: m.id, actorId: m.senderActorId ?? null, senderId: m.senderId ?? null, text: m.content ?? "", at: m.createdAt,
|
||||||
mine: !!myUserId && m.senderId === myUserId,
|
mine: !!myUserId && m.senderId === myUserId,
|
||||||
|
...(m.parentInteractionId ? { parentInteractionId: m.parentInteractionId } : {}),
|
||||||
|
...(m.attachment ? { attachment: { contentRef: m.attachment.contentRef, mimeType: m.attachment.mimeType, sizeBytes: m.attachment.sizeBytes } } : {}),
|
||||||
|
reactions: toReactions(m.annotations, myUserId),
|
||||||
});
|
});
|
||||||
|
|
||||||
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
||||||
@@ -37,15 +57,33 @@ export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
|||||||
return <LiveSocketProvider>{children}</LiveSocketProvider>;
|
return <LiveSocketProvider>{children}</LiveSocketProvider>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A tiny per-thread listener registry, reused for messages / typing / receipts / annotations.
|
||||||
|
function makeRegistry<T>() {
|
||||||
|
const map = new Map<string, Set<(v: T) => void>>();
|
||||||
|
const add = (key: string, cb: (v: T) => void) => {
|
||||||
|
if (!map.has(key)) map.set(key, new Set());
|
||||||
|
map.get(key)!.add(cb);
|
||||||
|
return () => { map.get(key)?.delete(cb); };
|
||||||
|
};
|
||||||
|
const emit = (key: string, v: T) => map.get(key)?.forEach((cb) => cb(v));
|
||||||
|
return { add, emit };
|
||||||
|
}
|
||||||
|
|
||||||
function LiveSocketProvider({ children }: { children: ReactNode }) {
|
function LiveSocketProvider({ children }: { children: ReactNode }) {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
const socketRef = useRef<MessageSocket | null>(null);
|
const socketRef = useRef<MessageSocket | null>(null);
|
||||||
const listeners = useRef<Map<string, Set<(m: UiMessage) => void>>>(new Map());
|
|
||||||
const myRef = useRef<string | undefined>(user?.id);
|
const myRef = useRef<string | undefined>(user?.id);
|
||||||
myRef.current = user?.id;
|
myRef.current = user?.id;
|
||||||
|
|
||||||
|
// One registry per event kind, keyed by threadId (plus a global message fan-out).
|
||||||
|
const msgReg = useRef(makeRegistry<UiMessage>()).current;
|
||||||
|
const anyMsg = useRef(new Set<(threadId: string, m: UiMessage) => void>()).current;
|
||||||
|
const typingReg = useRef(makeRegistry<string>()).current;
|
||||||
|
const receiptSet = useRef(new Set<(e: ReceiptHit) => void>()).current;
|
||||||
|
const annReg = useRef(makeRegistry<AnnotationEvent>()).current;
|
||||||
|
|
||||||
const url = rt.data?.url;
|
const url = rt.data?.url;
|
||||||
const token = rt.data?.token;
|
const token = rt.data?.token;
|
||||||
|
|
||||||
@@ -55,12 +93,19 @@ function LiveSocketProvider({ children }: { children: ReactNode }) {
|
|||||||
socketRef.current = socket;
|
socketRef.current = socket;
|
||||||
const offConnected = socket.onConnected(() => setReady(true));
|
const offConnected = socket.onConnected(() => setReady(true));
|
||||||
const offMessage = socket.on("message", (m) => {
|
const offMessage = socket.on("message", (m) => {
|
||||||
const cbs = listeners.current.get(m.threadId);
|
const ui = toUi(m, myRef.current);
|
||||||
if (cbs && cbs.size) { const ui = toUi(m, myRef.current); cbs.forEach((cb) => cb(ui)); }
|
msgReg.emit(m.threadId, ui);
|
||||||
|
anyMsg.forEach((cb) => cb(m.threadId, ui));
|
||||||
});
|
});
|
||||||
|
const offTyping = socket.on("typing", (e) => { if (e.userId !== myRef.current) typingReg.emit(e.threadId, e.userId); });
|
||||||
|
const offReceipt = socket.on("receipt", (e) => receiptSet.forEach((cb) => cb({ interactionId: e.interactionId, actorId: e.actorId })));
|
||||||
|
const offAnn = socket.on("annotation", (e) => annReg.emit(e.threadId, e));
|
||||||
socket.connect();
|
socket.connect();
|
||||||
return () => { offConnected(); offMessage(); socket.disconnect(); socketRef.current = null; setReady(false); };
|
return () => {
|
||||||
}, [url, token]);
|
offConnected(); offMessage(); offTyping(); offReceipt(); offAnn();
|
||||||
|
socket.disconnect(); socketRef.current = null; setReady(false);
|
||||||
|
};
|
||||||
|
}, [url, token, msgReg, anyMsg, typingReg, receiptSet, annReg]);
|
||||||
|
|
||||||
const openThread = useCallback(async (threadId: string): Promise<UiMessage[]> => {
|
const openThread = useCallback(async (threadId: string): Promise<UiMessage[]> => {
|
||||||
const s = socketRef.current;
|
const s = socketRef.current;
|
||||||
@@ -69,18 +114,36 @@ function LiveSocketProvider({ children }: { children: ReactNode }) {
|
|||||||
return res.history.map((m) => toUi(m, myRef.current));
|
return res.history.map((m) => toUi(m, myRef.current));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const send = useCallback(async (threadId: string, content: string) => {
|
const send = useCallback(async (threadId: string, content: string, opts?: { parentInteractionId?: string; attachment?: { contentRef: string; mimeType: string; sizeBytes: number } }) => {
|
||||||
const s = socketRef.current;
|
const s = socketRef.current;
|
||||||
if (!s) throw new Error("Not connected");
|
if (!s) throw new Error("Not connected");
|
||||||
await s.sendMessage(threadId, content);
|
const sendOpts = {
|
||||||
|
...(opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : {}),
|
||||||
|
...(opts?.attachment ? { attachment: opts.attachment } : {}),
|
||||||
|
};
|
||||||
|
await s.sendMessage(threadId, content, Object.keys(sendOpts).length ? sendOpts : undefined);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const subscribe = useCallback((threadId: string, cb: (m: UiMessage) => void) => {
|
const subscribe = useCallback((threadId: string, cb: (m: UiMessage) => void) => msgReg.add(threadId, cb), [msgReg]);
|
||||||
const map = listeners.current;
|
const onAnyMessage = useCallback((cb: (threadId: string, m: UiMessage) => void) => {
|
||||||
if (!map.has(threadId)) map.set(threadId, new Set());
|
anyMsg.add(cb); return () => { anyMsg.delete(cb); };
|
||||||
map.get(threadId)!.add(cb);
|
}, [anyMsg]);
|
||||||
return () => { map.get(threadId)?.delete(cb); };
|
const onTyping = useCallback((threadId: string, cb: (userId: string) => void) => typingReg.add(threadId, cb), [typingReg]);
|
||||||
}, []);
|
const onReceipt = useCallback((cb: (e: ReceiptHit) => void) => {
|
||||||
|
receiptSet.add(cb); return () => { receiptSet.delete(cb); };
|
||||||
|
}, [receiptSet]);
|
||||||
|
const onAnnotation = useCallback((threadId: string, cb: (e: AnnotationEvent) => void) => annReg.add(threadId, cb), [annReg]);
|
||||||
|
|
||||||
return <Ctx.Provider value={{ ready, openThread, send, subscribe }}>{children}</Ctx.Provider>;
|
const sendTyping = useCallback((threadId: string) => socketRef.current?.typing(threadId), []);
|
||||||
|
const markRead = useCallback((threadId: string, interactionId: string) => { void socketRef.current?.markRead(threadId, interactionId); }, []);
|
||||||
|
const react = useCallback((threadId: string, interactionId: string, emoji: string) => { void socketRef.current?.react(threadId, interactionId, emoji); }, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Ctx.Provider value={{
|
||||||
|
ready, myUserId: user?.id, openThread, send, subscribe, onAnyMessage,
|
||||||
|
sendTyping, onTyping, markRead, onReceipt, react, onAnnotation,
|
||||||
|
}}>
|
||||||
|
{children}
|
||||||
|
</Ctx.Provider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user