Skip to content

📧✨ Beautiful email. For everyone.

fix: preserve plain-text email line breaks (#44)

Paul Koeck5249e9c1237f
diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsx
index 14d8dca..1098616 100644
--- a/apps/desktop/src/renderer/src/Reader.tsx
+++ b/apps/desktop/src/renderer/src/Reader.tsx
@@ -36,6 +36,7 @@ import { Button, IconButton, Dropdown, MenuItem, Spinner } from '@inlark/ui'
import {
friendlyError,
isDraft,
+ plainTextHtml,
type Account,
type Message,
type Settings,
@@ -50,24 +51,13 @@ import { AccountMark } from './AccountMark'
import { HintIconButton } from './HintIconButton'
import { actionLimit } from './account-limits'
import { ShortcutHint, useShortcutText } from './shortcuts'
-import { emailSanitizeOptions } from './email-html'
+import { emailBodyHtml, emailSanitizeOptions } from './email-html'
import { offersAction } from './view-actions'
import { SecuritySummary, WithheldBody, withheld } from './MessageSecurity'
const formatAddress = (a: { name: string; email: string }) =>
a.name ? a.name + ' <' + a.email + '>' : a.email
-const linkPattern = /\b(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g
-const escapeText = (value: string) => {
- const holder = document.createElement('div')
- holder.textContent = value
- return holder.innerHTML
-}
-/** Plain text as HTML with web addresses made clickable. */
-const plainHtml = (value: string) =>
- '<div style="white-space:pre-wrap">' +
- escapeText(value).replace(linkPattern, (url) => '<a href="' + url + '">' + url + '</a>') +
- '</div>'
/**
* Mail that paints its own backgrounds, lays itself out with tables, or carries images (logos
* are usually drawn for white) is shown on white paper, as its sender designed it. Everything
@@ -220,14 +210,11 @@ export function EmailBody({
let active = true
const run = async () => {
const template = document.createElement('template')
- const plain = plainHtml(
+ const plain = plainTextHtml(
(message.text?.trim() ? message.text : message.preview) ||
'No readable message body is available.',
)
- template.innerHTML = DOMPurify.sanitize(
- (message.html?.trim() ? message.html : '') || plain,
- emailSanitizeOptions,
- )
+ template.innerHTML = DOMPurify.sanitize(emailBodyHtml(message), emailSanitizeOptions)
if (
!template.content.textContent?.trim() &&
(message.text?.trim() || message.preview?.trim())
@@ -410,6 +397,8 @@ export function EmailBody({
observer.current?.disconnect()
return
}
+ // A refreshed body can produce identical HTML after preparation reset the frame.
+ if (writtenSource.current === source) return
try {
const doc = frame.current?.contentDocument
if (!doc) {
@@ -434,7 +423,7 @@ export function EmailBody({
cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause)
setRenderIssue(describeIssue('Writing HTML frame', error, source))
}
- }, [source])
+ }, [source, frameReady])
useLayoutEffect(() => {
if (frameReady) resizeFrame()
}, [frameReady, source])
diff --git a/apps/desktop/src/renderer/src/email-html.ts b/apps/desktop/src/renderer/src/email-html.ts
index 1c2ccb2..287bcba 100644
--- a/apps/desktop/src/renderer/src/email-html.ts
+++ b/apps/desktop/src/renderer/src/email-html.ts
@@ -1,4 +1,15 @@
import type { Config } from 'dompurify'
+import { plainTextHtml, type Message } from '@inlark/core'
+
+/** Older cached JMAP messages may store the same plain-text part in both fields. */
+export function emailBodyHtml(message: Pick<Message, 'html' | 'text' | 'preview'>): string {
+ const html = message.html?.trim()
+ if (html && html !== message.text?.trim()) return message.html!
+ return plainTextHtml(
+ (message.text?.trim() ? message.text : message.preview) ||
+ 'No readable message body is available.',
+ )
+}
/** HTML from mail or a signature keeps its layout, but nothing that runs, submits or restyles the app. */
export const emailSanitizeOptions: Config = {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b5f3e34..556f371 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -3,3 +3,4 @@ export * from './mail'
export * from './errors'
export * from './schemas'
export * from './discovery'
+export * from './text-html'
diff --git a/packages/core/src/text-html.ts b/packages/core/src/text-html.ts
new file mode 100644
index 0000000..bc85f13
--- /dev/null
+++ b/packages/core/src/text-html.ts
@@ -0,0 +1,20 @@
+const linkPattern = /\b(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g
+const escapeHtml = (value: string) =>
+ value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;')
+
+/** Plain email text keeps its line breaks and spacing, with clickable web addresses. */
+export function plainTextHtml(value: string): string {
+ let html = '',
+ end = 0
+ for (const match of value.matchAll(linkPattern)) {
+ const url = escapeHtml(match[0])
+ html += escapeHtml(value.slice(end, match.index)) + '<a href="' + url + '">' + url + '</a>'
+ end = match.index + match[0].length
+ }
+ return '<div style="white-space:pre-wrap">' + html + escapeHtml(value.slice(end)) + '</div>'
+}
diff --git a/packages/jmap/src/index.ts b/packages/jmap/src/index.ts
index fd314bc..9d54377 100644
--- a/packages/jmap/src/index.ts
+++ b/packages/jmap/src/index.ts
@@ -4,6 +4,7 @@ import {
conversationFromMessages,
draftFingerprint,
parseUnsubscribe,
+ plainTextHtml,
ProviderError,
type Account,
type Address,
@@ -124,13 +125,27 @@ function structuredBodyParts(part: Json | undefined, type: string): Json[] {
]
}
function bodyParts(raw: Json, type: 'text/plain' | 'text/html'): Json[] {
- return type === 'text/html' ? raw.htmlBody || [] : raw.textBody || []
+ // These are display preferences, not MIME types: htmlBody can include plain-text parts.
+ if (type === 'text/html')
+ return (raw.htmlBody || []).filter((part: Json) =>
+ ['text/html', 'text/plain'].includes(part.type?.toLowerCase()),
+ )
+ return raw.textBody?.length
+ ? raw.textBody
+ : (raw.htmlBody || []).filter((part: Json) => part.type?.toLowerCase() === type)
+}
+function renderBodyPart(part: Json, content: string, type: 'text/plain' | 'text/html'): string {
+ return type === 'text/html' && part.type?.toLowerCase() === 'text/plain'
+ ? plainTextHtml(content)
+ : content
}
function bodyValue(raw: Json, type: 'text/plain' | 'text/html'): string {
const value = (parts: Json[]) =>
parts
- .map((part) => raw.bodyValues?.[part.partId]?.value || '')
- .filter((content) => content.trim())
+ .flatMap((part) => {
+ const content = raw.bodyValues?.[part.partId]?.value || ''
+ return content.trim() ? [renderBodyPart(part, content, type)] : []
+ })
.join('\n')
return value(bodyParts(raw, type)) || value(structuredBodyParts(raw.bodyStructure, type))
}
@@ -445,10 +460,14 @@ export class JmapProvider implements MailProvider {
const bytes = await this.download(account, {
blobId: part.blobId,
name: 'body',
- type,
+ type: part.type || type,
size: part.size || 0,
})
- message[field] = new TextDecoder(part.charset || 'utf-8').decode(bytes)
+ message[field] = renderBodyPart(
+ part,
+ new TextDecoder(part.charset || 'utf-8').decode(bytes),
+ type,
+ )
} catch {
// Keep the other body representation or the message preview available.
}
diff --git a/tests/fixtures/plain-email.txt b/tests/fixtures/plain-email.txt
new file mode 100644
index 0000000..933e489
--- /dev/null
+++ b/tests/fixtures/plain-email.txt
@@ -0,0 +1,28 @@
+Hi,
+
+I'm Bartek, founder of Watchgoose.
+
+Watchgoose monitors cron jobs, backups, scheduled tasks, and recurring
+workflows that can signal their status. It's Europe hosted, operated & owned.
+
+I'd like to give BlinkDisk project a needs matched paid plan, free, for as long as the
+project is eligible via our Open Source support initiative:
+https://watchgoose.com/open-source/
+
+FreeBSD.org, Rclone.org and FreshBSD.org already participate by offering Watchgoose
+as a benefit to its committers and/or using it for monitoring of their infrastructure.
+
+Obviously any acknowledgment through your normal process is absoltely optional and
+never a condition for the donation.
+
+Let me know if you'd be interested or have any questions about it.
+
+Kind regards,
+Bartek Rutkowski
+
+--
+Watchgoose | Cron monitoring that honks when jobs go quiet
+https://watchgoose.com | [email protected]
+ _,
+__( `)<
+\____)
diff --git a/tests/jmap.test.ts b/tests/jmap.test.ts
index 96c0541..fc59b99 100644
--- a/tests/jmap.test.ts
+++ b/tests/jmap.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
import { JmapProvider, jmapFilter, jmapPatch, parseUnsubscribe } from '../packages/jmap/src'
import { ipcSchemas } from '../packages/core/src'
const core = 'urn:ietf:params:jmap:core',
@@ -232,6 +233,88 @@ describe('JMAP provider', () => {
const [account] = await provider.connect()
expect((await provider.messages(account, ['nested'], true))[0].html).toBe('<p>Visible body</p>')
})
+ it('preserves plain-text formatting when JMAP lists the part in both body preferences', async () => {
+ const text = readFileSync(new URL('./fixtures/plain-email.txt', import.meta.url), 'utf8')
+ const part = { type: 'text/plain', partId: 'plain' }
+ const { provider, fetch } = fixture({
+ 'Email/get': () => ({
+ list: [
+ {
+ ...raw('plain'),
+ textBody: [part],
+ htmlBody: [part],
+ bodyStructure: part,
+ bodyValues: { plain: { value: text } },
+ },
+ ],
+ }),
+ })
+ const [account] = await provider.connect()
+ const [message] = await provider.messages(account, ['plain'], true)
+ expect(message.text).toBe(text)
+ expect(message.html).toContain('white-space:pre-wrap')
+ expect(message.html).toContain('Hi,\n\nI&#39;m Bartek')
+ expect(message.html).toContain(' _,\n__( `)&lt;\n\\____)')
+ expect(message.html).toContain('<a href="https://watchgoose.com/open-source/">')
+ expect(fetch.mock.calls.some(([url]) => String(url).includes('/download/'))).toBe(false)
+ })
+ it('renders mixed plain-text and HTML parts in their display order', async () => {
+ const parts = [
+ { type: 'text/plain', partId: 'intro' },
+ { type: 'text/html', partId: 'html' },
+ { type: 'text/plain', partId: 'signature' },
+ ]
+ const { provider } = fixture({
+ 'Email/get': () => ({
+ list: [
+ {
+ ...raw('mixed'),
+ htmlBody: parts,
+ textBody: parts,
+ bodyValues: {
+ intro: { value: 'Hi,\n\nAn introduction.' },
+ html: { value: '<p>A <strong>formatted</strong> body.</p>' },
+ signature: { value: 'Kind regards,\nSender <[email protected]>' },
+ },
+ },
+ ],
+ }),
+ })
+ const [account] = await provider.connect()
+ const [message] = await provider.messages(account, ['mixed'], true)
+ expect(message.html).toBe(
+ '<div style="white-space:pre-wrap">Hi,\n\nAn introduction.</div>\n' +
+ '<p>A <strong>formatted</strong> body.</p>\n' +
+ '<div style="white-space:pre-wrap">Kind regards,\nSender &lt;[email protected]&gt;</div>',
+ )
+ })
+ it('keeps downloaded plain-text body parts formatted as plain text', async () => {
+ const { provider, fetch } = fixture(
+ {
+ 'Email/get': () => ({
+ list: [
+ {
+ ...raw('plain-blob'),
+ htmlBody: [{ type: 'text/plain', blobId: 'plain-blob', size: 30 }],
+ bodyValues: {},
+ },
+ ],
+ }),
+ },
+ 'Hi,\n\nA downloaded plain body.',
+ )
+ const [account] = await provider.connect()
+ const [message] = await provider.messages(account, ['plain-blob'], true)
+ expect(message.html).toBe(
+ '<div style="white-space:pre-wrap">Hi,\n\nA downloaded plain body.</div>',
+ )
+ expect(message.text).toBe('Hi,\n\nA downloaded plain body.')
+ expect(
+ fetch.mock.calls
+ .filter(([url]) => String(url).includes('/download/'))
+ .every(([url]) => String(url).includes('type=text%2Fplain')),
+ ).toBe(true)
+ })
it('recovers a missing body value from its JMAP part blob', async () => {
const { provider, fetch } = fixture(
{
diff --git a/tests/reader-body.test.ts b/tests/reader-body.test.ts
index 5e8bf22..f259f8d 100644
--- a/tests/reader-body.test.ts
+++ b/tests/reader-body.test.ts
@@ -1,9 +1,37 @@
import { createElement } from '../apps/desktop/node_modules/react'
import { renderToStaticMarkup } from '../apps/desktop/node_modules/react-dom/server'
import { describe, expect, it, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
import type { Message } from '../packages/core/src'
+import { emailBodyHtml } from '../apps/desktop/src/renderer/src/email-html'
describe('email body fallback', () => {
+ it('repairs cached messages with the plain-text body duplicated in the HTML field', () => {
+ const text = readFileSync(new URL('./fixtures/plain-email.txt', import.meta.url), 'utf8')
+ const html = emailBodyHtml({ text, html: text, preview: 'Hi, I’m Bartek…' })
+ expect(html).toContain('white-space:pre-wrap')
+ expect(html).toContain('Hi,\n\nI&#39;m Bartek')
+ expect(html).toContain(' _,\n__( `)&lt;\n\\____)')
+ expect(html).toContain('<a href="https://watchgoose.com/open-source/">')
+ })
+ it('keeps sender HTML formatting when an actual HTML body is present', () => {
+ const html = '<p>Hello <strong>there</strong>.</p><p>Another paragraph.</p>'
+ expect(emailBodyHtml({ html, text: 'Hello there.\n\nAnother paragraph.', preview: '' })).toBe(
+ html,
+ )
+ })
+ it('escapes literal markup and link attributes in plain text', () => {
+ const html = emailBodyHtml({
+ text: 'Use <br> literally & keep "quotes".\nhttps://example.test/?a=1&b=2" title="unexpected',
+ preview: '',
+ })
+ expect(html).toContain('Use &lt;br&gt; literally &amp; keep &quot;quotes&quot;.\n')
+ expect(html).toContain(
+ '<a href="https://example.test/?a=1&amp;b=2">https://example.test/?a=1&amp;b=2</a>',
+ )
+ expect(html).not.toContain(' title="unexpected')
+ expect(html).not.toContain('<br>')
+ })
it('shows plain text outside the HTML frame until the frame has readable content', async () => {
vi.stubGlobal('location', { search: '', protocol: 'file:' })
vi.stubGlobal('window', {})