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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 | 2x 2x 2x 2x 2x 11x 11x 11x 1x 10x 1x 11x 1x 10x 10x 10x 1x 10x 1x 10x 10x 7x 10x 3x 7x 7x 1x 7x 3x 1x 1x 7x 1x 11x 1x 1x 11x 11x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 3x 3x 2x 2x 2x 79x 49x 49x 79x 11x 11x 11x 8x 8x 3x 3x 3x 1x 3x 3x 3x 3x 2x 3x 1x 2x 3x 3x 3x 1x 3x 79x 3x 3x 1x 3x 3x 79x 79x 24x 79x 10x 15x 15x 237x 474x 3x 2x 2x 11x 11x 4x 4x | import { useState, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { X, AlertCircle } from "lucide-react";
import { WhatsAppMessagePreview } from "./WhatsAppMessagePreview";
import { Button } from "../ui/button";
type TemplateFormProps = {
onSubmit: (data: {
name: string;
language: string;
category: string;
components: unknown[];
}) => void;
onClose: () => void;
isSubmitting: boolean;
serverError?: string;
};
const CATEGORIES = ["MARKETING", "UTILITY", "AUTHENTICATION"];
const LANGUAGES = [
{ value: "en", label: "English" },
{ value: "hi", label: "Hindi" },
{ value: "ta", label: "Tamil" },
{ value: "te", label: "Telugu" },
{ value: "kn", label: "Kannada" },
{ value: "mr", label: "Marathi" },
];
const MAX_BODY_LENGTH = 1024;
const MAX_HEADER_LENGTH = 60;
const MAX_FOOTER_LENGTH = 60;
function validateTemplate(params: {
name: string;
bodyText: string;
headerType: string;
headerText: string;
footerText: string;
}): string[] {
const errors: string[] = [];
const { name, bodyText, headerType, headerText, footerText } = params;
// Name validation
if (name.length < 1) {
errors.push("Template name is required.");
} else if (!/^[a-z][a-z0-9_]*$/.test(name)) {
errors.push(
"Name must start with a letter and contain only lowercase letters, numbers, and underscores.",
);
}
// Body validation
if (!bodyText.trim()) {
errors.push("Body text is required.");
} else {
Iif (bodyText.length > MAX_BODY_LENGTH) {
errors.push(
`Body text exceeds ${MAX_BODY_LENGTH} characters (currently ${bodyText.length}).`,
);
}
// Variables can't be at the start or end
const trimmed = bodyText.trim();
if (/^\{\{\d+\}\}/.test(trimmed)) {
errors.push(
"Body text cannot start with a variable. Add text before {{1}}.",
);
}
if (/\{\{\d+\}\}$/.test(trimmed)) {
errors.push(
"Body text cannot end with a variable. Add text after the last variable.",
);
}
// Variables must be sequential starting from {{1}}
const varMatches = bodyText.match(/\{\{(\d+)\}\}/g);
if (varMatches) {
const varNums = varMatches
.map((v) => Number.parseInt(v.replace(/\{|\}/g, ""), 10))
.sort((a, b) => a - b);
const unique = [...new Set(varNums)];
if (unique[0] !== 1) {
errors.push("Variables must start from {{1}}.");
}
for (let i = 1; i < unique.length; i++) {
if (unique[i] !== unique[i - 1] + 1) {
errors.push(
`Variables must be sequential. Missing {{${unique[i - 1] + 1}}}.`,
);
break;
}
}
// No consecutive variables without text between them
if (/\{\{\d+\}\}\s*\{\{\d+\}\}/.test(bodyText)) {
errors.push(
"Add text between consecutive variables (e.g., {{1}} and {{2}}).",
);
}
}
}
// Header validation
if (headerType === "text") {
Iif (!headerText.trim()) {
errors.push("Header text is required when header type is Text.");
I} else if (headerText.length > MAX_HEADER_LENGTH) {
errors.push(
`Header text exceeds ${MAX_HEADER_LENGTH} characters (currently ${headerText.length}).`,
);
}
}
// Footer validation
Iif (footerText.length > MAX_FOOTER_LENGTH) {
errors.push(
`Footer text exceeds ${MAX_FOOTER_LENGTH} characters (currently ${footerText.length}).`,
);
}
return errors;
}
export function TemplateForm({
onSubmit,
onClose,
isSubmitting,
serverError,
}: TemplateFormProps) {
const [name, setName] = useState("");
const [language, setLanguage] = useState("en");
const [category, setCategory] = useState("UTILITY");
const [bodyText, setBodyText] = useState("");
const [footerText, setFooterText] = useState("");
const [headerType, setHeaderType] = useState("none");
const [headerText, setHeaderText] = useState("");
const [validationErrors, setValidationErrors] = useState<string[]>([]);
// Track whether form has been modified
const hasUnsavedChanges =
name !== "" ||
bodyText !== "" ||
footerText !== "" ||
headerText !== "";
// Escape key to close (with unsaved changes warning)
const handleEscKey = useCallback(
(e: KeyboardEvent) => {
Eif (e.key === "Escape") {
if (hasUnsavedChanges) {
const confirmed = window.confirm(
"You have unsaved changes. Are you sure you want to close?",
);
if (!confirmed) return;
}
onClose();
}
},
[onClose, hasUnsavedChanges],
);
useEffect(() => {
document.addEventListener("keydown", handleEscKey);
return () => document.removeEventListener("keydown", handleEscKey);
}, [handleEscKey]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const errors = validateTemplate({
name,
bodyText,
headerType,
headerText,
footerText,
});
if (errors.length > 0) {
setValidationErrors(errors);
return;
}
setValidationErrors([]);
const components: Array<Record<string, unknown>> = [];
if (headerType === "text" && headerText) {
components.push({ type: "HEADER", format: "TEXT", text: headerText });
}
Eif (bodyText) {
const bodyComponent: Record<string, unknown> = {
type: "BODY",
text: bodyText,
};
// Meta requires example values when body has variables like {{1}}, {{2}}
const varMatches = bodyText.match(/\{\{\d+\}\}/g);
if (varMatches) {
const unique = [
...new Set(
varMatches.map((v) =>
Number.parseInt(v.replace(/\{|\}/g, ""), 10),
),
),
].sort((a, b) => a - b);
bodyComponent.example = {
body_text: [unique.map((_, i) => `sample_${i + 1}`)],
};
}
components.push(bodyComponent);
}
if (footerText) {
components.push({ type: "FOOTER", text: footerText });
}
onSubmit({ name, language, category, components });
};
const insertVariable = () => {
const matches = bodyText.match(/\{\{(\d+)\}\}/g) || [];
const uniqueNums = new Set(
matches.map((m) => Number.parseInt(m.replace(/\{|\}/g, ""), 10)),
);
const nextVar = uniqueNums.size > 0 ? Math.max(...uniqueNums) + 1 : 1;
setBodyText((prev) => `${prev}{{${nextVar}}}`);
};
const allErrors = [
...validationErrors,
...(serverError ? [serverError] : []),
];
// Generate preview text by replacing variables with sample values
const previewBody = bodyText.replace(
/\{\{(\d+)\}\}/g,
(_, num) => `[Value ${num}]`,
);
return createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4"
role="dialog"
aria-modal="true"
aria-label="Create Template"
>
{/* Backdrop */}
<div
className="fixed inset-0 bg-overlay-dark"
onClick={onClose}
aria-hidden="true"
/>
{/* Modal content */}
<div className="relative z-10 bg-background-elevated rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
<div className="flex items-center justify-between p-4 border-b border-border-default">
<h2 className="text-lg font-semibold text-foreground-default">
Create Template
</h2>
<button
type="button"
onClick={onClose}
className="p-1 text-foreground-muted hover:text-foreground-default"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-4">
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
{/* Left: Form fields */}
<div className="lg:col-span-3 space-y-4">
{/* Errors */}
{allErrors.length > 0 && (
<div className="rounded-md border border-error bg-error-light dark:bg-error/10 dark:border-error p-3">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-error mt-0.5 flex-shrink-0" />
<div className="text-sm text-error dark:text-error space-y-1">
{allErrors.map((err) => (
<p key={err}>{err}</p>
))}
</div>
</div>
</div>
)}
{/* Name */}
<div>
<label
htmlFor="template-name"
className="block text-sm font-medium text-foreground-default mb-1"
>
Template Name
</label>
<input
id="template-name"
type="text"
value={name}
onChange={(e) => {
setName(
e.target.value
.toLowerCase()
.replace(/[^a-z0-9_]/g, "_"),
);
setValidationErrors([]);
}}
placeholder="e.g., inquiry_notification"
required
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
/>
<p className="mt-1 text-xs text-foreground-subtle">
Lowercase letters, numbers, and underscores only.
</p>
</div>
{/* Category and Language */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label
htmlFor="template-category"
className="block text-sm font-medium text-foreground-default mb-1"
>
Category
</label>
<select
id="template-category"
value={category}
onChange={(e) => setCategory(e.target.value)}
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
>
{CATEGORIES.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
</div>
<div>
<label
htmlFor="template-language"
className="block text-sm font-medium text-foreground-default mb-1"
>
Language
</label>
<select
id="template-language"
value={language}
onChange={(e) => setLanguage(e.target.value)}
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
>
{LANGUAGES.map((l) => (
<option key={l.value} value={l.value}>
{l.label}
</option>
))}
</select>
</div>
</div>
{/* Header */}
<div>
<label
htmlFor="template-header-type"
className="block text-sm font-medium text-foreground-default mb-1"
>
Header
</label>
<select
id="template-header-type"
value={headerType}
onChange={(e) => setHeaderType(e.target.value)}
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
>
<option value="none">None</option>
<option value="text">Text</option>
</select>
{headerType === "text" && (
<>
<input
type="text"
value={headerText}
onChange={(e) => {
setHeaderText(e.target.value);
setValidationErrors([]);
}}
placeholder="Header text"
maxLength={MAX_HEADER_LENGTH}
className="mt-2 w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
/>
<p className="mt-1 text-xs text-foreground-subtle">
{headerText.length}/{MAX_HEADER_LENGTH} characters
</p>
</>
)}
</div>
{/* Body */}
<div>
<div className="flex items-center justify-between mb-1">
<label
htmlFor="template-body"
className="block text-sm font-medium text-foreground-default"
>
Body Text
</label>
<button
type="button"
onClick={insertVariable}
className="text-xs text-whatsapp-green hover:text-whatsapp-green-hover"
>
+ Add Variable
</button>
</div>
<textarea
id="template-body"
value={bodyText}
onChange={(e) => {
setBodyText(e.target.value);
setValidationErrors([]);
}}
placeholder="Hello {{1}}, we received your inquiry for {{2}}. We'll get back to you soon."
rows={4}
required
maxLength={MAX_BODY_LENGTH}
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green resize-none"
/>
<div className="flex items-center justify-between mt-1">
<p className="text-xs text-foreground-subtle">
Variables like {"{{1}}"} are replaced when sending.
Don't start or end with a variable.
</p>
<p className="text-xs text-foreground-subtle">
{bodyText.length}/{MAX_BODY_LENGTH}
</p>
</div>
</div>
{/* Footer */}
<div>
<label
htmlFor="template-footer"
className="block text-sm font-medium text-foreground-default mb-1"
>
Footer (optional)
</label>
<input
id="template-footer"
type="text"
value={footerText}
onChange={(e) => {
setFooterText(e.target.value);
setValidationErrors([]);
}}
placeholder="e.g., Interioring"
maxLength={MAX_FOOTER_LENGTH}
className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-whatsapp-green"
/>
{footerText && (
<p className="mt-1 text-xs text-foreground-subtle">
{footerText.length}/{MAX_FOOTER_LENGTH} characters
</p>
)}
</div>
</div>
{/* Right: Live preview */}
<div className="lg:col-span-2">
<div className="lg:sticky lg:top-4">
<p className="text-xs font-medium text-foreground-muted uppercase tracking-wide mb-2">
Preview
</p>
<WhatsAppMessagePreview
headerText={
headerType === "text" ? headerText || null : null
}
bodyText={previewBody}
footerText={footerText || null}
/>
</div>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 pt-4 mt-4 border-t border-border-default">
<Button
type="button"
variant="outline"
onClick={onClose}
>
Cancel
</Button>
<Button
type="submit"
disabled={!name || !bodyText || isSubmitting}
className="bg-whatsapp-green hover:bg-whatsapp-green-hover"
>
{isSubmitting ? "Creating..." : "Create Template"}
</Button>
</div>
</form>
</div>
</div>,
document.body,
);
}
|