📧✨ Beautiful email. For everyone.
fix: update compose signatures and skip empty drafts (#34)
Paul Koecke6cbc10237c8
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 19cad95..ac395ad 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -92,6 +92,7 @@ import {} from './AppDialogs'import { messageText } from './message-text'import { signatureBlock, signatureText } from './signature'+import { textSignatureMarker } from './composer-document'import { selectConversation } from './selection'import { ShortcutHint, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { emptyListState } from './empty-states'@@ -549,7 +550,11 @@ export function App() {? signatureBlock(signature.value): '': signature.value- ? '<p><br/>' + escapeHtml(signature.value).replace(/\n/g, '<br/>') + '</p>'+ ? '<p ' ++ textSignatureMarker ++ '=""><br/>' ++ escapeHtml(signature.value).replace(/\n/g, '<br/>') ++ '</p>': '') +quoteconst text = [@@ -590,7 +595,6 @@ export function App() {draft.attachments = (await api.stageRemoteAttachments(id, message.attachments)).map((a) => ({ ...a, cid: undefined }),)- await localSaveDraft(draft)setComposer(draft)} catch (e) {fail(e)@@ -2358,6 +2362,7 @@ export function App() {initial={composer}suggestions={suggestions}accounts={accounts}+ settings={settings}onClose={() => setComposer(undefined)}onOpenAccounts={() => openSettings('accounts')}notify={notify}diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 899bc3b..6fac4e1 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -23,10 +23,13 @@ import {import { Modal, Button, IconButton, Select, Spinner } from '@inlark/ui'import {friendlyError,+ identitySignature,type Address,type Account,type Draft,type SendResult,+ type Settings,+ type Identity,} from '@inlark/core'import { api, isDemo } from './api'import { localSaveDraft, localDeleteDraft } from './cache'@@ -35,6 +38,7 @@ import { formatBytes } from './mail-date'import { bindingText, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { SignatureNode } from './signature'import { linkTarget } from './link-target'+import { SignatureParagraph, hasDraftContent, replaceSignature } from './composer-document'const validAddress = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)/** The editor's own formatting keys, which follow the platform (⌘ on macOS, Ctrl elsewhere). */@@ -93,6 +97,7 @@ function draftProblem(draft: Draft): { text: string; detail?: string } | undefinexport function Composer({initial,accounts,+ settings,suggestions,onClose,onOpenAccounts,@@ -102,6 +107,7 @@ export function Composer({initial: Draftsuggestions: Address[]accounts: Account[]+ settings: SettingsonClose: () => void/** Opens Settings → Accounts, e.g. to sign in to the outgoing server again. */onOpenAccounts: () => void@@ -120,6 +126,7 @@ export function Composer({: 'Saved on this device',),[sending, setSending] = useState(false),+ [changingFrom, setChangingFrom] = useState(false),[showCc, setShowCc] = useState(initial.cc.length > 0 || initial.bcc.length > 0),[expanded, setExpanded] = useState(false),[linkOpen, setLinkOpen] = useState(false),@@ -129,13 +136,16 @@ export function Composer({[discardOpen, setDiscardOpen] = useState(false)const latest = useRef(draft),sync = useRef<Promise<unknown>>(Promise.resolve()),+ persisted = useRef(!!initial.serverId || initial.status !== 'local'),alive = useRef(true)const account = accounts.find((a) => a.id === draft.accountId)!const identities = useQuery({queryKey: ['identities', draft.accountId],queryFn: () => api.identities(draft.accountId),})- const locked = sending || draft.status === 'uncertain' || draft.status === 'sent'+ const identity = identities.data?.find((identity) => identity.id === draft.identityId)+ const signature = identity ? identitySignature(settings, identity) : undefined+ const locked = sending || changingFrom || draft.status === 'uncertain' || draft.status === 'sent'const lockedRef = useRef(locked)lockedRef.current = locked// A failed send is kept apart from the draft, so a later autosave can't clear the explanation.@@ -171,6 +181,7 @@ export function Composer({}),Placeholder.configure({ placeholder: 'Write your message…' }),SignatureNode,+ SignatureParagraph,],content:initial.html ||@@ -210,11 +221,19 @@ export function Composer({alive.current = false}}, [])+ const shouldSave = () =>+ persisted.current || (!!editor && hasDraftContent(latest.current, editor.getJSON(), signature))useEffect(() => {latest.current = draftif (['uncertain', 'sent', 'sending'].includes(draft.status)) return+ if (!editor || changingFrom) return+ if (!shouldSave()) {+ setState('Not saved')+ return+ }setState('Saving…')const localTimer = setTimeout(() => {+ persisted.current = truevoid localSaveDraft(latest.current).then(() => api.saveDraft(latest.current)).then(() => {@@ -269,20 +288,23 @@ export function Composer({clearTimeout(localTimer)clearTimeout(serverTimer)}- }, [draft.updatedAt])+ }, [draft.updatedAt, editor, changingFrom, signature?.format, signature?.value])const close = async () => {+ if (changingFrom) returntry {await sync.current- await localSaveDraft(latest.current)- await api.saveDraft(latest.current)- onSaved()+ if (shouldSave()) {+ await localSaveDraft(latest.current)+ await api.saveDraft(latest.current)+ onSaved()+ }onClose()} catch (e) {notify('Your draft could not be saved. ' + friendlyError(e), 'error')}}const send = async () => {- if (sending || account.status !== 'connected') return+ if (sending || changingFrom || account.status !== 'connected') returnconst fields = ['to', 'cc', 'bcc'] as constif (!fields.some((field) => latest.current[field].length)) {notify('Add a recipient before sending.', 'error')@@ -354,6 +376,33 @@ export function Composer({setSending(false)}}+ const selectIdentity = (identity: Identity) => {+ if (!editor) return+ editor.commands.command(replaceSignature(identitySignature(settings, identity)))+ update({+ accountId: identity.accountId,+ identityId: identity.id,+ html: editor.getHTML(),+ text: editor.getText(),+ })+ }+ const selectAccount = async (accountId: string) => {+ if (lockedRef.current || latest.current.serverId || accountId === latest.current.accountId)+ return+ setChangingFrom(true)+ try {+ const identities = await api.identities(accountId)+ await sync.current+ // A sync already underway may have bound the draft to its original account.+ if (!alive.current || latest.current.serverId) return+ if (!identities.length) throw new Error('This account has no permitted sending identities.')+ selectIdentity(identities[0])+ } catch (error) {+ notify(friendlyError(error), 'error')+ } finally {+ if (alive.current) setChangingFrom(false)+ }+ }const attachFiles = async () => {try {const attachments = await api.stageAttachments()@@ -390,7 +439,10 @@ export function Composer({useShortcutHandlers(shortcuts.bindings, {// Keep the library's input-aware defaults: modifier shortcuts work while writing,// but a custom letter or sequence must not send or discard a draft as someone types.- send: { run: () => void send(), enabled: !linkOpen && !discardOpen && !sending },+ send: {+ run: () => void send(),+ enabled: !linkOpen && !discardOpen && !sending && !changingFrom,+ },attachFiles: { run: () => void attachFiles(), enabled: canEdit },showCc: { run: () => focusRecipient('cc'), enabled: canEdit },showBcc: { run: () => focusRecipient('bcc'), enabled: canEdit },@@ -398,7 +450,10 @@ export function Composer({run: () => setExpanded((current) => !current),enabled: !linkOpen && !discardOpen,},- saveClose: { run: () => void close(), enabled: !linkOpen && !discardOpen && !sending },+ saveClose: {+ run: () => void close(),+ enabled: !linkOpen && !discardOpen && !sending && !changingFrom,+ },discardDraft: { run: () => setDiscardOpen(true), enabled: canEdit },})const addressField = (name: 'to' | 'cc' | 'bcc', label: string) => (@@ -433,7 +488,7 @@ export function Composer({opendisablePointerDismissalonOpenChange={(open) => {- if (!open && !sending) void close()+ if (!open && !sending && !changingFrom) void close()}}><Dialog.Portal>@@ -477,6 +532,8 @@ export function Composer({>{sending || state === 'Saving…' ? (<Spinner size={11} />+ ) : state === 'Not saved' ? (+ <FileText size={11} />) : state.startsWith('Sav') || state === 'All changes saved' ? (<Check size={11} />) : (@@ -502,7 +559,7 @@ export function Composer({size="icon"aria-label="Save and close"title={keys('saveClose')}- disabled={sending}+ disabled={sending || changingFrom}/>}>@@ -535,19 +592,7 @@ export function Composer({value={draft.accountId}disabled={locked || !!draft.serverId}options={accounts.map((a) => ({ value: a.id, label: a.name + ' · ' + a.email }))}- onValueChange={async (accountId) => {- try {- const identities = await api.identities(accountId)- update({- accountId,- identityId: identities[0]?.id || '',- serverId: undefined,- serverFingerprint: undefined,- })- } catch (error) {- notify(friendlyError(error), 'error')- }- }}+ onValueChange={(accountId) => void selectAccount(accountId)}/></div>{(identities.data?.length || 0) > 1 && (@@ -578,7 +623,10 @@ export function Composer({value: i.id,label: i.name + ' <' + i.email + '>',}))}- onValueChange={(identityId) => update({ identityId })}+ onValueChange={(identityId) => {+ const identity = identities.data?.find((identity) => identity.id === identityId)+ if (identity) selectIdentity(identity)+ }}/></div>)}@@ -762,7 +810,7 @@ export function Composer({<Buttonvariant="primary"onClick={() => void send()}- disabled={sending || account.status !== 'connected'}+ disabled={sending || changingFrom || account.status !== 'connected'}>{sending ? <Spinner size={14} /> : <Send size={13} />}{' '}{sendingdiff --git a/apps/desktop/src/renderer/src/composer-document.ts b/apps/desktop/src/renderer/src/composer-document.tsnew file mode 100644index 0000000..6968be1--- /dev/null+++ b/apps/desktop/src/renderer/src/composer-document.ts@@ -0,0 +1,81 @@+import { Extension, type Command, type JSONContent } from '@tiptap/react'+import type { Draft, Signature } from '@inlark/core'++export const textSignatureMarker = 'data-inlark-signature-text'++/** Plain signatures stay editable, but can be distinguished from the user's message. */+export const SignatureParagraph = Extension.create({+ name: 'signatureParagraph',+ addGlobalAttributes() {+ return [+ {+ types: ['paragraph'],+ attributes: {+ signature: {+ default: false,+ keepOnSplit: false,+ parseHTML: (element) => element.hasAttribute(textSignatureMarker),+ renderHTML: (attributes) => (attributes.signature ? { [textSignatureMarker]: '' } : {}),+ },+ },+ },+ ]+ },+})++export function signatureContent(signature: Signature): JSONContent | undefined {+ if (!signature.value.trim()) return undefined+ if (signature.format === 'html') return { type: 'signature', attrs: { html: signature.value } }+ const content: JSONContent[] = [{ type: 'hardBreak' }]+ signature.value.split('\n').forEach((text, index) => {+ if (index) content.push({ type: 'hardBreak' })+ if (text) content.push({ type: 'text', text })+ })+ return { type: 'paragraph', attrs: { signature: true }, content }+}++/** Replace only the marked signature, retaining the rest of the document and its formatting. */+export const replaceSignature =+ (signature: Signature): Command =>+ ({ tr, dispatch }) => {+ const content = signatureContent(signature)+ let from = tr.doc.content.size+ let to = from+ let found = false+ tr.doc.forEach((node, position) => {+ if (+ !found &&+ (node.type.name === 'signature' || (node.type.name === 'paragraph' && node.attrs.signature))+ ) {+ from = position+ to = position + node.nodeSize+ found = true+ }+ })+ if (dispatch) {+ if (content) tr.replaceWith(from, to, tr.doc.type.schema.nodeFromJSON(content))+ else if (found) tr.delete(from, to)+ }+ return true+ }++/** A sender choice or its automatic signature alone doesn't make a message worth saving. */+export function hasDraftContent(+ draft: Draft,+ document: JSONContent,+ signature?: Signature,+): boolean {+ if (draft.to.length || draft.cc.length || draft.bcc.length || draft.subject.trim()) return true+ if (draft.attachments.length || draft.inReplyTo?.length) return true+ const text = (node: JSONContent): string =>+ node.type === 'hardBreak' ? '\n' : node.text || (node.content || []).map(text).join('')+ const meaningful = (node: JSONContent): boolean => {+ if (node.type === 'signature') return false+ if (node.type === 'paragraph' && node.attrs?.signature) {+ // Editing an otherwise automatic plain signature is still work that must be saved.+ return !!signature && text(node).trim() !== signature.value.trim()+ }+ return !!node.text?.trim() || (node.content || []).some(meaningful)+ }+ return meaningful(document)+}diff --git a/tests/composer-document.test.ts b/tests/composer-document.test.tsnew file mode 100644index 0000000..a87bc68--- /dev/null+++ b/tests/composer-document.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it, vi } from 'vitest'+import { Editor, type Command, type JSONContent } from '../apps/desktop/node_modules/@tiptap/react'+import StarterKit from '../apps/desktop/node_modules/@tiptap/starter-kit'+import type { Draft, Signature } from '../packages/core/src'+import {+ SignatureParagraph,+ hasDraftContent,+ replaceSignature,+ signatureContent,+} from '../apps/desktop/src/renderer/src/composer-document'+import { SignatureNode } from '../apps/desktop/src/renderer/src/signature'++vi.mock('../apps/desktop/src/renderer/src/api', () => ({ api: {} }))++const plain: Signature = { format: 'text', value: 'Personal\[email protected]' }+const rich: Signature = { format: 'html', value: '<table><tr><td>Studio</td></tr></table>' }+const empty: Signature = { format: 'text', value: '' }+const paragraph = (text = ''): JSONContent => ({+ type: 'paragraph',+ content: text ? [{ type: 'text', text }] : [],+})+const document = (...content: JSONContent[]): JSONContent => ({ type: 'doc', content })+const draft: Draft = {+ id: 'draft',+ accountId: 'personal',+ identityId: 'identity',+ to: [],+ cc: [],+ bcc: [],+ subject: '',+ html: '',+ text: plain.value,+ attachments: [],+ updatedAt: '2026-10-07T10:00:00Z',+ status: 'local',+}++/** Run the actual replacement transaction against the editor's schema without mounting a view. */+function replace(content: JSONContent, signature: Signature): JSONContent {+ const editor = new Editor({+ element: null,+ extensions: [StarterKit, SignatureNode, SignatureParagraph],+ content,+ })+ try {+ const tr = editor.state.tr+ replaceSignature(signature)({ tr, dispatch: () => {} } as Parameters<Command>[0])+ return tr.doc.toJSON()+ } finally {+ editor.destroy()+ }+}++describe('composer signature switching', () => {+ it('replaces plain with HTML without changing written text, formatting, or quoted signatures', () => {+ const body: JSONContent = {+ type: 'paragraph',+ attrs: { signature: false },+ content: [{ type: 'text', text: 'Keep my message.', marks: [{ type: 'bold' }] }],+ }+ const quote: JSONContent = {+ type: 'blockquote',+ content: [signatureContent(rich)!],+ }+ const result = replace(document(body, signatureContent(plain)!, quote), rich)+ expect(result.content).toEqual([body, signatureContent(rich), quote])+ })++ it('switches HTML back to editable plain text with its line breaks intact', () => {+ const result = replace(document(paragraph('Body'), signatureContent(rich)!), plain)+ expect(result.content?.[1]).toEqual(signatureContent(plain))+ expect(result.content?.[0].content).toEqual(paragraph('Body').content)+ })++ it('adds a signature for an account that previously had none, without duplicating it on later switches', () => {+ const added = replace(document(paragraph()), plain)+ const switched = replace(added, rich)+ expect(switched.content).toHaveLength(2)+ expect(switched.content?.[1]).toEqual(signatureContent(rich))+ })++ it('removes the previous signature when the selected identity has no signature', () => {+ const result = replace(document(paragraph('Body'), signatureContent(plain)!), empty)+ expect(result.content).toHaveLength(1)+ expect(result.content?.[0].content).toEqual(paragraph('Body').content)+ })+})++describe('empty composer drafts', () => {+ it('does not save empty paragraphs, whitespace, or automatic plain and HTML signatures', () => {+ expect(hasDraftContent(draft, document(paragraph()))).toBe(false)+ expect(hasDraftContent(draft, document(paragraph(' \n ')))).toBe(false)+ expect(hasDraftContent(draft, document(paragraph(), signatureContent(plain)!), plain)).toBe(+ false,+ )+ expect(hasDraftContent(draft, document(paragraph(), signatureContent(rich)!), rich)).toBe(false)+ })++ it('saves written body text, quoted mail, and edits to an automatic plain signature', () => {+ expect(+ hasDraftContent(draft, document(paragraph('Hello'), signatureContent(plain)!), plain),+ ).toBe(true)+ expect(+ hasDraftContent(draft, document({ type: 'blockquote', content: [paragraph('Quote')] })),+ ).toBe(true)+ expect(+ hasDraftContent(+ draft,+ document(signatureContent({ ...plain, value: 'Edited signature' })!),+ plain,+ ),+ ).toBe(true)+ })++ it.each<Partial<Draft>>([+ { to: [{ email: '[email protected]' }] },+ { cc: [{ email: '[email protected]' }] },+ { bcc: [{ email: '[email protected]' }] },+ { subject: 'Subject' },+ { attachments: [{ id: 'file', name: 'file.txt', type: 'text/plain', size: 10 }] },+ { inReplyTo: ['[email protected]'] },+ ])('preserves a draft with populated message fields: %j', (fields) => {+ expect(hasDraftContent({ ...draft, ...fields }, document(paragraph()))).toBe(true)+ })+})