feat: add email templates with placeholder variables and composer integration

- Reusable email templates with local storage persistence
- Dynamic placeholder variables ({{recipientName}}, {{date}}, etc.) with auto-fill
- Template manager modal with category filtering and search
- Template picker integrated in composer toolbar (Ctrl+Shift+T)
- Settings tab for template management
- 48 unit tests for template utilities
- i18n support for all 8 languages
This commit is contained in:
Matthieu MALVACHE
2026-02-17 01:35:26 +01:00
committed by Matthieu MALVACHE
parent b65b2f26df
commit 2636a88820
23 changed files with 2422 additions and 36 deletions
+115 -2
View File
@@ -1,15 +1,21 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle } from "lucide-react";
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus } from "lucide-react";
import { cn } from "@/lib/utils";
import { useAuthStore } from "@/stores/auth-store";
import { useContactStore } from "@/stores/contact-store";
import { useTemplateStore } from "@/stores/template-store";
import { SubAddressHelper } from "@/components/identity/sub-address-helper";
import { generateSubAddress } from "@/lib/sub-addressing";
import { substitutePlaceholders } from "@/lib/template-utils";
import { TemplatePicker } from "@/components/templates/template-picker";
import { TemplateForm } from "@/components/templates/template-form";
import type { EmailTemplate } from "@/lib/template-types";
interface EmailComposerProps {
onSend?: (data: {
@@ -107,9 +113,18 @@ export function EmailComposer({
const fileInputRef = useRef<HTMLInputElement>(null);
const [selectedIdentityId, setSelectedIdentityId] = useState<string | null>(null);
const [subAddressTag, setSubAddressTag] = useState<string>('');
const [showTemplatePicker, setShowTemplatePicker] = useState(false);
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false);
const saveTemplateModalRef = useFocusTrap({
isActive: showSaveAsTemplate,
onEscape: () => setShowSaveAsTemplate(false),
restoreFocus: true,
});
const { client, identities, primaryIdentity } = useAuthStore();
const getAutocomplete = useContactStore((s) => s.getAutocomplete);
const addTemplate = useTemplateStore((s) => s.addTemplate);
const [autocompleteResults, setAutocompleteResults] = useState<Array<{ name: string; email: string }>>([]);
const [activeAutoField, setActiveAutoField] = useState<'to' | 'cc' | 'bcc' | null>(null);
const [autoSelectedIndex, setAutoSelectedIndex] = useState(-1);
@@ -174,6 +189,52 @@ export function EmailComposer({
}
};
const handleTemplateSelect = useCallback((template: EmailTemplate, filledValues: Record<string, string>) => {
const filledSubject = Object.keys(filledValues).length > 0
? substitutePlaceholders(template.subject, filledValues)
: template.subject;
const filledBody = Object.keys(filledValues).length > 0
? substitutePlaceholders(template.body, filledValues)
: template.body;
if (mode === 'compose') {
setSubject(filledSubject);
setBody(filledBody);
if (template.defaultRecipients?.to?.length) {
setTo(template.defaultRecipients.to.join(', '));
}
if (template.defaultRecipients?.cc?.length) {
setCc(template.defaultRecipients.cc.join(', '));
setShowCc(true);
}
if (template.defaultRecipients?.bcc?.length) {
setBcc(template.defaultRecipients.bcc.join(', '));
setShowBcc(true);
}
} else {
setBody((prev) => filledBody + prev);
}
if (template.identityId) {
setSelectedIdentityId(template.identityId);
}
setShowTemplatePicker(false);
}, [mode]);
useEffect(() => {
const handleTemplateKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName?.toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
setShowTemplatePicker(true);
}
};
window.addEventListener('keydown', handleTemplateKey);
return () => window.removeEventListener('keydown', handleTemplateKey);
}, []);
// Handle file selection
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!client || !event.target.files) return;
@@ -663,8 +724,25 @@ export function EmailComposer({
{t('discard')}
</button>
{/* Right side - Attach and Send */}
{/* Right side - Template, Save as Template, Attach and Send */}
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => setShowTemplatePicker(true)}
title={t('use_template')}
>
<FileText className="w-4 h-4 mr-2" />
{t('use_template')}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setShowSaveAsTemplate(true)}
title={t('save_as_template')}
>
<BookmarkPlus className="w-4 h-4" />
</Button>
<input
ref={fileInputRef}
type="file"
@@ -688,6 +766,41 @@ export function EmailComposer({
</div>
</div>
</div>
{showTemplatePicker && (
<TemplatePicker
isOpen={showTemplatePicker}
onClose={() => setShowTemplatePicker(false)}
onSelect={handleTemplateSelect}
/>
)}
{showSaveAsTemplate && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-150">
<div
ref={saveTemplateModalRef}
role="dialog"
aria-modal="true"
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-lg p-6 animate-in zoom-in-95 duration-200"
>
<h3 className="text-lg font-semibold text-foreground mb-4">{t('save_as_template')}</h3>
<TemplateForm
initialData={{
subject,
body,
to: to.split(',').map(s => s.trim()).filter(Boolean),
cc: cc.split(',').map(s => s.trim()).filter(Boolean),
bcc: bcc.split(',').map(s => s.trim()).filter(Boolean),
}}
onSave={(data) => {
addTemplate(data);
setShowSaveAsTemplate(false);
}}
onCancel={() => setShowSaveAsTemplate(false)}
/>
</div>
</div>
)}
</div>
);
}
+16
View File
@@ -135,6 +135,22 @@ export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsMod
))}
</div>
</section>
{/* Composer Section */}
<section className="md:col-span-2">
<h3 className="text-sm font-semibold text-foreground mb-3 uppercase tracking-wider">
{t("shortcuts.sections.composer")}
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{KEYBOARD_SHORTCUTS.composer.map((shortcut) => (
<ShortcutRow
key={shortcut.key}
shortcutKey={shortcut.key}
description={t(shortcut.description)}
/>
))}
</div>
</section>
</div>
{/* Footer tip */}
+138
View File
@@ -0,0 +1,138 @@
'use client';
import { useState, useRef } from 'react';
import { useTranslations } from 'next-intl';
import { SettingsSection } from './settings-section';
import { Button } from '@/components/ui/button';
import { TemplateManagerModal } from '@/components/templates/template-manager-modal';
import { useTemplateStore } from '@/stores/template-store';
import { toast } from '@/stores/toast-store';
import { debug } from '@/lib/debug';
import {
FileText,
Download,
Upload,
} from 'lucide-react';
const MAX_IMPORT_FILE_SIZE = 1 * 1024 * 1024;
export function TemplateSettings() {
const t = useTranslations('settings.templates');
const tNotif = useTranslations('notifications');
const { templates, exportAllTemplates, importTemplates: storeImport } = useTemplateStore();
const [showManager, setShowManager] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleExport = () => {
const json = exportAllTemplates();
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'email-templates.json';
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
toast.success(tNotif('templates_exported'));
};
const resetFileInput = () => {
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
if (file.size > MAX_IMPORT_FILE_SIZE) {
toast.error(tNotif('templates_import_errors'));
resetFileInput();
return;
}
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target?.result as string;
const result = storeImport(content);
if (result.errors.length > 0) {
toast.error(tNotif('templates_import_errors'));
} else if (result.count > 0) {
toast.success(tNotif('templates_imported', { count: result.count }));
} else {
toast.error(tNotif('templates_import_empty'));
}
resetFileInput();
};
reader.onerror = () => {
debug.error('FileReader error during template import:', reader.error);
toast.error(tNotif('templates_import_errors'));
resetFileInput();
};
reader.readAsText(file);
};
return (
<div className="space-y-6">
<SettingsSection title={t('title')} description={t('description')}>
<div className="flex items-center justify-between py-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<FileText className="w-4 h-4" />
<span>
{t('count', { count: templates.length })}
</span>
</div>
<Button
variant="outline"
size="sm"
onClick={() => setShowManager(true)}
>
{t('manage')}
</Button>
</div>
</SettingsSection>
<SettingsSection title={t('export_import')} description={t('export_import_description')}>
<div className="flex items-center gap-3 py-3">
<Button
variant="outline"
size="sm"
onClick={handleExport}
disabled={templates.length === 0}
>
<Download className="w-4 h-4 mr-1" />
{t('export')}
</Button>
<div>
<input
ref={fileInputRef}
type="file"
accept=".json"
onChange={handleImport}
className="hidden"
/>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="w-4 h-4 mr-1" />
{t('import')}
</Button>
</div>
</div>
</SettingsSection>
{showManager && (
<TemplateManagerModal
isOpen={showManager}
onClose={() => setShowManager(false)}
/>
)}
</div>
);
}
@@ -0,0 +1,114 @@
'use client';
import { useState, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { substitutePlaceholders, isBuiltInPlaceholder } from '@/lib/template-utils';
import { useFocusTrap } from '@/hooks/use-focus-trap';
import type { EmailTemplate } from '@/lib/template-types';
interface PlaceholderFillModalProps {
template: EmailTemplate;
placeholders: string[];
autoFilled: Record<string, string>;
onConfirm: (values: Record<string, string>) => void;
onSkip: () => void;
onClose: () => void;
}
export function PlaceholderFillModal({
template,
placeholders,
autoFilled,
onConfirm,
onSkip,
onClose,
}: PlaceholderFillModalProps) {
const t = useTranslations('templates');
const [values, setValues] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = {};
for (const p of placeholders) {
initial[p] = autoFilled[p] || '';
}
return initial;
});
const modalRef = useFocusTrap({
isActive: true,
onEscape: onClose,
restoreFocus: true,
});
const preview = useMemo(() => {
return substitutePlaceholders(template.body, values);
}, [template.body, values]);
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150">
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby="placeholder-fill-title"
className={cn(
'bg-background border border-border rounded-lg shadow-xl',
'w-full max-w-lg max-h-[85vh] overflow-hidden',
'animate-in zoom-in-95 duration-200'
)}
>
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
<h2 id="placeholder-fill-title" className="text-lg font-semibold text-foreground">
{t('fill_placeholders')}
</h2>
<button
onClick={onClose}
className="p-2 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="p-6 overflow-y-auto max-h-[calc(85vh-160px)] space-y-4">
{placeholders.map((p) => (
<div key={p}>
<label className="text-sm font-medium text-foreground flex items-center gap-2">
<span className="font-mono text-xs text-primary">{`{{${p}}}`}</span>
{isBuiltInPlaceholder(p) && (
<span className="text-xs text-muted-foreground">{t(`placeholders.${p}`)}</span>
)}
</label>
<Input
value={values[p]}
onChange={(e) => setValues((prev) => ({ ...prev, [p]: e.target.value }))}
placeholder={t('enter_value')}
className="mt-1"
/>
</div>
))}
{preview && (
<div className="mt-4 pt-4 border-t border-border">
<p className="text-xs font-medium text-muted-foreground mb-2">{t('preview')}</p>
<div className="text-sm text-foreground whitespace-pre-wrap p-3 rounded-md bg-muted/50 border border-border max-h-32 overflow-y-auto">
{preview}
</div>
</div>
)}
</div>
<div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-border">
<Button variant="ghost" size="sm" onClick={onSkip}>
{t('insert_raw')}
</Button>
<Button size="sm" onClick={() => onConfirm(values)}>
{t('insert_with_values')}
</Button>
</div>
</div>
</div>
);
}
+295
View File
@@ -0,0 +1,295 @@
'use client';
import { useState, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Star, Plus } from 'lucide-react';
import { cn } from '@/lib/utils';
import { validateTemplateName } from '@/lib/template-utils';
import { BUILT_IN_PLACEHOLDERS } from '@/lib/template-types';
import type { EmailTemplate } from '@/lib/template-types';
import { useTemplateStore } from '@/stores/template-store';
import { useAuthStore } from '@/stores/auth-store';
interface TemplateFormProps {
template?: EmailTemplate;
initialData?: {
subject?: string;
body?: string;
to?: string[];
cc?: string[];
bcc?: string[];
};
onSave: (data: Omit<EmailTemplate, 'id' | 'createdAt' | 'updatedAt'>) => void;
onCancel: () => void;
}
export function TemplateForm({ template, initialData, onSave, onCancel }: TemplateFormProps) {
const t = useTranslations('templates');
const tSettings = useTranslations('settings.templates');
const tComposer = useTranslations('email_composer');
const { identities } = useAuthStore();
const templates = useTemplateStore((s) => s.templates);
const [name, setName] = useState(template?.name || '');
const [category, setCategory] = useState(template?.category || '');
const [subject, setSubject] = useState(template?.subject || initialData?.subject || '');
const [body, setBody] = useState(template?.body || initialData?.body || '');
const [toRecipients, setToRecipients] = useState(
template?.defaultRecipients?.to?.join(', ') || initialData?.to?.join(', ') || ''
);
const [ccRecipients, setCcRecipients] = useState(
template?.defaultRecipients?.cc?.join(', ') || initialData?.cc?.join(', ') || ''
);
const [bccRecipients, setBccRecipients] = useState(
template?.defaultRecipients?.bcc?.join(', ') || initialData?.bcc?.join(', ') || ''
);
const [identityId, setIdentityId] = useState(template?.identityId || '');
const [isFavorite, setIsFavorite] = useState(template?.isFavorite || false);
const [nameError, setNameError] = useState<string | null>(null);
const [showPlaceholderMenu, setShowPlaceholderMenu] = useState<'subject' | 'body' | null>(null);
const existingCategories = useMemo(() => {
const cats = new Set(templates.map((t) => t.category).filter(Boolean));
return Array.from(cats).sort();
}, [templates]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const error = validateTemplateName(name);
if (error) {
setNameError(error);
return;
}
const parseRecipients = (val: string) =>
val.split(',').map((s) => s.trim()).filter(Boolean);
const to = parseRecipients(toRecipients);
const cc = parseRecipients(ccRecipients);
const bcc = parseRecipients(bccRecipients);
onSave({
name: name.trim(),
subject,
body,
category: category.trim(),
defaultRecipients: to.length || cc.length || bcc.length
? { to: to.length ? to : undefined, cc: cc.length ? cc : undefined, bcc: bcc.length ? bcc : undefined }
: undefined,
identityId: identityId || undefined,
isFavorite,
});
};
const insertPlaceholder = (placeholder: string, field: 'subject' | 'body') => {
const tag = `{{${placeholder}}}`;
if (field === 'subject') {
setSubject((prev) => prev + tag);
} else {
setBody((prev) => prev + tag);
}
setShowPlaceholderMenu(null);
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="text-sm font-medium text-foreground">{tSettings('name')}</label>
<Input
value={name}
onChange={(e) => { setName(e.target.value); setNameError(null); }}
placeholder={tSettings('name_placeholder')}
className={cn('mt-1', nameError && 'border-red-500')}
autoFocus
/>
{nameError && (
<p className="text-xs text-red-600 dark:text-red-400 mt-1">
{tSettings(`validation.${nameError}`)}
</p>
)}
</div>
<div>
<label className="text-sm font-medium text-foreground">{tSettings('category')}</label>
<Input
value={category}
onChange={(e) => setCategory(e.target.value)}
placeholder={tSettings('category_placeholder')}
className="mt-1"
list="template-categories"
/>
{existingCategories.length > 0 && (
<datalist id="template-categories">
{existingCategories.map((cat) => (
<option key={cat} value={cat} />
))}
</datalist>
)}
</div>
<div>
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-foreground">{tSettings('subject')}</label>
<div className="relative">
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={() => setShowPlaceholderMenu(showPlaceholderMenu === 'subject' ? null : 'subject')}
>
<Plus className="w-3 h-3 mr-1" />
{t('placeholder')}
</Button>
{showPlaceholderMenu === 'subject' && (
<PlaceholderDropdown
onSelect={(p) => insertPlaceholder(p, 'subject')}
onClose={() => setShowPlaceholderMenu(null)}
/>
)}
</div>
</div>
<Input
value={subject}
onChange={(e) => setSubject(e.target.value)}
placeholder={tSettings('subject_placeholder')}
className="mt-1"
/>
</div>
<div>
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-foreground">{tSettings('body')}</label>
<div className="relative">
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={() => setShowPlaceholderMenu(showPlaceholderMenu === 'body' ? null : 'body')}
>
<Plus className="w-3 h-3 mr-1" />
{t('placeholder')}
</Button>
{showPlaceholderMenu === 'body' && (
<PlaceholderDropdown
onSelect={(p) => insertPlaceholder(p, 'body')}
onClose={() => setShowPlaceholderMenu(null)}
/>
)}
</div>
</div>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder={tSettings('body_placeholder')}
rows={6}
className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-y"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div>
<label className="text-sm font-medium text-foreground">{tComposer('to')}</label>
<Input
value={toRecipients}
onChange={(e) => setToRecipients(e.target.value)}
placeholder={tSettings('recipients_placeholder')}
className="mt-1"
/>
</div>
<div>
<label className="text-sm font-medium text-foreground">{tComposer('cc')}</label>
<Input
value={ccRecipients}
onChange={(e) => setCcRecipients(e.target.value)}
placeholder={tSettings('recipients_placeholder')}
className="mt-1"
/>
</div>
<div>
<label className="text-sm font-medium text-foreground">{tComposer('bcc')}</label>
<Input
value={bccRecipients}
onChange={(e) => setBccRecipients(e.target.value)}
placeholder={tSettings('recipients_placeholder')}
className="mt-1"
/>
</div>
</div>
{identities.length > 1 && (
<div>
<label className="text-sm font-medium text-foreground">{tSettings('identity')}</label>
<select
value={identityId}
onChange={(e) => setIdentityId(e.target.value)}
className="mt-1 w-full px-3 py-2 text-sm rounded-md bg-background border border-border text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="">{tSettings('default_identity')}</option>
{identities.map((id) => (
<option key={id.id} value={id.id}>
{id.name ? `${id.name} <${id.email}>` : id.email}
</option>
))}
</select>
</div>
)}
<div className="flex items-center justify-between pt-2">
<button
type="button"
onClick={() => setIsFavorite(!isFavorite)}
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<Star className={cn('w-4 h-4', isFavorite && 'fill-amber-400 text-amber-400')} />
{tSettings('favorite')}
</button>
<div className="flex gap-2">
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
{tSettings('cancel')}
</Button>
<Button type="submit" size="sm">
{template ? tSettings('update') : tSettings('create')}
</Button>
</div>
</div>
</form>
);
}
function PlaceholderDropdown({
onSelect,
onClose,
}: {
onSelect: (name: string) => void;
onClose: () => void;
}) {
const t = useTranslations('templates');
return (
<>
<div className="fixed inset-0 z-40" onClick={onClose} />
<div className="absolute right-0 top-full mt-1 z-50 bg-popover border border-border rounded-md shadow-lg min-w-[180px]">
<div className="p-1">
{BUILT_IN_PLACEHOLDERS.map((p) => (
<button
key={p}
type="button"
className="w-full text-left px-3 py-1.5 text-sm rounded hover:bg-muted transition-colors"
onClick={() => onSelect(p)}
>
<span className="font-mono text-xs text-primary">{`{{${p}}}`}</span>
<span className="ml-2 text-muted-foreground">{t(`placeholders.${p}`)}</span>
</button>
))}
</div>
</div>
</>
);
}
@@ -0,0 +1,245 @@
'use client';
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { X, FileText, Pencil, Trash2, Star, Copy, Search } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { TemplateForm } from './template-form';
import { useTemplateStore } from '@/stores/template-store';
import { useFocusTrap } from '@/hooks/use-focus-trap';
import type { EmailTemplate } from '@/lib/template-types';
interface TemplateManagerModalProps {
isOpen: boolean;
onClose: () => void;
}
export function TemplateManagerModal({ isOpen, onClose }: TemplateManagerModalProps) {
const t = useTranslations('templates');
const tSettings = useTranslations('settings.templates');
const {
templates,
addTemplate,
updateTemplate,
deleteTemplate,
duplicateTemplate,
toggleFavorite,
searchTemplates,
} = useTemplateStore();
const [editingId, setEditingId] = useState<string | null>(null);
const [isCreating, setIsCreating] = useState(false);
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const modalRef = useFocusTrap({
isActive: isOpen,
onEscape: () => {
if (isCreating || editingId) {
setIsCreating(false);
setEditingId(null);
} else {
onClose();
}
},
restoreFocus: true,
});
const filtered = searchQuery ? searchTemplates(searchQuery) : templates;
const handleSave = (data: Omit<EmailTemplate, 'id' | 'createdAt' | 'updatedAt'>) => {
if (editingId) {
updateTemplate(editingId, data);
setEditingId(null);
} else {
addTemplate(data);
setIsCreating(false);
}
};
const handleDelete = (id: string) => {
deleteTemplate(id);
setDeleteConfirmId(null);
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-150">
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby="template-manager-title"
className={cn(
'bg-background border border-border rounded-lg shadow-xl',
'w-full max-w-3xl max-h-[90vh] overflow-hidden',
'animate-in zoom-in-95 duration-200'
)}
>
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
<div className="flex items-center gap-3">
<FileText className="w-5 h-5 text-muted-foreground" />
<h2 id="template-manager-title" className="text-lg font-semibold text-foreground">
{tSettings('title')}
</h2>
</div>
<button
onClick={onClose}
className="p-2 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="p-6 overflow-y-auto max-h-[calc(90vh-80px)]">
{!isCreating && !editingId && (
<div className="flex items-center gap-3 mb-4">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('search_placeholder')}
className="pl-9"
/>
</div>
<Button
onClick={() => setIsCreating(true)}
size="sm"
>
{tSettings('add')}
</Button>
</div>
)}
{isCreating && (
<div className="mb-6 p-4 border border-border rounded-lg bg-muted/30">
<h3 className="text-sm font-semibold mb-4">{tSettings('add')}</h3>
<TemplateForm
onSave={handleSave}
onCancel={() => setIsCreating(false)}
/>
</div>
)}
{editingId && (
<div className="mb-6 p-4 border border-border rounded-lg bg-muted/30">
<h3 className="text-sm font-semibold mb-4">{tSettings('edit')}</h3>
<TemplateForm
template={templates.find((t) => t.id === editingId)}
onSave={handleSave}
onCancel={() => setEditingId(null)}
/>
</div>
)}
<div className="space-y-2">
{filtered.map((template) => (
<div
key={template.id}
className="flex items-center gap-3 p-3 rounded-md border border-border hover:bg-muted/50 transition-colors"
>
<button
type="button"
onClick={() => toggleFavorite(template.id)}
className="flex-shrink-0"
>
<Star
className={cn(
'w-4 h-4 transition-colors',
template.isFavorite
? 'fill-amber-400 text-amber-400'
: 'text-muted-foreground hover:text-amber-400'
)}
/>
</button>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-foreground truncate">
{template.name}
</p>
{template.category && (
<span className="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary font-medium flex-shrink-0">
{template.category}
</span>
)}
</div>
{template.subject && (
<p className="text-xs text-muted-foreground truncate mt-0.5">
{template.subject}
</p>
)}
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<Button
variant="ghost"
size="sm"
onClick={() => { setEditingId(template.id); setIsCreating(false); }}
disabled={!!editingId || isCreating}
className="h-8 w-8 p-0"
>
<Pencil className="w-3.5 h-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => duplicateTemplate(template.id, t('copy_suffix'))}
disabled={!!editingId || isCreating}
className="h-8 w-8 p-0"
>
<Copy className="w-3.5 h-3.5" />
</Button>
{deleteConfirmId === template.id ? (
<div className="flex items-center gap-1">
<Button
variant="destructive"
size="sm"
onClick={() => handleDelete(template.id)}
className="h-7 text-xs"
>
{tSettings('confirm_delete')}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteConfirmId(null)}
className="h-7 text-xs"
>
{tSettings('cancel')}
</Button>
</div>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteConfirmId(template.id)}
disabled={!!editingId || isCreating}
className="h-8 w-8 p-0 hover:text-red-600 dark:hover:text-red-400"
>
<Trash2 className="w-3.5 h-3.5" />
</Button>
)}
</div>
</div>
))}
{filtered.length === 0 && !isCreating && (
<div className="flex flex-col items-center py-8 text-muted-foreground">
<FileText className="w-10 h-10 mb-3 opacity-40" />
<p className="text-sm">
{searchQuery ? t('no_results') : tSettings('no_templates')}
</p>
</div>
)}
</div>
</div>
</div>
</div>
);
}
+214
View File
@@ -0,0 +1,214 @@
'use client';
import { useState } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { X, Search, Star, FileText } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Input } from '@/components/ui/input';
import { useTemplateStore } from '@/stores/template-store';
import { useAuthStore } from '@/stores/auth-store';
import { useFocusTrap } from '@/hooks/use-focus-trap';
import {
getPlaceholdersFromTemplate,
getAutoFilledPlaceholders,
} from '@/lib/template-utils';
import { PlaceholderFillModal } from './placeholder-fill-modal';
import type { EmailTemplate } from '@/lib/template-types';
interface TemplatePickerProps {
isOpen: boolean;
onClose: () => void;
onSelect: (template: EmailTemplate, filledValues: Record<string, string>) => void;
}
export function TemplatePicker({ isOpen, onClose, onSelect }: TemplatePickerProps) {
const t = useTranslations('templates');
const locale = useLocale();
const { templates, getFavorites, getRecent, getTemplatesByCategory, searchTemplates, recordUsage } =
useTemplateStore();
const { primaryIdentity } = useAuthStore();
const [searchQuery, setSearchQuery] = useState('');
const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplate | null>(null);
const [showFillModal, setShowFillModal] = useState(false);
const modalRef = useFocusTrap({
isActive: isOpen && !showFillModal,
onEscape: onClose,
restoreFocus: true,
});
const favorites = getFavorites();
const recent = getRecent();
const byCategory = getTemplatesByCategory();
const filtered = searchQuery ? searchTemplates(searchQuery) : null;
const handleSelectTemplate = (template: EmailTemplate) => {
const placeholders = getPlaceholdersFromTemplate(template);
recordUsage(template.id);
if (placeholders.length > 0) {
setSelectedTemplate(template);
setShowFillModal(true);
} else {
onSelect(template, {});
}
};
const finishSelection = (values: Record<string, string>) => {
if (selectedTemplate) {
onSelect(selectedTemplate, values);
}
setShowFillModal(false);
setSelectedTemplate(null);
};
if (!isOpen) return null;
const autoFilled = getAutoFilledPlaceholders({
senderName: primaryIdentity?.name,
locale,
});
const renderTemplateItem = (template: EmailTemplate) => (
<button
key={template.id}
type="button"
onClick={() => handleSelectTemplate(template)}
className="w-full text-left p-3 rounded-md hover:bg-muted transition-colors group"
>
<div className="flex items-center gap-2">
{template.isFavorite && (
<Star className="w-3 h-3 fill-amber-400 text-amber-400 flex-shrink-0" />
)}
<span className="text-sm font-medium text-foreground truncate">
{template.name}
</span>
{template.category && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium flex-shrink-0">
{template.category}
</span>
)}
</div>
{template.subject && (
<p className="text-xs text-muted-foreground truncate mt-1">
{template.subject}
</p>
)}
</button>
);
const renderSection = (title: string, items: EmailTemplate[]) => {
if (items.length === 0) return null;
return (
<div className="mb-4">
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1 px-3">
{title}
</h3>
<div className="space-y-0.5">{items.map(renderTemplateItem)}</div>
</div>
);
};
const categorizedEntries = Object.entries(byCategory).filter(
([cat]) => cat !== ''
);
const favoriteIds = new Set(favorites.map((f) => f.id));
const recentFiltered = recent.filter((r) => !favoriteIds.has(r.id));
const shownIds = new Set([
...favoriteIds,
...recentFiltered.map((r) => r.id),
]);
const uncategorizedFiltered = (byCategory[''] || []).filter(
(i) => !shownIds.has(i.id)
);
return (
<>
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-150">
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby="template-picker-title"
className={cn(
'bg-background border border-border rounded-lg shadow-xl',
'w-full max-w-md max-h-[70vh] overflow-hidden',
'animate-in zoom-in-95 duration-200'
)}
>
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
<h2 id="template-picker-title" className="text-sm font-semibold text-foreground">{t('picker_title')}</h2>
<button
onClick={onClose}
className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="px-4 py-2 border-b border-border">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('search_placeholder')}
className="pl-9 h-9"
autoFocus
/>
</div>
</div>
<div className="overflow-y-auto max-h-[calc(70vh-120px)] p-2">
{templates.length === 0 && (
<div className="flex flex-col items-center py-8 text-muted-foreground">
<FileText className="w-8 h-8 mb-2 opacity-40" />
<p className="text-sm">{t('no_templates')}</p>
</div>
)}
{filtered ? (
filtered.length > 0 ? (
<div className="space-y-0.5">
{filtered.map(renderTemplateItem)}
</div>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{t('no_results')}
</div>
)
) : (
<>
{renderSection(t('section_favorites'), favorites)}
{renderSection(t('section_recent'), recentFiltered)}
{categorizedEntries.map(([cat, items]) =>
renderSection(
cat,
items.filter((i) => !shownIds.has(i.id))
)
)}
{renderSection(t('section_uncategorized'), uncategorizedFiltered)}
</>
)}
</div>
</div>
</div>
{showFillModal && selectedTemplate && (
<PlaceholderFillModal
template={selectedTemplate}
placeholders={getPlaceholdersFromTemplate(selectedTemplate)}
autoFilled={autoFilled}
onConfirm={finishSelection}
onSkip={() => finishSelection({})}
onClose={() => {
setShowFillModal(false);
setSelectedTemplate(null);
}}
/>
)}
</>
);
}