Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertCircle, Copy, FileText, Loader2, Plus, Search, Trash2 } from 'lucide-react';
import { type MessageTemplate, type TemplatePayload } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
import { useToast } from '../hooks/useToast';
import {
useCreateTemplateMutation,
useDeleteTemplateMutation,
useSessionsQuery,
useTemplatesQuery,
useUpdateTemplateMutation,
} from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import { Modal } from '../components/Modal';
import { copyToClipboard } from '../utils/clipboard';
import './Templates.css';
type TemplateForm = {
name: string;
header: string;
body: string;
footer: string;
};
const emptyForm: TemplateForm = {
name: '',
header: '',
body: '',
footer: '',
};
function extractPlaceholders(template: TemplateForm | MessageTemplate) {
const source = [template.header, template.body, template.footer].filter(Boolean).join('\n');
return Array.from(new Set(Array.from(source.matchAll(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g), match => match[1]))).sort();
}
function toPayload(form: TemplateForm): TemplatePayload {
return {
name: form.name.trim(),
header: form.header.trim() || null,
body: form.body.trim(),
footer: form.footer.trim() || null,
};
}
function renderPreview(template: TemplateForm, values: Record<string, string>) {
return [template.header, template.body, template.footer]
.filter(Boolean)
.join('\n\n')
.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, key: string) => values[key] || `{{${key}}}`);
}
export function Templates() {
const { t } = useTranslation();
useDocumentTitle(t('templates.title'));
const { canWrite } = useRole();
const { data: sessions = [], isLoading: loadingSessions, error: sessionsError } = useSessionsQuery();
// A failed read is not "no sessions": the gateway may simply be restarting. A failed background refetch keeps
// the cached list, so only a read that never produced one counts.
const sessionsFailed = !!sessionsError && sessions.length === 0;
const [selectedSessionId, setSelectedSessionId] = useState('');
const [form, setForm] = useState<TemplateForm>(emptyForm);
// The draft on screen now, read by a save that resolves after the operator may have moved on.
const formRef = useRef(form);
useEffect(() => {
formRef.current = form;
}, [form]);
// Bumped whenever the editor starts another draft (new, opened or session switched), unlike edits to the same one.
const draftRef = useRef(0);
const [editingTemplate, setEditingTemplate] = useState<MessageTemplate | null>(null);
const [deleteTarget, setDeleteTarget] = useState<MessageTemplate | null>(null);
const toast = useToast();
const [previewValues, setPreviewValues] = useState<Record<string, string>>({});
const [searchTerm, setSearchTerm] = useState('');
// The template list route is OPERATOR-only and the gateway records every refusal as a failed authentication,
// so a key that cannot write is not sent it.
const {
data: templates = [],
isLoading: loadingTemplates,
error: templatesError,
} = useTemplatesQuery(selectedSessionId, canWrite && !!selectedSessionId);
const createMutation = useCreateTemplateMutation();
const updateMutation = useUpdateTemplateMutation();
const deleteMutation = useDeleteTemplateMutation();
const selectedSession = sessions.find(session => session.id === selectedSessionId);
const placeholders = useMemo(() => extractPlaceholders(form), [form]);
const preview = useMemo(() => renderPreview(form, previewValues), [form, previewValues]);
const filteredTemplates = useMemo(() => {
const query = searchTerm.trim().toLowerCase();
if (!query) return templates;
return templates.filter(template =>
[template.name, template.header, template.body, template.footer]
.filter(Boolean)
.some(value => value!.toLowerCase().includes(query)),
);
}, [searchTerm, templates]);
const isSaving = createMutation.isPending || updateMutation.isPending;
// The row whose update is in flight: the list shows its pre-save values until the update settles, and
// reopening it then would load them into the editor to be saved back. Every other row is current.
const updatingId = updateMutation.isPending ? updateMutation.variables?.id : undefined;
// Select the first session, and again once the selected one is gone (deleted elsewhere): a stale id
// matches no option, so the select would show another session while every read and write still
// went to the deleted one.
useEffect(() => {
if (sessions.some(session => session.id === selectedSessionId)) return;
const next = sessions[0]?.id ?? '';
if (next === selectedSessionId) return;
setSelectedSessionId(next);
draftRef.current += 1;
setForm(emptyForm);
setEditingTemplate(null);
setPreviewValues({});
}, [selectedSessionId, sessions]);
useEffect(() => {
setPreviewValues(current => {
const next: Record<string, string> = {};
for (const key of placeholders) {
next[key] = current[key] || '';
}
return next;
});
}, [placeholders]);
const resetForm = () => {
draftRef.current += 1;
setForm(emptyForm);
setEditingTemplate(null);
setPreviewValues({});
};
const openEdit = (template: MessageTemplate) => {
draftRef.current += 1;
setEditingTemplate(template);
setForm({
name: template.name,
header: template.header || '',
body: template.body,
footer: template.footer || '',
});
// An explicit smooth ignores the CSS scroll-behavior, so the preference is asked for here.
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
};
const handleSave = async () => {
if (!selectedSessionId || !form.name.trim() || !form.body.trim()) return;
const savedForm = form;
const draft = draftRef.current;
try {
let saved: MessageTemplate;
if (editingTemplate) {
saved = await updateMutation.mutateAsync({
sessionId: selectedSessionId,
id: editingTemplate.id,
data: toPayload(form),
});
toast.success(t('templates.toasts.updated'));
} else {
saved = await createMutation.mutateAsync({
sessionId: selectedSessionId,
data: toPayload(form),
});
toast.success(t('templates.toasts.created'));
}
// Edits typed into this draft while the save was in flight stay on screen; point them at the saved
// row so the next save updates it (a second create would fail the unique name check) and the
// editor header reflects the stored name.
if (draftRef.current === draft && formRef.current !== savedForm) setEditingTemplate(saved);
// Every edit, template switch and session switch replaces the form object, so a save that
// resolves after any of them must leave the newer draft alone.
if (formRef.current === savedForm) resetForm();
} catch (err) {
toast.error(
t(editingTemplate ? 'templates.toasts.updateFailed' : 'templates.toasts.createFailed', {
message: err instanceof Error ? err.message : t('common.unknownError'),
}),
);
}
};
const handleDelete = async () => {
if (!selectedSessionId || !deleteTarget) return;
const draft = draftRef.current;
try {
await deleteMutation.mutateAsync({ sessionId: selectedSessionId, id: deleteTarget.id });
toast.success(t('templates.toasts.deleted'));
if (draftRef.current === draft && editingTemplate?.id === deleteTarget.id) resetForm();
setDeleteTarget(current => (current === deleteTarget ? null : current));
} catch (err) {
toast.error(
t('templates.toasts.deleteFailed', {
message: err instanceof Error ? err.message : t('common.unknownError'),
}),
);
}
};
const copyName = async (name: string) => {
if (await copyToClipboard(name)) {
toast.success(t('templates.toasts.copied'));
}
};
if (loadingSessions) {
return (
<div className="templates-page templates-loading">
<Loader2 className="animate-spin" size={32} />
</div>
);
}
return (
<div className="templates-page">
<PageHeader
title={t('templates.title')}
subtitle={t('templates.subtitle')}
actions={
<select
className="templates-session-select"
aria-label={t('templates.sessionSelect')}
value={selectedSessionId}
onChange={event => {
setSelectedSessionId(event.target.value);
resetForm();
}}
>
{sessions.length === 0 && (
<option value="">{t(sessionsFailed ? 'dashboard.loadError' : 'templates.noSessions')}</option>
)}
{sessions.map(session => (
<option key={session.id} value={session.id}>
{session.name}
</option>
))}
</select>
}
/>
{sessionsFailed ? (
<div className="templates-empty-page" role="alert">
<AlertCircle size={48} strokeWidth={1} />
<h3>{t('dashboard.loadError')}</h3>
<p>{sessionsError.message}</p>
</div>
) : sessions.length === 0 ? (
<div className="templates-empty-page">
<FileText size={48} strokeWidth={1} />
<h3>{t('templates.empty.noSessionsTitle')}</h3>
<p>{t('templates.empty.noSessionsDesc')}</p>
</div>
) : (
<div className="templates-workspace">
<aside className="templates-library">
<div className="templates-library-header">
<div>
<h2>{t('templates.savedTitle')}</h2>
<span>{t('templates.count', { count: templates.length })}</span>
</div>
<button className="btn-primary templates-new-btn" onClick={resetForm} disabled={!canWrite}>
<Plus size={16} />
{t('templates.newTemplate')}
</button>
</div>
<div className="templates-search">
<Search size={16} />
<input
value={searchTerm}
onChange={event => setSearchTerm(event.target.value)}
placeholder={t('common.search')}
/>
</div>
{/* No session selected yet means the first-session effect has not run: the read is still to start. */}
{loadingTemplates || !selectedSessionId ? (
<div className="templates-loading-inline">
<Loader2 className="animate-spin" size={24} />
</div>
) : (templatesError || !canWrite) && templates.length === 0 ? (
// A failed read is not an empty library: a key below operator is refused here (the route is
// OPERATOR-only, so it is never sent), and a gateway error would otherwise read as "no templates
// saved". The 403 branch stays for a key whose role the page took for a writer's.
<div className="templates-empty-list" role="alert">
<AlertCircle size={40} strokeWidth={1} />
{!canWrite || (templatesError as { status?: number } | null)?.status === 403 ? (
<>
<h3>{t('templates.empty.forbiddenTitle')}</h3>
<p>{t('templates.empty.forbiddenDesc')}</p>
</>
) : (
<>
<h3>{t('templates.empty.loadErrorTitle')}</h3>
<p>{templatesError?.message}</p>
</>
)}
</div>
) : templates.length === 0 ? (
<div className="templates-empty-list">
<FileText size={40} strokeWidth={1} />
<h3>{t('templates.empty.title')}</h3>
<p>{t('templates.empty.description')}</p>
</div>
) : filteredTemplates.length === 0 ? (
<div className="templates-empty-list compact">
<Search size={32} strokeWidth={1.5} />
<h3>{t('templates.empty.noMatch', 'No templates match your search.')}</h3>
</div>
) : (
<div className="template-list" role="list">
{filteredTemplates.map(template => {
const templatePlaceholders = extractPlaceholders(template);
const isSelected = editingTemplate?.id === template.id;
return (
<div
key={template.id}
className={`template-list-row ${canWrite ? 'deletable' : ''}`}
role="listitem"
>
<button
className={`template-list-item ${isSelected ? 'selected' : ''}`}
onClick={() => openEdit(template)}
disabled={template.id === updatingId}
type="button"
>
<span className="template-list-title">{template.name}</span>
<span className="template-list-body">{template.body}</span>
<span className="template-list-meta">
{templatePlaceholders.length > 0
? templatePlaceholders.map(key => `{{${key}}}`).join(' ')
: t('templates.noPlaceholders')}
</span>
</button>
{canWrite && (
<button
className="icon-btn danger template-list-delete"
title={t('common.delete')}
aria-label={t('common.delete')}
onClick={() => setDeleteTarget({ ...template })}
type="button"
>
<Trash2 size={14} />
</button>
)}
</div>
);
})}
</div>
)}
</aside>
<section className="template-editor">
<div className="template-editor-header">
<div>
<h2>{editingTemplate ? t('templates.editTitle') : t('templates.createTitle')}</h2>
<p>{selectedSession ? t('templates.sessionHint', { name: selectedSession.name }) : ''}</p>
</div>
<div className="template-header-actions">
{editingTemplate && (
<button
className="icon-btn"
title={t('templates.actions.copyName')}
onClick={() => void copyName(editingTemplate.name)}
type="button"
>
<Copy size={16} />
</button>
)}
{editingTemplate && canWrite && (
<button
className="icon-btn danger"
title={t('common.delete')}
onClick={() => setDeleteTarget({ ...editingTemplate })}
type="button"
>
<Trash2 size={16} />
</button>
)}
</div>
</div>
<div className="template-form">
<div className="form-group">
<label htmlFor="tpl-1">{t('common.name')}</label>
<input
id="tpl-1"
value={form.name}
onChange={event => setForm({ ...form, name: event.target.value })}
placeholder={t('templates.namePlaceholder')}
disabled={!canWrite}
/>
</div>
<div className="template-message-fields">
<div className="form-group">
<label htmlFor="tpl-2">{t('templates.header')}</label>
<input
id="tpl-2"
value={form.header}
onChange={event => setForm({ ...form, header: event.target.value })}
placeholder={t('templates.headerPlaceholder')}
disabled={!canWrite}
/>
</div>
<div className="form-group body-field">
<label htmlFor="tpl-3">{t('templates.body')}</label>
<textarea
id="tpl-3"
value={form.body}
onChange={event => setForm({ ...form, body: event.target.value })}
placeholder={t('templates.bodyPlaceholder')}
rows={10}
disabled={!canWrite}
/>
</div>
<div className="form-group">
<label htmlFor="tpl-4">{t('templates.footer')}</label>
<input
id="tpl-4"
value={form.footer}
onChange={event => setForm({ ...form, footer: event.target.value })}
placeholder={t('templates.footerPlaceholder')}
disabled={!canWrite}
/>
</div>
</div>
<div className="template-editor-actions">
<button className="btn-secondary" onClick={resetForm} disabled={isSaving} type="button">
{t('common.cancel')}
</button>
<button
className="btn-primary"
onClick={handleSave}
disabled={!canWrite || isSaving || !selectedSessionId || !form.name.trim() || !form.body.trim()}
type="button"
>
{isSaving ? <Loader2 size={18} className="animate-spin" /> : <Plus size={18} />}
{canWrite
? t(editingTemplate ? 'templates.saveChanges' : 'templates.createTemplate')
: t('templates.viewOnly')}
</button>
</div>
</div>
</section>
<aside className="template-preview">
<div className="template-preview-header">
<h2>{t('templates.previewTitle')}</h2>
<span>{placeholders.length}</span>
</div>
<div className="template-preview-message">
<pre>{preview || t('templates.previewEmpty')}</pre>
</div>
<div className="template-variable-panel">
{placeholders.length > 0 ? (
<div className="placeholder-list">
{placeholders.map(key => (
<label key={key}>
<span>{`{{${key}}}`}</span>
<input
value={previewValues[key] || ''}
onChange={event => setPreviewValues({ ...previewValues, [key]: event.target.value })}
placeholder={t('templates.previewValuePlaceholder')}
/>
</label>
))}
</div>
) : (
<p className="template-muted">{t('templates.noPlaceholders')}</p>
)}
</div>
</aside>
</div>
)}
{deleteTarget && (
<Modal
open
onClose={() => setDeleteTarget(null)}
title={t('templates.deleteTitle')}
className="modal-sm"
closeLabel={t('common.close')}
footer={
<>
<button className="btn-secondary" onClick={() => setDeleteTarget(null)}>
{t('common.cancel')}
</button>
<button className="btn-danger" onClick={handleDelete} disabled={deleteMutation.isPending}>
{deleteMutation.isPending ? <Loader2 size={18} className="animate-spin" /> : <Trash2 size={18} />}
{t('common.delete')}
</button>
</>
}
>
<p>{t('templates.deleteConfirm', { name: deleteTarget.name })}</p>
</Modal>
)}
</div>
);
}