Compare commits
2 Commits
2056592d51
...
4b50d682e6
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b50d682e6 | |||
| adb5a6bb7b |
@@ -6,14 +6,14 @@
|
|||||||
// 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, type Membership, type UiConversation, type UiMessage, type UiPerson } from "@/lib/messenger-api";
|
||||||
import { MessengerSocketProvider } from "@/lib/messenger-socket";
|
import { MessengerSocketProvider, useMessengerSocket } from "@/lib/messenger-socket";
|
||||||
|
|
||||||
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 +24,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 +78,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} 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,36 +118,55 @@ 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, onError }: { conv: UiConversation; nameOf: (id: string) => string; 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 endRef = useRef<HTMLDivElement>(null);
|
const endRef = useRef<HTMLDivElement>(null);
|
||||||
|
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]);
|
||||||
|
|
||||||
|
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 submit() {
|
async function submit() {
|
||||||
const text = draft.trim();
|
const text = draft.trim();
|
||||||
if (!text || sending) return;
|
if (!text || sending) return;
|
||||||
setDraft(""); setSending(true);
|
const parent = replyTo?.id;
|
||||||
try { await t.send(text); }
|
setDraft(""); setReplyTo(null); setSending(true);
|
||||||
|
try { await t.send(text, parent ? { parentInteractionId: parent } : undefined); }
|
||||||
catch (e) { setDraft(text); onError((e as Error).message); }
|
catch (e) { setDraft(text); onError((e as Error).message); }
|
||||||
finally { setSending(false); }
|
finally { setSending(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)" }}>
|
||||||
@@ -159,28 +179,37 @@ function ThreadView({ conv, onError }: { conv: UiConversation; onError: (m: stri
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<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,
|
onReact={(emoji) => t.react(msg.id, emoji)}
|
||||||
}}>
|
onReply={() => setReplyTo(msg)}
|
||||||
{msg.text}
|
/>
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 10.5, color: "var(--muted)", textAlign: msg.mine ? "right" : "left", marginTop: 2 }}>{timeOf(msg.at)}</div>
|
|
||||||
</div>
|
|
||||||
))}
|
))}
|
||||||
<div ref={endRef} />
|
<div ref={endRef} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
|
||||||
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
|
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
|
||||||
<input
|
<input
|
||||||
value={draft} onChange={(e) => setDraft(e.target.value)}
|
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}
|
||||||
/>
|
/>
|
||||||
@@ -190,6 +219,81 @@ function ThreadView({ conv, onError }: { conv: UiConversation; onError: (m: stri
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function MessageBubble({
|
||||||
|
msg, parent, seen, showStatus, onReact, onReply,
|
||||||
|
}: {
|
||||||
|
msg: UiMessage; parent?: UiMessage; seen: boolean; showStatus: boolean;
|
||||||
|
onReact: (emoji: string) => void; onReply: () => void;
|
||||||
|
}) {
|
||||||
|
const [hover, setHover] = useState(false);
|
||||||
|
const [picker, setPicker] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
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" }}
|
||||||
|
>
|
||||||
|
{parent && (
|
||||||
|
<div style={{ maxWidth: "100%", padding: "4px 10px", marginBottom: 3, borderRadius: 8, background: "var(--panel-2)", borderLeft: "3px solid var(--orange)", fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||||
|
<span style={{ opacity: 0.8 }}>↩ {parent.text}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6, flexDirection: msg.mine ? "row-reverse" : "row" }}>
|
||||||
|
<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.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,
|
||||||
}: {
|
}: {
|
||||||
|
|||||||
+160
-27
@@ -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,12 @@ 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 UiMessage {
|
||||||
|
id: string; actorId: string | null; senderId?: string | null; text: string; at: string; mine: boolean;
|
||||||
|
parentInteractionId?: string | null;
|
||||||
|
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 +43,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 +78,10 @@ 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 }) => Promise<void>;
|
||||||
|
react: (interactionId: string, emoji: string) => void;
|
||||||
|
typingUserIds: string[];
|
||||||
|
seenIds: Set<string>;
|
||||||
refetch: () => void;
|
refetch: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,11 +93,14 @@ export function useThread(threadId: string): ThreadData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ======================================================================== */
|
/* ======================================================================== */
|
||||||
/* 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 +111,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 +156,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,29 +171,74 @@ 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 }) => {
|
||||||
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;
|
const m = (await sdk.command("crm.messenger.send", { threadId, content })) as MessageDTO;
|
||||||
if (m.actorId) setMyActorId(m.actorId);
|
if (m.actorId) setMyActorId(m.actorId);
|
||||||
@@ -151,16 +246,35 @@ function useLiveThread(threadId: string): ThreadData {
|
|||||||
}
|
}
|
||||||
}, [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 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 +297,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 +341,31 @@ 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,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 }) => 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,10 @@ 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 } : {}),
|
||||||
|
reactions: toReactions(m.annotations, myUserId),
|
||||||
});
|
});
|
||||||
|
|
||||||
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
||||||
@@ -37,15 +56,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 +92,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 +113,32 @@ 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 }) => {
|
||||||
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);
|
await s.sendMessage(threadId, content, opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : 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