Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | 31x 31x 31x 31x 31x 31x 29x 28x 6x 1x 3x 1x 1x 31x 31x 31x 31x 27x 19x 18x 6x 12x 2x 10x 2x 8x 2x 2x 6x 1x 5x 2x 2x 3x 3x 3x 2x 6x 6x 6x 6x 6x 6x 3x 3x 3x 5x 5x 6x 6x 2x 2x 2x 2x 4x 4x 1x 3x 35x 35x 35x 2x 35x 35x 1x 34x 4x 30x 30x 30x 31x 31x 31x 31x 30x 31x 31x | import { useMemo } from "react";
import { Check, CheckCheck, AlertCircle } from "lucide-react";
import { cn } from "../../lib/utils";
import type { WaMessage, WaTemplate } from "../../lib/api/whatsapp";
import {
parseTemplateComponents,
getTemplateBodyText,
renderPreviewText,
} from "./template-utils";
type MessageThreadProps = {
messages: WaMessage[];
templates?: WaTemplate[];
isLoading: boolean;
};
function formatTime(dateStr: string): string {
return new Date(dateStr).toLocaleTimeString("en-IN", {
hour: "2-digit",
minute: "2-digit",
});
}
function formatDate(dateStr: string): string {
const date = new Date(dateStr);
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
if (date.toDateString() === today.toDateString()) return "Today";
if (date.toDateString() === yesterday.toDateString()) return "Yesterday";
return date.toLocaleDateString("en-IN", {
day: "numeric",
month: "short",
year: "numeric",
});
}
function StatusIcon({ status }: { status: string }) {
switch (status) {
case "sent":
return <Check className="h-3 w-3 text-foreground-subtle" />;
case "delivered":
return <CheckCheck className="h-3 w-3 text-foreground-subtle" />;
case "read":
return <CheckCheck className="h-3 w-3 text-info" />;
case "failed":
return <AlertCircle className="h-3 w-3 text-error" />;
default:
return null;
}
}
type SentComponent = {
type?: string;
parameters?: Array<{ text?: string; type?: string }>;
};
function parseContent(
content: string | null,
type: string,
templateMap?: Map<string, WaTemplate>,
templateName?: string | null,
): string {
Iif (!content) return "";
try {
const parsed = JSON.parse(content);
if (typeof parsed === "string") return parsed;
// Text messages
if (parsed.body) return parsed.body;
if (parsed.text?.body) return parsed.text.body;
// Template messages — resolve body text with parameter values
if (type === "template") {
return resolveTemplateMessage(parsed, templateMap, templateName);
}
// Image / video / document
if (type === "image") {
return parsed.caption ? `[Image] ${parsed.caption}` : "[Image]";
}
if (type === "video") {
return parsed.caption ? `[Video] ${parsed.caption}` : "[Video]";
}
if (type === "document") {
const name = parsed.filename ?? "Document";
return parsed.caption ? `[${name}] ${parsed.caption}` : `[${name}]`;
}
if (type === "audio") {
return "[Voice message]";
}
// Location
if (type === "location") {
const parts = [parsed.name, parsed.address].filter(Boolean);
return parts.length > 0
? `[Location] ${parts.join(", ")}`
: `[Location] ${parsed.latitude}, ${parsed.longitude}`;
}
// Interactive (button/list replies)
Eif (type === "interactive") {
const title =
parsed.buttonReply?.title ?? parsed.listReply?.title ?? "";
return title ? `[Reply] ${title}` : "[Interactive message]";
}
return parsed.body ?? content;
} catch {
return content;
}
}
/**
* Resolve a template message into the text the customer would see.
* Looks up the template definition to get the body text with {{N}} placeholders,
* then substitutes the parameter values that were sent with the message.
*/
function resolveTemplateMessage(
parsed: Record<string, unknown>,
templateMap?: Map<string, WaTemplate>,
templateName?: string | null,
): string {
// Extract sent parameters from the message content
// Format 1: { templateName, language, components: [...] }
const sentComponents = (parsed.components ?? []) as SentComponent[];
// Format 2: full payload { template: { name, components: [...] } }
const nestedTemplate = parsed.template as
| { name?: string; components?: SentComponent[] }
| undefined;
const msgComponents = nestedTemplate?.components ?? sentComponents;
const name =
templateName ??
(parsed.templateName as string) ??
nestedTemplate?.name ??
"";
// Build parameter values map from sent components
const values: Record<string, string> = {};
for (const comp of msgComponents) {
const compType = (comp.type ?? "").toUpperCase();
Iif (compType !== "BODY" && compType !== "HEADER") continue;
for (const [idx, param] of (comp.parameters ?? []).entries()) {
Eif (param.text) {
values[`${compType}_${idx + 1}`] = param.text;
}
}
}
// Look up the template definition to get the body text with placeholders
const template = name ? templateMap?.get(name) : undefined;
if (template?.components) {
const defComponents = parseTemplateComponents(template.components);
const bodyText = getTemplateBodyText(defComponents);
Eif (bodyText) {
return renderPreviewText(bodyText, "BODY", values);
}
}
// Fallback: show parameter values if template definition unavailable
const paramTexts = Object.values(values);
if (paramTexts.length > 0) {
return paramTexts.join(", ");
}
return name ? `[Template: ${name}]` : "[Template message]";
}
export function MessageThread({
messages,
templates,
isLoading,
}: MessageThreadProps) {
const templateMap = useMemo(() => {
const map = new Map<string, WaTemplate>();
for (const t of templates ?? []) {
map.set(t.name, t);
}
return map;
}, [templates]);
if (isLoading) {
return (
<div className="flex-1 flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-whatsapp-green" />
</div>
);
}
if (messages.length === 0) {
return (
<div className="flex-1 flex items-center justify-center text-foreground-muted">
<p className="text-sm">No messages yet</p>
</div>
);
}
// Group messages by date
const groupedMessages: { date: string; messages: WaMessage[] }[] = [];
let currentDate = "";
for (const msg of messages) {
const date = formatDate(msg.dateCreated);
if (date !== currentDate) {
currentDate = date;
groupedMessages.push({ date, messages: [msg] });
} else E{
groupedMessages[groupedMessages.length - 1].messages.push(msg);
}
}
return (
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{groupedMessages.map((group) => (
<div key={group.date}>
{/* Date Separator */}
<div className="flex items-center justify-center my-4">
<span className="bg-background-muted text-foreground-muted text-xs px-3 py-1 rounded-full">
{group.date}
</span>
</div>
{/* Messages */}
<div className="space-y-2">
{group.messages.map((msg) => (
<div
key={msg.id}
className={cn(
"flex",
msg.direction === "outbound"
? "justify-end"
: "justify-start",
)}
>
<div
className={cn(
"max-w-[75%] rounded-lg px-3 py-2 shadow-sm",
msg.direction === "outbound"
? "bg-whatsapp-bubble-sent dark:bg-whatsapp-green/20 text-foreground-default"
: "bg-background-default border border-border-default text-foreground-default",
)}
>
{/* Template badge */}
{msg.templateName && (
<p className="text-xs font-medium text-whatsapp-green dark:text-whatsapp-green mb-1">
Template: {msg.templateName}
</p>
)}
{/* Message content */}
<p className="text-sm whitespace-pre-wrap break-words">
{parseContent(msg.content, msg.type, templateMap, msg.templateName)}
</p>
{/* Time and status */}
<div className="flex items-center justify-end gap-1 mt-1">
<span className="text-xs text-foreground-subtle">
{formatTime(msg.dateCreated)}
</span>
{msg.direction === "outbound" && (
<StatusIcon status={msg.status} />
)}
</div>
</div>
</div>
))}
</div>
</div>
))}
</div>
);
}
|