Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): pull out core rendering logic, setup snapshot test suite for email rendering (#946)
teo3b338a24c091
diff --git a/js/app/bun.lock b/js/app/bun.lockindex cb833758f7..67b99ae3e6 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -63,6 +63,7 @@"@tauri-apps/plugin-os": "~2","@tauri-apps/plugin-websocket": "~2","@thisbeyond/solid-dnd": "^0.7.5",+ "@vitest/ui": "^4.0.17","async-lock": "^1.4.1","async-mutex": "^0.5.0","brace-expansion": "^4.0.1",@@ -1386,7 +1387,9 @@"@vitest/spy": ["@vitest/[email protected]", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw=="],- "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],+ "@vitest/ui": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/utils": "4.0.17", "fflate": "^0.8.2", "flatted": "^3.3.3", "pathe": "^2.0.3", "sirv": "^3.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3" }, "peerDependencies": { "vitest": "4.0.17" } }, "sha512-hRDjg6dlDz7JlZAvjbiCdAJ3SDG+NH8tjZe21vjxfvT2ssYAn72SRXMge3dKKABm3bIJ3C+3wdunIdur8PHEAw=="],++ "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.0.17", "tinyrainbow": "^3.0.3" } }, "sha512-RG6iy+IzQpa9SB8HAFHJ9Y+pTzI+h8553MrciN9eC6TFBErqrQaTas4vG+MVj8S4uKk8uTT2p0vgZPnTdxd96w=="],"@wapython/unionfs": ["@wapython/[email protected]", "", { "dependencies": { "fs-monkey": "^1.0.0" } }, "sha512-7809nAVelP9TqXCq5c1yCwymPreTXrK4n4q/zxOlQOIIz4PNmoQmIKiLnwkKk39GDnLmP1MvP9ZkBDyXCCmTfg=="],@@ -3052,7 +3055,7 @@"tinypool": ["[email protected]", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="],- "tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],+ "tinyrainbow": ["[email protected]", "", {}, "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q=="],"tinyspy": ["[email protected]", "", {}, "sha512-t2T/WLB2WRgZ9EpE4jgPJ9w+i66UZfDc8wHh0xrwiRNN+UwH98GIJkTeZqX9rg0i0ptwzqW+uYeIF0T4F8LR7A=="],@@ -3822,14 +3825,32 @@"@typescript-eslint/utils/eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],+ "@vitest/browser/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],+"@vitest/browser/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw=="],+ "@vitest/browser/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],+"@vitest/coverage-v8/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],"@vitest/coverage-v8/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw=="],+ "@vitest/coverage-v8/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],++ "@vitest/expect/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],++ "@vitest/expect/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],+"@vitest/mocker/estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],+ "@vitest/pretty-format/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],++ "@vitest/runner/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],++ "@vitest/ui/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],++ "@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^3.0.3" } }, "sha512-Ah3VAYmjcEdHg6+MwFE17qyLqBHZ+ni2ScKCiW2XrlSBV4H3Z7vYfPfz7CWQ33gyu76oc0Ai36+kgLU3rfF4nw=="],+"ansi-escapes/type-fest": ["[email protected]", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="],"array-buffer-byte-length/call-bind": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.1" } }, "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w=="],@@ -4228,6 +4249,10 @@"vite-tsconfig-paths/tsconfck": ["[email protected]", "", { "peerDependencies": { "typescript": "^5.0.0" }, "optionalPeers": ["typescript"], "bin": { "tsconfck": "bin/tsconfck.js" } }, "sha512-00eoI6WY57SvZEVjm13stEVE90VkEdJAFGgpFLTsZbJyW/LwFQ7uQxJHWpZ2hzSWgCPKc9AnBnNP+0X7o3hAmQ=="],+ "vitest/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],++ "vitest/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],+"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="],"wasi-js/debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="],@@ -4462,6 +4487,12 @@"@vitest/coverage-v8/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],+ "@vitest/runner/@vitest/utils/tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],++ "@vitest/ui/tinyglobby/fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],++ "@vitest/ui/tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],+"array-buffer-byte-length/call-bind/es-define-property": ["[email protected]", "", { "dependencies": { "get-intrinsic": "^1.2.4" } }, "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ=="],"array-buffer-byte-length/call-bind/get-intrinsic": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "hasown": "^2.0.0" } }, "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ=="],diff --git a/js/app/justfile b/js/app/justfileindex f8ad70bc21..85348e7c70 100644--- a/js/app/justfile+++ b/js/app/justfile@@ -25,6 +25,12 @@ build-tauri:test-watch:bunx --bun vitest+test-email-rendering:+ cd packages/core/email/tests && bunx playwright test && bunx playwright show-report++test-email-rendering-update:+ cd packages/core/email/tests && bunx playwright test --update-snapshots+preview-prod:cd packages/app && MODE=production NODE_ENV=production bun run preview:proddiff --git a/js/app/package.json b/js/app/package.jsonindex e2796ef7d9..e60f22a582 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -77,6 +77,7 @@"@tauri-apps/plugin-os": "~2","@tauri-apps/plugin-websocket": "~2","@thisbeyond/solid-dnd": "^0.7.5",+ "@vitest/ui": "^4.0.17","async-lock": "^1.4.1","async-mutex": "^0.5.0","brace-expansion": "^4.0.1",diff --git a/js/app/packages/block-email/component/EmailMessageBody.tsx b/js/app/packages/block-email/component/EmailMessageBody.tsxindex 1a93835207..0ea4ce8045 100644--- a/js/app/packages/block-email/component/EmailMessageBody.tsx+++ b/js/app/packages/block-email/component/EmailMessageBody.tsx@@ -3,6 +3,11 @@ import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/Simport { channelTheme } from '@core/component/LexicalMarkdown/theme';import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';+import {+ parseEmailContent,+ processEmailColors,+ type ThemeColorParams,+} from '@core/email';import DotsThree from '@icon/regular/dots-three.svg';import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';import { useEmail } from '@service-gql/client';@@ -16,10 +21,8 @@ import {Switch,untrack,} from 'solid-js';-// import { selectedTheme } from '@core/signal/theme';+import { themeReactive } from '../../block-theme/signals/themeReactive';import { themeUpdate } from '../../block-theme/signals/themeSignals';-import { parseEmailContent } from '../util/parseEmailHTML';-import { processEmailColors } from '../util/transformEmailColors';interface EmailMessageBodyProps {message: MessageWithBodyReplyless;@@ -165,7 +168,18 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {if (root) {if (isPersonal()) {queueMicrotask(() => {- untrack(() => processEmailColors(root));+ untrack(() => {+ const theme: ThemeColorParams = {+ inkL: themeReactive.c0.l[0](),+ inkC: themeReactive.c0.c[0](),+ inkH: themeReactive.c0.h[0](),+ panelL: themeReactive.b1.l[0](),+ accentL: themeReactive.a0.l[0](),+ accentC: themeReactive.a0.c[0](),+ accentH: themeReactive.a0.h[0](),+ };+ processEmailColors(root, theme);+ });});} else if (source()?.hasTable) {const contentWrapper = root.querySelector('div');diff --git a/js/app/packages/core/.gitignore b/js/app/packages/core/.gitignoreindex 76add878f8..2c6a0cd689 100644--- a/js/app/packages/core/.gitignore+++ b/js/app/packages/core/.gitignore@@ -1,2 +1,6 @@node_modules-dist\ No newline at end of file+dist++# Playwright+playwright-report/+test-results/\ No newline at end of filediff --git a/js/app/packages/core/email/index.ts b/js/app/packages/core/email/index.tsnew file mode 100644index 0000000000..f9fcbe5437--- /dev/null+++ b/js/app/packages/core/email/index.ts@@ -0,0 +1,12 @@+// Email body parsing utilities+export {+ parseEmailContent,+ trimTrailingBrs,+ type ParsedEmailContent,+} from './parse-email-html';++// Color transformation utilities+export {+ processEmailColors,+ type ThemeColorParams,+} from './transform-email-colors';diff --git a/js/app/packages/block-email/util/parseEmailHTML.ts b/js/app/packages/core/email/parse-email-html.tssimilarity index 100%rename from js/app/packages/block-email/util/parseEmailHTML.tsrename to js/app/packages/core/email/parse-email-html.tsdiff --git a/js/app/packages/core/email/tests/email-rendering.pw.ts b/js/app/packages/core/email/tests/email-rendering.pw.tsnew file mode 100644index 0000000000..1ac6b62e9f--- /dev/null+++ b/js/app/packages/core/email/tests/email-rendering.pw.ts@@ -0,0 +1,186 @@+import fs from 'node:fs';+import path from 'node:path';+import { expect, test } from '@playwright/test';+import { DEFAULT_THEMES } from '../../../block-theme/constants';+import type { ThemeColorParams } from '../transform-email-colors';++// =============================================================================+// Types+// =============================================================================++/**+ * Email fixture format - matches the structure from email service.+ *+ * ## Adding a new fixture:+ * 1. Create a JSON file in the fixtures/ directory (e.g., `my-email.json`)+ * 2. Copy `body_html_sanitized` from an email API response into the file+ * 3. Run `just test-email-rendering-update` to generate baseline screenshots+ * 4. Commit the fixture and snapshots+ *+ * ## Example fixture file:+ * ```json+ * {+ * "name": "outlook-signature",+ * "description": "Email with Outlook signature formatting",+ * "body_html_sanitized": "<p>Hello...</p><div class='signature'>...</div>"+ * }+ * ```+ */+interface EmailFixture {+ /** Unique name for the fixture (used in snapshot filenames) */+ name: string;+ /** Description of what this fixture tests */+ description: string;+ /** The sanitized HTML body - copy directly from email service `body_html_sanitized` field */+ body_html_sanitized: string;+}++// =============================================================================+// Configuration+// =============================================================================++/** Themes to test - uses actual Macro theme definitions */+const THEMES = ['Macro Dark', 'Macro Light'] as const;++// =============================================================================+// Theme Helpers+// =============================================================================++function getThemeConfig(themeName: string): ThemeColorParams {+ const theme = DEFAULT_THEMES.find((t) => t.name === themeName);+ if (!theme) {+ throw new Error(`Theme "${themeName}" not found in DEFAULT_THEMES`);+ }+ return {+ inkL: theme.tokens.c0.l,+ inkC: theme.tokens.c0.c,+ inkH: theme.tokens.c0.h,+ panelL: theme.tokens.b1.l,+ accentL: theme.tokens.a0.l,+ accentC: theme.tokens.a0.c,+ accentH: theme.tokens.a0.h,+ };+}++function generateThemeCSS(themeName: string): string {+ const theme = DEFAULT_THEMES.find((t) => t.name === themeName);+ if (!theme) return '';++ const vars = Object.entries(theme.tokens)+ .map(+ ([key, value]) =>+ `--${key}l: ${value.l}; --${key}c: ${value.c}; --${key}h: ${value.h}deg;`+ )+ .join('\n ');++ return `:root {\n ${vars}\n }`;+}++// =============================================================================+// HTML Generation+// =============================================================================++function createTestHTML(fixture: EmailFixture, themeName: string): string {+ const themeCSS = generateThemeCSS(themeName);+ const theme = getThemeConfig(themeName);+ const bgColor = `oklch(${theme.panelL} 0 0)`;+ const textColor = `oklch(${theme.inkL} ${theme.inkC} ${theme.inkH})`;++ return `<!DOCTYPE html>+<html>+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <style>+ ${themeCSS}++ * { margin: 0; padding: 0; box-sizing: border-box; }++ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 14px;+ line-height: 1.5;+ background-color: ${bgColor};+ color: ${textColor};+ padding: 16px;+ }++ .email-container {+ max-width: 600px;+ width: 100%;+ padding: 16px;+ background-color: ${bgColor};+ }++ /* Default link styling using accent color */+ a {+ color: oklch(${theme.accentL} ${theme.accentC} ${theme.accentH});+ }+ </style>+ </head>+ <body>+ <div class="email-container">+ ${fixture.body_html_sanitized}+ </div>+ </body>+</html>`;+}++// =============================================================================+// Fixture Loading+// =============================================================================++function loadFixtures(): EmailFixture[] {+ const fixturesDir = path.join(import.meta.dirname, 'fixtures');++ if (!fs.existsSync(fixturesDir)) {+ return [];+ }++ const files = fs.readdirSync(fixturesDir).filter((f) => f.endsWith('.json'));++ return files.map((file) => {+ const content = fs.readFileSync(path.join(fixturesDir, file), 'utf-8');+ return JSON.parse(content) as EmailFixture;+ });+}++// =============================================================================+// Snapshot Naming+// =============================================================================++function snapshotName(fixtureName: string, themeName: string): string {+ const themeSuffix = themeName.toLowerCase().replace(/\s+/g, '-');+ return `${fixtureName}-${themeSuffix}.png`;+}++// =============================================================================+// Tests+// =============================================================================++const fixtures = loadFixtures();++test.describe('Email Rendering', () => {+ for (const fixture of fixtures) {+ test(fixture.name, async ({ page }, testInfo) => {+ await page.setViewportSize({ width: 700, height: 800 });++ for (const themeName of THEMES) {+ const html = createTestHTML(fixture, themeName);+ await page.setContent(html);+ await page.waitForLoadState('networkidle');++ // Attach screenshot to report (visible even for passing tests)+ const screenshot = await page.screenshot();+ await testInfo.attach(`${themeName}`, {+ body: screenshot,+ contentType: 'image/png',+ });++ await expect(page).toHaveScreenshot(+ snapshotName(fixture.name, themeName)+ );+ }+ });+ }+});diff --git a/js/app/packages/core/email/tests/fixtures/nested-quotes.json b/js/app/packages/core/email/tests/fixtures/nested-quotes.jsonnew file mode 100644index 0000000000..45684d8726--- /dev/null+++ b/js/app/packages/core/email/tests/fixtures/nested-quotes.json@@ -0,0 +1,5 @@+{+ "name": "nested-quotes",+ "description": "Email thread with nested blockquotes",+ "body_html_sanitized": "<p>Thanks for the update!</p><blockquote style=\"border-left: 2px solid #ccc; margin: 10px 0; padding-left: 10px; color: #666;\"><p>On Monday, John wrote:</p><blockquote style=\"border-left: 2px solid #ccc; margin: 10px 0; padding-left: 10px; color: #888;\"><p>Original message here with some longer content that might wrap to multiple lines.</p></blockquote><p>My reply to the original.</p></blockquote><p>And here's my final response.</p>"+}diff --git a/js/app/packages/core/email/tests/fixtures/styled-email.json b/js/app/packages/core/email/tests/fixtures/styled-email.jsonnew file mode 100644index 0000000000..fc1c90396d--- /dev/null+++ b/js/app/packages/core/email/tests/fixtures/styled-email.json@@ -0,0 +1,5 @@+{+ "name": "styled-email",+ "description": "Email with inline styles and formatting",+ "body_html_sanitized": "<div style=\"font-family: Arial, sans-serif;\"><h1 style=\"color: #333; margin-bottom: 16px;\">Welcome!</h1><p style=\"color: #666; font-size: 14px; line-height: 1.5;\">Thank you for signing up. We're excited to have you on board.</p><a href=\"#\" style=\"color: blue; text-decoration: underline;\">Click here to get started</a></div>"+}diff --git a/js/app/packages/core/email/tests/parse-email-html.test.ts b/js/app/packages/core/email/tests/parse-email-html.test.tsnew file mode 100644index 0000000000..568c1440ed--- /dev/null+++ b/js/app/packages/core/email/tests/parse-email-html.test.ts@@ -0,0 +1,133 @@+import { describe, expect, it } from 'vitest';+import { parseEmailContent, trimTrailingBrs } from '../parse-email-html';++describe('trimTrailingBrs', () => {+ it('removes trailing br elements', () => {+ const div = document.createElement('div');+ div.innerHTML = '<p>Hello</p><br><br><br>';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('<p>Hello</p>');+ });++ it('removes trailing empty text nodes and br elements', () => {+ const div = document.createElement('div');+ div.innerHTML = '<p>Hello</p><br> <br>';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('<p>Hello</p>');+ });++ it('preserves trailing img elements', () => {+ const div = document.createElement('div');+ div.innerHTML = '<p>Hello</p><br><img src="test.jpg">';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('<p>Hello</p><br><img src="test.jpg">');+ });++ it('preserves meaningful text content', () => {+ const div = document.createElement('div');+ div.innerHTML = '<p>Hello</p><br>World';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('<p>Hello</p><br>World');+ });++ it('removes nested trailing br elements', () => {+ const div = document.createElement('div');+ div.innerHTML = '<p>Hello</p><div><br><br></div>';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('<p>Hello</p>');+ });++ it('handles empty element', () => {+ const div = document.createElement('div');+ div.innerHTML = '';+ trimTrailingBrs(div);+ expect(div.innerHTML).toBe('');+ });+});++describe('parseEmailContent', () => {+ it('parses simple HTML content', () => {+ const html = '<p>Hello World</p>';+ const result = parseEmailContent(html);+ expect(result.mainContent).toBe('<p>Hello World</p>');+ expect(result.signature).toBeNull();+ expect(result.hasTable).toBe(false);+ });++ it('detects tables in content', () => {+ const html = '<table><tr><td>Cell</td></tr></table>';+ const result = parseEmailContent(html);+ expect(result.hasTable).toBe(true);+ });++ it('extracts Gmail signature', () => {+ const html = `+ <p>Hello</p>+ <div class="gmail_signature_prefix">--</div>+ <div class="gmail_signature">John Doe</div>+ `;+ const result = parseEmailContent(html, true, false);+ expect(result.mainContent).not.toContain('gmail_signature');+ expect(result.signature).toContain('John Doe');+ });++ it('preserves signature when removeSignature is false', () => {+ const html = `+ <p>Hello</p>+ <div class="gmail_signature_prefix">--</div>+ <div class="gmail_signature">John Doe</div>+ `;+ const result = parseEmailContent(html, false, false);+ expect(result.mainContent).toContain('gmail_signature');+ expect(result.signature).toBeNull();+ });++ it('preserves style tags from head', () => {+ const html = `+ <!DOCTYPE html>+ <html>+ <head>+ <style>.highlight { color: red; }</style>+ </head>+ <body>+ <p class="highlight">Hello</p>+ </body>+ </html>+ `;+ const result = parseEmailContent(html);+ expect(result.mainContent).toContain('<style>');+ expect(result.mainContent).toContain('.highlight { color: red; }');+ });++ it('removes trailing br elements when removeTrailingBrs is true', () => {+ const html = '<p>Hello</p><br><br>';+ const result = parseEmailContent(html, true, true);+ expect(result.mainContent).not.toMatch(/<br>$/);+ });++ it('preserves trailing br elements when removeTrailingBrs is false', () => {+ const html = '<p>Hello</p><br><br>';+ const result = parseEmailContent(html, true, false);+ expect(result.mainContent).toContain('<br>');+ });++ it('handles malformed HTML gracefully', () => {+ const html = '<p>Unclosed paragraph<div>Nested div</p></div>';+ const result = parseEmailContent(html);+ // Browser DOM parser will fix the malformed HTML+ expect(result.mainContent).toBeTruthy();+ });++ it('handles empty HTML', () => {+ const html = '';+ const result = parseEmailContent(html);+ expect(result.mainContent).toBe('');+ expect(result.hasTable).toBe(false);+ });++ it('handles HTML with only whitespace', () => {+ const html = ' \n\t ';+ const result = parseEmailContent(html);+ expect(result.hasTable).toBe(false);+ });+});diff --git a/js/app/packages/core/email/tests/playwright.config.ts b/js/app/packages/core/email/tests/playwright.config.tsnew file mode 100644index 0000000000..307be81901--- /dev/null+++ b/js/app/packages/core/email/tests/playwright.config.ts@@ -0,0 +1,32 @@+import { defineConfig, devices } from '@playwright/test';++export default defineConfig({+ testDir: '.',+ testMatch: '*.pw.ts',+ fullyParallel: true,+ forbidOnly: !!process.env.CI,+ retries: process.env.CI ? 2 : 0,+ workers: process.env.CI ? 1 : undefined,+ reporter: 'html',++ use: {+ baseURL: 'about:blank',+ trace: 'on-first-retry',+ },++ projects: [+ {+ name: 'chromium',+ use: { ...devices['Desktop Chrome'] },+ },+ ],++ snapshotDir: './snapshots',+ snapshotPathTemplate: '{snapshotDir}/{testFilePath}/{arg}{ext}',++ expect: {+ toHaveScreenshot: {+ maxDiffPixels: 100,+ },+ },+});diff --git a/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.png b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.pngnew file mode 100644index 0000000000..b2476b54d6Binary files /dev/null and b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.png differdiff --git a/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.png b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.pngnew file mode 100644index 0000000000..3203d78bedBinary files /dev/null and b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.png differdiff --git a/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.png b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.pngnew file mode 100644index 0000000000..6f50f4dc57Binary files /dev/null and b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.png differdiff --git a/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.png b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.pngnew file mode 100644index 0000000000..099aa11e43Binary files /dev/null and b/js/app/packages/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.png differdiff --git a/js/app/packages/core/email/tests/transform-email-colors.test.ts b/js/app/packages/core/email/tests/transform-email-colors.test.tsnew file mode 100644index 0000000000..6a8714dee0--- /dev/null+++ b/js/app/packages/core/email/tests/transform-email-colors.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest';+import {+ findClosestContrastingColor,+ normalizeRGBA,+ parseRGBA,+ rgbaToOklch,+} from '../transform-email-colors';++describe('parseRGBA', () => {+ it('parses rgb() format', () => {+ const result = parseRGBA('rgb(255, 128, 64)');+ expect(result).toEqual({ r: 255, g: 128, b: 64, a: 1 });+ });++ it('parses rgba() format with alpha', () => {+ const result = parseRGBA('rgba(255, 128, 64, 0.5)');+ expect(result).toEqual({ r: 255, g: 128, b: 64, a: 0.5 });+ });++ it('parses rgba() format with space syntax', () => {+ const result = parseRGBA('rgba(255 128 64 / 0.5)');+ expect(result).toEqual({ r: 255, g: 128, b: 64, a: 0.5 });+ });++ it('handles transparent', () => {+ const result = parseRGBA('transparent');+ expect(result).toEqual({ r: 0, g: 0, b: 0, a: 0 });+ });++ it('returns null for invalid format', () => {+ const result = parseRGBA('invalid');+ expect(result).toBeNull();+ });++ it('returns null for empty string', () => {+ const result = parseRGBA('');+ expect(result).toBeNull();+ });+});++describe('normalizeRGBA', () => {+ it('normalizes 0-255 values to 0-1 range', () => {+ const result = normalizeRGBA({ r: 255, g: 128, b: 0, a: 0.5 });+ expect(result).toEqual({ r: 1, g: 128 / 255, b: 0, a: 0.5 });+ });++ it('clamps values to 0-1 range', () => {+ const result = normalizeRGBA({ r: 300, g: -10, b: 255, a: 1 });+ expect(result?.r).toBe(1);+ expect(result?.g).toBe(0);+ expect(result?.b).toBe(1);+ });++ it('returns null for null input', () => {+ const result = normalizeRGBA(null);+ expect(result).toBeNull();+ });+});++describe('rgbaToOklch', () => {+ it('converts black to OKLCH', () => {+ const result = rgbaToOklch({ r: 0, g: 0, b: 0, a: 1 });+ expect(result?.l).toBeCloseTo(0, 2);+ expect(result?.c).toBeCloseTo(0, 2);+ });++ it('converts white to OKLCH', () => {+ const result = rgbaToOklch({ r: 1, g: 1, b: 1, a: 1 });+ expect(result?.l).toBeCloseTo(1, 2);+ expect(result?.c).toBeCloseTo(0, 2);+ });++ it('preserves alpha value', () => {+ const result = rgbaToOklch({ r: 0.5, g: 0.5, b: 0.5, a: 0.75 });+ expect(result?.a).toBe(0.75);+ });++ it('converts red to OKLCH with correct hue range', () => {+ const result = rgbaToOklch({ r: 1, g: 0, b: 0, a: 1 });+ expect(result?.l).toBeGreaterThan(0);+ expect(result?.c).toBeGreaterThan(0);+ expect(result?.h).toBeGreaterThanOrEqual(0);+ expect(result?.h).toBeLessThan(360);+ });++ it('returns null for null input', () => {+ const result = rgbaToOklch(null);+ expect(result).toBeNull();+ });+});++describe('findClosestContrastingColor', () => {+ const CONTRAST_THRESHOLD = 0.5;++ it('increases lightness when fg is lighter than bg but contrast is low', () => {+ const fg = { l: 0.6, c: 0.1, h: 180 };+ const bgL = 0.5;+ const result = findClosestContrastingColor(fg, bgL);+ expect(Math.abs(result.l - bgL)).toBeGreaterThanOrEqual(+ CONTRAST_THRESHOLD - 0.01+ );+ });++ it('decreases lightness when fg is darker than bg but contrast is low', () => {+ const fg = { l: 0.4, c: 0.1, h: 180 };+ const bgL = 0.5;+ const result = findClosestContrastingColor(fg, bgL);+ expect(Math.abs(result.l - bgL)).toBeGreaterThanOrEqual(+ CONTRAST_THRESHOLD - 0.01+ );+ });++ it('preserves chroma and hue', () => {+ const fg = { l: 0.5, c: 0.15, h: 270, a: 0.8 };+ const bgL = 0.5;+ const result = findClosestContrastingColor(fg, bgL);+ expect(result.c).toBe(0.15);+ expect(result.h).toBe(270);+ expect(result.a).toBe(0.8);+ });++ it('handles edge case when candidate exceeds bounds', () => {+ const fg = { l: 0.9, c: 0.1, h: 180 };+ const bgL = 0.8;+ const result = findClosestContrastingColor(fg, bgL);+ expect(result.l).toBeGreaterThanOrEqual(0);+ expect(result.l).toBeLessThanOrEqual(1);+ });++ it('defaults alpha to 1 when not provided', () => {+ const fg = { l: 0.5, c: 0.1, h: 180 };+ const bgL = 0.5;+ const result = findClosestContrastingColor(fg, bgL);+ expect(result.a).toBe(1);+ });+});diff --git a/js/app/packages/block-email/util/transformEmailColors.ts b/js/app/packages/core/email/transform-email-colors.tssimilarity index 91%rename from js/app/packages/block-email/util/transformEmailColors.tsrename to js/app/packages/core/email/transform-email-colors.tsindex 98ddd5ee83..716b7a8087 100644--- a/js/app/packages/block-email/util/transformEmailColors.ts+++ b/js/app/packages/core/email/transform-email-colors.ts@@ -1,5 +1,3 @@-import { themeReactive } from '../../block-theme/signals/themeReactive';-export interface TextNodeContrast {text: string;fg: OKLCH | null;@@ -8,6 +6,16 @@ export interface TextNodeContrast {insideAnchor: boolean;}+export interface ThemeColorParams {+ inkL: number;+ inkC: number;+ inkH: number;+ panelL: number;+ accentL: number;+ accentC: number;+ accentH: number;+}+const CONTRAST_THRESHOLD = 0.5;const EPSILON = 0.0001;@@ -17,21 +25,13 @@ type OKLCH = { l: number; c: number; h: number; a?: number };/*** Process the colors of the email content so that 1) the text colors are in line with our theme colors, and 2) the text colors have enough contrast with the background colors.* @param root - The root node of the email content.+ * @param theme - The theme color parameters.*/-export function processEmailColors(root: Node) {- const inkL = themeReactive.c0.l[0]();- const inkC = themeReactive.c0.c[0]();- const inkH = themeReactive.c0.h[0]();-- const panelL = themeReactive.b1.l[0]();-- const accentL = themeReactive.a0.l[0]();- const accentC = themeReactive.a0.c[0]();- const accentH = themeReactive.a0.h[0]();+export function processEmailColors(root: Node, theme: ThemeColorParams) {+ const { inkL, inkC, inkH, panelL, accentL, accentC, accentH } = theme;const themeIsDarkModish = inkL > panelL;const textNodeColors = computeTextNodeColor(root);- // console.log('textNodeColors', textNodeColors);textNodeColors.forEach((textNodeColor) => {// if the text has a background color set, trust that the email sender's choices and don't change anythingif ((textNodeColor.bg?.a ?? 0) > 0) return;@@ -143,7 +143,7 @@ export function rgbaToOklch(rgba: RGBA | null): OKLCH | null {}// parses the result of getComputedStyle().color-function parseRGBA(color: string): RGBA | null {+export function parseRGBA(color: string): RGBA | null {if (!color) return null;const s = color.trim().toLowerCase();if (s === 'transparent') return { r: 0, g: 0, b: 0, a: 0 };@@ -161,7 +161,7 @@ function parseRGBA(color: string): RGBA | null {return null;}-function normalizeRGBA(rgba: RGBA | null) {+export function normalizeRGBA(rgba: RGBA | null) {if (!rgba) return null;const clamp01 = (x: number) => Math.max(0, Math.min(1, x));return {@@ -172,7 +172,7 @@ function normalizeRGBA(rgba: RGBA | null) {};}-function computeTextNodeColor(root: Node): TextNodeContrast[] {+export function computeTextNodeColor(root: Node): TextNodeContrast[] {const out: TextNodeContrast[] = [];const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {