feat: split a pasted address list into recipient chips
Pasting a list of addresses into To/Cc/Bcc now creates one chip per address instead of dropping the whole blob in as a single invalid chip. A paste is split only when it actually contains a separator; a lone address falls through to normal editing. - Separators: commas, semicolons, and any whitespace/newline - covers comma/space dumps, spreadsheet columns and Outlook-style `;` lists. - Display names are preserved: `Name <email>`, a fully-quoted `"Name <email>"` entry, and `"Doe, John" <email>` (comma inside a quoted name) each stay a single chip with the name intact. - Bare-address runs split per address; a `<addr>` token is unwrapped; tokens that aren't valid addresses are left behind in the input for the user to fix rather than becoming junk chips. - Deduped case-insensitively within the paste and against existing chips. Implemented as splitPastedRecipients in email-composer-utils, layered on the shared quote/angle-aware splitter: splitRecipients gains an optional `separators` argument so the composer/mailto serialization boundary (comma-only) and the paste path (`,;\n\r`) share one implementation. Wired into the recipient chip input's onPaste handler (To/Cc/Bcc).
This commit is contained in:
committed by
Linus Rath
parent
638fc7db4e
commit
344795a8d9
@@ -160,6 +160,7 @@ vi.mock('@/lib/plugin-hooks', () => ({
|
||||
vi.mock('@/lib/email-sanitization', () => ({
|
||||
sanitizeSignatureHtml: (v: string) => v,
|
||||
sanitizeEmailHtml: (v: string) => v,
|
||||
parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/reply-identity', () => ({ resolveReplyFrom: () => null }));
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { fireEvent } from '@testing-library/dom';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { EmailComposer } from '../email-composer';
|
||||
|
||||
// ─── Heavy component mocks (mirrors recipient-chip-drag.test.tsx) ──────────────
|
||||
|
||||
vi.mock('@/components/email/rich-text-editor', () => ({
|
||||
RichTextEditor: ({ onChange }: { onChange?: (html: string) => void }) => (
|
||||
React.createElement('div', { 'data-testid': 'rich-text-editor', onClick: () => onChange?.('') })
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null }));
|
||||
vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null }));
|
||||
vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null }));
|
||||
vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null }));
|
||||
vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null }));
|
||||
vi.mock('@/hooks/use-focus-trap', () => ({
|
||||
useFocusTrap: () => ({ ref: { current: null } }),
|
||||
}));
|
||||
vi.mock('@/hooks/use-pro-multi-account-identities', () => ({
|
||||
useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }),
|
||||
stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }),
|
||||
}));
|
||||
|
||||
// ─── Store mocks ──────────────────────────────────────────────────────────────
|
||||
|
||||
vi.mock('@/stores/auth-store', () => {
|
||||
const state = {
|
||||
client: null,
|
||||
identities: [],
|
||||
primaryIdentity: null,
|
||||
isAuthenticated: false,
|
||||
isDemoMode: false,
|
||||
activeAccountId: null,
|
||||
connectionLost: false,
|
||||
getClientForAccount: () => undefined,
|
||||
getAllConnectedClients: () => new Map(),
|
||||
syncIdentities: () => {},
|
||||
refreshIdentities: async () => {},
|
||||
};
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useAuthStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/identity-store', () => {
|
||||
const state = { identities: [], defaultIdentityId: null };
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useIdentityStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/account-store', () => {
|
||||
const state = { accounts: [], getAccountById: () => undefined };
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useAccountStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/smime-store', () => {
|
||||
const state = {
|
||||
certs: [],
|
||||
signingEnabled: false,
|
||||
encryptionEnabled: false,
|
||||
defaultSigningCertId: null,
|
||||
defaultEncryptionCertId: null,
|
||||
};
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useSmimeStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/email-store', () => {
|
||||
const state = {
|
||||
draftSaveEnabled: false,
|
||||
sendRawEmail: async () => ({ sent: true }),
|
||||
};
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useEmailStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/settings-store', () => {
|
||||
const state = {
|
||||
timeFormat: '24h',
|
||||
plainTextMode: false,
|
||||
subAddressDelimiter: '+',
|
||||
autoSelectReplyIdentity: true,
|
||||
attachmentReminderEnabled: false,
|
||||
attachmentReminderKeywords: [],
|
||||
sendDelaySeconds: 0,
|
||||
signaturePosition: 'above_quote',
|
||||
signatureSeparatorEnabled: false,
|
||||
requestReadReceiptDefault: false,
|
||||
addTrustedSender: () => {},
|
||||
trustedSendersAddressBook: null,
|
||||
};
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useSettingsStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/contact-store', () => {
|
||||
const state = {
|
||||
contacts: [],
|
||||
getAutocomplete: async () => [],
|
||||
addToTrustedSendersBook: async () => {},
|
||||
};
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useContactStore: hook };
|
||||
});
|
||||
|
||||
vi.mock('@/stores/template-store', () => {
|
||||
const state = { templates: [], addTemplate: async () => {} };
|
||||
const hook = (sel?: (s: typeof state) => unknown) =>
|
||||
typeof sel === 'function' ? sel(state) : state;
|
||||
hook.getState = () => state;
|
||||
hook.setState = (p: Partial<typeof state>) => Object.assign(state, p);
|
||||
return { useTemplateStore: hook };
|
||||
});
|
||||
|
||||
// ─── Misc dependency mocks ────────────────────────────────────────────────────
|
||||
|
||||
vi.mock('@/stores/toast-store', () => ({
|
||||
toast: { info: () => {}, error: () => {}, success: () => {} },
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/plugin-hooks', () => ({
|
||||
emailHooks: {
|
||||
onComposerOpen: { call: async () => [] },
|
||||
onRecipientChange: { call: async () => [] },
|
||||
getRecipientSuggestions: { call: async () => [] },
|
||||
onSend: { call: async () => [] },
|
||||
beforeSend: { call: async () => [] },
|
||||
},
|
||||
contactHooks: {
|
||||
search: { call: async () => [] },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/email-sanitization', () => ({
|
||||
sanitizeSignatureHtml: (v: string) => v,
|
||||
sanitizeEmailHtml: (v: string) => v,
|
||||
parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/reply-identity', () => ({ resolveReplyFrom: () => null }));
|
||||
vi.mock('@/lib/email-threading', () => ({
|
||||
computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }),
|
||||
}));
|
||||
vi.mock('@/lib/signature-utils', () => ({
|
||||
appendPlainTextSignature: (body: string) => body,
|
||||
getPlainTextSignature: () => '',
|
||||
}));
|
||||
vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' }));
|
||||
vi.mock('@/lib/smime/smime-sign', () => ({ smimeSign: async () => null }));
|
||||
vi.mock('@/lib/smime/smime-encrypt', () => ({ smimeEncrypt: async () => null }));
|
||||
vi.mock('@/lib/smime/mime-builder', () => ({
|
||||
buildMimeMessage: () => null,
|
||||
wrapCmsAsSmimeMessage: () => null,
|
||||
}));
|
||||
vi.mock('@/lib/debug', () => ({ debug: () => {} }));
|
||||
vi.mock('@/components/email/quoted-html', () => ({
|
||||
buildQuotedHtmlBlock: () => '',
|
||||
serializeEditorContent: () => '',
|
||||
}));
|
||||
vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s }));
|
||||
|
||||
// ─── Shared test data ─────────────────────────────────────────────────────────
|
||||
|
||||
const EMPTY_DATA = {
|
||||
to: '',
|
||||
cc: '',
|
||||
bcc: '',
|
||||
subject: '',
|
||||
body: '',
|
||||
showCc: true,
|
||||
showBcc: true,
|
||||
selectedIdentityId: null,
|
||||
subAddressTag: '',
|
||||
mode: 'compose' as const,
|
||||
draftId: null,
|
||||
};
|
||||
|
||||
/** next-intl is mocked to return the key, so the To placeholder is "to_placeholder". */
|
||||
const toInput = () => screen.getByPlaceholderText('to_placeholder') as HTMLInputElement;
|
||||
const ccInput = () => screen.getByPlaceholderText('cc_placeholder') as HTMLInputElement;
|
||||
|
||||
const paste = (input: HTMLElement, text: string) =>
|
||||
fireEvent.paste(input, { clipboardData: { getData: () => text } });
|
||||
|
||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('RecipientChipInput paste', () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); });
|
||||
|
||||
it('splits a pasted list (comma / semicolon / whitespace) into one chip per address', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput(); // capture once — placeholder disappears once chips exist
|
||||
paste(input, 'a@x.com b@y.com; c@z.com');
|
||||
|
||||
expect(screen.getByText('a@x.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('b@y.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('c@z.com')).toBeInTheDocument();
|
||||
// all consumed → input cleared
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('chips the valid addresses and leaves invalid text in the input', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, 'foo bar a@x.com');
|
||||
|
||||
expect(screen.getByText('a@x.com')).toBeInTheDocument();
|
||||
expect(input.value).toBe('foo bar');
|
||||
});
|
||||
|
||||
it('does not pre-empt a single-address paste (no delimiter → normal editing)', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
paste(toInput(), 'single@x.com');
|
||||
|
||||
// The handler bailed out, so no chip was created from the single token.
|
||||
expect(screen.queryByText('single@x.com')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps display names from a fully-quoted "Name <email>" list', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, '"Alice Smith <alice@x.com>", "Alex Smith <alex@x.com>"');
|
||||
|
||||
// Chips render as "Name (email)" when a display name is present.
|
||||
expect(screen.getByText('Alice Smith (alice@x.com)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Alex Smith (alex@x.com)')).toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('keeps a `Name <email>` pair as a single named chip', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, 'John Doe <j@x.com>, jane@y.com');
|
||||
|
||||
expect(screen.getByText('John Doe (j@x.com)')).toBeInTheDocument();
|
||||
expect(screen.getByText('jane@y.com')).toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('keeps a comma inside a quoted display name intact', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, '"Doe, John" <j@x.com>; bob@z.com');
|
||||
|
||||
expect(screen.getByText('Doe, John (j@x.com)')).toBeInTheDocument();
|
||||
expect(screen.getByText('bob@z.com')).toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('splits a newline-separated block (e.g. a spreadsheet column)', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, 'a@x.com\nb@y.com\nc@z.com');
|
||||
|
||||
expect(screen.getByText('a@x.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('b@y.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('c@z.com')).toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('dedupes case-insensitively within the paste and against existing chips', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput(); // DOM node persists across pastes (placeholder just clears)
|
||||
paste(input, 'a@x.com, A@X.com, b@y.com'); // within-paste dup collapses
|
||||
paste(input, 'A@X.COM, c@z.com'); // dup of an existing chip is dropped
|
||||
|
||||
expect(screen.getByText('b@y.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('c@z.com')).toBeInTheDocument();
|
||||
// a@x.com appears exactly once despite three case variants across two pastes.
|
||||
expect(screen.getAllByText('a@x.com')).toHaveLength(1);
|
||||
expect(screen.queryByText('A@X.COM')).not.toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('chips the valid (named) entries and leaves a non-address token behind', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
const input = toInput();
|
||||
paste(input, '"VIP" <vip@x.com>, not-an-email, b@y.com');
|
||||
|
||||
expect(screen.getByText('VIP (vip@x.com)')).toBeInTheDocument();
|
||||
expect(screen.getByText('b@y.com')).toBeInTheDocument();
|
||||
expect(input.value).toBe('not-an-email');
|
||||
});
|
||||
|
||||
it('works on the Cc field (shared handler)', () => {
|
||||
render(<EmailComposer initialData={EMPTY_DATA} />);
|
||||
paste(ccInput(), 'x@a.com; y@b.com');
|
||||
|
||||
expect(screen.getByText('x@a.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('y@b.com')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
parseRecipient,
|
||||
parseRecipientList,
|
||||
formatRecipientList,
|
||||
splitPastedRecipients,
|
||||
type Recipient,
|
||||
} from "@/lib/email-composer-utils";
|
||||
import { RichTextEditor } from "@/components/email/rich-text-editor";
|
||||
@@ -2919,6 +2920,20 @@ function RecipientChipInput({
|
||||
}
|
||||
};
|
||||
|
||||
// Pasting a list of addresses (comma/semicolon/whitespace separated) splits
|
||||
// into one chip per valid address; anything that isn't a valid address is
|
||||
// left in the input for the user to fix. A single address with no separator
|
||||
// falls through to the browser's normal paste so it stays editable.
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
const text = e.clipboardData.getData('text');
|
||||
if (!/[\s,;]/.test(text.trim())) return;
|
||||
const { valid, invalid } = splitPastedRecipients(text, chips.map(c => c.email));
|
||||
if (valid.length === 0) return;
|
||||
e.preventDefault();
|
||||
onChipsChange([...chips, ...valid]);
|
||||
onInputChange([inputText.trim(), invalid.join(' ')].filter(Boolean).join(' '));
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (activeAutoField === field && autocompleteResults.length > 0) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Escape' ||
|
||||
@@ -3113,6 +3128,7 @@ function RecipientChipInput({
|
||||
value={inputText}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onBlur={handleBlur}
|
||||
className="flex-1 min-w-[120px] border-0 outline-none h-7 text-sm bg-transparent text-foreground placeholder:text-muted-foreground"
|
||||
role="combobox"
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
parseRecipient,
|
||||
parseRecipientList,
|
||||
formatRecipientList,
|
||||
splitPastedRecipients,
|
||||
} from "../email-composer-utils";
|
||||
|
||||
describe("plainTextToComposerBody", () => {
|
||||
@@ -150,6 +151,16 @@ describe("splitRecipients", () => {
|
||||
it("returns an empty array for an empty string", () => {
|
||||
expect(splitRecipients("")).toEqual([]);
|
||||
});
|
||||
|
||||
it("only splits on the given separators (default comma keeps semicolons/newlines literal)", () => {
|
||||
expect(splitRecipients("a@x.com; b@y.com")).toEqual(["a@x.com; b@y.com"]);
|
||||
});
|
||||
|
||||
it("splits on a wider separator set while keeping quotes/angles literal", () => {
|
||||
expect(
|
||||
splitRecipients('"Doo, John" <john@doo.org>; a@x.com\nb@y.com', ',;\n\r'),
|
||||
).toEqual(['"Doo, John" <john@doo.org>', "a@x.com", "b@y.com"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatRecipient / parseRecipient", () => {
|
||||
@@ -198,3 +209,68 @@ describe("parseRecipientList / formatRecipientList", () => {
|
||||
expect(parseRecipientList("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitPastedRecipients", () => {
|
||||
it("splits on commas, semicolons and whitespace (incl. newline/tab)", () => {
|
||||
const { valid, invalid } = splitPastedRecipients(
|
||||
"a@x.com, b@y.com; c@z.com\nd@w.com\te@v.com f@u.com",
|
||||
);
|
||||
expect(valid.map((r) => r.email)).toEqual([
|
||||
"a@x.com", "b@y.com", "c@z.com", "d@w.com", "e@v.com", "f@u.com",
|
||||
]);
|
||||
expect(invalid).toEqual([]);
|
||||
});
|
||||
|
||||
it("collapses runs of mixed separators and drops empties", () => {
|
||||
const { valid } = splitPastedRecipients(" a@x.com ,; , b@y.com ");
|
||||
expect(valid.map((r) => r.email)).toEqual(["a@x.com", "b@y.com"]);
|
||||
});
|
||||
|
||||
it("partitions invalid tokens into `invalid`, keeping valid as chips", () => {
|
||||
const { valid, invalid } = splitPastedRecipients("a@x.com not-an-email b@y.com");
|
||||
expect(valid.map((r) => r.email)).toEqual(["a@x.com", "b@y.com"]);
|
||||
expect(invalid).toEqual(["not-an-email"]);
|
||||
});
|
||||
|
||||
it("unwraps an angle-bracketed token before validating", () => {
|
||||
const { valid } = splitPastedRecipients("<a@x.com>");
|
||||
expect(valid).toEqual([{ email: "a@x.com" }]);
|
||||
});
|
||||
|
||||
it("keeps a `Name <email>` pair as a single chip with its display name", () => {
|
||||
const { valid, invalid } = splitPastedRecipients("John Doe <j@x.com>");
|
||||
expect(valid).toEqual([{ name: "John Doe", email: "j@x.com" }]);
|
||||
expect(invalid).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a fully-quoted `\"Name <email>\"` entry with its display name", () => {
|
||||
const { valid, invalid } = splitPastedRecipients(
|
||||
'"Alice Smith <alice@x.com>", "Alex Smith <alex@x.com>"',
|
||||
);
|
||||
expect(valid).toEqual([
|
||||
{ name: "Alice Smith", email: "alice@x.com" },
|
||||
{ name: "Alex Smith", email: "alex@x.com" },
|
||||
]);
|
||||
expect(invalid).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a comma inside a quoted display name intact", () => {
|
||||
const { valid } = splitPastedRecipients('"Doe, John" <j@x.com>; bob@z.com');
|
||||
expect(valid).toEqual([
|
||||
{ name: "Doe, John", email: "j@x.com" },
|
||||
{ email: "bob@z.com" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes case-insensitively within the paste and against existing emails", () => {
|
||||
const { valid } = splitPastedRecipients(
|
||||
"a@x.com A@X.com b@y.com c@z.com",
|
||||
["B@Y.com"],
|
||||
);
|
||||
expect(valid.map((r) => r.email)).toEqual(["a@x.com", "c@z.com"]);
|
||||
});
|
||||
|
||||
it("returns empty arrays for blank input", () => {
|
||||
expect(splitPastedRecipients(" ")).toEqual({ valid: [], invalid: [] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isValidEmail } from "@/lib/validation";
|
||||
|
||||
const HTML_ESCAPE_MAP = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
@@ -56,13 +58,16 @@ export function rewriteCidImagesForEditor(html: string): string {
|
||||
export type Recipient = { name?: string; email: string };
|
||||
|
||||
/**
|
||||
* Splits a comma-separated recipient string into individual entries. Commas
|
||||
* inside a quoted display name (`"Doo, John" <john@doo.org>`) or angle brackets
|
||||
* (`<a,b@x>`) are treated as literal, not separators. Only used at the
|
||||
* (de)serialization boundary — the live composer state is an array, so the UI
|
||||
* never round-trips through this. Trims each part and drops empties.
|
||||
* Splits a recipient string into individual entries on any character in
|
||||
* `separators`, treating those characters as literal when they sit inside a
|
||||
* quoted display name (`"Doo, John" <john@doo.org>`) or angle brackets
|
||||
* (`<a,b@x>`). Trims each part and drops empties.
|
||||
*
|
||||
* Defaults to comma-only, the (de)serialization boundary used by the composer
|
||||
* state and mailto handling. Pasted lists pass a wider set (see
|
||||
* {@link splitPasteEntries}) because they also use `;` and line breaks.
|
||||
*/
|
||||
export function splitRecipients(value: string): string[] {
|
||||
export function splitRecipients(value: string, separators = ','): string[] {
|
||||
const result: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
@@ -77,7 +82,7 @@ export function splitRecipients(value: string): string[] {
|
||||
} else if (ch === '>' && !inQuotes) {
|
||||
inAngle = false;
|
||||
current += ch;
|
||||
} else if (ch === ',' && !inQuotes && !inAngle) {
|
||||
} else if (separators.includes(ch) && !inQuotes && !inAngle) {
|
||||
const trimmed = current.trim();
|
||||
if (trimmed) result.push(trimmed);
|
||||
current = '';
|
||||
@@ -140,6 +145,71 @@ export function formatRecipientList(recipients: Recipient[]): string {
|
||||
return recipients.map((r) => formatRecipient(r.name, r.email)).join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level split of a pasted block into recipient entries on commas,
|
||||
* semicolons and newlines (separators inside a quoted name or angle brackets
|
||||
* stay literal). Broader than the comma-only default of {@link splitRecipients}
|
||||
* because pasted lists also use `;` and line breaks as separators.
|
||||
*/
|
||||
function splitPasteEntries(value: string): string[] {
|
||||
return splitRecipients(value, ',;\n\r');
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits pasted text into recipient candidates and partitions them: valid email
|
||||
* addresses become `Recipient`s (deduped case-insensitively against
|
||||
* `existingEmails` and within the paste), and everything else is returned as
|
||||
* `invalid` for the caller to drop back into the input field.
|
||||
*
|
||||
* Handles both structured and bare lists, preserving display names:
|
||||
* - `"Name <email>"` (the whole recipient quoted), `Name <email>`, and
|
||||
* `"Doe, John" <email>` entries are kept intact with their display name.
|
||||
* - Bare-address dumps (`a@x.com b@y.com`, spreadsheet columns, comma/space/
|
||||
* semicolon/newline separated) split into one chip per address.
|
||||
* - A token wrapped in angle brackets (`<a@x.com>`) is unwrapped before
|
||||
* validating, so an `a <a@x.com>` fragment still yields the address.
|
||||
*/
|
||||
export function splitPastedRecipients(
|
||||
text: string,
|
||||
existingEmails: string[] = [],
|
||||
): { valid: Recipient[]; invalid: string[] } {
|
||||
const seen = new Set(existingEmails.map((e) => e.toLowerCase()));
|
||||
const valid: Recipient[] = [];
|
||||
const invalid: string[] = [];
|
||||
|
||||
// Adds a recipient if its address is valid and unseen. Returns true when the
|
||||
// entry is fully handled (valid or a known duplicate) so the caller can stop.
|
||||
const tryAdd = (r: Recipient): boolean => {
|
||||
if (!isValidEmail(r.email)) return false;
|
||||
const key = r.email.toLowerCase();
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
valid.push(r.name ? { name: r.name, email: r.email } : { email: r.email });
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Split on commas, semicolons and newlines in a quote/angle-aware way so a
|
||||
// `"Doe, John" <j@x.com>` or fully-quoted `"Name <email>"` entry stays a
|
||||
// single recipient (separators inside the name or the address are literal).
|
||||
for (const entry of splitPasteEntries(text)) {
|
||||
// 1. Structured: `Name <email>`, a bare address, or the whole
|
||||
// `Name <email>` wrapped in quotes (unwrap once and retry).
|
||||
if (tryAdd(parseRecipient(entry))) continue;
|
||||
const unwrapped = unquoteName(entry);
|
||||
if (unwrapped !== entry && tryAdd(parseRecipient(unwrapped))) continue;
|
||||
|
||||
// 2. Fallback: a bare-address run (`a@x.com b@y.com`) or a
|
||||
// `John Doe <j@x.com>` fragment where only the <addr> is valid.
|
||||
// Whitespace/semicolon-tokenize; leftover tokens stay behind.
|
||||
for (const token of entry.split(/[\s;]+/).map((t) => t.trim()).filter(Boolean)) {
|
||||
if (!tryAdd({ email: token.replace(/^<|>$/g, '') })) invalid.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
return { valid, invalid };
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the placeholder src on `<img data-cid="...">` elements with the
|
||||
* resolved data URL once the inline blob has been fetched. Leaves images
|
||||
|
||||
Reference in New Issue
Block a user