From 1b7de69747b3e1971d94f00e7d509af6fbb6e2e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8D=E8=A7=81=E6=99=93=E7=A9=BA?= Date: Wed, 30 Sep 2026 17:49:25 +0800 Subject: [PATCH 1/4] feat(mail): add Gmail-style inbox tabs and reliable everyday workflows Add scoped inbox categories, manual overrides, full-width list and optional reading pane. Improve draft editing and list actions; protect compose send/attachment races, deep links, stale selection and pagination flags. Includes schema migration 0028 and expanded regression coverage. Local tests: 586 passed; typecheck and Cloudflare build passed. Hosted browser verification pending. --- .github/workflows/ci.yml | 4 +- DESIGN.md | 16 + README.md | 7 + migrations/0028_inbox_categories.sql | 9 + package.json | 2 +- playwright.config.ts | 2 +- schema.sql | 2 + scripts/e2e/start-local.ts | 5 +- src/lib/client/compose-controller.test.ts | 26 + src/lib/client/compose-controller.ts | 13 + src/lib/client/compose-shortcuts.test.ts | 41 ++ src/lib/client/compose-shortcuts.ts | 22 + src/lib/client/layout-preferences.test.ts | 11 +- src/lib/client/layout-preferences.ts | 9 +- src/lib/client/mailbox-controller.test.ts | 42 ++ src/lib/client/mailbox-controller.ts | 19 +- src/lib/client/workspace-api.ts | 6 + .../client/workspace-url-controller.test.ts | 18 +- src/lib/client/workspace-url-controller.ts | 11 +- src/lib/components/mail/ComposeModal.svelte | 155 ++++-- src/lib/components/mail/ComposeWindow.svelte | 8 +- src/lib/components/mail/FolderHeader.svelte | 24 +- .../components/mail/InboxCategoryTabs.svelte | 45 ++ src/lib/components/mail/MessageDetail.svelte | 3 + src/lib/components/mail/MessageHeader.svelte | 10 +- src/lib/components/mail/MessageList.svelte | 18 +- .../components/mail/MessageListItem.svelte | 74 ++- src/lib/domain/mail/categories.test.ts | 49 ++ src/lib/domain/mail/categories.ts | 68 +++ src/lib/domain/mail/index.ts | 1 + src/lib/domain/mail/types.ts | 26 + src/lib/i18n/messages.ts | 28 ++ src/lib/server/db/inbound.ts | 3 +- src/lib/server/db/inbox-categories.ts | 23 + src/lib/server/db/mailbox.ts | 12 +- src/lib/server/db/messages.ts | 28 +- src/lib/server/db/migrations.test.ts | 9 +- src/lib/server/db/schema-version.ts | 2 +- src/lib/server/workspace/categories.ts | 101 ++++ .../server/workspace/mailbox-query.test.ts | 25 + src/lib/server/workspace/mailbox-query.ts | 19 +- .../workspace/mailbox.integration.test.ts | 130 +++++ src/lib/server/workspace/mailbox.ts | 28 +- src/lib/server/workspace/reader.test.ts | 12 + src/lib/server/workspace/reader.ts | 16 +- src/lib/server/workspace/shared.ts | 10 + src/lib/server/workspace/trash.ts | 8 +- src/routes/+page.server.ts | 3 +- src/routes/+page.svelte | 208 ++++++-- .../workspace/mailbox/categories/+server.ts | 13 + .../mailbox/categories/server.test.ts | 114 +++++ .../api/workspace/mailbox/mutate/+server.ts | 7 + .../workspace/mailbox/mutate/server.test.ts | 14 + .../api/workspace/messages/[id]/+server.ts | 10 +- .../workspace/messages/[id]/server.test.ts | 39 ++ tests/e2e/compose-safety.spec.ts | 198 ++++++++ tests/e2e/firefox-smoke.spec.ts | 3 +- tests/e2e/fixtures.ts | 10 + tests/e2e/gmail-workflows.spec.ts | 470 ++++++++++++++++++ tests/e2e/webkit-smoke.spec.ts | 6 +- tests/e2e/workspace.spec.ts | 30 +- 61 files changed, 2151 insertions(+), 174 deletions(-) create mode 100644 migrations/0028_inbox_categories.sql create mode 100644 src/lib/client/compose-shortcuts.test.ts create mode 100644 src/lib/client/compose-shortcuts.ts create mode 100644 src/lib/components/mail/InboxCategoryTabs.svelte create mode 100644 src/lib/domain/mail/categories.test.ts create mode 100644 src/lib/domain/mail/categories.ts create mode 100644 src/lib/server/db/inbox-categories.ts create mode 100644 src/lib/server/workspace/categories.ts create mode 100644 src/routes/api/workspace/mailbox/categories/+server.ts create mode 100644 src/routes/api/workspace/mailbox/categories/server.test.ts create mode 100644 tests/e2e/compose-safety.spec.ts create mode 100644 tests/e2e/gmail-workflows.spec.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30769d4..137333f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,8 +70,8 @@ jobs: - run: bun run test:a11y env: CI: true - - name: upload Playwright diagnostics - if: ${{ failure() }} + - name: upload Playwright diagnostics and UI evidence + if: ${{ always() }} uses: actions/upload-artifact@v4 with: name: playwright-diagnostics-${{ github.run_id }} diff --git a/DESIGN.md b/DESIGN.md index ce4d684..d0df1c9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -854,3 +854,19 @@ API 受理不能显示为“已送达”。在 webhook 确认之前使用“已 本轮浏览器证据使用隔离的本地 Worker、D1/R2 合成 fixture 和 Chromium Playwright fallback;Browser plugin 不在当前环境中。回归尺寸包含 320、390、480、768、900、901、1023、1024、1280、1366 px,并覆盖短视口、移动横屏、中文/英文、浅色/深色、标准/紧凑密度、侧栏状态、长主题和长正文。1366 × 768 的几何验收要求正文起点不超过 220 px,实际可见正文至少占视口 60%;可见高度按视口、详情面板和祖先裁剪区域的交集计算,不使用 `scrollHeight` 或 iframe 声明高度冒充可见空间。 可访问性和 CSS 依据于 2026-09-17 复核的 [W3C WCAG 2.2](https://www.w3.org/TR/WCAG22/)、[WAI-ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/)、[Tailwind CSS 加载样式层文档](https://tailwindcss.com/docs/adding-custom-styles#using-css-layers);实现保留项目现有组件和 token,不引入全局 `!important`、隐藏滚动条、缩放/变形或无证据的大范围重构。 + +## 25. 2026-09-30 Gmail 式收件工作流 + +本节更新默认邮件列表与收件分类的交互规范;颜色、FlareMail 品牌、邮件安全和多地址身份规则保持原规范。 + +- 默认使用全宽邮件列表。桌面每行依次展示选择框、星标、对端、主题与摘要、日期;未读行使用浅色背景和加粗文字。打开邮件后进入阅读页,返回恢复同一列表和触发控件焦点。浏览器前进/后退保留文件夹、搜索、地址筛选与分类。 +- 文件夹标题提供“显示分栏预览 / 关闭分栏预览”。分栏继续支持原有宽度拖拽与键盘操作;阅读布局与显示密度独立保存在当前浏览器。窄屏继续一次显示一个主面板。 +- 收件箱分类只以横向 Tab 展示:全部、主要、推广、社交、更新、论坛。窄屏在分类条内部横向滚动,页面本身不横向溢出。Tab 使用 roving tabindex、方向键、Home/End、tabpanel 关系和可见选中下划线;侧栏不增加分类菜单。 +- “全部”为默认入口,避免旧邮件因启用分类而看似消失。其余分类根据发件地址与主题的本地保守规则判定,不调用外部 AI,不读取正文。分类只是组织提示,不是垃圾邮件、安全或身份认证判断。可为选中邮件手动指定分类,也可恢复自动分类。 +- 分类在服务端筛选后分页,并进入游标和批量操作范围;列表计数不是当前加载页的数量。搜索、未读/星标与域名/地址筛选和分类共同生效。邮件按明确选择操作,不因一个 Tab 扩大到别的地址或会话。 +- 全宽模式下点击草稿直接续写。草稿列表有可发现的移入垃圾箱入口,沿用可撤销删除和垃圾箱恢复;已接收/已发送邮件正文保持只读,修改内容应通过草稿、回复或转发完成。 +- 列表提供归档/移回收件箱、已读/未读、删除等快捷操作;鼠标悬停与键盘焦点可显示桌面行操作,手机仍可通过阅读页完成同等操作。 +- Ctrl/Cmd+Enter 仅表示明确发送,不接受收件人联想后顺带发送;IME 组合输入和长按不触发发送。附件准备只合并服务器持久化元数据,不覆盖正在编辑的正文;上传/取消进行中不能关闭或保存退出编辑器。 +- 深链接可读取当前分页之外的 Owner 邮件,但不能把它插入当前分类/搜索分页或污染游标。迟到的读/星标响应不能抢回用户已切换的阅读选择,更新后的读/星标状态不能被下一页旧缓存覆盖。 + +数据库新增 `0028_inbox_categories.sql`(schema 28);部署该版本前需要按既有发布流程应用迁移。本轮仅本地合成数据验证,不代表生产收发信已验收。 diff --git a/README.md b/README.md index 5c420b1..f47e573 100644 --- a/README.md +++ b/README.md @@ -159,3 +159,10 @@ Domain、Resend、D1 Time Travel 与 Email Routing 顺序的唯一权威说明 - [docs/SLO.md](./docs/SLO.md):建议性 SLO、阻塞阈值与无 PII 可观测性契约。 - [TODO.md](./TODO.md):重构完成后的剩余产品路线。 - [GEMINI_UI_PROMPT.md](./GEMINI_UI_PROMPT.md):已归档的旧视觉提示,不再是实现依据。 + +### 收件分类与邮件日常操作 + +- 收件箱顶部提供横向分类标签:全部、主要、推广、社交、更新、论坛。默认显示全部邮件;自动分类只在本地依据发件人和主题匹配,可以勾选邮件后手动更改或恢复自动分类。 +- 默认使用全宽列表,点击进入阅读,再返回原筛选;标题栏可切换为分栏预览。分类、搜索、邮件地址筛选、分页和浏览器前进/后退可组合使用。 +- 点击草稿即可续写;列表支持星标、已读/未读、归档和移入垃圾箱。删除后可撤销,也可从垃圾箱恢复。收件与已发送正文不直接改写,通过回复、转发或草稿编辑生成新邮件。 +- 分类功能需要数据库迁移 `0028_inbox_categories.sql`,沿用部署文档中的迁移与发布流程。已有邮箱地址、回复发件身份和正文安全隔离不变。 diff --git a/migrations/0028_inbox_categories.sql b/migrations/0028_inbox_categories.sql new file mode 100644 index 0000000..ce0c2df --- /dev/null +++ b/migrations/0028_inbox_categories.sql @@ -0,0 +1,9 @@ +-- NULL keeps automatic metadata classification; a value records the Owner's choice. +ALTER TABLE workspace_messages ADD COLUMN inbox_category TEXT + CHECK (inbox_category IS NULL OR inbox_category IN ('primary', 'promotions', 'social', 'updates', 'forums')); +ALTER TABLE email_messages ADD COLUMN inbox_category TEXT + CHECK (inbox_category IS NULL OR inbox_category IN ('primary', 'promotions', 'social', 'updates', 'forums')); + +UPDATE workspace_schema_metadata +SET schema_version = 28, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') +WHERE schema_name = 'flaremail'; diff --git a/package.json b/package.json index 79c1c20..f0bb5d4 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "test": "bun test src scripts", "test:unit": "bun test src/lib/client src/lib/components/mail/domain-capabilities.test.ts src/lib/components/ui src/lib/domain/mail src/lib/domain/utf8.test.ts src/lib/i18n src/lib/server/auth src/lib/server/config src/lib/server/body.test.ts src/lib/server/cloudflare-email-routing.test.ts src/lib/server/db/attachments.test.ts src/lib/server/db/capabilities.test.ts src/lib/server/db/deliveries.test.ts src/lib/server/db/mail-identities.test.ts src/lib/server/db/messages.test.ts src/lib/server/email.test.ts src/lib/server/inbound/parser.test.ts src/lib/server/mail-identities/check.test.ts src/lib/server/mail-identities/health-refresh.test.ts src/lib/server/mail-identities/routing.test.ts src/lib/server/mail-identities/sending.test.ts src/lib/server/mail-identities/validation.test.ts src/lib/server/mail/html-sanitize.test.ts src/lib/server/outbound/gateway.test.ts src/lib/server/outbound/rate-limit.test.ts src/lib/server/outbound/system.test.ts src/lib/server/resend-domains.test.ts src/lib/server/search/fts.test.ts src/lib/server/workspace/compose-body.test.ts src/lib/server/telegram/api.test.ts src/lib/server/telegram/config.test.ts src/lib/server/telegram/message.test.ts src/lib/server/scheduled.test.ts", - "test:integration": "bun test src/lib/server/email.integration.test.ts src/lib/server/workspace/attachment.integration.test.ts src/lib/server/workspace/outbound.integration.test.ts src/lib/server/workspace/delivery.integration.test.ts src/lib/server/workspace/draft.integration.test.ts src/lib/server/workspace/mailbox.integration.test.ts src/lib/server/workspace/mutation-query-counter.integration.test.ts src/lib/server/workspace/trash.integration.test.ts src/lib/server/db/migrations.test.ts src/lib/server/db/telegram.test.ts src/lib/server/telegram/dispatcher.test.ts src/routes/api/health/health.test.ts src/routes/api/readiness/readiness.test.ts src/routes/api/workspace/mailbox/mutate/server.test.ts 'src/routes/api/workspace/mail-identities/[addressId]/server.test.ts'", + "test:integration": "bun test src/lib/server/email.integration.test.ts src/lib/server/workspace/attachment.integration.test.ts src/lib/server/workspace/outbound.integration.test.ts src/lib/server/workspace/delivery.integration.test.ts src/lib/server/workspace/draft.integration.test.ts src/lib/server/workspace/mailbox.integration.test.ts src/lib/server/workspace/mutation-query-counter.integration.test.ts src/lib/server/workspace/trash.integration.test.ts src/lib/server/db/migrations.test.ts src/lib/server/db/telegram.test.ts src/lib/server/telegram/dispatcher.test.ts src/routes/api/health/health.test.ts src/routes/api/readiness/readiness.test.ts src/routes/api/workspace/mailbox/mutate/server.test.ts src/routes/api/workspace/mailbox/categories/server.test.ts 'src/routes/api/workspace/mail-identities/[addressId]/server.test.ts'", "test:remaining": "bun test scripts src/hooks.server.test.ts src/lib/server/attachment-download.test.ts src/lib/server/attachment-integrity.test.ts src/lib/server/http/api.test.ts src/lib/server/resend-webhook.test.ts src/lib/server/workspace/mailbox-query.test.ts src/lib/server/workspace/reader.test.ts src/lib/server/workspace/r2-cleanup.test.ts src/lib/server/workspace/session.test.ts src/lib/server/workspace/shared.test.ts src/routes/api/send/server.test.ts src/routes/api/webhooks/resend/server.test.ts src/routes/api/webhooks/telegram/server.test.ts src/routes/api/workspace/notifications/telegram/settings/server.test.ts 'src/routes/api/workspace/messages/[id]/html/html.test.ts' 'src/routes/api/workspace/messages/[id]/server.test.ts' src/routes/api/workspace/session/server.test.ts src/routes/api/workspace/trash/trash.test.ts", "test:e2e": "bun scripts/playwright-projects.ts chromium", "test:e2e:webkit": "bun scripts/playwright-projects.ts webkit", diff --git a/playwright.config.ts b/playwright.config.ts index 761b201..7d415bb 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -20,7 +20,7 @@ const webkitLaunchOptions = process.env.PLAYWRIGHT_WEBKIT_EXECUTABLE_PATH const firefoxLaunchOptions = process.env.PLAYWRIGHT_FIREFOX_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_FIREFOX_EXECUTABLE_PATH } : undefined; -const chromiumTestMatch = /workspace\.spec\.ts/u; +const chromiumTestMatch = /(?:workspace|gmail-workflows|compose-safety)\.spec\.ts/u; const webkitSmokeTestMatch = /webkit-smoke\.spec\.ts/u; const firefoxSmokeTestMatch = /firefox-smoke\.spec\.ts/u; // Linux browser video finalization is unreliable here; failures still retain diff --git a/schema.sql b/schema.sql index b17780b..a54c6b2 100644 --- a/schema.sql +++ b/schema.sql @@ -1,4 +1,5 @@ CREATE TABLE IF NOT EXISTS email_messages ( + inbox_category TEXT CHECK (inbox_category IS NULL OR inbox_category IN ('primary', 'promotions', 'social', 'updates', 'forums')), id TEXT PRIMARY KEY, message_id TEXT, "from" TEXT NOT NULL, @@ -188,6 +189,7 @@ CREATE TABLE IF NOT EXISTS workspace_sessions ( ); CREATE TABLE IF NOT EXISTS workspace_messages ( + inbox_category TEXT CHECK (inbox_category IS NULL OR inbox_category IN ('primary', 'promotions', 'social', 'updates', 'forums')), id TEXT PRIMARY KEY, user_id TEXT NOT NULL, folder TEXT NOT NULL CHECK (folder IN ('inbox', 'sent')), diff --git a/scripts/e2e/start-local.ts b/scripts/e2e/start-local.ts index 306ece8..5ff6b73 100644 --- a/scripts/e2e/start-local.ts +++ b/scripts/e2e/start-local.ts @@ -219,7 +219,10 @@ await run('bunx', [ const worker = Bun.spawn( [ 'bunx', 'wrangler', 'dev', '--config', 'wrangler.toml', '--local', '--persist-to', persistTo, - '--port', port, '--ip', '127.0.0.1', '--show-interactive-dev-session=false', + '--port', port, '--ip', '127.0.0.1', + // Keep parallel local suites deterministic without network-interface probing. + '--inspector-port', process.env.FLAREMAIL_E2E_INSPECTOR_PORT ?? String(Number(port) + 10000), + '--inspector-ip', '127.0.0.1', '--show-interactive-dev-session=false', '--var', 'APP_ENV:development', '--var', 'ALLOW_FAKE_SERVICES:true', '--var', 'OUTBOUND_PROVIDER:demo', '--var', 'OUTBOUND_FROM_EMAIL:e2e@flaremail.test', '--var', 'OUTBOUND_FROM_NAME:FlareMail E2E', '--var', `RESEND_WEBHOOK_SECRET:${webhookSecret}` diff --git a/src/lib/client/compose-controller.test.ts b/src/lib/client/compose-controller.test.ts index eed34c9..d9038bc 100644 --- a/src/lib/client/compose-controller.test.ts +++ b/src/lib/client/compose-controller.test.ts @@ -6,6 +6,7 @@ import { createEmptyComposeInput, formatComposeSavedAt, hasComposeContent, + mergePreparedComposeInput, mergeSavedDraftMetadata, serializeComposeInput, withComposeDraftId, @@ -89,6 +90,31 @@ describe('compose controller', () => { expect(merged.bodyRevision).toBe('body-object-2'); }); + test('attachment preparation preserves newer editor content and only adopts server metadata', () => { + const attachment = { id: 'attachment-1', filename: 'evidence.txt', contentType: 'text/plain', size: 8, inline: false }; + const current = { + ...createEmptyComposeInput(), + to: [{ name: 'New recipient', email: 'new@example.com' }], + subject: 'Latest subject', body: 'Latest body', html: '

Latest HTML

', + senderAddressId: 'latest-sender', bodyRevision: 'old-body', + forwardAttachmentCandidates: [attachment] + }; + const prepared = { + ...current, draftId: 'draft-1', expectedUpdatedAt: '2026-09-30T10:00:00.000Z', + to: [{ name: 'Old recipient', email: 'old@example.com' }], + subject: 'Old subject', body: 'Old body', html: '

Old HTML

', + senderAddressId: 'old-sender', bodyRevision: 'prepared-body', + attachments: [attachment], attachmentRevision: 3, + forwardAttachmentCandidates: undefined + }; + expect(mergePreparedComposeInput(current, prepared)).toEqual({ + ...current, draftId: 'draft-1', expectedUpdatedAt: prepared.expectedUpdatedAt, + bodyRevision: 'prepared-body', attachments: [attachment], attachmentRevision: 3 + }); + expect(mergePreparedComposeInput(current, { ...prepared, bodyRevision: undefined }).bodyRevision).toBeUndefined(); + expect(current.bodyRevision).toBe('old-body'); + }); + test('treats attachments as content and preserves their optimistic revision in draft metadata', () => { const attachment = { id: 'attachment-1', filename: 'evidence.txt', contentType: 'text/plain', size: 8, inline: false }; const input = { ...createEmptyComposeInput(), attachments: [attachment], attachmentRevision: 3 }; diff --git a/src/lib/client/compose-controller.ts b/src/lib/client/compose-controller.ts index 7c6a536..0230661 100644 --- a/src/lib/client/compose-controller.ts +++ b/src/lib/client/compose-controller.ts @@ -45,6 +45,19 @@ export function withComposePersistence( }; } +/** Attachment preparation persists an older snapshot; only its server metadata is authoritative. */ +export function mergePreparedComposeInput(current: ComposeInput, prepared: ComposeInput): ComposeInput { + return { + ...withComposePersistence(current, { + draftId: prepared.draftId, + expectedUpdatedAt: prepared.expectedUpdatedAt, + bodyRevision: prepared.bodyRevision ?? null + }), + attachments: prepared.attachments ?? [], + attachmentRevision: prepared.attachmentRevision ?? 0 + }; +} + export function hasComposeContent(input: ComposeInput | null) { return Boolean(input && (parseAddressList(input.to ?? input.toEmail ?? '').length || parseAddressList(input.cc ?? '').length || parseAddressList(input.bcc ?? '').length || input.subject.trim() || input.body.trim() || input.html?.trim() || input.attachments?.length)); } diff --git a/src/lib/client/compose-shortcuts.test.ts b/src/lib/client/compose-shortcuts.test.ts new file mode 100644 index 0000000..a8cdf01 --- /dev/null +++ b/src/lib/client/compose-shortcuts.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from 'bun:test'; +import { isComposeSendShortcut, isRecipientCommitKey, shouldHandleRecipientKey } from './compose-shortcuts'; + +const key = (overrides: Partial = {}) => ({ + key: 'Enter', ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, + isComposing: false, repeat: false, defaultPrevented: false, ...overrides +}); + +describe('compose keyboard actions', () => { + test('reserves Ctrl and Command Enter for sending without selecting a suggestion', () => { + for (const modifier of [{ ctrlKey: true }, { metaKey: true }]) { + expect(isComposeSendShortcut(key(modifier))).toBe(true); + expect(shouldHandleRecipientKey(key(modifier))).toBe(false); + expect(isRecipientCommitKey(key(modifier))).toBe(false); + } + expect(isComposeSendShortcut(key())).toBe(false); + expect(isRecipientCommitKey(key())).toBe(true); + }); + + test('ignores IME confirmation, held keys, already-handled events and extra modifiers', () => { + for (const suppressed of [ + { isComposing: true }, { keyCode: 229 }, { repeat: true }, + { defaultPrevented: true }, { altKey: true }, { shiftKey: true } + ]) { + expect(isComposeSendShortcut(key({ ctrlKey: true, ...suppressed }))).toBe(false); + expect(shouldHandleRecipientKey(key(suppressed))).toBe(false); + expect(isRecipientCommitKey(key(suppressed))).toBe(false); + } + }); + + test('supports address separators without consuming ordinary text or navigation keys', () => { + for (const separator of [',', ',', ';', ';']) { + expect(isRecipientCommitKey(key({ key: separator }))).toBe(true); + expect(isRecipientCommitKey(key({ key: separator, isComposing: true }))).toBe(false); + } + for (const ordinary of ['a', '@', 'Tab', 'ArrowDown', 'Escape']) { + expect(isRecipientCommitKey(key({ key: ordinary }))).toBe(false); + expect(isComposeSendShortcut(key({ key: ordinary, ctrlKey: true }))).toBe(false); + } + }); +}); diff --git a/src/lib/client/compose-shortcuts.ts b/src/lib/client/compose-shortcuts.ts new file mode 100644 index 0000000..a453876 --- /dev/null +++ b/src/lib/client/compose-shortcuts.ts @@ -0,0 +1,22 @@ +type ComposeKeyEvent = Pick & { keyCode?: number }; + +function isFreshKey(event: ComposeKeyEvent) { + // Safari can report the final IME Enter as keyCode 229 without isComposing. + return !event.defaultPrevented && !event.isComposing && event.keyCode !== 229 && !event.repeat; +} + +export function isComposeSendShortcut(event: ComposeKeyEvent) { + return isFreshKey(event) && event.key === 'Enter' && (event.ctrlKey || event.metaKey) + && !event.altKey && !event.shiftKey; +} + +/** Recipient selection must never consume a send shortcut or an IME candidate key. */ +export function shouldHandleRecipientKey(event: ComposeKeyEvent) { + return isFreshKey(event) && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey; +} + +export function isRecipientCommitKey(event: ComposeKeyEvent) { + return shouldHandleRecipientKey(event) && ['Enter', ',', ',', ';', ';'].includes(event.key); +} diff --git a/src/lib/client/layout-preferences.test.ts b/src/lib/client/layout-preferences.test.ts index 1d0938a..ef881d5 100644 --- a/src/lib/client/layout-preferences.test.ts +++ b/src/lib/client/layout-preferences.test.ts @@ -45,6 +45,15 @@ describe('layout preferences', () => { test('round trips versioned values through storage', () => { const storage = memoryStorage(); writeLayoutPreferences({ version: 1, sidebarCollapsed: true, listWidth: 414, density: 'compact' }, storage); - expect(readLayoutPreferences(storage)).toEqual({ version: 1, sidebarCollapsed: true, listWidth: 414, density: 'compact' }); + expect(readLayoutPreferences(storage)).toEqual({ version: 1, sidebarCollapsed: true, listWidth: 414, density: 'compact', readingLayout: 'list' }); }); }); + + +test('defaults to the Gmail-style list and preserves an explicit reading pane preference', () => { + expect(DEFAULT_LAYOUT_PREFERENCES.readingLayout).toBe('list'); + expect(normalizeLayoutPreferences({ readingLayout: 'invalid' }).readingLayout).toBe('list'); + const storage = memoryStorage(); + writeLayoutPreferences({ ...DEFAULT_LAYOUT_PREFERENCES, readingLayout: 'split' }, storage); + expect(readLayoutPreferences(storage).readingLayout).toBe('split'); +}); diff --git a/src/lib/client/layout-preferences.ts b/src/lib/client/layout-preferences.ts index 9f272aa..76cd133 100644 --- a/src/lib/client/layout-preferences.ts +++ b/src/lib/client/layout-preferences.ts @@ -1,3 +1,5 @@ +export type ReadingLayout = 'list' | 'split'; + export type DisplayDensity = 'comfortable' | 'compact'; export type LayoutPreferences = { @@ -5,6 +7,7 @@ export type LayoutPreferences = { sidebarCollapsed: boolean; listWidth: number; density: DisplayDensity; + readingLayout?: ReadingLayout; }; export const LAYOUT_PREFERENCES_KEY = 'flaremail-layout-v1'; @@ -12,7 +15,8 @@ export const DEFAULT_LAYOUT_PREFERENCES: LayoutPreferences = { version: 1, sidebarCollapsed: false, listWidth: 440, - density: 'comfortable' + density: 'comfortable', + readingLayout: 'list' }; const MIN_LIST_WIDTH = 280; @@ -47,7 +51,8 @@ export function normalizeLayoutPreferences(value: unknown): LayoutPreferences { version: 1, sidebarCollapsed: input.sidebarCollapsed === true, listWidth: clampListWidth(typeof input.listWidth === 'number' ? input.listWidth : DEFAULT_LAYOUT_PREFERENCES.listWidth), - density: input.density === 'compact' ? 'compact' : 'comfortable' + density: input.density === 'compact' ? 'compact' : 'comfortable', + readingLayout: input.readingLayout === 'split' ? 'split' : 'list' }; } diff --git a/src/lib/client/mailbox-controller.test.ts b/src/lib/client/mailbox-controller.test.ts index 2b89a5d..8ff3883 100644 --- a/src/lib/client/mailbox-controller.test.ts +++ b/src/lib/client/mailbox-controller.test.ts @@ -302,3 +302,45 @@ function makePage(folder: MailMessage['folder'], messages: MailMessage[]) { deliveryStatus: null }; } + +test('category scopes refresh and pagination and ignores stale tab responses', async () => { + const calls: Array = []; + const applied: string[] = []; + let resolveFirst: ((value: { page: MailboxPage }) => void) | undefined; + const controller = new MailboxController(async (params) => { + calls.push(params); + if (params.get('category') === 'primary') return new Promise((resolve) => { resolveFirst = resolve; }); + return { page: { ...makePage('inbox', []), category: 'updates', hasMore: true, nextCursor: 'updates-cursor' } }; + }, { onPage: (page) => applied.push(page.category ?? 'all'), onLoading: () => undefined, onError: () => undefined }); + const stale = controller.refresh('inbox', '', 'all', null, null, 'primary'); + await controller.refresh('inbox', 'invoice', 'unread', { kind: 'address', id: 'personal' }, null, 'updates'); + resolveFirst?.({ page: { ...makePage('inbox', []), category: 'primary' } }); + expect(await stale).toBe(false); + expect(applied).toEqual(['updates']); + expect(calls[1].get('category')).toBe('updates'); + expect(calls[1].get('identity')).toBe('address:personal'); + expect(calls[1].get('q')).toBe('invoice'); + await controller.loadMore('inbox', 'invoice', 'unread', { ...makePage('inbox', []), category: 'updates', hasMore: true, nextCursor: 'updates-cursor' }, { kind: 'address', id: 'personal' }, null, 'updates'); + expect(calls[2].get('cursor')).toBe('updates-cursor'); + expect(calls[2].get('category')).toBe('updates'); +}); + +test('does not merge a message from another inbox category into the active tab', () => { + const incoming = { ...message('incoming', 'inbox', '2026-08-14T02:00:00.000Z'), inboxCategory: 'social' as const }; + const page = { ...makePage('inbox', []), category: 'updates' as const }; + const result = mergeMessageDelta({ mailbox: cloneMailbox(), mailboxPages: { inbox: page }, metrics }, delta(incoming), deltaOptions()); + expect(result.messageApplied).toBe(false); + expect(result.snapshot.mailbox.inbox).toEqual([]); + const matched = mergeMessageDelta({ mailbox: cloneMailbox(), mailboxPages: { inbox: page }, metrics }, delta({ ...incoming, inboxCategory: 'updates' }), deltaOptions()); + expect(matched.messageApplied).toBe(true); +}); + +test('keeps updated read and star flags when another page is appended', () => { + const first = { ...message('first', 'inbox', '2026-08-14T02:00:00.000Z'), inboxCategory: 'primary' as const }; + const page = { ...makePage('inbox', [first]), category: 'primary' as const, nextCursor: 'next', hasMore: true }; + const state = mergeMailboxPage(snapshot(cloneMailbox()), page, false); + const patched = mergeMessageDelta(state, delta({ ...first, read: true, starred: true }), deltaOptions()); + expect(patched.snapshot.mailboxPages?.inbox?.messages[0]).toMatchObject({ read: true, starred: true }); + const appended = mergeMailboxPage(patched.snapshot, { ...page, messages: [message('second', 'inbox', '2026-08-13T02:00:00.000Z')], nextCursor: null, hasMore: false }, true); + expect(appended.mailbox.inbox.find((item) => item.id === 'first')).toMatchObject({ read: true, starred: true }); +}); diff --git a/src/lib/client/mailbox-controller.ts b/src/lib/client/mailbox-controller.ts index 719d34b..c810b89 100644 --- a/src/lib/client/mailbox-controller.ts +++ b/src/lib/client/mailbox-controller.ts @@ -3,6 +3,7 @@ import { cloneMailbox, cloneProfile, type MailboxSection, + type InboxCategoryFilter, type MailboxIdentityFilter, type MailboxMetricsScope, type MailMessage, @@ -239,7 +240,8 @@ export function mergeMessageDelta( const pageMatchesCurrentScope = !targetPage || sameIdentityFilter(targetPage.identityFilter, identityFilter); const query = targetPage?.query ?? (section === options.currentSection ? options.query ?? '' : ''); const filter = targetPage?.filter ?? (section === options.currentSection ? options.filter ?? 'all' : 'all'); - const canMergeMessage = section !== 'starred' && section !== 'label' && identityMatches && pageMatchesCurrentScope && !query.trim() && filter === 'all'; + const categoryMatches = section !== 'inbox' || !targetPage?.category || targetPage.category === 'all' || result.message.inboxCategory === targetPage.category; + const canMergeMessage = categoryMatches && section !== 'starred' && section !== 'label' && identityMatches && pageMatchesCurrentScope && !query.trim() && filter === 'all'; if (options.removeDraftId && snapshot.mailboxPages?.drafts) { const draftsPage = snapshot.mailboxPages.drafts; @@ -316,7 +318,9 @@ export function mergeMessageDelta( return { snapshot: { mailbox: nextMailbox, - mailboxPages: snapshot.mailboxPages, + mailboxPages: targetPage && section === folder + ? { ...snapshot.mailboxPages, [folder]: { ...targetPage, messages: nextMailbox[folder] } } + : snapshot.mailboxPages, metrics: metricsApplied ? result.metrics : snapshot.metrics }, selectedMessageId: selectNextMessage( @@ -377,12 +381,12 @@ export class MailboxController { private readonly callbacks: MailboxControllerCallbacks ) {} - async refresh(folder: MailboxSection, query: string, filter: MailFilter, identityFilter: MailboxIdentityFilter | null = null, labelId: string | null = null) { + async refresh(folder: MailboxSection, query: string, filter: MailFilter, identityFilter: MailboxIdentityFilter | null = null, labelId: string | null = null, category: InboxCategoryFilter = 'all') { const request = this.request.begin(); this.setLoading(true, false); try { const params = new URLSearchParams({ folder, limit: '40' }); - this.addFilters(params, query, filter, identityFilter, labelId); + this.addFilters(params, query, filter, identityFilter, labelId, category); const result = await this.fetchPage(params, request.signal); if (request.isCurrent()) { this.callbacks.onPage(result.page, false); @@ -396,7 +400,7 @@ export class MailboxController { return false; } - async loadMore(folder: MailboxSection, query: string, filter: MailFilter, currentPage: MailboxPage | undefined, identityFilter: MailboxIdentityFilter | null = null, labelId: string | null = null) { + async loadMore(folder: MailboxSection, query: string, filter: MailFilter, currentPage: MailboxPage | undefined, identityFilter: MailboxIdentityFilter | null = null, labelId: string | null = null, category: InboxCategoryFilter = 'all') { if (!currentPage?.nextCursor || !currentPage.hasMore) return; const request = this.request.begin(); this.setLoading(true, true); @@ -406,7 +410,7 @@ export class MailboxController { cursor: currentPage.nextCursor, limit: String(currentPage.limit) }); - this.addFilters(params, query, filter, identityFilter, labelId); + this.addFilters(params, query, filter, identityFilter, labelId, category); const result = await this.fetchPage(params, request.signal); if (request.isCurrent()) { this.callbacks.onPage(result.page, true); @@ -431,7 +435,8 @@ export class MailboxController { this.callbacks.onLoading(loading, append); } - private addFilters(params: URLSearchParams, query: string, filter: MailFilter, identityFilter: MailboxIdentityFilter | null, labelId: string | null) { + private addFilters(params: URLSearchParams, query: string, filter: MailFilter, identityFilter: MailboxIdentityFilter | null, labelId: string | null, category: InboxCategoryFilter) { + if (params.get('folder') === 'inbox' && category !== 'all') params.set('category', category); if (query.trim()) params.set('q', query.trim()); if (filter !== 'all') params.set('filter', filter); if (identityFilter) params.set('identity', `${identityFilter.kind}:${identityFilter.id}`); diff --git a/src/lib/client/workspace-api.ts b/src/lib/client/workspace-api.ts index 0e120c3..c1aeb5a 100644 --- a/src/lib/client/workspace-api.ts +++ b/src/lib/client/workspace-api.ts @@ -354,3 +354,9 @@ export function emptyTrash() { body: JSON.stringify({ action: 'empty' }) }); } + +export function setInboxCategory(ids: string[], category: import('$lib/domain/mail').MailInboxCategory | null, scope: { section: 'inbox'; identityFilter: import('$lib/domain/mail').MailboxIdentityFilter | null; category: import('$lib/domain/mail').InboxCategoryFilter }) { + return requestJson<{ summaries: Array> }>('/api/workspace/mailbox/categories', { + method: 'PATCH', body: JSON.stringify({ ids, category, scope }) + }); +} diff --git a/src/lib/client/workspace-url-controller.test.ts b/src/lib/client/workspace-url-controller.test.ts index 42c6f95..75e5d7e 100644 --- a/src/lib/client/workspace-url-controller.test.ts +++ b/src/lib/client/workspace-url-controller.test.ts @@ -4,7 +4,7 @@ import { readWorkspaceUrl, updateWorkspaceUrl } from './workspace-url-controller describe('workspace URL controller', () => { test('normalizes invalid state without dropping unrelated parameters', () => { const url = new URL('https://flaremail.example/?folder=unknown&q=123456789&filter=bad&keep=yes'); - expect(readWorkspaceUrl(url)).toEqual({ section: 'inbox', managementView: 'settings', managementDomainId: null, query: '123456789', filter: 'all', identityFilter: null, messageId: null, labelId: null }); + expect(readWorkspaceUrl(url)).toEqual({ section: 'inbox', managementView: 'settings', managementDomainId: null, query: '123456789', filter: 'all', category: 'all', identityFilter: null, messageId: null, labelId: null }); const next = updateWorkspaceUrl(url, { section: 'profile', query: '', filter: 'all', messageId: null }); expect(next.toString()).toBe('https://flaremail.example/?folder=settings&keep=yes'); }); @@ -18,10 +18,10 @@ describe('workspace URL controller', () => { messageId: 'message-1' }); expect(readWorkspaceUrl(next)).toEqual({ - section: 'sent', managementView: 'settings', managementDomainId: null, query: 'invoice', filter: 'starred', identityFilter: { kind: 'address', id: 'address-1' }, messageId: 'message-1', labelId: null + section: 'sent', managementView: 'settings', managementDomainId: null, query: 'invoice', filter: 'starred', category: 'all', identityFilter: { kind: 'address', id: 'address-1' }, messageId: 'message-1', labelId: null }); expect(readWorkspaceUrl(new URL('https://flaremail.example/?folder=trash&q=invoice&filter=starred&identity=address:address-1'))) - .toEqual({ section: 'trash', managementView: 'settings', managementDomainId: null, query: '', filter: 'all', identityFilter: null, messageId: null, labelId: null }); + .toEqual({ section: 'trash', managementView: 'settings', managementDomainId: null, query: '', filter: 'all', category: 'all', identityFilter: null, messageId: null, labelId: null }); }); test('preserves a global Starred deep link and its address scope', () => { @@ -35,7 +35,7 @@ describe('workspace URL controller', () => { test('keeps domain and address management deep links separate from mailbox folders', () => { const domainUrl = updateWorkspaceUrl(new URL('https://flaremail.example/?folder=inbox'), { - section: 'profile', managementView: 'domains', query: '', filter: 'all', identityFilter: null, messageId: null + section: 'profile', managementView: 'domains', query: '', filter: 'all', category: 'all', identityFilter: null, messageId: null }); expect(readWorkspaceUrl(domainUrl).managementView).toBe('domains'); expect(domainUrl.searchParams.get('view')).toBe('domains'); @@ -54,3 +54,13 @@ describe('workspace URL controller', () => { expect(updateWorkspaceUrl(settingsUrl, { section: 'profile', managementView: 'domains' }).hash).toBe(''); }); }); + + +test('inbox category round trips with search and identity, and clears when leaving inbox', () => { + const url = updateWorkspaceUrl(new URL('https://flaremail.example/?folder=inbox&q=invoice&identity=address:personal'), { category: 'updates', messageId: null }); + expect(readWorkspaceUrl(url)).toMatchObject({ category: 'updates', query: 'invoice', identityFilter: { kind: 'address', id: 'personal' } }); + expect(readWorkspaceUrl(updateWorkspaceUrl(url, { messageId: 'message-1' })).category).toBe('updates'); + expect(updateWorkspaceUrl(url, { section: 'drafts' }).searchParams.has('category')).toBe(false); + expect(readWorkspaceUrl(new URL('https://flaremail.example/?category=unknown')).category).toBe('all'); + expect(readWorkspaceUrl(new URL('https://flaremail.example/?folder=sent&category=updates')).category).toBe('all'); +}); diff --git a/src/lib/client/workspace-url-controller.ts b/src/lib/client/workspace-url-controller.ts index e670071..a4823ff 100644 --- a/src/lib/client/workspace-url-controller.ts +++ b/src/lib/client/workspace-url-controller.ts @@ -1,4 +1,4 @@ -import type { MailboxIdentityFilter, MailboxSection } from '$lib/domain/mail'; +import type { MailboxIdentityFilter, MailboxSection, InboxCategoryFilter } from '$lib/domain/mail'; import type { MailFilter, WorkspaceSection } from './mailbox-controller'; export type WorkspaceUrlState = { @@ -7,6 +7,7 @@ export type WorkspaceUrlState = { managementDomainId: string | null; query: string; filter: MailFilter; + category: InboxCategoryFilter; identityFilter: MailboxIdentityFilter | null; messageId: string | null; labelId: string | null; @@ -18,6 +19,7 @@ export type WorkspaceUrlUpdates = { managementDomainId?: string | null; query?: string; filter?: MailFilter; + category?: InboxCategoryFilter; identityFilter?: MailboxIdentityFilter | null; messageId?: string | null; labelId?: string | null; @@ -27,6 +29,7 @@ export function readWorkspaceUrl(url: URL): WorkspaceUrlState { const folder = url.searchParams.get('folder'); const section = folder === 'sent' || folder === 'drafts' || folder === 'archive' || folder === 'starred' || folder === 'label' || folder === 'trash' ? folder : folder === 'settings' ? 'profile' : 'inbox'; const filter = url.searchParams.get('filter'); + const category = url.searchParams.get('category'); const view = url.searchParams.get('view'); const managementDomainId = url.searchParams.get('domain'); const identity = url.searchParams.get('identity'); @@ -38,6 +41,7 @@ export function readWorkspaceUrl(url: URL): WorkspaceUrlState { ? managementDomainId : null, query: section === 'trash' || section === 'profile' ? '' : url.searchParams.get('q')?.slice(0, 200) ?? '', filter: section !== 'trash' && section !== 'profile' && (filter === 'unread' || filter === 'starred') ? filter : 'all', + category: section === 'inbox' && ['primary', 'promotions', 'social', 'updates', 'forums'].includes(category ?? '') ? category as InboxCategoryFilter : 'all', identityFilter: section !== 'trash' && section !== 'profile' && identityMatch ? { kind: identityMatch[1] as 'domain' | 'address', id: identityMatch[2] } : null, messageId: section === 'profile' ? null : url.searchParams.get('message'), labelId: section === 'label' && /^[A-Za-z0-9:._-]{1,128}$/u.test(url.searchParams.get('label') ?? '') ? url.searchParams.get('label') : null @@ -68,6 +72,11 @@ export function updateWorkspaceUrl(url: URL, updates: WorkspaceUrlUpdates) { next.searchParams.delete('domain'); } } + if (updates.category !== undefined || updates.section !== undefined) { + const category = updates.category ?? 'all'; + if ((updates.section ?? readWorkspaceUrl(url).section) === 'inbox' && category !== 'all') next.searchParams.set('category', category); + else next.searchParams.delete('category'); + } if (updates.query !== undefined) { const query = updates.query.trim().slice(0, 200); if (query) next.searchParams.set('q', query); diff --git a/src/lib/components/mail/ComposeModal.svelte b/src/lib/components/mail/ComposeModal.svelte index 1b60fd5..cb54254 100644 --- a/src/lib/components/mail/ComposeModal.svelte +++ b/src/lib/components/mail/ComposeModal.svelte @@ -13,7 +13,8 @@ import type { ComposeInput, ComposeMode, MailMessage, UserProfile, WorkspaceSnapshot } from '$lib/domain/mail'; import { mailSenderSendBlockReason } from '$lib/domain/mail/sender-readiness'; import { MAIL_HEALTH_MAX_AGE_MS } from '$lib/domain/mail/health'; - import { withComposePersistence } from '$lib/client/compose-controller'; + import { mergePreparedComposeInput, withComposePersistence } from '$lib/client/compose-controller'; + import { isComposeSendShortcut, isRecipientCommitKey, shouldHandleRecipientKey } from '$lib/client/compose-shortcuts'; import { matchRecipientSuggestions } from '$lib/client/recipient-suggestions'; import { deleteDraftAttachment, @@ -131,6 +132,7 @@ let baseline = $state(''); let touched = $state>({}); let attempted = $state(false); + let sending = $state(false); let showCc = $state(false); let showBcc = $state(false); let showHtml = $state(false); @@ -146,6 +148,10 @@ let dragActive = $state(false); let attachmentMutationError = $state(''); let forwardAttachmentImporting = $state(false); + let activeAttachmentOperations = $state(0); + let cancellingAttachmentIds = $state([]); + type AttachmentUploadSession = { cancelled: boolean; finished: Promise; cancel?: () => void }; + const attachmentUploadSessions = new Map(); let senderFreshnessNow = $state(Date.now()); let attachmentTasks = $state task.state !== 'failed')); + const attachmentBusy = $derived(activeAttachmentOperations > 0 || attachmentTasks.some((task) => task.state !== 'failed')); + const closeDisabled = $derived(sending || forwardAttachmentImporting || attachmentBusy); + const saveDisabled = $derived(authExpired || pending || closeDisabled); const attachmentFailed = $derived(attachmentTasks.some((task) => task.state === 'failed')); const persistedAttachmentBlocked = $derived((input.attachments ?? []).some((attachment) => attachment.state && attachment.state !== 'ready')); - const sendDisabled = $derived(authExpired || pending || forwardAttachmentImporting || attachmentBusy || attachmentFailed || persistedAttachmentBlocked || !validation.ok || !selectedSender || selectedSenderBlockReason !== null); + const sendDisabled = $derived(authExpired || pending || sending || showCloseConfirm || Boolean(draftConflict) || forwardAttachmentImporting || attachmentBusy || attachmentFailed || persistedAttachmentBlocked || !validation.ok || !selectedSender || selectedSenderBlockReason !== null); const autosaveTone = $derived( autosaveStatus === 'error' ? 'text-[var(--fm-danger)]' @@ -307,12 +315,15 @@ async function preparedAttachmentInput() { if (!onPrepareAttachments) throw new Error(t('compose.attachmentServiceUnavailable')); const prepared = await onPrepareAttachments(inputWithRecipientDrafts); - input = createComposeState(prepared, prepared.draftId); - onInputChange?.(input); - return input; + // Keep edits made while the preparation request was in flight. Pending + // recipient text stays in its input, rather than becoming a duplicate chip. + input = mergePreparedComposeInput(input, prepared); + onInputChange?.(inputWithRecipientDrafts); + return inputWithRecipientDrafts; } async function startAttachmentUpload(id: string, file: File) { + if (attachmentUploadSessions.has(id) || cancellingAttachmentIds.includes(id)) return false; if (!attachmentTasks.some((task) => task.id === id)) { attachmentTasks = [...attachmentTasks, { id, file, progress: 0, state: 'queued', error: '' }]; } @@ -320,9 +331,17 @@ updateAttachmentTask(id, { state: 'failed', cancel: undefined, error: t('compose.authExpiredDraftPreserved') }); return false; } + let finishSession!: () => void; + const session: AttachmentUploadSession = { + cancelled: false, + finished: new Promise((resolve) => (finishSession = resolve)) + }; + attachmentUploadSessions.set(id, session); + activeAttachmentOperations += 1; updateAttachmentTask(id, { state: 'uploading', progress: 0, error: '' }); try { const prepared = await preparedAttachmentInput(); + if (session.cancelled) return false; if (!prepared.draftId) throw new Error(t('compose.draftUnavailable')); const operation = uploadDraftAttachment( prepared.draftId, @@ -331,18 +350,26 @@ prepared.attachmentRevision ?? 0, (progress) => updateAttachmentTask(id, { progress }) ); + session.cancel = operation.cancel; updateAttachmentTask(id, { cancel: operation.cancel }); const result = await operation.promise; + if (session.cancelled) return false; applyAttachmentResult(result); attachmentTasks = attachmentTasks.filter((task) => task.id !== id); return true; } catch (error) { - updateAttachmentTask(id, { - state: 'failed', - cancel: undefined, - error: displayError(error, t('compose.uploadFailed')) - }); + if (!session.cancelled) { + updateAttachmentTask(id, { + state: 'failed', + cancel: undefined, + error: displayError(error, t('compose.uploadFailed')) + }); + } return false; + } finally { + attachmentUploadSessions.delete(id); + activeAttachmentOperations -= 1; + finishSession(); } } @@ -417,23 +444,33 @@ } async function cancelAttachmentTask(task: (typeof attachmentTasks)[number]) { - if (authExpired) return; - task.cancel?.(); - const draftId = input.draftId; - if (draftId) { - try { + if (authExpired || cancellingAttachmentIds.includes(task.id)) return; + cancellingAttachmentIds = [...cancellingAttachmentIds, task.id]; + activeAttachmentOperations += 1; + const session = attachmentUploadSessions.get(task.id); + if (session) { + session.cancelled = true; + session.cancel?.(); + } + try { + // Let preparation settle before cleanup so its late response cannot + // overwrite the cancellation's revision or restart the upload. + await session?.finished; + const draftId = input.draftId; + if (draftId) { applyAttachmentResult(await deleteDraftAttachment(draftId, task.id, input.attachmentRevision ?? 0)); - attachmentTasks = attachmentTasks.filter((candidate) => candidate.id !== task.id); - } catch (error) { - const message = error instanceof Error - ? t('compose.cancelAttachmentUnconfirmed', { error: error.message }) - : t('compose.cancelAttachmentRetry'); - updateAttachmentTask(task.id, { state: 'failed', cancel: undefined, error: message }); - attachmentMutationError = message; } - return; + attachmentTasks = attachmentTasks.filter((candidate) => candidate.id !== task.id); + } catch (error) { + const message = error instanceof Error + ? t('compose.cancelAttachmentUnconfirmed', { error: error.message }) + : t('compose.cancelAttachmentRetry'); + updateAttachmentTask(task.id, { state: 'failed', cancel: undefined, error: message }); + attachmentMutationError = message; + } finally { + cancellingAttachmentIds = cancellingAttachmentIds.filter((id) => id !== task.id); + activeAttachmentOperations -= 1; } - attachmentTasks = attachmentTasks.filter((candidate) => candidate.id !== task.id); } function choosePersistedRetry(attachmentId: string) { @@ -450,21 +487,27 @@ } async function removeAttachment(attachmentId: string) { - if (authExpired || !input.draftId) return; + if (authExpired || attachmentBusy || !input.draftId) return; + activeAttachmentOperations += 1; try { applyAttachmentResult(await deleteDraftAttachment(input.draftId, attachmentId, input.attachmentRevision ?? 0)); } catch (error) { attachmentMutationError = displayError(error, t('compose.deleteAttachmentFailed')); + } finally { + activeAttachmentOperations -= 1; } } async function renameAttachment(attachmentId: string) { - if (authExpired || !input.draftId) return; + if (authExpired || attachmentBusy || !input.draftId) return; + activeAttachmentOperations += 1; const filename = renameValues[attachmentId]?.trim() ?? ''; try { applyAttachmentResult(await renameDraftAttachment(input.draftId, attachmentId, filename, input.attachmentRevision ?? 0)); } catch (error) { attachmentMutationError = displayError(error, t('compose.renameAttachmentFailed')); + } finally { + activeAttachmentOperations -= 1; } } @@ -521,6 +564,7 @@ } function handleToKeydown(event: KeyboardEvent) { + if (!shouldHandleRecipientKey(event)) return; if (toSuggestionsOpen && toSuggestions.length > 0) { if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); @@ -539,7 +583,7 @@ toSuggestionsOpen = false; return; } - if (event.key === 'Enter' || event.key === ',' || event.key === ',' || event.key === ';' || event.key === ';') { + if (isRecipientCommitKey(event)) { event.preventDefault(); commitRecipient('to'); } @@ -568,7 +612,7 @@ } function requestClose() { - if (showCloseConfirm) return; + if (showCloseConfirm || closeDisabled) return; if (isDirty) { showCloseConfirm = true; return; @@ -582,11 +626,13 @@ } function saveAndClose() { + if (authExpired || closeDisabled) return; showCloseConfirm = false; void onClose(inputWithRecipientDrafts); } function discardAndClose() { + if (closeDisabled) return; showCloseConfirm = false; if (onDiscard) { onDiscard(); @@ -598,10 +644,22 @@ function handleShortcut(event: KeyboardEvent) { const dialog = document.querySelector('.compose-dialog'); - if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && dialog?.dataset.minimized !== 'true' && dialog?.contains(event.target as Node)) { + if (isComposeSendShortcut(event) && dialog?.dataset.minimized !== 'true' && dialog?.contains(event.target as Node)) { event.preventDefault(); - attempted = true; - if (!sendDisabled) void onSend(validation.value); + void sendCompose(); + } + } + + async function sendCompose() { + attempted = true; + if (sendDisabled) return; + // Lock synchronously: another click or shortcut may arrive before the parent's + // pending prop has propagated back to this component. + sending = true; + try { + await onSend(validation.value); + } finally { + sending = false; } } @@ -620,6 +678,7 @@ description={profile.name || t('compose.workspaceIdentity')} mobileStatus={mobileAutosaveStatus} mobileStatusTone={autosaveTone} + {closeDisabled} onClose={requestClose} >
event.preventDefault()} onpaste={pastedFiles}> @@ -704,7 +763,7 @@ {#each parseAddressList(input.cc ?? '') as address (address.email)} removeRecipient('cc', address.email)} /> {/each} - updateRecipientDraft('cc', event.currentTarget.value)} onpaste={(event) => pasteRecipients('cc', event)} onkeydown={(event) => { if (event.key === 'Enter' || event.key === ',' || event.key === ',' || event.key === ';' || event.key === ';') { event.preventDefault(); commitRecipient('cc'); } }} onblur={() => commitRecipient('cc')} /> + updateRecipientDraft('cc', event.currentTarget.value)} onpaste={(event) => pasteRecipients('cc', event)} onkeydown={(event) => { if (isRecipientCommitKey(event)) { event.preventDefault(); commitRecipient('cc'); } }} onblur={() => commitRecipient('cc')} /> {#if fieldError('cc')}

{fieldError('cc')}

{/if} @@ -717,7 +776,7 @@ {#each parseAddressList(input.bcc ?? '') as address (address.email)} removeRecipient('bcc', address.email)} /> {/each} - updateRecipientDraft('bcc', event.currentTarget.value)} onpaste={(event) => pasteRecipients('bcc', event)} onkeydown={(event) => { if (event.key === 'Enter' || event.key === ',' || event.key === ',' || event.key === ';' || event.key === ';') { event.preventDefault(); commitRecipient('bcc'); } }} onblur={() => commitRecipient('bcc')} /> + updateRecipientDraft('bcc', event.currentTarget.value)} onpaste={(event) => pasteRecipients('bcc', event)} onkeydown={(event) => { if (isRecipientCommitKey(event)) { event.preventDefault(); commitRecipient('bcc'); } }} onblur={() => commitRecipient('bcc')} /> {#if fieldError('bcc')}

{fieldError('bcc')}

{/if} @@ -784,7 +843,7 @@ ondragover={(event) => event.preventDefault()} ondragleave={() => (dragActive = false)} ondrop={(event) => { event.preventDefault(); dragActive = false; void addFiles([...event.dataTransfer?.files ?? []]); }} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') fileInput?.click(); }} + onkeydown={(event) => { if (shouldHandleRecipientKey(event) && (event.key === 'Enter' || event.key === ' ')) { event.preventDefault(); fileInput?.click(); } }} > @@ -809,9 +868,9 @@ {formatAttachmentSize(attachment.size)} {#if attachment.state && attachment.state !== 'ready'}{attachment.state === 'failed' ? t('compose.uploadFailed') : t('compose.uploadIncomplete')}{/if}
- {#if attachment.id && attachment.state === 'failed'} choosePersistedRetry(attachment.id!)}>{/if} - {#if attachment.id && (!attachment.state || attachment.state === 'ready')}{/if} - {#if attachment.id} void removeAttachment(attachment.id!)}>{/if} + {#if attachment.id && attachment.state === 'failed'} choosePersistedRetry(attachment.id!)}>{/if} + {#if attachment.id && (!attachment.state || attachment.state === 'ready')}{/if} + {#if attachment.id} void removeAttachment(attachment.id!)}>{/if}
{/each} @@ -821,7 +880,7 @@
    {#each attachmentTasks as task (task.id)}
  • -
    {task.file.name}{task.state === 'failed' ? t('compose.failed') : `${task.progress}%`}{#if task.state === 'failed'}{/if}
    +
    {task.file.name}{task.state === 'failed' ? t('compose.failed') : `${task.progress}%`}{#if task.state === 'failed'}{/if}
    {#if task.state === 'failed'}{:else}{task.progress}%{/if}
  • {/each} @@ -839,9 +898,9 @@ {t('compose.conflictTitle')} {t('compose.conflictDescription', { local: formatConflictDate(localEditedAt, t('time.justNow')), server: formatConflictDate(draftConflict.sentAt, t('compose.unknown')) })}
    - - - + + +
    {/if} @@ -860,7 +919,7 @@ -
    +
    {autosaveMessage} @@ -873,9 +932,9 @@ {readyAttachmentCount ? t('compose.addedAttachmentCount', { count: readyAttachmentCount }) : ''}
    - - - + + + {/snippet} @@ -894,8 +953,8 @@ {#snippet footer()}
    - - + +
    {/snippet} diff --git a/src/lib/components/mail/ComposeWindow.svelte b/src/lib/components/mail/ComposeWindow.svelte index 37ba18b..e1bcf81 100644 --- a/src/lib/components/mail/ComposeWindow.svelte +++ b/src/lib/components/mail/ComposeWindow.svelte @@ -16,6 +16,7 @@ mobileStatusTone = 'text-[var(--fm-text-muted)]', children, footer, + closeDisabled = false, onClose }: { id: string; @@ -25,6 +26,7 @@ mobileStatusTone?: string; children?: Snippet; footer?: Snippet; + closeDisabled?: boolean; onClose: () => void; } = $props(); @@ -156,7 +158,7 @@ if (event.shiftKey && document.activeElement === first && last) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last && first) { event.preventDefault(); first.focus(); } } - if (event.key === 'Escape' && !event.defaultPrevented) { + if (event.key === 'Escape' && !event.defaultPrevented && !closeDisabled) { event.stopPropagation(); onClose(); } @@ -201,7 +203,7 @@ >
    - +
    {#if !minimized} diff --git a/src/lib/components/mail/FolderHeader.svelte b/src/lib/components/mail/FolderHeader.svelte index ce3db44..545df3d 100644 --- a/src/lib/components/mail/FolderHeader.svelte +++ b/src/lib/components/mail/FolderHeader.svelte @@ -1,6 +1,6 @@ -
    +

    {heading}

    @@ -97,6 +101,10 @@ {translateCount(i18n.locale, 'mail.unreadCount', unreadCount)} {/if}
    +
    + onToggleReadingLayout?.()}> + {#if readingLayout === 'list'} +
    {#if activeSection !== 'profile'} @@ -137,3 +146,14 @@ {/if}
    + + diff --git a/src/lib/components/mail/InboxCategoryTabs.svelte b/src/lib/components/mail/InboxCategoryTabs.svelte new file mode 100644 index 0000000..f662582 --- /dev/null +++ b/src/lib/components/mail/InboxCategoryTabs.svelte @@ -0,0 +1,45 @@ + + +
    + {#each categories as item, index (item.id)} + + {/each} +
    + + diff --git a/src/lib/components/mail/MessageDetail.svelte b/src/lib/components/mail/MessageDetail.svelte index 92b8195..9c965d4 100644 --- a/src/lib/components/mail/MessageDetail.svelte +++ b/src/lib/components/mail/MessageDetail.svelte @@ -31,6 +31,7 @@ onToggleStar, onManageLabels, onToggleRead, + onArchive, onRemove, onRestore, onPermanentDelete, @@ -73,6 +74,7 @@ onToggleStar?: (message: MailMessage) => void | Promise; onManageLabels?: (message: MailMessage) => void; onToggleRead?: (message: MailMessage) => void | Promise; + onArchive?: (message: MailMessage) => void | Promise; onRemove?: (message: MailMessage) => void | Promise; onRestore?: (message: MailMessage) => void | Promise; onPermanentDelete?: (message: MailMessage) => void | Promise; @@ -136,6 +138,7 @@ {onToggleStar} {onManageLabels} {onToggleRead} + {onArchive} {onRemove} {onRestore} {onPermanentDelete} diff --git a/src/lib/components/mail/MessageHeader.svelte b/src/lib/components/mail/MessageHeader.svelte index 4d2c4bf..e15c8db 100644 --- a/src/lib/components/mail/MessageHeader.svelte +++ b/src/lib/components/mail/MessageHeader.svelte @@ -1,6 +1,7 @@ -
    +
    {#if loading}
    {#each Array(7) as _, index (index)} @@ -164,6 +176,7 @@ {#each visibleItems as item (itemKey(item))} {#if item.kind === 'thread'} {:else} import { + Archive, + Inbox, + Mail, + MailOpen, + Trash2, AlertCircle, Ban, CheckCircle2, @@ -17,6 +22,11 @@ type AppSection = MailboxSection | 'trash' | 'profile'; let { + fullWidth = false, + pending = false, + onArchive, + onToggleRead, + onRemove, activeSection, message = null, thread = null, @@ -27,6 +37,11 @@ selectedForBulk = false, onToggleSelect }: { + fullWidth?: boolean; + pending?: boolean; + onArchive?: (message: MailMessage) => void | Promise; + onToggleRead?: (message: MailMessage) => void | Promise; + onRemove?: (message: MailMessage) => void | Promise; activeSection: AppSection; message?: MailMessage | null; thread?: MailThread | null; @@ -149,6 +164,8 @@
    {#if selected}{/if} @@ -172,24 +189,26 @@ aria-label={accessibleLabel} onclick={handleSelect} > -
    {:else} @@ -242,6 +281,29 @@ {/if}