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:
@@ -74,6 +74,14 @@ This webmail client is designed to work seamlessly with [**Stalwart Mail Server*
|
||||
- Configurable notification sound and enable/disable toggles
|
||||
- Keyboard shortcuts: m/w/d/a (views), t (today), n (new event), arrows (navigate)
|
||||
|
||||
### Email Templates
|
||||
- Reusable email templates with category organization (General, Business, Personal, Support, Follow-up)
|
||||
- Dynamic placeholder variables (`{{recipientName}}`, `{{date}}`, etc.) with auto-fill from composer context
|
||||
- Template picker in compose toolbar with search and category filter
|
||||
- Custom placeholder prompt when inserting templates
|
||||
- Template manager for creating, editing, duplicating, and deleting templates
|
||||
- Settings tab for template management
|
||||
|
||||
### Email Filters
|
||||
- Server-side email filtering with JMAP Sieve Scripts (RFC 9661)
|
||||
- Visual rule builder with conditions (From, To, Subject, Size, Body, etc.) and actions (Move, Forward, Mark read, Star, Discard, Reject, etc.)
|
||||
@@ -208,6 +216,7 @@ docker run -p 3000:3000 -e JMAP_SERVER_URL=https://mail.example.com jmap-webmail
|
||||
| `u` | Mark as unread |
|
||||
| `/` | Focus search |
|
||||
| `x` | Expand/collapse thread |
|
||||
| `Ctrl+Shift+T` | Insert template |
|
||||
| `?` | Show shortcuts help |
|
||||
|
||||
## Screenshots
|
||||
|
||||
+12
-1
@@ -162,6 +162,17 @@ This document tracks the development status and planned features for JMAP Webmai
|
||||
- [x] Push notification handling for SieveScript state changes
|
||||
- [x] i18n support (all 8 languages)
|
||||
|
||||
### Email Templates
|
||||
- [x] Reusable email templates with local storage persistence
|
||||
- [x] Category organization (General, Business, Personal, Support, Follow-up, custom)
|
||||
- [x] Dynamic placeholder variables with auto-fill from composer context
|
||||
- [x] Template manager modal (create, edit, duplicate, delete)
|
||||
- [x] Template picker in composer toolbar with search and category filter
|
||||
- [x] Custom placeholder prompt on template insertion
|
||||
- [x] Settings tab for template management
|
||||
- [x] Keyboard shortcut (Ctrl+Shift+T to insert template)
|
||||
- [x] i18n support (all 8 languages)
|
||||
|
||||
### Email Display
|
||||
- [x] Proper email layout without horizontal scroll or clipping
|
||||
- [x] Blocked image container collapsing (no empty spaces in newsletters)
|
||||
@@ -183,6 +194,7 @@ This document tracks the development status and planned features for JMAP Webmai
|
||||
- [x] Unit tests for calendar notification store (8 tests)
|
||||
- [x] Unit tests for calendar invitation parsing (25 tests)
|
||||
- [x] Unit tests for calendar participants (26 tests)
|
||||
- [x] Unit tests for template utilities (48 tests)
|
||||
- [x] XSS attack vector testing
|
||||
- [x] Playwright E2E framework setup
|
||||
|
||||
@@ -197,7 +209,6 @@ This document tracks the development status and planned features for JMAP Webmai
|
||||
### Advanced Features
|
||||
- [ ] Free/busy queries (Principal/getAvailability)
|
||||
- [ ] Calendar sharing UI (JMAP Sharing RFC 9670)
|
||||
- [ ] Email templates
|
||||
- [ ] Email encryption (PGP/GPG)
|
||||
- [ ] OAuth2/OIDC authentication (opt-in, Basic Auth remains default)
|
||||
|
||||
|
||||
@@ -12,11 +12,12 @@ import { IdentitySettings } from '@/components/settings/identity-settings';
|
||||
import { VacationSettings } from '@/components/settings/vacation-settings';
|
||||
import { CalendarSettings } from '@/components/settings/calendar-settings';
|
||||
import { FilterSettings } from '@/components/settings/filter-settings';
|
||||
import { TemplateSettings } from '@/components/settings/template-settings';
|
||||
import { AdvancedSettings } from '@/components/settings/advanced-settings';
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type Tab = 'appearance' | 'email' | 'account' | 'identities' | 'vacation' | 'calendar' | 'filters' | 'advanced';
|
||||
type Tab = 'appearance' | 'email' | 'account' | 'identities' | 'vacation' | 'calendar' | 'filters' | 'templates' | 'advanced';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const router = useRouter();
|
||||
@@ -36,6 +37,7 @@ export default function SettingsPage() {
|
||||
...(supportsVacation ? [{ id: 'vacation' as Tab, label: t('tabs.vacation') }] : []),
|
||||
...(supportsCalendar ? [{ id: 'calendar' as Tab, label: t('tabs.calendar') }] : []),
|
||||
...(supportsSieve ? [{ id: 'filters' as Tab, label: t('tabs.filters') }] : []),
|
||||
{ id: 'templates', label: t('tabs.templates') },
|
||||
{ id: 'advanced', label: t('tabs.advanced') },
|
||||
];
|
||||
|
||||
@@ -97,6 +99,7 @@ export default function SettingsPage() {
|
||||
{activeTab === 'vacation' && <VacationSettings />}
|
||||
{activeTab === 'calendar' && <CalendarSettings />}
|
||||
{activeTab === 'filters' && <FilterSettings />}
|
||||
{activeTab === 'templates' && <TemplateSettings />}
|
||||
{activeTab === 'advanced' && <AdvancedSettings />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 */}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -284,4 +284,7 @@ export const KEYBOARD_SHORTCUTS = {
|
||||
threads: [
|
||||
{ key: "x", description: "shortcuts.threads.expand_collapse" },
|
||||
],
|
||||
composer: [
|
||||
{ key: "t", description: "shortcuts.composer.template_picker" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
extractPlaceholders,
|
||||
substitutePlaceholders,
|
||||
hasUnresolvedPlaceholders,
|
||||
validateTemplateName,
|
||||
getAutoFilledPlaceholders,
|
||||
getPlaceholdersFromTemplate,
|
||||
isBuiltInPlaceholder,
|
||||
filterTemplates,
|
||||
exportTemplates,
|
||||
importTemplates,
|
||||
} from '../template-utils';
|
||||
import type { EmailTemplate } from '../template-types';
|
||||
|
||||
function makeTemplate(overrides: Partial<EmailTemplate> = {}): EmailTemplate {
|
||||
return {
|
||||
id: 'test-id',
|
||||
name: 'Test Template',
|
||||
subject: '',
|
||||
body: '',
|
||||
category: '',
|
||||
isFavorite: false,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('extractPlaceholders', () => {
|
||||
it('extracts single placeholder', () => {
|
||||
expect(extractPlaceholders('Hello {{name}}')).toEqual(['name']);
|
||||
});
|
||||
|
||||
it('extracts multiple placeholders', () => {
|
||||
const result = extractPlaceholders('{{greeting}} {{name}}, welcome to {{company}}');
|
||||
expect(result).toEqual(['greeting', 'name', 'company']);
|
||||
});
|
||||
|
||||
it('deduplicates repeated placeholders', () => {
|
||||
expect(extractPlaceholders('{{name}} and {{name}}')).toEqual(['name']);
|
||||
});
|
||||
|
||||
it('returns empty array for no placeholders', () => {
|
||||
expect(extractPlaceholders('No placeholders here')).toEqual([]);
|
||||
});
|
||||
|
||||
it('handles empty string', () => {
|
||||
expect(extractPlaceholders('')).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores malformed placeholders', () => {
|
||||
expect(extractPlaceholders('{{}} {name} {{ name }}')).toEqual([]);
|
||||
});
|
||||
|
||||
it('handles underscored names', () => {
|
||||
expect(extractPlaceholders('{{first_name}} {{last_name}}')).toEqual(['first_name', 'last_name']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('substitutePlaceholders', () => {
|
||||
it('replaces a single placeholder', () => {
|
||||
expect(substitutePlaceholders('Hello {{name}}', { name: 'Alice' })).toBe('Hello Alice');
|
||||
});
|
||||
|
||||
it('replaces multiple placeholders', () => {
|
||||
const result = substitutePlaceholders('{{greeting}} {{name}}', {
|
||||
greeting: 'Hi',
|
||||
name: 'Bob',
|
||||
});
|
||||
expect(result).toBe('Hi Bob');
|
||||
});
|
||||
|
||||
it('leaves unresolved placeholders', () => {
|
||||
expect(substitutePlaceholders('{{known}} {{unknown}}', { known: 'yes' })).toBe('yes {{unknown}}');
|
||||
});
|
||||
|
||||
it('sanitizes XSS in values', () => {
|
||||
const result = substitutePlaceholders('{{name}}', { name: '<script>alert(1)</script>' });
|
||||
expect(result).not.toContain('<script>');
|
||||
});
|
||||
|
||||
it('handles empty values', () => {
|
||||
expect(substitutePlaceholders('{{name}}', { name: '' })).toBe('');
|
||||
});
|
||||
|
||||
it('handles no placeholders in text', () => {
|
||||
expect(substitutePlaceholders('No placeholders', { name: 'test' })).toBe('No placeholders');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasUnresolvedPlaceholders', () => {
|
||||
it('returns true when placeholders exist', () => {
|
||||
expect(hasUnresolvedPlaceholders('Hello {{name}}')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when no placeholders', () => {
|
||||
expect(hasUnresolvedPlaceholders('Hello world')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for empty string', () => {
|
||||
expect(hasUnresolvedPlaceholders('')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns consistent results on consecutive calls', () => {
|
||||
const text = 'Hello {{name}}';
|
||||
expect(hasUnresolvedPlaceholders(text)).toBe(true);
|
||||
expect(hasUnresolvedPlaceholders(text)).toBe(true);
|
||||
expect(hasUnresolvedPlaceholders(text)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateTemplateName', () => {
|
||||
it('returns null for valid name', () => {
|
||||
expect(validateTemplateName('My Template')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns empty for empty string', () => {
|
||||
expect(validateTemplateName('')).toBe('empty');
|
||||
});
|
||||
|
||||
it('returns empty for whitespace only', () => {
|
||||
expect(validateTemplateName(' ')).toBe('empty');
|
||||
});
|
||||
|
||||
it('returns too_long for name over 200 chars', () => {
|
||||
expect(validateTemplateName('a'.repeat(201))).toBe('too_long');
|
||||
});
|
||||
|
||||
it('accepts name at exactly 200 chars', () => {
|
||||
expect(validateTemplateName('a'.repeat(200))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAutoFilledPlaceholders', () => {
|
||||
it('includes date and day_of_week', () => {
|
||||
const result = getAutoFilledPlaceholders({});
|
||||
expect(result).toHaveProperty('date');
|
||||
expect(result).toHaveProperty('day_of_week');
|
||||
});
|
||||
|
||||
it('includes sender_name when provided', () => {
|
||||
const result = getAutoFilledPlaceholders({ senderName: 'John' });
|
||||
expect(result.sender_name).toBe('John');
|
||||
});
|
||||
|
||||
it('omits sender_name when not provided', () => {
|
||||
const result = getAutoFilledPlaceholders({});
|
||||
expect(result).not.toHaveProperty('sender_name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPlaceholdersFromTemplate', () => {
|
||||
it('extracts from both subject and body', () => {
|
||||
const tpl = makeTemplate({
|
||||
subject: 'Hello {{name}}',
|
||||
body: 'Welcome to {{company}}',
|
||||
});
|
||||
expect(getPlaceholdersFromTemplate(tpl)).toEqual(['name', 'company']);
|
||||
});
|
||||
|
||||
it('deduplicates across subject and body', () => {
|
||||
const tpl = makeTemplate({
|
||||
subject: '{{name}}',
|
||||
body: '{{name}} again',
|
||||
});
|
||||
expect(getPlaceholdersFromTemplate(tpl)).toEqual(['name']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBuiltInPlaceholder', () => {
|
||||
it('returns true for built-in names', () => {
|
||||
expect(isBuiltInPlaceholder('date')).toBe(true);
|
||||
expect(isBuiltInPlaceholder('sender_name')).toBe(true);
|
||||
expect(isBuiltInPlaceholder('recipient_name')).toBe(true);
|
||||
expect(isBuiltInPlaceholder('company')).toBe(true);
|
||||
expect(isBuiltInPlaceholder('day_of_week')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for custom names', () => {
|
||||
expect(isBuiltInPlaceholder('custom_field')).toBe(false);
|
||||
expect(isBuiltInPlaceholder('project')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportTemplates', () => {
|
||||
it('produces valid JSON with metadata', () => {
|
||||
const templates = [makeTemplate()];
|
||||
const json = exportTemplates(templates);
|
||||
const parsed = JSON.parse(json);
|
||||
expect(parsed.version).toBe(1);
|
||||
expect(parsed.type).toBe('webmail-templates');
|
||||
expect(parsed.templates).toHaveLength(1);
|
||||
expect(parsed.exportedAt).toBeDefined();
|
||||
});
|
||||
|
||||
it('handles empty array', () => {
|
||||
const json = exportTemplates([]);
|
||||
const parsed = JSON.parse(json);
|
||||
expect(parsed.templates).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('importTemplates', () => {
|
||||
it('imports valid export data', () => {
|
||||
const original = [makeTemplate({ name: 'Test' })];
|
||||
const json = exportTemplates(original);
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates).toHaveLength(1);
|
||||
expect(result.templates[0].name).toBe('Test');
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('assigns new IDs on import', () => {
|
||||
const original = [makeTemplate({ name: 'Test' })];
|
||||
const json = exportTemplates(original);
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates[0].id).not.toBe('test-id');
|
||||
});
|
||||
|
||||
it('returns error for invalid JSON', () => {
|
||||
const result = importTemplates('not json');
|
||||
expect(result.templates).toHaveLength(0);
|
||||
expect(result.errors).toContain('invalid_json');
|
||||
});
|
||||
|
||||
it('returns error for wrong type', () => {
|
||||
const result = importTemplates(JSON.stringify({ type: 'other', version: 1, templates: [] }));
|
||||
expect(result.errors).toContain('invalid_type');
|
||||
});
|
||||
|
||||
it('returns error for unsupported version', () => {
|
||||
const result = importTemplates(JSON.stringify({ type: 'webmail-templates', version: 99, templates: [] }));
|
||||
expect(result.errors).toContain('unsupported_version');
|
||||
});
|
||||
|
||||
it('returns error for non-object input', () => {
|
||||
const result = importTemplates('"just a string"');
|
||||
expect(result.errors).toContain('invalid_format');
|
||||
});
|
||||
|
||||
it('skips entries without name', () => {
|
||||
const json = JSON.stringify({
|
||||
type: 'webmail-templates',
|
||||
version: 1,
|
||||
templates: [{ subject: 'no name' }, { name: 'Valid' }],
|
||||
});
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates).toHaveLength(1);
|
||||
expect(result.templates[0].name).toBe('Valid');
|
||||
expect(result.errors).toContain('missing_template_name');
|
||||
});
|
||||
|
||||
it('sanitizes imported values against XSS', () => {
|
||||
const json = JSON.stringify({
|
||||
type: 'webmail-templates',
|
||||
version: 1,
|
||||
templates: [{ name: '<img onerror=alert(1) src=x>', subject: '<script>alert(1)</script>' }],
|
||||
});
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates[0].name).not.toContain('onerror');
|
||||
expect(result.templates[0].subject).not.toContain('<script>');
|
||||
});
|
||||
|
||||
it('handles missing templates array', () => {
|
||||
const result = importTemplates(JSON.stringify({ type: 'webmail-templates', version: 1 }));
|
||||
expect(result.errors).toContain('invalid_templates');
|
||||
});
|
||||
|
||||
it('imports defaultRecipients correctly', () => {
|
||||
const json = JSON.stringify({
|
||||
type: 'webmail-templates',
|
||||
version: 1,
|
||||
templates: [{
|
||||
name: 'With Recipients',
|
||||
defaultRecipients: { to: ['a@b.com'], cc: ['c@d.com'] },
|
||||
}],
|
||||
});
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates[0].defaultRecipients?.to).toEqual(['a@b.com']);
|
||||
expect(result.templates[0].defaultRecipients?.cc).toEqual(['c@d.com']);
|
||||
});
|
||||
|
||||
it('round-trips export and import', () => {
|
||||
const originals = [
|
||||
makeTemplate({ name: 'Template 1', subject: 'Hi {{name}}', category: 'work', isFavorite: true }),
|
||||
makeTemplate({ name: 'Template 2', body: 'Body text', category: 'personal' }),
|
||||
];
|
||||
const json = exportTemplates(originals);
|
||||
const result = importTemplates(json);
|
||||
expect(result.templates).toHaveLength(2);
|
||||
expect(result.templates[0].name).toBe('Template 1');
|
||||
expect(result.templates[0].subject).toBe('Hi {{name}}');
|
||||
expect(result.templates[1].name).toBe('Template 2');
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterTemplates', () => {
|
||||
const templates = [
|
||||
makeTemplate({ id: '1', name: 'Follow-up', subject: 'Re: meeting', category: 'work' }),
|
||||
makeTemplate({ id: '2', name: 'Welcome', subject: 'Hello there', category: 'personal' }),
|
||||
makeTemplate({ id: '3', name: 'Invoice', subject: 'Monthly bill', category: 'work' }),
|
||||
];
|
||||
|
||||
it('filters by name', () => {
|
||||
const result = filterTemplates(templates, 'follow');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].id).toBe('1');
|
||||
});
|
||||
|
||||
it('filters by subject', () => {
|
||||
const result = filterTemplates(templates, 'meeting');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].id).toBe('1');
|
||||
});
|
||||
|
||||
it('filters by category', () => {
|
||||
const result = filterTemplates(templates, 'personal');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].id).toBe('2');
|
||||
});
|
||||
|
||||
it('is case-insensitive', () => {
|
||||
expect(filterTemplates(templates, 'WELCOME')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('returns all when multiple match', () => {
|
||||
expect(filterTemplates(templates, 'work')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('returns empty array for no matches', () => {
|
||||
expect(filterTemplates(templates, 'xyz')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
export interface EmailTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
subject: string;
|
||||
body: string;
|
||||
category: string;
|
||||
defaultRecipients?: {
|
||||
to?: string[];
|
||||
cc?: string[];
|
||||
bcc?: string[];
|
||||
};
|
||||
identityId?: string;
|
||||
isFavorite: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PlaceholderVariable {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const BUILT_IN_PLACEHOLDERS = [
|
||||
'recipient_name',
|
||||
'company',
|
||||
'date',
|
||||
'day_of_week',
|
||||
'sender_name',
|
||||
] as const;
|
||||
|
||||
export type BuiltInPlaceholder = (typeof BUILT_IN_PLACEHOLDERS)[number];
|
||||
@@ -0,0 +1,172 @@
|
||||
import DOMPurify from 'dompurify';
|
||||
import type { EmailTemplate } from './template-types';
|
||||
import { BUILT_IN_PLACEHOLDERS } from './template-types';
|
||||
|
||||
const PLACEHOLDER_REGEX = /\{\{(\w+)\}\}/g;
|
||||
const MAX_TEMPLATE_NAME_LENGTH = 200;
|
||||
const STRIP_HTML_CONFIG = { ALLOWED_TAGS: [] as string[], ALLOWED_ATTR: [] as string[] };
|
||||
|
||||
export function extractPlaceholders(text: string): string[] {
|
||||
const matches = new Set<string>();
|
||||
let match: RegExpExecArray | null;
|
||||
const regex = new RegExp(PLACEHOLDER_REGEX.source, 'g');
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
matches.add(match[1]);
|
||||
}
|
||||
return Array.from(matches);
|
||||
}
|
||||
|
||||
export function substitutePlaceholders(
|
||||
text: string,
|
||||
values: Record<string, string>
|
||||
): string {
|
||||
return text.replace(PLACEHOLDER_REGEX, (full, name) => {
|
||||
if (values[name] === undefined) return full;
|
||||
return DOMPurify.sanitize(values[name], STRIP_HTML_CONFIG);
|
||||
});
|
||||
}
|
||||
|
||||
export function hasUnresolvedPlaceholders(text: string): boolean {
|
||||
return new RegExp(PLACEHOLDER_REGEX.source).test(text);
|
||||
}
|
||||
|
||||
export function validateTemplateName(name: string): string | null {
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) return 'empty';
|
||||
if (trimmed.length > MAX_TEMPLATE_NAME_LENGTH) return 'too_long';
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface AutoFillContext {
|
||||
senderName?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export function getAutoFilledPlaceholders(
|
||||
context: AutoFillContext
|
||||
): Record<string, string> {
|
||||
const now = new Date();
|
||||
const locale = context.locale || 'en';
|
||||
|
||||
const values: Record<string, string> = {
|
||||
date: now.toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' }),
|
||||
day_of_week: now.toLocaleDateString(locale, { weekday: 'long' }),
|
||||
};
|
||||
|
||||
if (context.senderName) {
|
||||
values.sender_name = context.senderName;
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
export function getPlaceholdersFromTemplate(template: EmailTemplate): string[] {
|
||||
const combined = `${template.subject} ${template.body}`;
|
||||
return extractPlaceholders(combined);
|
||||
}
|
||||
|
||||
export function isBuiltInPlaceholder(name: string): boolean {
|
||||
return (BUILT_IN_PLACEHOLDERS as readonly string[]).includes(name);
|
||||
}
|
||||
|
||||
export function filterTemplates(templates: EmailTemplate[], query: string): EmailTemplate[] {
|
||||
const lower = query.toLowerCase();
|
||||
return templates.filter(
|
||||
(t) =>
|
||||
t.name.toLowerCase().includes(lower) ||
|
||||
t.subject.toLowerCase().includes(lower) ||
|
||||
t.category.toLowerCase().includes(lower)
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizeText(value: unknown): string {
|
||||
return DOMPurify.sanitize(String(value || ''), STRIP_HTML_CONFIG);
|
||||
}
|
||||
|
||||
interface ExportData {
|
||||
version: 1;
|
||||
type: 'webmail-templates';
|
||||
exportedAt: string;
|
||||
templates: EmailTemplate[];
|
||||
}
|
||||
|
||||
export function exportTemplates(templates: EmailTemplate[]): string {
|
||||
const data: ExportData = {
|
||||
version: 1,
|
||||
type: 'webmail-templates',
|
||||
exportedAt: new Date().toISOString(),
|
||||
templates,
|
||||
};
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
templates: EmailTemplate[];
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export function importTemplates(json: string): ImportResult {
|
||||
const errors: string[] = [];
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(json);
|
||||
} catch {
|
||||
return { templates: [], errors: ['invalid_json'] };
|
||||
}
|
||||
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
return { templates: [], errors: ['invalid_format'] };
|
||||
}
|
||||
|
||||
const data = parsed as Record<string, unknown>;
|
||||
|
||||
if (data.type !== 'webmail-templates') {
|
||||
return { templates: [], errors: ['invalid_type'] };
|
||||
}
|
||||
|
||||
if (data.version !== 1) {
|
||||
return { templates: [], errors: ['unsupported_version'] };
|
||||
}
|
||||
|
||||
if (!Array.isArray(data.templates)) {
|
||||
return { templates: [], errors: ['invalid_templates'] };
|
||||
}
|
||||
|
||||
const templates: EmailTemplate[] = [];
|
||||
for (const item of data.templates) {
|
||||
if (typeof item !== 'object' || item === null) {
|
||||
errors.push('invalid_template_entry');
|
||||
continue;
|
||||
}
|
||||
|
||||
const t = item as Record<string, unknown>;
|
||||
if (typeof t.name !== 'string' || !t.name.trim()) {
|
||||
errors.push('missing_template_name');
|
||||
continue;
|
||||
}
|
||||
|
||||
const recipients = t.defaultRecipients as Record<string, unknown> | undefined;
|
||||
|
||||
templates.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: sanitizeText(t.name),
|
||||
subject: sanitizeText(t.subject),
|
||||
body: sanitizeText(t.body),
|
||||
category: sanitizeText(t.category),
|
||||
defaultRecipients: recipients && typeof recipients === 'object'
|
||||
? {
|
||||
to: Array.isArray(recipients.to) ? (recipients.to as string[]).map(String) : undefined,
|
||||
cc: Array.isArray(recipients.cc) ? (recipients.cc as string[]).map(String) : undefined,
|
||||
bcc: Array.isArray(recipients.bcc) ? (recipients.bcc as string[]).map(String) : undefined,
|
||||
}
|
||||
: undefined,
|
||||
identityId: typeof t.identityId === 'string' ? t.identityId : undefined,
|
||||
isFavorite: Boolean(t.isFavorite),
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return { templates, errors };
|
||||
}
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Betreff: {subject}",
|
||||
"to": "An: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Sub-Adresse entfernen"
|
||||
"remove_sub_address": "Sub-Adresse entfernen",
|
||||
"use_template": "Vorlage",
|
||||
"save_as_template": "Als Vorlage speichern"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Lädt...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Fehler beim Speichern der Abwesenheitsnotiz-Einstellungen",
|
||||
"filters_saved": "Filter erfolgreich gespeichert",
|
||||
"filters_save_failed": "Fehler beim Speichern der Filter",
|
||||
"filters_deleted": "Filterregel gelöscht"
|
||||
"filters_deleted": "Filterregel gelöscht",
|
||||
"templates_exported": "Vorlagen erfolgreich exportiert",
|
||||
"templates_imported": "{count, plural, one {# Vorlage importiert} other {# Vorlagen importiert}}",
|
||||
"templates_import_errors": "Einige Vorlagen konnten nicht importiert werden",
|
||||
"templates_import_empty": "Keine Vorlagen in der Datei gefunden"
|
||||
},
|
||||
"date": {
|
||||
"today": "Heute",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Abwesenheitsnotiz",
|
||||
"advanced": "Erweitert",
|
||||
"calendar": "Kalender",
|
||||
"filters": "Filter"
|
||||
"filters": "Filter",
|
||||
"templates": "Vorlagen"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Darstellung",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# Bedingung} other {# Bedingungen}}",
|
||||
"actions_count": "{count, plural, one {# Aktion} other {# Aktionen}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "E-Mail-Vorlagen",
|
||||
"description": "Erstellen Sie wiederverwendbare E-Mail-Vorlagen mit Platzhaltervariablen",
|
||||
"add": "Neue Vorlage",
|
||||
"edit": "Vorlage bearbeiten",
|
||||
"name": "Vorlagenname",
|
||||
"name_placeholder": "z.B.: Nachfass-E-Mail",
|
||||
"category": "Kategorie",
|
||||
"category_placeholder": "z.B.: Arbeit, Persönlich",
|
||||
"subject": "Betreff",
|
||||
"subject_placeholder": "E-Mail-Betreffzeile",
|
||||
"body": "Text",
|
||||
"body_placeholder": "E-Mail-Inhalt...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Senden als",
|
||||
"default_identity": "Standard-Identität",
|
||||
"favorite": "Favorit",
|
||||
"cancel": "Abbrechen",
|
||||
"create": "Erstellen",
|
||||
"update": "Aktualisieren",
|
||||
"confirm_delete": "Löschen",
|
||||
"no_templates": "Keine Vorlagen",
|
||||
"manage": "Vorlagen verwalten",
|
||||
"count": "{count, plural, one {# Vorlage} other {# Vorlagen}}",
|
||||
"export_import": "Exportieren und Importieren",
|
||||
"export_import_description": "Sichern Sie Ihre Vorlagen oder übertragen Sie sie auf ein anderes Gerät",
|
||||
"export": "Exportieren",
|
||||
"import": "Importieren",
|
||||
"validation": {
|
||||
"empty": "Vorlagenname ist erforderlich",
|
||||
"too_long": "Vorlagenname darf maximal 200 Zeichen haben"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navigation",
|
||||
"actions": "E-Mail-Aktionen",
|
||||
"global": "Global",
|
||||
"threads": "Unterhaltungen"
|
||||
"threads": "Unterhaltungen",
|
||||
"composer": "Verfassen"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Nächste E-Mail",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Unterhaltung erweitern/einklappen"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Vorlagenauswahl öffnen"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Vorlage wählen",
|
||||
"search_placeholder": "Vorlagen suchen...",
|
||||
"section_favorites": "Favoriten",
|
||||
"section_recent": "Zuletzt verwendet",
|
||||
"section_uncategorized": "Sonstige",
|
||||
"no_templates": "Keine Vorlagen",
|
||||
"no_results": "Keine Vorlagen gefunden",
|
||||
"fill_placeholders": "Platzhalterwerte ausfüllen",
|
||||
"enter_value": "Wert eingeben...",
|
||||
"preview": "Vorschau",
|
||||
"insert_with_values": "Mit Werten einfügen",
|
||||
"insert_raw": "Unverändert einfügen",
|
||||
"copy_suffix": "(Kopie)",
|
||||
"placeholder": "Variable",
|
||||
"placeholders": {
|
||||
"recipient_name": "Name des Empfängers",
|
||||
"company": "Firmenname",
|
||||
"date": "Heutiges Datum",
|
||||
"day_of_week": "Wochentag",
|
||||
"sender_name": "Ihr Name"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Kontakte",
|
||||
"search_placeholder": "Kontakte suchen...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Subject: {subject}",
|
||||
"to": "To: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Remove sub-address"
|
||||
"remove_sub_address": "Remove sub-address",
|
||||
"use_template": "Template",
|
||||
"save_as_template": "Save as Template"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Loading...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Failed to save vacation responder settings",
|
||||
"filters_saved": "Filters saved successfully",
|
||||
"filters_save_failed": "Failed to save filters",
|
||||
"filters_deleted": "Filter rule deleted"
|
||||
"filters_deleted": "Filter rule deleted",
|
||||
"templates_exported": "Templates exported successfully",
|
||||
"templates_imported": "{count, plural, one {# template} other {# templates}} imported",
|
||||
"templates_import_errors": "Some templates could not be imported",
|
||||
"templates_import_empty": "No templates found in the file"
|
||||
},
|
||||
"date": {
|
||||
"today": "Today",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Vacation Responder",
|
||||
"advanced": "Advanced",
|
||||
"calendar": "Calendar",
|
||||
"filters": "Filters"
|
||||
"filters": "Filters",
|
||||
"templates": "Templates"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Appearance",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# condition} other {# conditions}}",
|
||||
"actions_count": "{count, plural, one {# action} other {# actions}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "Email Templates",
|
||||
"description": "Create reusable email templates with placeholder variables",
|
||||
"add": "New Template",
|
||||
"edit": "Edit Template",
|
||||
"name": "Template Name",
|
||||
"name_placeholder": "e.g., Follow-up email",
|
||||
"category": "Category",
|
||||
"category_placeholder": "e.g., Work, Personal",
|
||||
"subject": "Subject",
|
||||
"subject_placeholder": "Email subject line",
|
||||
"body": "Body",
|
||||
"body_placeholder": "Email body content...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Send As",
|
||||
"default_identity": "Default identity",
|
||||
"favorite": "Favorite",
|
||||
"cancel": "Cancel",
|
||||
"create": "Create",
|
||||
"update": "Update",
|
||||
"confirm_delete": "Delete",
|
||||
"no_templates": "No templates yet",
|
||||
"manage": "Manage Templates",
|
||||
"count": "{count, plural, one {# template} other {# templates}}",
|
||||
"export_import": "Export & Import",
|
||||
"export_import_description": "Back up your templates or transfer them to another device",
|
||||
"export": "Export",
|
||||
"import": "Import",
|
||||
"validation": {
|
||||
"empty": "Template name is required",
|
||||
"too_long": "Template name must be 200 characters or less"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navigation",
|
||||
"actions": "Email Actions",
|
||||
"global": "Global",
|
||||
"threads": "Threads"
|
||||
"threads": "Threads",
|
||||
"composer": "Composer"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Next email",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Expand/collapse thread"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Open template picker"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Choose a Template",
|
||||
"search_placeholder": "Search templates...",
|
||||
"section_favorites": "Favorites",
|
||||
"section_recent": "Recent",
|
||||
"section_uncategorized": "Other",
|
||||
"no_templates": "No templates yet",
|
||||
"no_results": "No templates found",
|
||||
"fill_placeholders": "Fill Placeholder Values",
|
||||
"enter_value": "Enter a value...",
|
||||
"preview": "Preview",
|
||||
"insert_with_values": "Insert with Values",
|
||||
"insert_raw": "Insert Raw",
|
||||
"copy_suffix": "(copy)",
|
||||
"placeholder": "Variable",
|
||||
"placeholders": {
|
||||
"recipient_name": "Recipient name",
|
||||
"company": "Company name",
|
||||
"date": "Current date",
|
||||
"day_of_week": "Day of the week",
|
||||
"sender_name": "Your name"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contacts",
|
||||
"search_placeholder": "Search contacts...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Asunto: {subject}",
|
||||
"to": "Para: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Eliminar sub-dirección"
|
||||
"remove_sub_address": "Eliminar sub-dirección",
|
||||
"use_template": "Plantilla",
|
||||
"save_as_template": "Guardar como plantilla"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Cargando...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Error al guardar la configuración de respuesta automática",
|
||||
"filters_saved": "Filtros guardados correctamente",
|
||||
"filters_save_failed": "Error al guardar los filtros",
|
||||
"filters_deleted": "Regla de filtrado eliminada"
|
||||
"filters_deleted": "Regla de filtrado eliminada",
|
||||
"templates_exported": "Plantillas exportadas correctamente",
|
||||
"templates_imported": "{count, plural, one {# plantilla importada} other {# plantillas importadas}}",
|
||||
"templates_import_errors": "Algunas plantillas no se pudieron importar",
|
||||
"templates_import_empty": "No se encontraron plantillas en el archivo"
|
||||
},
|
||||
"date": {
|
||||
"today": "Hoy",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Respuesta automática",
|
||||
"advanced": "Avanzado",
|
||||
"calendar": "Calendario",
|
||||
"filters": "Filtros"
|
||||
"filters": "Filtros",
|
||||
"templates": "Plantillas"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Apariencia",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# condición} other {# condiciones}}",
|
||||
"actions_count": "{count, plural, one {# acción} other {# acciones}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "Plantillas de correo",
|
||||
"description": "Crea plantillas reutilizables con variables de marcador de posición",
|
||||
"add": "Nueva plantilla",
|
||||
"edit": "Editar plantilla",
|
||||
"name": "Nombre de la plantilla",
|
||||
"name_placeholder": "ej.: Correo de seguimiento",
|
||||
"category": "Categoría",
|
||||
"category_placeholder": "ej.: Trabajo, Personal",
|
||||
"subject": "Asunto",
|
||||
"subject_placeholder": "Línea de asunto del correo",
|
||||
"body": "Cuerpo",
|
||||
"body_placeholder": "Contenido del correo...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Enviar como",
|
||||
"default_identity": "Identidad predeterminada",
|
||||
"favorite": "Favorito",
|
||||
"cancel": "Cancelar",
|
||||
"create": "Crear",
|
||||
"update": "Actualizar",
|
||||
"confirm_delete": "Eliminar",
|
||||
"no_templates": "Sin plantillas",
|
||||
"manage": "Gestionar plantillas",
|
||||
"count": "{count, plural, one {# plantilla} other {# plantillas}}",
|
||||
"export_import": "Exportar e importar",
|
||||
"export_import_description": "Haz una copia de seguridad de tus plantillas o transfiérelas a otro dispositivo",
|
||||
"export": "Exportar",
|
||||
"import": "Importar",
|
||||
"validation": {
|
||||
"empty": "El nombre de la plantilla es obligatorio",
|
||||
"too_long": "El nombre de la plantilla no debe superar los 200 caracteres"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navegación",
|
||||
"actions": "Acciones de Correo",
|
||||
"global": "Global",
|
||||
"threads": "Conversaciones"
|
||||
"threads": "Conversaciones",
|
||||
"composer": "Redacción"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Siguiente correo",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Expandir/contraer conversación"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Abrir selector de plantillas"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Elegir una plantilla",
|
||||
"search_placeholder": "Buscar plantillas...",
|
||||
"section_favorites": "Favoritos",
|
||||
"section_recent": "Recientes",
|
||||
"section_uncategorized": "Otros",
|
||||
"no_templates": "Sin plantillas",
|
||||
"no_results": "No se encontraron plantillas",
|
||||
"fill_placeholders": "Completar valores de marcadores",
|
||||
"enter_value": "Introduce un valor...",
|
||||
"preview": "Vista previa",
|
||||
"insert_with_values": "Insertar con valores",
|
||||
"insert_raw": "Insertar sin completar",
|
||||
"copy_suffix": "(copia)",
|
||||
"placeholder": "Variable",
|
||||
"placeholders": {
|
||||
"recipient_name": "Nombre del destinatario",
|
||||
"company": "Nombre de la empresa",
|
||||
"date": "Fecha actual",
|
||||
"day_of_week": "Día de la semana",
|
||||
"sender_name": "Tu nombre"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contactos",
|
||||
"search_placeholder": "Buscar contactos...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Objet : {subject}",
|
||||
"to": "À : {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Retirer le sous-adressage"
|
||||
"remove_sub_address": "Retirer le sous-adressage",
|
||||
"use_template": "Modèle",
|
||||
"save_as_template": "Enregistrer comme modèle"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Chargement...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Échec de l'enregistrement des paramètres du répondeur d'absence",
|
||||
"filters_saved": "Filtres enregistrés avec succès",
|
||||
"filters_save_failed": "Échec de l'enregistrement des filtres",
|
||||
"filters_deleted": "Règle de filtrage supprimée"
|
||||
"filters_deleted": "Règle de filtrage supprimée",
|
||||
"templates_exported": "Modèles exportés avec succès",
|
||||
"templates_imported": "{count, plural, one {# modèle importé} other {# modèles importés}}",
|
||||
"templates_import_errors": "Certains modèles n'ont pas pu être importés",
|
||||
"templates_import_empty": "Aucun modèle trouvé dans le fichier"
|
||||
},
|
||||
"date": {
|
||||
"today": "Aujourd'hui",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Répondeur d'absence",
|
||||
"advanced": "Avancé",
|
||||
"calendar": "Calendrier",
|
||||
"filters": "Filtres"
|
||||
"filters": "Filtres",
|
||||
"templates": "Modèles"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Apparence",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# condition} other {# conditions}}",
|
||||
"actions_count": "{count, plural, one {# action} other {# actions}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "Modèles d'e-mails",
|
||||
"description": "Créez des modèles d'e-mails réutilisables avec des variables",
|
||||
"add": "Nouveau modèle",
|
||||
"edit": "Modifier le modèle",
|
||||
"name": "Nom du modèle",
|
||||
"name_placeholder": "ex : E-mail de suivi",
|
||||
"category": "Catégorie",
|
||||
"category_placeholder": "ex : Travail, Personnel",
|
||||
"subject": "Objet",
|
||||
"subject_placeholder": "Objet de l'e-mail",
|
||||
"body": "Corps",
|
||||
"body_placeholder": "Contenu de l'e-mail...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Envoyer en tant que",
|
||||
"default_identity": "Identité par défaut",
|
||||
"favorite": "Favori",
|
||||
"cancel": "Annuler",
|
||||
"create": "Créer",
|
||||
"update": "Mettre à jour",
|
||||
"confirm_delete": "Supprimer",
|
||||
"no_templates": "Aucun modèle",
|
||||
"manage": "Gérer les modèles",
|
||||
"count": "{count, plural, one {# modèle} other {# modèles}}",
|
||||
"export_import": "Exporter et importer",
|
||||
"export_import_description": "Sauvegardez vos modèles ou transférez-les sur un autre appareil",
|
||||
"export": "Exporter",
|
||||
"import": "Importer",
|
||||
"validation": {
|
||||
"empty": "Le nom du modèle est requis",
|
||||
"too_long": "Le nom du modèle ne doit pas dépasser 200 caractères"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navigation",
|
||||
"actions": "Actions email",
|
||||
"global": "Global",
|
||||
"threads": "Conversations"
|
||||
"threads": "Conversations",
|
||||
"composer": "Rédaction"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Email suivant",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Développer/réduire la conversation"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Ouvrir le sélecteur de modèles"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Choisir un modèle",
|
||||
"search_placeholder": "Rechercher des modèles...",
|
||||
"section_favorites": "Favoris",
|
||||
"section_recent": "Récents",
|
||||
"section_uncategorized": "Autres",
|
||||
"no_templates": "Aucun modèle",
|
||||
"no_results": "Aucun modèle trouvé",
|
||||
"fill_placeholders": "Remplir les variables",
|
||||
"enter_value": "Entrez une valeur...",
|
||||
"preview": "Aperçu",
|
||||
"insert_with_values": "Insérer avec les valeurs",
|
||||
"insert_raw": "Insérer brut",
|
||||
"copy_suffix": "(copie)",
|
||||
"placeholder": "Variable",
|
||||
"placeholders": {
|
||||
"recipient_name": "Nom du destinataire",
|
||||
"company": "Nom de l'entreprise",
|
||||
"date": "Date du jour",
|
||||
"day_of_week": "Jour de la semaine",
|
||||
"sender_name": "Votre nom"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contacts",
|
||||
"search_placeholder": "Rechercher des contacts...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Oggetto: {subject}",
|
||||
"to": "A: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Rimuovi sotto-indirizzo"
|
||||
"remove_sub_address": "Rimuovi sotto-indirizzo",
|
||||
"use_template": "Modello",
|
||||
"save_as_template": "Salva come modello"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Caricamento...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Impossibile salvare le impostazioni del risponditore automatico",
|
||||
"filters_saved": "Filtri salvati con successo",
|
||||
"filters_save_failed": "Impossibile salvare i filtri",
|
||||
"filters_deleted": "Regola di filtraggio eliminata"
|
||||
"filters_deleted": "Regola di filtraggio eliminata",
|
||||
"templates_exported": "Modelli esportati con successo",
|
||||
"templates_imported": "{count, plural, one {# modello importato} other {# modelli importati}}",
|
||||
"templates_import_errors": "Alcuni modelli non sono stati importati",
|
||||
"templates_import_empty": "Nessun modello trovato nel file"
|
||||
},
|
||||
"date": {
|
||||
"today": "Oggi",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Risponditore automatico",
|
||||
"advanced": "Avanzate",
|
||||
"calendar": "Calendario",
|
||||
"filters": "Filtri"
|
||||
"filters": "Filtri",
|
||||
"templates": "Modelli"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Aspetto",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# condizione} other {# condizioni}}",
|
||||
"actions_count": "{count, plural, one {# azione} other {# azioni}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "Modelli email",
|
||||
"description": "Crea modelli email riutilizzabili con variabili segnaposto",
|
||||
"add": "Nuovo modello",
|
||||
"edit": "Modifica modello",
|
||||
"name": "Nome del modello",
|
||||
"name_placeholder": "es.: Email di follow-up",
|
||||
"category": "Categoria",
|
||||
"category_placeholder": "es.: Lavoro, Personale",
|
||||
"subject": "Oggetto",
|
||||
"subject_placeholder": "Oggetto dell'email",
|
||||
"body": "Corpo",
|
||||
"body_placeholder": "Contenuto dell'email...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Invia come",
|
||||
"default_identity": "Identità predefinita",
|
||||
"favorite": "Preferito",
|
||||
"cancel": "Annulla",
|
||||
"create": "Crea",
|
||||
"update": "Aggiorna",
|
||||
"confirm_delete": "Elimina",
|
||||
"no_templates": "Nessun modello",
|
||||
"manage": "Gestisci modelli",
|
||||
"count": "{count, plural, one {# modello} other {# modelli}}",
|
||||
"export_import": "Esporta e importa",
|
||||
"export_import_description": "Esegui il backup dei modelli o trasferiscili su un altro dispositivo",
|
||||
"export": "Esporta",
|
||||
"import": "Importa",
|
||||
"validation": {
|
||||
"empty": "Il nome del modello è obbligatorio",
|
||||
"too_long": "Il nome del modello non deve superare i 200 caratteri"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navigazione",
|
||||
"actions": "Azioni sui messaggi",
|
||||
"global": "Globali",
|
||||
"threads": "Conversazioni"
|
||||
"threads": "Conversazioni",
|
||||
"composer": "Composizione"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Messaggio successivo",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Espandi/comprimi conversazione"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Apri selettore modelli"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Scegli un modello",
|
||||
"search_placeholder": "Cerca modelli...",
|
||||
"section_favorites": "Preferiti",
|
||||
"section_recent": "Recenti",
|
||||
"section_uncategorized": "Altri",
|
||||
"no_templates": "Nessun modello",
|
||||
"no_results": "Nessun modello trovato",
|
||||
"fill_placeholders": "Compila i valori segnaposto",
|
||||
"enter_value": "Inserisci un valore...",
|
||||
"preview": "Anteprima",
|
||||
"insert_with_values": "Inserisci con valori",
|
||||
"insert_raw": "Inserisci grezzo",
|
||||
"copy_suffix": "(copia)",
|
||||
"placeholder": "Variabile",
|
||||
"placeholders": {
|
||||
"recipient_name": "Nome del destinatario",
|
||||
"company": "Nome dell'azienda",
|
||||
"date": "Data odierna",
|
||||
"day_of_week": "Giorno della settimana",
|
||||
"sender_name": "Il tuo nome"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contatti",
|
||||
"search_placeholder": "Cerca contatti...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "件名: {subject}",
|
||||
"to": "宛先: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "サブアドレスを削除"
|
||||
"remove_sub_address": "サブアドレスを削除",
|
||||
"use_template": "テンプレート",
|
||||
"save_as_template": "テンプレートとして保存"
|
||||
},
|
||||
"common": {
|
||||
"loading": "読み込み中...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "不在応答の設定の保存に失敗しました",
|
||||
"filters_saved": "フィルターを保存しました",
|
||||
"filters_save_failed": "フィルターの保存に失敗しました",
|
||||
"filters_deleted": "フィルタールールが削除されました"
|
||||
"filters_deleted": "フィルタールールが削除されました",
|
||||
"templates_exported": "テンプレートをエクスポートしました",
|
||||
"templates_imported": "{count}件のテンプレートをインポートしました",
|
||||
"templates_import_errors": "一部のテンプレートをインポートできませんでした",
|
||||
"templates_import_empty": "ファイルにテンプレートが見つかりません"
|
||||
},
|
||||
"date": {
|
||||
"today": "今日",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "不在応答",
|
||||
"advanced": "詳細設定",
|
||||
"calendar": "カレンダー",
|
||||
"filters": "フィルター"
|
||||
"filters": "フィルター",
|
||||
"templates": "テンプレート"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "外観",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, other {#個の条件}}",
|
||||
"actions_count": "{count, plural, other {#個のアクション}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "メールテンプレート",
|
||||
"description": "プレースホルダー変数付きの再利用可能なメールテンプレートを作成",
|
||||
"add": "新規テンプレート",
|
||||
"edit": "テンプレートを編集",
|
||||
"name": "テンプレート名",
|
||||
"name_placeholder": "例:フォローアップメール",
|
||||
"category": "カテゴリー",
|
||||
"category_placeholder": "例:仕事、個人",
|
||||
"subject": "件名",
|
||||
"subject_placeholder": "メールの件名",
|
||||
"body": "本文",
|
||||
"body_placeholder": "メール本文...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "送信者",
|
||||
"default_identity": "デフォルトのID",
|
||||
"favorite": "お気に入り",
|
||||
"cancel": "キャンセル",
|
||||
"create": "作成",
|
||||
"update": "更新",
|
||||
"confirm_delete": "削除",
|
||||
"no_templates": "テンプレートがありません",
|
||||
"manage": "テンプレートを管理",
|
||||
"count": "{count}件のテンプレート",
|
||||
"export_import": "エクスポートとインポート",
|
||||
"export_import_description": "テンプレートのバックアップや別のデバイスへの転送",
|
||||
"export": "エクスポート",
|
||||
"import": "インポート",
|
||||
"validation": {
|
||||
"empty": "テンプレート名は必須です",
|
||||
"too_long": "テンプレート名は200文字以内にしてください"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "ナビゲーション",
|
||||
"actions": "メール操作",
|
||||
"global": "全般",
|
||||
"threads": "スレッド"
|
||||
"threads": "スレッド",
|
||||
"composer": "作成"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "次のメール",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "スレッドの展開/折りたたみ"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "テンプレートピッカーを開く"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "テンプレートを選択",
|
||||
"search_placeholder": "テンプレートを検索...",
|
||||
"section_favorites": "お気に入り",
|
||||
"section_recent": "最近使用",
|
||||
"section_uncategorized": "その他",
|
||||
"no_templates": "テンプレートがありません",
|
||||
"no_results": "テンプレートが見つかりません",
|
||||
"fill_placeholders": "プレースホルダーの値を入力",
|
||||
"enter_value": "値を入力...",
|
||||
"preview": "プレビュー",
|
||||
"insert_with_values": "値を挿入",
|
||||
"insert_raw": "そのまま挿入",
|
||||
"copy_suffix": "(コピー)",
|
||||
"placeholder": "変数",
|
||||
"placeholders": {
|
||||
"recipient_name": "宛先の名前",
|
||||
"company": "会社名",
|
||||
"date": "今日の日付",
|
||||
"day_of_week": "曜日",
|
||||
"sender_name": "あなたの名前"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "連絡先",
|
||||
"search_placeholder": "連絡先を検索...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Onderwerp: {subject}",
|
||||
"to": "Aan: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Sub-adres verwijderen"
|
||||
"remove_sub_address": "Sub-adres verwijderen",
|
||||
"use_template": "Sjabloon",
|
||||
"save_as_template": "Opslaan als sjabloon"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Laden...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Kan afwezigheidsinstellingen niet opslaan",
|
||||
"filters_saved": "Filters succesvol opgeslagen",
|
||||
"filters_save_failed": "Filters opslaan mislukt",
|
||||
"filters_deleted": "Filterregel verwijderd"
|
||||
"filters_deleted": "Filterregel verwijderd",
|
||||
"templates_exported": "Sjablonen succesvol geëxporteerd",
|
||||
"templates_imported": "{count, plural, one {# sjabloon geïmporteerd} other {# sjablonen geïmporteerd}}",
|
||||
"templates_import_errors": "Sommige sjablonen konden niet worden geïmporteerd",
|
||||
"templates_import_empty": "Geen sjablonen gevonden in het bestand"
|
||||
},
|
||||
"date": {
|
||||
"today": "Vandaag",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Afwezigheidsmelder",
|
||||
"advanced": "Geavanceerd",
|
||||
"calendar": "Agenda",
|
||||
"filters": "Filters"
|
||||
"filters": "Filters",
|
||||
"templates": "Sjablonen"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Uiterlijk",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# voorwaarde} other {# voorwaarden}}",
|
||||
"actions_count": "{count, plural, one {# actie} other {# acties}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "E-mailsjablonen",
|
||||
"description": "Maak herbruikbare e-mailsjablonen met plaatshoudervariabelen",
|
||||
"add": "Nieuw sjabloon",
|
||||
"edit": "Sjabloon bewerken",
|
||||
"name": "Sjabloonnaam",
|
||||
"name_placeholder": "bijv.: Opvolgmail",
|
||||
"category": "Categorie",
|
||||
"category_placeholder": "bijv.: Werk, Persoonlijk",
|
||||
"subject": "Onderwerp",
|
||||
"subject_placeholder": "E-mailonderwerp",
|
||||
"body": "Inhoud",
|
||||
"body_placeholder": "E-mailinhoud...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Verzenden als",
|
||||
"default_identity": "Standaard identiteit",
|
||||
"favorite": "Favoriet",
|
||||
"cancel": "Annuleren",
|
||||
"create": "Aanmaken",
|
||||
"update": "Bijwerken",
|
||||
"confirm_delete": "Verwijderen",
|
||||
"no_templates": "Geen sjablonen",
|
||||
"manage": "Sjablonen beheren",
|
||||
"count": "{count, plural, one {# sjabloon} other {# sjablonen}}",
|
||||
"export_import": "Exporteren en importeren",
|
||||
"export_import_description": "Maak een back-up van uw sjablonen of breng ze over naar een ander apparaat",
|
||||
"export": "Exporteren",
|
||||
"import": "Importeren",
|
||||
"validation": {
|
||||
"empty": "Sjabloonnaam is verplicht",
|
||||
"too_long": "Sjabloonnaam mag maximaal 200 tekens zijn"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navigatie",
|
||||
"actions": "E-mailacties",
|
||||
"global": "Globaal",
|
||||
"threads": "Gesprekken"
|
||||
"threads": "Gesprekken",
|
||||
"composer": "Opstellen"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Volgende e-mail",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Gesprek uitklappen/inklappen"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Sjabloonkiezer openen"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Kies een sjabloon",
|
||||
"search_placeholder": "Sjablonen zoeken...",
|
||||
"section_favorites": "Favorieten",
|
||||
"section_recent": "Recent",
|
||||
"section_uncategorized": "Overig",
|
||||
"no_templates": "Geen sjablonen",
|
||||
"no_results": "Geen sjablonen gevonden",
|
||||
"fill_placeholders": "Plaatshouderwaarden invullen",
|
||||
"enter_value": "Voer een waarde in...",
|
||||
"preview": "Voorbeeld",
|
||||
"insert_with_values": "Invoegen met waarden",
|
||||
"insert_raw": "Onbewerkt invoegen",
|
||||
"copy_suffix": "(kopie)",
|
||||
"placeholder": "Variabele",
|
||||
"placeholders": {
|
||||
"recipient_name": "Naam ontvanger",
|
||||
"company": "Bedrijfsnaam",
|
||||
"date": "Huidige datum",
|
||||
"day_of_week": "Dag van de week",
|
||||
"sender_name": "Uw naam"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contacten",
|
||||
"search_placeholder": "Contacten zoeken...",
|
||||
|
||||
+71
-4
@@ -288,7 +288,9 @@
|
||||
"subject": "Assunto: {subject}",
|
||||
"to": "Para: {recipients}"
|
||||
},
|
||||
"remove_sub_address": "Remover sub-endereço"
|
||||
"remove_sub_address": "Remover sub-endereço",
|
||||
"use_template": "Modelo",
|
||||
"save_as_template": "Salvar como modelo"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Carregando...",
|
||||
@@ -342,7 +344,11 @@
|
||||
"vacation_save_failed": "Falha ao salvar configurações de resposta automática",
|
||||
"filters_saved": "Filtros salvos com sucesso",
|
||||
"filters_save_failed": "Falha ao salvar os filtros",
|
||||
"filters_deleted": "Regra de filtragem eliminada"
|
||||
"filters_deleted": "Regra de filtragem eliminada",
|
||||
"templates_exported": "Modelos exportados com sucesso",
|
||||
"templates_imported": "{count, plural, one {# modelo importado} other {# modelos importados}}",
|
||||
"templates_import_errors": "Alguns modelos não puderam ser importados",
|
||||
"templates_import_empty": "Nenhum modelo encontrado no arquivo"
|
||||
},
|
||||
"date": {
|
||||
"today": "Hoje",
|
||||
@@ -398,7 +404,8 @@
|
||||
"vacation": "Resposta automática",
|
||||
"advanced": "Avançado",
|
||||
"calendar": "Calendário",
|
||||
"filters": "Filtros"
|
||||
"filters": "Filtros",
|
||||
"templates": "Modelos"
|
||||
},
|
||||
"appearance": {
|
||||
"title": "Aparência",
|
||||
@@ -782,6 +789,39 @@
|
||||
"conditions_count": "{count, plural, one {# condição} other {# condições}}",
|
||||
"actions_count": "{count, plural, one {# ação} other {# ações}}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"title": "Modelos de e-mail",
|
||||
"description": "Crie modelos de e-mail reutilizáveis com variáveis de marcador",
|
||||
"add": "Novo modelo",
|
||||
"edit": "Editar modelo",
|
||||
"name": "Nome do modelo",
|
||||
"name_placeholder": "ex.: E-mail de acompanhamento",
|
||||
"category": "Categoria",
|
||||
"category_placeholder": "ex.: Trabalho, Pessoal",
|
||||
"subject": "Assunto",
|
||||
"subject_placeholder": "Linha de assunto do e-mail",
|
||||
"body": "Corpo",
|
||||
"body_placeholder": "Conteúdo do e-mail...",
|
||||
"recipients_placeholder": "email@example.com",
|
||||
"identity": "Enviar como",
|
||||
"default_identity": "Identidade padrão",
|
||||
"favorite": "Favorito",
|
||||
"cancel": "Cancelar",
|
||||
"create": "Criar",
|
||||
"update": "Atualizar",
|
||||
"confirm_delete": "Excluir",
|
||||
"no_templates": "Sem modelos",
|
||||
"manage": "Gerenciar modelos",
|
||||
"count": "{count, plural, one {# modelo} other {# modelos}}",
|
||||
"export_import": "Exportar e importar",
|
||||
"export_import_description": "Faça backup dos seus modelos ou transfira-os para outro dispositivo",
|
||||
"export": "Exportar",
|
||||
"import": "Importar",
|
||||
"validation": {
|
||||
"empty": "O nome do modelo é obrigatório",
|
||||
"too_long": "O nome do modelo não pode exceder 200 caracteres"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
@@ -825,7 +865,8 @@
|
||||
"navigation": "Navegação",
|
||||
"actions": "Ações de E-mail",
|
||||
"global": "Global",
|
||||
"threads": "Conversas"
|
||||
"threads": "Conversas",
|
||||
"composer": "Redação"
|
||||
},
|
||||
"navigation": {
|
||||
"next_email": "Próximo e-mail",
|
||||
@@ -853,6 +894,9 @@
|
||||
},
|
||||
"threads": {
|
||||
"expand_collapse": "Expandir/recolher conversa"
|
||||
},
|
||||
"composer": {
|
||||
"template_picker": "Abrir seletor de modelos"
|
||||
}
|
||||
},
|
||||
"threads": {
|
||||
@@ -931,6 +975,29 @@
|
||||
"subaddress_tag": "+{tag}"
|
||||
}
|
||||
},
|
||||
"templates": {
|
||||
"picker_title": "Escolher um modelo",
|
||||
"search_placeholder": "Pesquisar modelos...",
|
||||
"section_favorites": "Favoritos",
|
||||
"section_recent": "Recentes",
|
||||
"section_uncategorized": "Outros",
|
||||
"no_templates": "Sem modelos",
|
||||
"no_results": "Nenhum modelo encontrado",
|
||||
"fill_placeholders": "Preencher valores dos marcadores",
|
||||
"enter_value": "Insira um valor...",
|
||||
"preview": "Pré-visualização",
|
||||
"insert_with_values": "Inserir com valores",
|
||||
"insert_raw": "Inserir bruto",
|
||||
"copy_suffix": "(cópia)",
|
||||
"placeholder": "Variável",
|
||||
"placeholders": {
|
||||
"recipient_name": "Nome do destinatário",
|
||||
"company": "Nome da empresa",
|
||||
"date": "Data atual",
|
||||
"day_of_week": "Dia da semana",
|
||||
"sender_name": "Seu nome"
|
||||
}
|
||||
},
|
||||
"contacts": {
|
||||
"title": "Contatos",
|
||||
"search_placeholder": "Pesquisar contatos...",
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import type { EmailTemplate } from '@/lib/template-types';
|
||||
import {
|
||||
exportTemplates as exportUtil,
|
||||
importTemplates as importUtil,
|
||||
filterTemplates,
|
||||
} from '@/lib/template-utils';
|
||||
|
||||
const MAX_RECENT = 5;
|
||||
|
||||
interface TemplateStore {
|
||||
templates: EmailTemplate[];
|
||||
recentTemplateIds: string[];
|
||||
|
||||
addTemplate: (template: Omit<EmailTemplate, 'id' | 'createdAt' | 'updatedAt'>) => EmailTemplate;
|
||||
updateTemplate: (id: string, updates: Partial<Omit<EmailTemplate, 'id' | 'createdAt'>>) => void;
|
||||
deleteTemplate: (id: string) => void;
|
||||
duplicateTemplate: (id: string, nameSuffix?: string) => EmailTemplate | null;
|
||||
toggleFavorite: (id: string) => void;
|
||||
recordUsage: (id: string) => void;
|
||||
|
||||
getTemplatesByCategory: () => Record<string, EmailTemplate[]>;
|
||||
getFavorites: () => EmailTemplate[];
|
||||
getRecent: () => EmailTemplate[];
|
||||
searchTemplates: (query: string) => EmailTemplate[];
|
||||
|
||||
exportAllTemplates: () => string;
|
||||
importTemplates: (json: string) => { count: number; errors: string[] };
|
||||
}
|
||||
|
||||
export const useTemplateStore = create<TemplateStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
templates: [],
|
||||
recentTemplateIds: [],
|
||||
|
||||
addTemplate: (data) => {
|
||||
const now = new Date().toISOString();
|
||||
const template: EmailTemplate = {
|
||||
...data,
|
||||
id: crypto.randomUUID(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
set((state) => ({
|
||||
templates: [...state.templates, template],
|
||||
}));
|
||||
return template;
|
||||
},
|
||||
|
||||
updateTemplate: (id, updates) => {
|
||||
set((state) => ({
|
||||
templates: state.templates.map((t) =>
|
||||
t.id === id
|
||||
? { ...t, ...updates, updatedAt: new Date().toISOString() }
|
||||
: t
|
||||
),
|
||||
}));
|
||||
},
|
||||
|
||||
deleteTemplate: (id) => {
|
||||
set((state) => ({
|
||||
templates: state.templates.filter((t) => t.id !== id),
|
||||
recentTemplateIds: state.recentTemplateIds.filter((rid) => rid !== id),
|
||||
}));
|
||||
},
|
||||
|
||||
duplicateTemplate: (id, nameSuffix) => {
|
||||
const original = get().templates.find((t) => t.id === id);
|
||||
if (!original) return null;
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const duplicate: EmailTemplate = {
|
||||
...original,
|
||||
id: crypto.randomUUID(),
|
||||
name: `${original.name} ${nameSuffix || '(copy)'}`,
|
||||
isFavorite: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
set((state) => ({
|
||||
templates: [...state.templates, duplicate],
|
||||
}));
|
||||
return duplicate;
|
||||
},
|
||||
|
||||
toggleFavorite: (id) => {
|
||||
set((state) => ({
|
||||
templates: state.templates.map((t) =>
|
||||
t.id === id ? { ...t, isFavorite: !t.isFavorite, updatedAt: new Date().toISOString() } : t
|
||||
),
|
||||
}));
|
||||
},
|
||||
|
||||
recordUsage: (id) => {
|
||||
set((state) => {
|
||||
const filtered = state.recentTemplateIds.filter((rid) => rid !== id);
|
||||
return {
|
||||
recentTemplateIds: [id, ...filtered].slice(0, MAX_RECENT),
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
getTemplatesByCategory: () => {
|
||||
const { templates } = get();
|
||||
const grouped: Record<string, EmailTemplate[]> = {};
|
||||
for (const t of templates) {
|
||||
const cat = t.category || '';
|
||||
if (!grouped[cat]) grouped[cat] = [];
|
||||
grouped[cat].push(t);
|
||||
}
|
||||
return grouped;
|
||||
},
|
||||
|
||||
getFavorites: () => {
|
||||
return get().templates.filter((t) => t.isFavorite);
|
||||
},
|
||||
|
||||
getRecent: () => {
|
||||
const { templates, recentTemplateIds } = get();
|
||||
return recentTemplateIds
|
||||
.map((id) => templates.find((t) => t.id === id))
|
||||
.filter(Boolean) as EmailTemplate[];
|
||||
},
|
||||
|
||||
searchTemplates: (query) => {
|
||||
return filterTemplates(get().templates, query);
|
||||
},
|
||||
|
||||
exportAllTemplates: () => {
|
||||
return exportUtil(get().templates);
|
||||
},
|
||||
|
||||
importTemplates: (json) => {
|
||||
const result = importUtil(json);
|
||||
if (result.templates.length > 0) {
|
||||
set((state) => ({
|
||||
templates: [...state.templates, ...result.templates],
|
||||
}));
|
||||
}
|
||||
return { count: result.templates.length, errors: result.errors };
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'template-storage',
|
||||
version: 1,
|
||||
}
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user