📧✨ Beautiful email. For everyone.
feat: support HTML email signatures (#19)
Paul Koeck0ce4378f10f5
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 84c6ce5..b7f2268 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -48,7 +48,7 @@ import {scopeKey,unlinkedServerDrafts,friendlyError,- identityKey,+ identitySignature,mailtoDraft,replyRecipients,type Address,@@ -89,6 +89,7 @@ import {type FolderDialogState,} from './AppDialogs'import { messageText } from './message-text'+import { signatureBlock, signatureText } from './signature'import { selectConversation } from './selection'import { ShortcutHint, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { emptyListState } from './empty-states'@@ -506,8 +507,7 @@ export function App() {? replyRecipients(message, identities, kind === 'replyAll'): undefinedconst identity = recipients?.identity || identities[0]- const signature =- settings.signatures[identityKey(id, identity.id)] ?? identity.textSignature ?? ''+ const signature = identitySignature(settings, identity)const who = (list: Address[]) =>list.map((a) => (a.name ? a.name + ' <' + a.email + '>' : a.email)).join(', ')const header = !message@@ -540,11 +540,17 @@ export function App() {'<p>' +escapeHtml(partial.text || '').replace(/\n/g, '<br/>') +'</p>' +- (signature ? '<p><br/>' + escapeHtml(signature).replace(/\n/g, '<br/>') + '</p>' : '') ++ (signature.format === 'html'+ ? signature.value.trim()+ ? signatureBlock(signature.value)+ : ''+ : signature.value+ ? '<p><br/>' + escapeHtml(signature.value).replace(/\n/g, '<br/>') + '</p>'+ : '') +quoteconst text = [partial.text || '',- signature,+ signature.format === 'html' ? signatureText(signature.value) : signature.value,message? header.join('\n') + '\n' + (kind === 'forward' ? body : body.replace(/^/gm, '> ')): '',diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 81bfc49..982b11b 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -32,6 +32,7 @@ import { localSaveDraft, localDeleteDraft } from './cache'import { RecipientField } from './RecipientField'import { formatBytes } from './mail-date'import { bindingText, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'+import { SignatureNode } from './signature'/** Plain wording for a finished send; the Drafts view offers recovery for anything left over. */function sentMessage(result: SendResult): string {@@ -155,6 +156,7 @@ export function Composer({link: { openOnClick: false },}),Placeholder.configure({ placeholder: 'Write your message…' }),+ SignatureNode,],content:initial.html ||diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsxindex 9c95b6f..674389d 100644--- a/apps/desktop/src/renderer/src/Reader.tsx+++ b/apps/desktop/src/renderer/src/Reader.tsx@@ -45,6 +45,7 @@ import { AccountMark } from './AccountMark'import { HintIconButton } from './HintIconButton'import { actionLimit } from './account-limits'import { ShortcutHint, useShortcutText } from './shortcuts'+import { emailSanitizeOptions } from './email-html'const formatAddress = (a: { name: string; email: string }) =>a.name ? a.name + ' <' + a.email + '>' : a.email@@ -201,30 +202,10 @@ export function EmailBody({(message.text?.trim() ? message.text : message.preview) ||'No readable message body is available.',)- template.innerHTML = DOMPurify.sanitize((message.html?.trim() ? message.html : '') || plain, {- FORBID_TAGS: [- 'script',- 'style',- 'iframe',- 'frame',- 'object',- 'embed',- 'form',- 'input',- 'button',- 'textarea',- 'select',- 'meta',- 'base',- 'link',- 'svg',- 'math',- 'video',- 'audio',- 'source',- ],- FORBID_ATTR: ['srcset', 'action', 'formaction', 'ping', 'autofocus', 'contenteditable'],- })+ template.innerHTML = DOMPurify.sanitize(+ (message.html?.trim() ? message.html : '') || plain,+ emailSanitizeOptions,+ )if (!template.content.textContent?.trim() &&(message.text?.trim() || message.preview?.trim())diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsxindex afb0819..10e30b4 100644--- a/apps/desktop/src/renderer/src/Settings.tsx+++ b/apps/desktop/src/renderer/src/Settings.tsx@@ -529,12 +529,17 @@ export function SettingsPanel({{bootstrap.accounts.length ? (<><p className="settings-lead">- Added to new messages, replies and forwards. Changes save as you type.+ Added to new messages, replies and forwards. Write plain text or HTML. Changes+ save as you type.</p><SignatureSettingsaccounts={bootstrap.accounts}- signatures={bootstrap.settings.signatures}- onSave={(signatures) => update({ signatures })}+ signatures={{+ signatures: bootstrap.settings.signatures,+ htmlSignatures: bootstrap.settings.htmlSignatures,+ }}+ remoteImages={bootstrap.settings.remoteImages}+ onSave={update}/></>) : (diff --git a/apps/desktop/src/renderer/src/SignatureSettings.tsx b/apps/desktop/src/renderer/src/SignatureSettings.tsxindex 985f1ee..8896656 100644--- a/apps/desktop/src/renderer/src/SignatureSettings.tsx+++ b/apps/desktop/src/renderer/src/SignatureSettings.tsx@@ -2,23 +2,55 @@ import { useEffect, useRef, useState } from 'react'import { useQueries } from '@tanstack/react-query'import { Check } from '@inlark/ui/icons'import { Spinner } from '@inlark/ui'-import { identityKey, type Account, type Settings as Preferences } from '@inlark/core'+import {+ identityKey,+ identitySignature,+ type Account,+ type Identity,+ type Settings as Preferences,+} from '@inlark/core'import { api } from './api'import { AccountMark } from './AccountMark'+import { SegmentedControl } from './SegmentedControl'+import { SignaturePreview, signatureText } from './signature'-type Signatures = Preferences['signatures']+type Signatures = Pick<Preferences, 'signatures' | 'htmlSignatures'>+type Format = 'text' | 'html'++const formats = [+ { value: 'text', label: 'Text' },+ { value: 'html', label: 'HTML' },+] as constconst same = (a: Signatures, b: Signatures) =>- Object.keys({ ...a, ...b }).every((key) => (a[key] ?? '') === (b[key] ?? ''))+ Object.keys({ ...a.signatures, ...b.signatures, ...a.htmlSignatures, ...b.htmlSignatures }).every(+ (key) =>+ (a.signatures[key] ?? '') === (b.signatures[key] ?? '') &&+ !!a.htmlSignatures?.[key] === !!b.htmlSignatures?.[key],+ )++const escapeHtml = (value: string) =>+ value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')++/** A first draft of the signature in the other format, when there's nothing better to restore. */+const convert = (value: string, to: Format) =>+ to === 'html'+ ? value.trim()+ ? '<p>' + escapeHtml(value).replace(/\n/g, '<br>\n') + '</p>'+ : ''+ : signatureText(value)/** Every account's signatures on one page, saved automatically as they're typed. */export function SignatureSettings({accounts,signatures,+ remoteImages,onSave,}: {accounts: Account[]signatures: Signatures+ /** Remote images in an HTML signature can only be previewed when these are allowed. */+ remoteImages: booleanonSave: (signatures: Signatures) => Promise<boolean>}) {const identities = useQueries({@@ -28,11 +60,14 @@ export function SignatureSettings({enabled: account.status === 'connected',})),})- const [values, setValues] = useState(signatures)+ const [values, setValues] = useState<Signatures>(signatures)const [savedKey, setSavedKey] = useState<string>()const latest = useRef(values)const saved = useRef(signatures)const edited = useRef<string>(undefined)+ // What each signature said in the format it was switched away from, so switching back+ // restores it rather than a lossy conversion.+ const previous = useRef(new Map<string, Record<Format, string | undefined>>())latest.current = valuesconst save = async (next: Signatures) => {if (same(next, saved.current)) return@@ -53,16 +88,52 @@ export function SignatureSettings({return () => clearTimeout(timer)}, [savedKey])+ const set = (key: string, value: string, format: Format) => {+ edited.current = key+ setValues((current) => {+ const { [key]: _, ...html } = current.htmlSignatures || {}+ return {+ signatures: { ...current.signatures, [key]: value },+ htmlSignatures: format === 'html' ? { ...html, [key]: true } : html,+ }+ })+ }+ const switchFormat = (identity: Identity, format: Format) => {+ const key = identityKey(identity.accountId, identity.id)+ const current = identitySignature(latest.current, identity)+ if (current.format === format) return+ const remembered = previous.current.get(key) || { text: undefined, html: undefined }+ previous.current.set(key, { ...remembered, [current.format]: current.value })+ const restored = remembered[format]+ set(key, restored?.trim() ? restored : convert(current.value, format), format)+ }++ const formatSwitch = (identity: Identity, address?: string) => (+ <SegmentedControl+ className="signature-format"+ label={'Signature format' + (address ? ' for ' + address : '')}+ value={identitySignature(values, identity).format}+ options={formats}+ onChange={(format) => switchFormat(identity, format)}+ />+ )+return (<div className="signature-accounts">{accounts.map((account, index) => {const query = identities[index]+ // A lone address is already named by the header, which then also holds its format.+ const lone =+ query.data?.length === 1 && query.data[0].email === account.email+ ? query.data[0]+ : undefinedreturn (<section className="signature-account" key={account.id}><header><AccountMark account={account} size={20} /><strong>{account.name}</strong><span>{account.email}</span>+ {lone && account.status === 'connected' && formatSwitch(lone)}</header>{account.status !== 'connected' ? (<p className="signature-note">Reconnect this account to edit its signatures.</p>@@ -76,37 +147,58 @@ export function SignatureSettings({query.data.map((identity) => {const key = identityKey(account.id, identity.id)const id = 'signature-' + key+ const signature = identitySignature(values, identity)+ const html = signature.format === 'html'+ const name = identity === lone ? account.name + ' signature' : undefinedreturn (<div className="signature-identity" key={key}>- {/* The address only needs naming when it isn't obvious from the header. */}- {(query.data.length > 1 || identity.email !== account.email) && (- <label htmlFor={id}>- {identity.name ? identity.name + ' · ' : ''}- {identity.email}- </label>+ {identity !== lone && (+ <div className="signature-identity-heading">+ <label htmlFor={id}>+ {identity.name ? identity.name + ' · ' : ''}+ {identity.email}+ </label>+ {formatSwitch(identity, identity.email)}+ </div>+ )}+ <div className="signature-editor">+ <textarea+ id={id}+ rows={html ? 6 : 3}+ className={html ? 'signature-code' : undefined}+ aria-label={name && (html ? name + ' HTML' : name)}+ value={signature.value}+ placeholder={html ? 'Paste or write HTML…' : 'No signature'}+ spellCheck={!html}+ autoCapitalize={html ? 'off' : undefined}+ autoCorrect={html ? 'off' : undefined}+ onChange={(e) => set(key, e.target.value, signature.format)}+ onBlur={() => void save(latest.current)}+ />+ <span+ className={'signature-saved' + (savedKey === key ? ' visible' : '')}+ aria-live="polite"+ >+ {savedKey === key && (+ <>+ <Check size={11} /> Saved+ </>+ )}+ </span>+ </div>+ {html && signature.value.trim() && (+ <div className="signature-preview">+ <span>Preview</span>+ <SignaturePreview html={signature.value} />+ {!remoteImages &&+ /<img[^>]+src\s*=\s*["']?https?:/i.test(signature.value) && (+ <p className="signature-note">+ Turn on Load remote images in General to preview linked images.+ Recipients still see them.+ </p>+ )}+ </div>)}- <textarea- id={id}- rows={3}- aria-label={query.data.length > 1 ? undefined : account.name + ' signature'}- value={values[key] ?? identity.textSignature ?? ''}- placeholder="No signature"- onChange={(e) => {- edited.current = key- setValues((current) => ({ ...current, [key]: e.target.value }))- }}- onBlur={() => void save(latest.current)}- />- <span- className={'signature-saved' + (savedKey === key ? ' visible' : '')}- aria-live="polite"- >- {savedKey === key && (- <>- <Check size={11} /> Saved- </>- )}- </span></div>)})diff --git a/apps/desktop/src/renderer/src/email-html.ts b/apps/desktop/src/renderer/src/email-html.tsnew file mode 100644index 0000000..1c2ccb2--- /dev/null+++ b/apps/desktop/src/renderer/src/email-html.ts@@ -0,0 +1,27 @@+import type { Config } from 'dompurify'++/** HTML from mail or a signature keeps its layout, but nothing that runs, submits or restyles the app. */+export const emailSanitizeOptions: Config = {+ FORBID_TAGS: [+ 'script',+ 'style',+ 'iframe',+ 'frame',+ 'object',+ 'embed',+ 'form',+ 'input',+ 'button',+ 'textarea',+ 'select',+ 'meta',+ 'base',+ 'link',+ 'svg',+ 'math',+ 'video',+ 'audio',+ 'source',+ ],+ FORBID_ATTR: ['srcset', 'action', 'formaction', 'ping', 'autofocus', 'contenteditable'],+}diff --git a/apps/desktop/src/renderer/src/message-text.ts b/apps/desktop/src/renderer/src/message-text.tsindex 1144c12..5eb7cb4 100644--- a/apps/desktop/src/renderer/src/message-text.ts+++ b/apps/desktop/src/renderer/src/message-text.ts@@ -1,13 +1,18 @@import DOMPurify from 'dompurify'import type { Message } from '@inlark/core'+/** The readable text of an HTML fragment, keeping its line and block breaks. */+export function htmlText(html: string): string {+ const separated = html.replace(/<br\s*\/?\s*>|<\/(?:p|div|li|h[1-6]|tr)>/gi, '$&\n')+ const text = DOMPurify.sanitize(separated, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] })+ const decoded = document.createElement('textarea')+ decoded.innerHTML = text+ return decoded.value.trim()+}+/** Preserve an HTML-only message's complete text when quoting it in the basic editor. */export function messageText(message: Message): string {if (message.text) return message.textif (!message.html) return message.preview- const separated = message.html.replace(/<br\s*\/?\s*>|<\/(?:p|div|li|h[1-6]|tr)>/gi, '$&\n')- const text = DOMPurify.sanitize(separated, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] })- const decoded = document.createElement('textarea')- decoded.innerHTML = text- return decoded.value.trim() || message.preview+ return htmlText(message.html) || message.preview}diff --git a/apps/desktop/src/renderer/src/signature.tsx b/apps/desktop/src/renderer/src/signature.tsxnew file mode 100644index 0000000..6b04438--- /dev/null+++ b/apps/desktop/src/renderer/src/signature.tsx@@ -0,0 +1,167 @@+import { useEffect, useRef } from 'react'+import DOMPurify from 'dompurify'+import {+ Node,+ NodeViewWrapper,+ ReactNodeViewRenderer,+ type ReactNodeViewProps,+} from '@tiptap/react'+import { X } from '@inlark/ui/icons'+import { api } from './api'+import { emailSanitizeOptions } from './email-html'+import { htmlText } from './message-text'++/** Marks an HTML signature in a draft, so it reopens as one block instead of loose markup. */+const marker = 'data-inlark-signature'++/** Remembers the latest result: the composer serializes its signature on every keystroke. */+const lastResult = (compute: (html: string) => string) => {+ let input: string | undefined+ let output = ''+ return (html: string) => {+ if (html !== input) [input, output] = [html, compute(html)]+ return output+ }+}++export const sanitizeSignature = lastResult(+ (html) => DOMPurify.sanitize(html, emailSanitizeOptions) as string,+)++/**+ * The plain-text alternative of an HTML signature. Whitespace in the code isn't layout, and+ * table cells, usually separate blocks of contact details, each end a line.+ */+export const signatureText = lastResult((html) =>+ htmlText(+ sanitizeSignature(html)+ .replace(/\s+/g, ' ')+ .replace(/<\/t[dh]>/gi, '$&<br>'),+ )+ .split('\n')+ .map((line) => line.replace(/\s+/g, ' ').trim())+ .join('\n')+ .replace(/\n{3,}/g, '\n\n'),+)++/** An HTML signature as the composer's starting markup. */+export const signatureBlock = (html: string) =>+ '<div ' + marker + '="">' + sanitizeSignature(html) + '</div>'++const fontStack = "Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"+/**+ * Shows signature HTML inside `host`, isolated in a shadow root so neither its markup nor the+ * app's styles leak across. Signatures are designed for the white most recipients read on, so+ * they're always shown on paper, in their own colours. Remote images load through the same privacy rules as mail; the+ * stored markup keeps their original addresses. Returns a function that stops pending loads.+ */+export function showSignature(host: HTMLElement, html: string): () => void {+ let active = true+ const root = host.shadowRoot || host.attachShadow({ mode: 'open' })+ const template = document.createElement('template')+ template.innerHTML = sanitizeSignature(html)+ const style = document.createElement('style')+ // The paper is an element of its own: the app's reset outranks `:host` box styles.+ style.textContent =+ ':host{display:block;contain:layout paint}.paper{overflow:hidden;font:13px/1.6 ' ++ fontStack ++ ';overflow-wrap:anywhere;background:#fff;color:#24262b;border-radius:6px;padding:14px 16px}' ++ 'p{margin:0 0 8px}p:last-child{margin:0}img{max-width:100%}a{color:#5a4fb0}'+ const images = [...template.content.querySelectorAll('img')].map((image) => {+ const source = image.getAttribute('src') || ''+ image.setAttribute('referrerpolicy', 'no-referrer')+ if (!source.startsWith('data:')) image.removeAttribute('src')+ return { image, source }+ })+ const paper = document.createElement('div')+ paper.className = 'paper'+ paper.append(template.content)+ root.replaceChildren(style, paper)+ for (const { image, source } of images) {+ if (source.startsWith('data:')) continue+ const fallback = () => {+ if (active) image.replaceWith(document.createTextNode(image.alt || ''))+ }+ if (!/^https?:/i.test(source)) fallback()+ else+ void api+ .remoteImage(source)+ .then((data) => {+ if (!active) return+ if (data) image.src = data+ else fallback()+ })+ .catch(fallback)+ }+ return () => {+ active = false+ }+}++/** A read-only rendering of signature HTML, as recipients will see it. */+export function SignaturePreview({ html }: { html: string }) {+ const host = useRef<HTMLDivElement>(null)+ useEffect(() => showSignature(host.current!, html), [html])+ return (+ <div+ ref={host}+ // A preview is only something to look at; following its links would leave the app.+ onClickCapture={(event) => event.preventDefault()}+ />+ )+}++function SignatureView({ node, selected, deleteNode }: ReactNodeViewProps) {+ return (+ <NodeViewWrapper+ className={'compose-signature' + (selected ? ' selected' : '')}+ contentEditable={false}+ >+ <SignaturePreview html={node.attrs.html} />+ <button+ type="button"+ className="compose-signature-remove"+ aria-label="Remove signature"+ title="Remove signature"+ onClick={deleteNode}+ >+ <X size={12} />+ </button>+ </NodeViewWrapper>+ )+}++/**+ * An HTML signature in the composer. The basic editor would flatten its tables and styling,+ * so it stays one block that's sent exactly as written and can only be removed as a whole.+ */+export const SignatureNode = Node.create({+ name: 'signature',+ group: 'block',+ atom: true,+ selectable: true,+ draggable: false,+ addAttributes() {+ return {+ html: {+ default: '',+ parseHTML: (element) => element.innerHTML,+ renderHTML: () => ({}),+ },+ }+ },+ parseHTML() {+ return [{ tag: 'div[' + marker + ']' }]+ },+ renderHTML({ node }) {+ // An inert document, so serializing a draft never starts loading its images.+ const element = document.implementation.createHTMLDocument('').createElement('div')+ element.setAttribute(marker, '')+ element.innerHTML = sanitizeSignature(node.attrs.html)+ return element+ },+ renderText: ({ node }) => signatureText(node.attrs.html),+ addNodeView() {+ return ReactNodeViewRenderer(SignatureView)+ },+})diff --git a/apps/desktop/src/renderer/src/styles.css b/apps/desktop/src/renderer/src/styles.cssindex 6926d81..af92975 100644--- a/apps/desktop/src/renderer/src/styles.css+++ b/apps/desktop/src/renderer/src/styles.css@@ -1585,15 +1585,37 @@ svg.starred {text-overflow: ellipsis;white-space: nowrap;}-.signature-identity {- position: relative;-}.signature-identity + .signature-identity {- margin-top: 14px;+ margin-top: 18px;}-.signature-identity label {- margin-bottom: 6px;+.signature-identity-heading {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-bottom: 8px;+}+.signature-account > header .signature-format {+ flex-shrink: 0;+}+.signature-identity-heading label {+ flex: 1;+ min-width: 0;+ margin: 0;color: var(--secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.signature-format {+ margin-left: auto;+}+.signature-format .segmented-option {+ height: 24px;+ padding: 0 9px;+ font-size: 11px;+}+.signature-editor {+ position: relative;}.signature-identity textarea {display: block;@@ -1602,6 +1624,29 @@ svg.starred {line-height: 1.6;resize: vertical;}+.signature-identity textarea.signature-code {+ min-height: 120px;+ font-family: ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;+ font-size: 11.5px;+ tab-size: 2;+ overflow-wrap: anywhere;+}+.signature-preview {+ margin-top: 10px;+}+.signature-preview > span {+ display: block;+ margin-bottom: 6px;+ font-size: 11px;+ color: var(--muted);+}+.signature-preview > div {+ max-height: 260px;+ overflow: auto;+}+.signature-preview .signature-note {+ margin-top: 8px;+}.signature-saved {position: absolute;right: 10px;@@ -1794,6 +1839,47 @@ svg.starred {padding-left: 16px;color: var(--muted);}+/* An HTML signature is one block: shown as recipients see it, removed as a whole. */+.compose-signature {+ position: relative;+ margin: 4px 0 16px;+ border-radius: 7px;+ outline: 1px solid transparent;+ outline-offset: 4px;+ transition: outline-color 120ms ease;+}+.compose-signature:hover {+ outline-color: var(--border);+}+.compose-signature.selected {+ outline: 2px solid var(--accent);+}+.compose-signature-remove {+ position: absolute;+ top: -2px;+ right: -2px;+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ background: var(--raised);+ color: var(--muted);+ opacity: 0;+ transition: opacity 120ms ease;+}+.compose-signature:hover .compose-signature-remove,+.compose-signature.selected .compose-signature-remove,+.compose-signature-remove:focus-visible {+ opacity: 1;+}+.compose-signature-remove:hover {+ color: var(--text);+}+.compose-editor[contenteditable='false'] .compose-signature-remove {+ display: none;+}.compose-editor p.is-editor-empty:first-child:before {content: attr(data-placeholder);color: var(--faint);diff --git a/packages/core/src/mail.ts b/packages/core/src/mail.tsindex 6e61732..6268aff 100644--- a/packages/core/src/mail.ts+++ b/packages/core/src/mail.ts@@ -6,12 +6,29 @@ import type {Message,ProviderPage,QueryPage,+ Settings,} from './model'export const scopeKey = (accountId: string, id: string) => JSON.stringify([accountId, id])export const accountKey = (connectionId: string, remoteId: string) =>JSON.stringify([connectionId, remoteId])export const identityKey = (accountId: string, id: string) => scopeKey(accountId, id)+export interface Signature {+ format: 'text' | 'html'+ value: string+}+/** The signature for an identity: the user's own when they wrote one, else the server's. */+export function identitySignature(+ settings: Pick<Settings, 'signatures' | 'htmlSignatures'>,+ identity: Pick<Identity, 'accountId' | 'id' | 'textSignature' | 'htmlSignature'>,+): Signature {+ const key = identityKey(identity.accountId, identity.id)+ const own = settings.signatures[key]+ if (own !== undefined)+ return { format: settings.htmlSignatures?.[key] ? 'html' : 'text', value: own }+ if (identity.htmlSignature?.trim()) return { format: 'html', value: identity.htmlSignature }+ return { format: 'text', value: identity.textSignature ?? '' }+}export function conversationFromMessages(accountId: string,threadId: string,diff --git a/packages/core/src/model.ts b/packages/core/src/model.tsindex 869c32c..0acf114 100644--- a/packages/core/src/model.ts+++ b/packages/core/src/model.ts@@ -200,6 +200,8 @@ export interface Settings {closeToTray: booleandefaultAccountId?: stringsignatures: Record<string, string>+ /** Identities whose signature is HTML code rather than plain text, keyed like `signatures`. */+ htmlSignatures?: Record<string, boolean>/** Where the reader goes after a conversation leaves the current view. */afterArchive?: 'next' | 'previous' | 'list'/**diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.tsindex d932454..c46c6bb 100644--- a/packages/core/src/schemas.ts+++ b/packages/core/src/schemas.ts@@ -170,6 +170,7 @@ export const settingsSchema = z.object({closeToTray: z.boolean(),defaultAccountId: id.optional(),signatures: z.record(z.string(), z.string().max(100_000)),+ htmlSignatures: z.record(z.string(), z.boolean()).optional(),afterArchive: z.enum(['next', 'previous', 'list']).optional(),shortcuts: z.record(z.string().max(64), z.array(z.array(z.string().min(1).max(64)).min(1).max(4)).max(16))diff --git a/tests/core.test.ts b/tests/core.test.tsindex 8eced81..6939247 100644--- a/tests/core.test.ts+++ b/tests/core.test.ts@@ -11,6 +11,9 @@ import {draftSchema,sendDraftSchema,defaultSettings,+ identityKey,+ identitySignature,+ settingsSchema,appearanceSchema,nextAccountColor,accountColors,@@ -211,3 +214,41 @@ describe('account appearance', () => {)})})++describe('signatures', () => {+ const identity = { accountId: 'a', id: 'i' }+ const key = identityKey('a', 'i')++ it('prefers the signature written in Inlark, in the format it was written in', () => {+ const server = { ...identity, textSignature: 'Server', htmlSignature: '<b>Server</b>' }+ expect(identitySignature({ signatures: { [key]: 'Paul' } }, server)).toEqual({+ format: 'text',+ value: 'Paul',+ })+ expect(+ identitySignature(+ { signatures: { [key]: '<b>Paul</b>' }, htmlSignatures: { [key]: true } },+ server,+ ),+ ).toEqual({ format: 'html', value: '<b>Paul</b>' })+ // Clearing a signature is a choice, not a reason to fall back to the server's.+ expect(identitySignature({ signatures: { [key]: '' } }, server).value).toBe('')+ })++ it('falls back to the server identity, preferring its HTML signature', () => {+ expect(identitySignature(defaultSettings, { ...identity, htmlSignature: '<i>Hi</i>' })).toEqual(+ { format: 'html', value: '<i>Hi</i>' },+ )+ expect(+ identitySignature(defaultSettings, { ...identity, textSignature: 'Hi', htmlSignature: ' ' }),+ ).toEqual({ format: 'text', value: 'Hi' })+ expect(identitySignature(defaultSettings, identity)).toEqual({ format: 'text', value: '' })+ })++ it('accepts settings saved before HTML signatures existed', () => {+ expect(settingsSchema.parse({ ...defaultSettings, signatures: { [key]: 'Paul' } })).toEqual({+ ...defaultSettings,+ signatures: { [key]: 'Paul' },+ })+ })+})