Compare commits

...
37 Commits
Author SHA1 Message Date
Linus Rath 705b942800 Merge dev into main - version 1.4.5 2026-03-20 18:10:08 +01:00
Linus Rath d68b81e6b8 chore: bump version to 1.4.5 2026-03-20 18:10:00 +01:00
Linus Rath 616e4d018d fix: expand recurring events in CalendarEvent/query (closes #65)
Add expandRecurrences: true to CalendarEvent/query when a date range
filter is provided, so the JMAP server returns individual occurrences
of recurring events instead of only the master event.
2026-03-20 17:53:30 +01:00
Linus Rath 68e141b787 feat: add mobile visibility toggle for sidebar apps and update related components 2026-03-20 17:44:26 +01:00
Linus Rath 1e6f5e2c8c fix: correct JSX syntax in CalendarToolbar component 2026-03-20 17:25:01 +01:00
Linus Rath 9495b34430 feat: add prev/next navigation buttons and date label to desktop calendar toolbar
Closes #59
2026-03-20 17:23:22 +01:00
Linus Rath 65fc489b9c feat: add pending event preview functionality to calendar views and event modal 2026-03-20 17:21:44 +01:00
Linus Rath bd686c092c fix: validate event start field when fetching calendar events 2026-03-20 17:11:36 +01:00
Linus Rath 6cff98ddb8 feat: implement pagination for fetching contacts and add maxObjectsInGet capability 2026-03-20 16:47:27 +01:00
Linus Rath dcc35335f5 feat: add setting to show event start time in month view 2026-03-20 16:42:07 +01:00
Linus Rath 8a54ae2456 feat: add NotFound component to handle 404 errors and redirect unauthenticated users 2026-03-20 16:31:57 +01:00
Linus Rath e26654a005 fix: enhance account switching logic and clear stores on account change 2026-03-20 16:29:32 +01:00
Linus Rath c1c06c68bb fix: improve draft handling in email composer and enhance session cookie verification logic 2026-03-20 15:45:25 +01:00
Linus Rath 74cf642182 Merge branch 'dev' 2026-03-20 00:16:41 +01:00
Linus Rath c5b1731a63 feat: add attachment position setting in email settings
- Introduced a new setting for attachment position in email settings, allowing users to choose between displaying attachments beside the sender or below the header.
- Updated the settings store to include the new attachment position type and default value.
- Added translations for the new setting in multiple languages (de, en, es, fr, it, ja, nl, pt).
2026-03-19 21:14:18 +01:00
Linus Rath 40cf164df3 fix: update calendar agenda view to auto-scroll to today's events and ensure today's date is included in the groups 2026-03-19 19:25:34 +01:00
Linus Rath ff56245db8 fix: improve account restoration logic and handle stale accounts in auth store 2026-03-19 19:21:08 +01:00
Linus Rath 9b4de4d152 fix: remove claude directory from .dockerignore and .gitignore 2026-03-19 19:06:31 +01:00
Linus Rath 0c9e60db8b fix: update flatted to 3.4.2 2026-03-19 19:01:40 +01:00
Linus Rath def8ee89fa Merge branch 'dev' 2026-03-19 18:57:57 +01:00
Linus Rath e7e07a38d7 fix: use native ARM runners instead of QEMU for Docker builds 2026-03-19 18:57:17 +01:00
Linus Rath a009e5ae32 fix: enhance health check functionality with detailed memory diagnostics and stable liveness probe 2026-03-19 18:50:59 +01:00
Linus Rath b141240fa3 Merge dev into main - version 1.4.4 2026-03-19 18:18:23 +01:00
Linus Rath 44896dee3e chore: bump version to 1.4.4 2026-03-19 18:12:16 +01:00
Linus Rath a5c5fa6669 fix: improve mailbox role management by ensuring roles are cleared from all mailboxes when reassigning 2026-03-19 18:00:09 +01:00
Linus Rath 95af61c4be fix: enhance account management by updating existing accounts and improving session handling 2026-03-19 17:47:18 +01:00
Linus Rath 34e495dde3 Fix email signature rendering 2026-03-19 17:20:39 +01:00
Linus Rath 0b721661e9 Fix logout redirects and unauthenticated home rendering 2026-03-19 17:01:27 +01:00
Linus Rath 9fa851a674 feat: implement CalDAV discovery API and enhance calendar ID handling 2026-03-19 16:56:00 +01:00
Linus Rath 41f91244d9 Fix duplicate calendar edits and prevent double-save submissions 2026-03-19 14:40:16 +01:00
Linus Rath 77514bd054 fix: RFC 9553 compliance for contacts (birthday, addresses) 2026-03-19 13:33:53 +01:00
Linus RathandGitHub 4501b3894b Merge pull request #51 from bulwarkmail/dev
v1.4.3 — Multi-Account Support, Contact Improvements, and Settings Encryption
2026-03-19 10:19:21 +01:00
Linus Rath 2edf2fab89 chore: bump version to 1.4.3 2026-03-19 10:16:47 +01:00
Linus Rath d493bb17dc feat: implement account switcher component and state management
- Add AccountSwitcher component for managing user accounts with UI for switching, adding, and logging out.
- Create account state manager to handle snapshots of account-specific states for efficient switching.
- Introduce utility functions for account management, including ID generation and avatar color assignment.
- Implement Zustand store for account management, supporting addition, removal, and state retrieval of accounts.
2026-03-19 10:08:57 +01:00
Linus Rath 234129397d feat: improve error logging and enhance settings sync functionality 2026-03-19 08:54:33 +01:00
Linus Rath 9b3a47f9be feat: enhance contact management with import functionality and keyword filtering 2026-03-19 08:38:59 +01:00
Linus Rath 0fcc932e66 fix: adjust popover alignment to the right 2026-03-19 07:44:11 +01:00
76 changed files with 4154 additions and 751 deletions
-2
View File
@@ -5,9 +5,7 @@ node_modules
.env*
!.env.example
!.env.dev.example
.claude/
scripts/
TODO.md
CLAUDE.md
*.md
!README.md
+79 -17
View File
@@ -20,9 +20,20 @@ on:
tags: ["v*.*.*"]
workflow_dispatch:
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
build:
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
runner: ubuntu-latest
- platform: linux/arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
@@ -31,9 +42,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -48,21 +56,75 @@ jobs:
id: meta
uses: docker/metadata-action@v5
with:
images: |
ghcr.io/${{ github.repository }}
images: ${{ env.IMAGE_NAME }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v6
with:
context: .
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha,scope=${{ matrix.platform }}
cache-to: type=gha,mode=max,scope=${{ matrix.platform }}
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
merge:
runs-on: ubuntu-latest
needs: build
permissions:
contents: read
packages: write
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Create manifest list and push
working-directory: /tmp/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}
-3
View File
@@ -42,9 +42,6 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
# claude code
.claude/
# settings sync data
/data/
+59
View File
@@ -1,5 +1,64 @@
# Changelog
## 1.4.5 (2026-03-20)
### Features
- **Calendar**: Add prev/next navigation buttons and date label to desktop calendar toolbar
- **Calendar**: Add pending event preview functionality to calendar views and event modal
- **Calendar**: Add setting to show event start time in month view
- **Contacts**: Implement pagination for fetching contacts with maxObjectsInGet capability
- **Email**: Add attachment position setting in email settings
- **Layout**: Add mobile visibility toggle for sidebar apps
- **Error**: Add NotFound component to handle 404 errors and redirect unauthenticated users
### Fixes
- **Auth**: Enhance account switching logic and clear stores on account change
- **Auth**: Improve account restoration logic and handle stale accounts
- **Auth**: Improve draft handling in email composer and enhance session cookie verification
- **Calendar**: Expand recurring events in CalendarEvent/query so individual occurrences are returned (#65)
- **Calendar**: Validate event start field when fetching calendar events
- **Calendar**: Auto-scroll agenda view to today's events and include today's date in groups
- **Calendar**: Correct JSX syntax in CalendarToolbar component
- **Dependencies**: Update flatted to 3.4.2
- **DevOps**: Use native ARM runners instead of QEMU for Docker builds
- **DevOps**: Enhance health check with detailed memory diagnostics and stable liveness probe
## 1.4.4 (2026-03-19)
### Features
- **Calendar**: Implement CalDAV discovery API with automatic calendar home resolution for multi-account setups
- **Calendar**: Enhance calendar management settings with mailbox role reassignment controls
- **Email**: Add signature rendering utilities with HTML-to-text conversion and sanitization
### Fixes
- **Auth**: Fix account session handling to update existing accounts instead of duplicating entries
- **Auth**: Fix logout redirects and unauthenticated home page rendering
- **Calendar**: Fix duplicate calendar edits and prevent double-save submissions in event modal
- **Calendar**: Remove stale calendar ID references in favor of CalDAV-discovered IDs
- **Contacts**: Improve RFC 9553 compliance for contact birthdays and address formatting
- **Email**: Fix email signature rendering for identity signatures
- **Folders**: Improve mailbox role management by clearing roles from all mailboxes before reassigning
## 1.4.3 (2026-03-19)
### Features
- **Auth**: Implement multi-account support with up to 5 simultaneous accounts and instant switching
- **Auth**: Add account switcher component with connection status, default account selection, and per-account logout
- **Auth**: Support multi-account OAuth and basic auth with per-account session persistence
- **Contacts**: Enhance contacts sidebar with collapsible sections, bulk operations, and address book grouping
- **Contacts**: Add contact import functionality and keyword filtering
- **Settings**: Add per-account encrypted settings storage with server-side sync support
### Fixes
- **UI**: Adjust popover alignment in sub-address helper component
- **Settings**: Improve error logging in settings sync functionality
## 1.4.2 (2026-03-19)
### Features
+47 -47
View File
@@ -3,7 +3,7 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="public/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg" />
<source media="(prefers-color-scheme: light)" srcset="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" />
<img src="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="480" />
<img src="public/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg" alt="Bulwark Webmail" width="280" />
</picture>
# Bulwark Webmail
@@ -12,7 +12,7 @@ A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.ar
Built with Next.js and the JMAP protocol.
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.4.2-green.svg)](CHANGELOG.md)
[![Version](https://img.shields.io/badge/version-1.4.3-green.svg)](CHANGELOG.md)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue)](https://ghcr.io/bulwarkmail/webmail)
</div>
@@ -25,16 +25,16 @@ Built with Next.js and the JMAP protocol.
<tr>
<td width="50%">
<img src="screenshots/inbox.png" width="100%" alt="Inbox - three-pane layout with sidebar, email list, and viewer (dark mode)">
<img src="screenshots/inbox.png" width="100%" alt="Inbox three-pane layout with sidebar, email list, and viewer (dark mode)">
**Mail** - Three-pane layout with sidebar, email list, and viewer
**Mail** Three-pane layout with sidebar, email list, and viewer
</td>
<td width="50%">
<img src="screenshots/calendar.png" width="100%" alt="Calendar">
**Calendar** - Month, week, day, and agenda views with event management
**Calendar** Month, week, day, and agenda views with event management
</td>
</tr>
@@ -43,14 +43,14 @@ Built with Next.js and the JMAP protocol.
<img src="screenshots/contacts.png" width="100%" alt="Contacts">
**Contacts** - Contact management with groups and vCard support
**Contacts** Contact management with groups and vCard support
</td>
<td width="50%">
<img src="screenshots/files.png" width="100%" alt="File browser">
**Files** - Cloud file browser with upload, preview, and folder navigation
**Files** Cloud file browser with upload, preview, and folder navigation
</td>
</tr>
@@ -62,16 +62,16 @@ Built with Next.js and the JMAP protocol.
<tr>
<td width="50%">
<img src="screenshots/inbox%20whitemode.png" width="100%" alt="Inbox - light mode">
<img src="screenshots/inbox%20whitemode.png" width="100%" alt="Inbox light mode">
**Light mode** - Full theme support with intelligent color transformation
**Light mode** Full theme support with intelligent color transformation
</td>
<td width="50%">
<img src="screenshots/settings.png" width="100%" alt="Settings">
**Settings** - Appearance, identities, filters, templates, and more
**Settings** Appearance, identities, filters, templates, and more
</td>
</tr>
@@ -80,7 +80,7 @@ Built with Next.js and the JMAP protocol.
<img src="screenshots/login.png" width="100%" alt="Login page">
**Login** - Configurable branding with OAuth2/OIDC and 2FA support
**Login** Configurable branding with OAuth2/OIDC and 2FA support
</td>
<td width="50%">
@@ -94,21 +94,21 @@ Built with Next.js and the JMAP protocol.
### Mail
- **Read, compose, reply, reply-all, forward** with rich HTML rendering
- **Threading** - Gmail-style inline expansion with thread navigation
- **Threading** Gmail-style inline expansion with thread navigation
- **Draft auto-save** with discard confirmation
- **Attachments** - upload, download, and inline preview
- **Search** - full-text with JMAP filter panel, search chips, cross-mailbox queries, wildcard support, and OR conditions
- **Batch operations** - multi-select with checkboxes, archive, delete, move, tag
- **Archive modes** - archive directly or organize archived mail by year or month
- **Attachments** upload, download, and inline preview
- **Search** full-text with JMAP filter panel, search chips, cross-mailbox queries, wildcard support, and OR conditions
- **Batch operations** multi-select with checkboxes, archive, delete, move, tag
- **Archive modes** archive directly or organize archived mail by year or month
- **Print** emails directly from the viewer
- **Color tags/labels** and star/unstar
- **Virtual scrolling** for large mailboxes
- **Quick reply** from the viewer
- **Sender avatars** - favicon-based with negative caching for performance
- **Sender avatars** favicon-based with negative caching for performance
- **Recipient popover** for quick contact interaction
- **Folder management** - create, rename, delete folders with icon picker and subfolder support
- **Tag counts** - unread and total counts displayed in sidebar
- **TNEF support** - extract Outlook `winmail.dat` message bodies and attachments automatically
- **TNEF support** — extract Outlook `winmail.dat` message bodies and attachments automatically
- **Folder management** — create, rename, delete folders with icon picker and subfolder support
- **Tag counts** — unread and total counts displayed in sidebar
### Calendar
@@ -116,8 +116,8 @@ Built with Next.js and the JMAP protocol.
- **Event hover preview** popover with details
- **Drag-and-drop rescheduling**, click-drag creation, edge-resize (15-min snap)
- **Recurring events** with edit/delete scope (this / this and following / all)
- **Participant scheduling** - iTIP invitations, organizer/attendee UI, RSVP
- **Inline calendar invitations** in email viewer - auto-detect `.ics`, RSVP, import
- **Participant scheduling** iTIP invitations, organizer/attendee UI, RSVP
- **Inline calendar invitations** in email viewer auto-detect `.ics`, RSVP, import
- **iCalendar import** with preview and bulk create
- **Notifications** with configurable sound and alert persistence
- **Real-time sync** via JMAP push
@@ -128,15 +128,15 @@ Built with Next.js and the JMAP protocol.
- **Contact groups** with group expansion and member management
- **vCard import/export** (RFC 6350) with duplicate detection
- **Autocomplete** in composer (To/Cc/Bcc)
- **Bulk operations** - multi-select, delete, group add, export
- **Bulk operations** multi-select, delete, group add, export
### Filters & Automation
- **Server-side email filters** via JMAP Sieve Scripts (RFC 9661)
- **Visual rule builder** - conditions (From, To, Subject, Size, Body…) and actions (Move, Forward, Star, Discard…)
- **Visual rule builder** conditions (From, To, Subject, Size, Body…) and actions (Move, Forward, Star, Discard…)
- **Raw Sieve editor** with syntax validation
- **Vacation responder** with date range scheduling and sidebar indicator
- **Email templates** - reusable, categorized, with placeholder auto-fill (`{{recipientName}}`, `{{date}}`, etc.)
- **Email templates** reusable, categorized, with placeholder auto-fill (`{{recipientName}}`, `{{date}}`, etc.)
### Files
@@ -144,39 +144,39 @@ Built with Next.js and the JMAP protocol.
- **Upload and download** files with progress tracking and folder upload support
- **Folder navigation** with breadcrumb path and tree sidebar
- **Grid and list views** with sorting by name, size, or date
- **Clipboard operations** - cut, copy, paste, duplicate files
- **Clipboard operations** cut, copy, paste, duplicate files
- **File preview** for images, text, audio, video, and more
- **Favorites and recent files** for quick access
- **Bulk operations** - multi-select, delete, move, download
- **Bulk operations** multi-select, delete, move, download
### Security & Privacy
- **External content blocked** by default - trusted senders list for auto-load
- **External content blocked** by default trusted senders list for auto-load
- **HTML sanitization** via DOMPurify with XSS prevention
- **S/MIME** - manage certificates, sign outgoing mail, encrypt to recipients, decrypt messages, and verify signatures
- **S/MIME** manage certificates, sign outgoing mail, encrypt to recipients, decrypt messages, and verify signatures
- **SPF/DKIM/DMARC** status indicators
- **OAuth2/OIDC with PKCE** for SSO (Keycloak, Authentik, or built-in), with OAuth-only mode
- **TOTP two-factor authentication**
- **Account security panel** - manage passwords and 2FA via Stalwart admin API
- **"Remember me"** - AES-256-GCM encrypted httpOnly cookie (opt-in)
- **Security headers** - CSP with per-request nonce, X-Frame-Options, Referrer-Policy
- **Account security panel** manage passwords and 2FA via Stalwart admin API
- **"Remember me"** AES-256-GCM encrypted httpOnly cookie (opt-in)
- **Security headers** CSP with per-request nonce, X-Frame-Options, Referrer-Policy
- **Newsletter unsubscribe** (RFC 2369)
### Interface
- **Three-pane layout** - sidebar, email list, viewer with resizable columns
- **Three-pane layout** sidebar, email list, viewer with resizable columns
- **Dark and light themes** with intelligent email color transformation
- **Responsive** - desktop sidebar + mobile bottom tab bar with tablet support
- **Keyboard shortcuts** - full navigation without a mouse
- **Always-light email rendering** option for problematic HTML messages in dark theme
- **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support
- **Keyboard shortcuts** — full navigation without a mouse
- **Drag-and-drop** email organization between mailboxes and tag assignment
- **Right-click context menus**, toast notifications with undo, form validation with shake feedback
- **Always-light email rendering** option for problematic HTML messages in dark theme
- **Customizable toolbar** position, custom favicon, sidebar/login logos, and login page branding
- **Sidebar apps** - pin custom tools to the navigation rail and open them inline or in a new tab
- **Settings sync** - preferences synchronized with the server (encrypted)
- **Sidebar apps** pin custom tools to the navigation rail and open them inline or in a new tab
- **Settings sync** preferences synchronized with the server (encrypted)
- **Storage quota** display
- **Shared folders** - multi-account access
- **Accessibility** - WCAG AA contrast, reduced-motion support, focus trap, screen reader live regions
- **Shared folders** multi-account access
- **Accessibility** WCAG AA contrast, reduced-motion support, focus trap, screen reader live regions
### Internationalization
@@ -187,13 +187,13 @@ Automatic browser detection with persistent preference.
### Identity Management
- **Multiple sender identities** with per-identity signatures
- **Sub-addressing** - `user+tag@domain.com` with contextual tag suggestions
- **Identity refresh** - keep the identity manager aligned with server-side changes after edits
- **Identity refresh** — keep the identity manager aligned with server-side changes after edits
- **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions
- **Identity badges** in viewer and email list
### Operations
- **Automatic update check** - server logs when a newer release is available
- **Automatic update check** server logs when a newer release is available
---
@@ -211,7 +211,7 @@ Or with Docker Compose:
```bash
cp .env.example .env.local
# Edit .env.local - set JMAP_SERVER_URL
# Edit .env.local set JMAP_SERVER_URL
docker compose up -d
```
@@ -222,7 +222,7 @@ git clone https://github.com/bulwarkmail/webmail.git
cd webmail
npm install
cp .env.example .env.local
# Edit .env.local - set JMAP_SERVER_URL
# Edit .env.local set JMAP_SERVER_URL
npm run build && npm start
```
@@ -246,7 +246,7 @@ JMAP_SERVER_URL=https://mail.example.com
APP_NAME=My Webmail
```
All variables are **runtime** - Docker deployments can be configured without rebuilding.
All variables are **runtime** Docker deployments can be configured without rebuilding.
<details>
<summary>Server Listen Address</summary>
@@ -313,7 +313,7 @@ Credentials encrypted with AES-256-GCM, stored in an httpOnly cookie (30-day exp
## Why Stalwart?
[Stalwart](https://github.com/stalwartlabs/mail-server) is a mail server written in Rust with **native JMAP support** - not IMAP/SMTP with JMAP bolted on. It handles JMAP, IMAP, SMTP, and ManageSieve in a single binary. Self-hosted, no third-party dependencies.
[Stalwart](https://github.com/stalwartlabs/mail-server) is a mail server written in Rust with **native JMAP support** not IMAP/SMTP with JMAP bolted on. It handles JMAP, IMAP, SMTP, and ManageSieve in a single binary. Self-hosted, no third-party dependencies.
## Contributing
+1 -1
View File
@@ -1 +1 @@
1.4.2
1.4.5
+1
View File
@@ -53,6 +53,7 @@ function OAuthCallbackInner() {
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("oauth_code_verifier");
sessionStorage.removeItem("oauth_server_url");
sessionStorage.removeItem("oauth_add_account_mode");
let redirectTo = `/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
+30 -17
View File
@@ -7,7 +7,7 @@ import { Plus } from "lucide-react";
import {
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
addMonths, subMonths, addWeeks, subWeeks, addDays, subDays,
format, parseISO,
startOfDay, format, parseISO,
} from "date-fns";
import { useCalendarStore } from "@/stores/calendar-store";
import { isCalendarViewMode } from "@/stores/calendar-store";
@@ -25,7 +25,7 @@ import { CalendarDayView } from "@/components/calendar/calendar-day-view";
import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view";
import { MiniCalendar } from "@/components/calendar/mini-calendar";
import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel";
import { EventModal } from "@/components/calendar/event-modal";
import { EventModal, type PendingEventPreview } from "@/components/calendar/event-modal";
import { EventDetailPopover } from "@/components/calendar/event-detail-popover";
import { ICalImportModal } from "@/components/calendar/ical-import-modal";
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
@@ -82,6 +82,7 @@ export default function CalendarPage() {
const [pendingScopeAction, setPendingScopeAction] = useState<PendingScopeAction | null>(null);
const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null);
const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null);
const [pendingPreview, setPendingPreview] = useState<PendingEventPreview | null>(null);
const hasFetched = useRef(false);
// Sidebar resize state
@@ -156,11 +157,15 @@ export default function CalendarPage() {
start: format(d, "yyyy-MM-dd'T'00:00:00"),
end: format(d, "yyyy-MM-dd'T'23:59:59"),
};
case "agenda":
case "agenda": {
// Agenda always starts from today at the earliest
const today = startOfDay(new Date());
const agendaStart = d >= today ? d : today;
return {
start: format(d, "yyyy-MM-dd'T'00:00:00"),
end: format(addDays(d, 30), "yyyy-MM-dd'T'23:59:59"),
start: format(agendaStart, "yyyy-MM-dd'T'00:00:00"),
end: format(addDays(agendaStart, 30), "yyyy-MM-dd'T'23:59:59"),
};
}
}
}, [selectedDate, normalizedViewMode, firstDayOfWeek]);
@@ -264,12 +269,13 @@ export default function CalendarPage() {
}, [closeDetail, openEditModal]);
const handleHoverEvent = useCallback((event: CalendarEvent, anchorRect: DOMRect) => {
if (isMobile) return;
if (hoverTimerRef.current) { clearTimeout(hoverTimerRef.current); hoverTimerRef.current = null; }
// Don't show hover popover if the sidebar is already open for this event
if (showEventModal && editEvent?.id === event.id) return;
setDetailEvent(event);
setDetailAnchorRect(anchorRect);
}, [showEventModal, editEvent]);
}, [isMobile, showEventModal, editEvent]);
const handleHoverLeave = useCallback(() => {
hoverTimerRef.current = setTimeout(() => {
@@ -611,6 +617,7 @@ export default function CalendarPage() {
const visibleEvents = useMemo(() =>
events.filter((e) => {
if (!e.start || !e.calendarIds) return false;
const calIds = Object.keys(e.calendarIds);
return calIds.some((id) => selectedCalendarIds.includes(id));
}),
@@ -643,6 +650,7 @@ export default function CalendarPage() {
onCreateAtTime={openCreateModal}
firstDayOfWeek={firstDayOfWeek}
isMobile={isMobile}
pendingPreview={pendingPreview}
/>
);
case "week":
@@ -659,6 +667,7 @@ export default function CalendarPage() {
firstDayOfWeek={firstDayOfWeek}
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
/>
);
case "day":
@@ -673,6 +682,7 @@ export default function CalendarPage() {
onCreateAtTime={openCreateModal}
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
/>
);
case "agenda":
@@ -703,7 +713,7 @@ export default function CalendarPage() {
};
return (
<div className="flex h-dvh bg-background overflow-hidden">
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
{/* Left Navigation Rail */}
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -711,7 +721,7 @@ export default function CalendarPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
@@ -766,7 +776,7 @@ export default function CalendarPage() {
)}
{!inlineApp && (
<div className="flex flex-col flex-1 min-w-0">
<div className="flex flex-col flex-1 min-w-0 min-h-0">
<CalendarToolbar
selectedDate={selectedDate}
viewMode={normalizedViewMode}
@@ -803,7 +813,8 @@ export default function CalendarPage() {
onDelete={handleDeleteEvent}
onDuplicate={handleDuplicateEvent}
onRsvp={handleRsvp}
onClose={() => { setShowEventModal(false); setEditEvent(null); }}
onClose={() => { setShowEventModal(false); setEditEvent(null); setPendingPreview(null); }}
onPreviewChange={setPendingPreview}
currentUserEmails={currentUserEmails}
isMobile={false}
/>
@@ -826,13 +837,15 @@ export default function CalendarPage() {
{/* Mobile Bottom Navigation */}
{isMobile && (
<NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
<div className="shrink-0">
<NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
</div>
)}
{detailEvent && detailAnchorRect && (
+68 -16
View File
@@ -13,6 +13,7 @@ import { ContactForm } from "@/components/contacts/contact-form";
import { ContactGroupForm } from "@/components/contacts/contact-group-form";
import { ContactGroupDetail } from "@/components/contacts/contact-group-detail";
import { ContactsSidebar, type ContactCategory } from "@/components/contacts/contacts-sidebar";
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
import { exportContacts } from "@/components/contacts/contact-export";
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
import { useAuthStore } from "@/stores/auth-store";
@@ -73,10 +74,12 @@ export default function ContactsPage() {
bulkDeleteContacts,
bulkAddToGroup,
moveContactToAddressBook,
importContacts,
} = useContactStore();
const [view, setView] = useState<View>("list");
const [activeCategory, setActiveCategory] = useState<ContactCategory>("all");
const [showImportDialog, setShowImportDialog] = useState(false);
const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
const hasFetched = useRef(false);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
@@ -84,10 +87,10 @@ export default function ContactsPage() {
// Panel resize state - sidebar (categories)
const [sidebarWidth, setSidebarWidth] = useState(() => {
try { const v = localStorage.getItem("contacts-sidebar-width"); return v ? Number(v) : 180; } catch { return 180; }
try { const v = localStorage.getItem("contacts-sidebar-width"); return v ? Number(v) : 256; } catch { return 256; }
});
const [isSidebarResizing, setIsSidebarResizing] = useState(false);
const sidebarDragStartWidth = useRef(180);
const sidebarDragStartWidth = useRef(256);
// Panel resize state - contact list
const [listWidth, setListWidth] = useState(() => {
@@ -125,21 +128,17 @@ export default function ContactsPage() {
// Contacts to display based on active category
const displayedContacts = useMemo(() => {
if (activeCategory === "all") return individuals.filter(c => !c.isShared);
if (activeCategory === "all") return individuals;
if ("addressBookId" in activeCategory) {
const bookId = activeCategory.addressBookId;
return individuals.filter(c => {
if (!c.addressBookIds) return false;
// Check both namespaced (accountId:bookId) and raw bookId
if (c.addressBookIds[bookId]) return true;
// For shared contacts, match namespaced id
if (c.isShared && c.accountId) {
const namespacedId = `${c.accountId}:${Object.keys(c.addressBookIds).find(k => c.addressBookIds[k])}`;
return namespacedId === bookId;
}
return false;
return c.addressBookIds[bookId] === true;
});
}
if ("keyword" in activeCategory) {
return individuals.filter(c => c.keywords?.[activeCategory.keyword]);
}
// Show members of the selected group
return getGroupMembers(activeCategory.groupId);
}, [activeCategory, individuals, getGroupMembers]);
@@ -151,6 +150,9 @@ export default function ContactsPage() {
const book = addressBooks.find(b => b.id === activeCategory.addressBookId);
return book?.name || t("tabs.all");
}
if ("keyword" in activeCategory) {
return activeCategory.keyword;
}
const group = contacts.find(c => c.id === activeCategory.groupId);
return group ? getContactDisplayName(group) : t("tabs.all");
}, [activeCategory, contacts, addressBooks, t]);
@@ -160,6 +162,7 @@ export default function ContactsPage() {
clearSelection();
if (typeof category === "object" && "groupId" in category) {
setSelectedGroupId(category.groupId);
setView("group-detail");
} else {
setSelectedGroupId(null);
}
@@ -179,6 +182,13 @@ export default function ContactsPage() {
}
}, [client, moveContactToAddressBook, t]);
const handleImportContacts = useCallback(async (importedContacts: ContactCard[]) => {
return importContacts(
supportsSync && client ? client : null,
importedContacts
);
}, [supportsSync, client, importContacts]);
const handleSelectContact = (id: string) => {
setSelectedContact(id);
clearSelection();
@@ -273,6 +283,35 @@ export default function ContactsPage() {
setView("group-edit");
};
const handleEditGroupFromSidebar = useCallback((groupId: string) => {
setSelectedGroupId(groupId);
setActiveCategory({ groupId });
setView("group-edit");
}, []);
const handleDeleteGroupFromSidebar = useCallback(async (groupId: string) => {
const confirmed = await confirmDialog({
title: t("groups.delete_confirm_title"),
message: t("groups.delete_confirm"),
confirmText: t("form.delete"),
variant: "destructive",
});
if (!confirmed) return;
try {
await deleteGroup(supportsSync && client ? client : null, groupId);
toast.success(t("toast.deleted"));
if (selectedGroupId === groupId) {
setSelectedGroupId(null);
setActiveCategory("all");
setView("list");
}
} catch (error) {
console.error('Failed to delete group:', error);
toast.error(t("toast.error_delete"));
}
}, [confirmDialog, deleteGroup, supportsSync, client, selectedGroupId, t]);
const handleDeleteGroup = async () => {
if (!selectedGroup) return;
@@ -416,7 +455,6 @@ export default function ContactsPage() {
isMobile={isMobile}
onSelectMember={(id) => {
setSelectedContact(id);
setActiveCategory("all");
setView("detail");
}}
/>
@@ -506,7 +544,7 @@ export default function ContactsPage() {
};
return (
<div className="flex h-dvh bg-background overflow-hidden">
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
{/* Navigation Rail - desktop only */}
{!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -514,7 +552,7 @@ export default function ContactsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
@@ -548,17 +586,20 @@ export default function ContactsPage() {
onSelectCategory={handleSelectCategory}
onCreateGroup={handleCreateGroup}
onCreateContact={handleCreateNew}
onImport={() => setShowImportDialog(true)}
onEditGroup={handleEditGroupFromSidebar}
onDeleteGroup={handleDeleteGroupFromSidebar}
onDropContacts={handleDropContacts}
/>
</div>
<ResizeHandle
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }}
onResize={(delta) => setSidebarWidth(Math.max(140, Math.min(300, sidebarDragStartWidth.current + delta)))}
onResize={(delta) => setSidebarWidth(Math.max(180, Math.min(400, sidebarDragStartWidth.current + delta)))}
onResizeEnd={() => {
setIsSidebarResizing(false);
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth));
}}
onDoubleClick={() => { setSidebarWidth(180); localStorage.setItem("contacts-sidebar-width", "180"); }}
onDoubleClick={() => { setSidebarWidth(256); localStorage.setItem("contacts-sidebar-width", "256"); }}
/>
</>
)}
@@ -642,6 +683,17 @@ export default function ContactsPage() {
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<ConfirmDialog {...confirmDialogProps} />
{showImportDialog && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-background rounded-lg border border-border shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden">
<ContactImportDialog
existingContacts={contacts}
onImport={handleImportContacts}
onClose={() => setShowImportDialog(false)}
/>
</div>
</div>
)}
</div>
);
}
+1 -1
View File
@@ -357,7 +357,7 @@ export default function FilesPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+25 -15
View File
@@ -2,7 +2,7 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { useRouter } from "@/i18n/navigation";
import { useParams } from "next/navigation";
import { useParams, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -16,7 +16,7 @@ import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
const APP_VERSION = "1.4.2";
const APP_VERSION = "1.4.3";
const THEME_OPTIONS = [
{ value: "light" as const, icon: Sun, label: "Light" },
@@ -28,6 +28,8 @@ export default function LoginPage() {
const router = useRouter();
const t = useTranslations("login");
const params = useParams();
const searchParams = useSearchParams();
const isAddAccountMode = searchParams.get("mode") === "add-account";
const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore();
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError } = useConfig();
@@ -102,7 +104,7 @@ export default function LoginPage() {
}, [serverUrl]);
useEffect(() => {
if (isAuthenticated) {
if (isAuthenticated && !isAddAccountMode) {
let redirectTo = '/';
try {
const saved = sessionStorage.getItem('redirect_after_login');
@@ -113,7 +115,7 @@ export default function LoginPage() {
} catch { /* ignore */ }
router.push(redirectTo);
}
}, [isAuthenticated, router]);
}, [isAuthenticated, router, isAddAccountMode]);
useEffect(() => {
clearError();
@@ -303,6 +305,9 @@ export default function LoginPage() {
sessionStorage.setItem("oauth_code_verifier", verifier);
sessionStorage.setItem("oauth_state", state);
sessionStorage.setItem("oauth_server_url", serverUrl!);
if (isAddAccountMode) {
sessionStorage.setItem("oauth_add_account_mode", "true");
}
const authUrl = new URL(oauthMetadata.authorization_endpoint);
authUrl.searchParams.set("response_type", "code");
@@ -329,15 +334,7 @@ export default function LoginPage() {
if (success) {
saveUsername(formData.username);
let redirectTo = '/';
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* ignore */ }
router.push(redirectTo);
router.push('/');
}
};
@@ -426,10 +423,10 @@ export default function LoginPage() {
/>
</div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight">
{appName}
{isAddAccountMode ? t("add_account_title") : appName}
</h1>
<p className="text-sm text-muted-foreground mt-1.5">
{t("title") !== appName ? t("title") : "Sign in to your account"}
{isAddAccountMode ? t("add_account_subtitle") : (t("title") !== appName ? t("title") : "Sign in to your account")}
</p>
</div>
@@ -737,6 +734,19 @@ export default function LoginPage() {
)}
</form>
)}
{isAddAccountMode && (
<div className="mt-4">
<Button
type="button"
variant="ghost"
className="w-full h-10 text-sm text-muted-foreground hover:text-foreground"
onClick={() => router.push('/')}
>
{t("cancel")}
</Button>
</div>
)}
</div>
</div>
+11 -7
View File
@@ -41,6 +41,7 @@ import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { Input } from "@/components/ui/input";
import { FilePreviewModal } from "@/components/files/file-preview-modal";
import { isFilePreviewable } from "@/lib/file-preview";
import { appendPlainTextSignature } from "@/lib/signature-utils";
import { Search, Filter, ChevronDown, X, Paperclip, Star, Mail, MailOpen, RotateCcw, PenSquare, PenLine, CheckSquare, Square } from "lucide-react";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { Button } from "@/components/ui/button";
@@ -769,7 +770,9 @@ export default function Home() {
const handleLogout = () => {
logout();
router.push('/login');
if (!useAuthStore.getState().isAuthenticated) {
router.push('/login');
}
};
const handleSearch = async (query: string) => {
@@ -813,13 +816,13 @@ export default function Home() {
};
}, []);
const handleDownloadAttachment = async (blobId: string, name: string, type?: string) => {
const handleDownloadAttachment = async (blobId: string, name: string, type?: string, forceDownload?: boolean) => {
if (!client) return;
try {
const { mailAttachmentAction } = useSettingsStore.getState();
if (mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) {
if (!forceDownload && mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) {
setPreviewAttachment({ blobId, name, type });
return;
}
@@ -860,10 +863,7 @@ export default function Home() {
const primaryIdentity = identities[0];
// Append signature from the primary identity
let finalBody = body;
if (primaryIdentity?.textSignature) {
finalBody = body + '\n\n-- \n' + primaryIdentity.textSignature;
}
const finalBody = appendPlainTextSignature(body, primaryIdentity);
// Send reply with just the body text
await sendEmail(
@@ -1020,6 +1020,10 @@ export default function Home() {
</button>
);
if (!isAuthenticated) {
return null;
}
return (
<DragDropProvider>
<div className="flex flex-col h-dvh bg-background overflow-hidden">
+2 -2
View File
@@ -286,7 +286,7 @@ export default function SettingsPage() {
{/* Logout */}
<div className="border-t border-border px-5 py-3">
<button
onClick={() => { logout(); router.push('/login'); }}
onClick={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
className="w-full flex items-center gap-3 py-2.5 text-sm text-destructive hover:bg-muted rounded-md px-2 transition-colors duration-150"
>
<LogOut className="w-4 h-4" />
@@ -317,7 +317,7 @@ export default function SettingsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+31 -8
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE, SESSION_COOKIE_MAX_AGE } from '@/lib/auth/session-cookie';
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
const COOKIE_OPTIONS = {
httpOnly: true,
@@ -12,20 +12,30 @@ const COOKIE_OPTIONS = {
maxAge: SESSION_COOKIE_MAX_AGE,
};
function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
if (raw === null) return 0;
const slot = parseInt(raw, 10);
if (isNaN(slot) || slot < 0 || slot > 4) return 0;
return slot;
}
export async function POST(request: NextRequest) {
try {
if (process.env.OAUTH_ENABLED === 'true' && process.env.OAUTH_ONLY === 'true') {
return NextResponse.json({ error: 'Basic authentication is disabled' }, { status: 403 });
}
const { serverUrl, username, password } = await request.json();
const { serverUrl, username, password, slot: bodySlot } = await request.json();
if (!serverUrl || !username || !password) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
const cookieName = sessionCookieName(slot);
const token = encryptSession(serverUrl, username, password);
const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE, token, COOKIE_OPTIONS);
cookieStore.set(cookieName, token, COOKIE_OPTIONS);
return NextResponse.json({ ok: true });
} catch (error) {
@@ -34,10 +44,12 @@ export async function POST(request: NextRequest) {
}
}
export async function GET() {
export async function GET(request: NextRequest) {
try {
const slot = getSlot(request);
const cookieName = sessionCookieName(slot);
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
const token = cookieStore.get(cookieName)?.value;
if (!token) {
return NextResponse.json({ error: 'No session' }, { status: 401 });
@@ -45,7 +57,7 @@ export async function GET() {
const credentials = decryptSession(token);
if (!credentials) {
cookieStore.delete(SESSION_COOKIE);
cookieStore.delete(cookieName);
return NextResponse.json({ error: 'Invalid session' }, { status: 401 });
}
@@ -58,10 +70,21 @@ export async function GET() {
}
}
export async function DELETE() {
export async function DELETE(request: NextRequest) {
try {
const cookieStore = await cookies();
cookieStore.delete(SESSION_COOKIE);
const all = request.nextUrl.searchParams.get('all') === 'true';
if (all) {
// Delete all session cookies (slots 0-4)
for (let i = 0; i <= 4; i++) {
cookieStore.delete(sessionCookieName(i));
}
} else {
const slot = getSlot(request);
cookieStore.delete(sessionCookieName(slot));
}
return NextResponse.json({ ok: true });
} catch (error) {
logger.error('Session clear error', { error: error instanceof Error ? error.message : 'Unknown error' });
+52 -10
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { REFRESH_TOKEN_COOKIE } from '@/lib/oauth/tokens';
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
@@ -14,6 +14,15 @@ const COOKIE_OPTIONS = {
maxAge: 30 * 24 * 60 * 60,
};
function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
if (raw === null) return 0;
const slot = parseInt(raw, 10);
if (isNaN(slot) || slot < 0 || slot > 4) return 0;
return slot;
}
function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
@@ -53,12 +62,13 @@ function buildOAuthParams(base: Record<string, string>): URLSearchParams {
export async function POST(request: NextRequest) {
try {
const { code, code_verifier, redirect_uri } = await request.json();
const { code, code_verifier, redirect_uri, slot: bodySlot } = await request.json();
if (!code || !code_verifier || !redirect_uri) {
return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });
}
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
@@ -93,8 +103,9 @@ export async function POST(request: NextRequest) {
});
if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies();
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
}
return response;
@@ -104,10 +115,12 @@ export async function POST(request: NextRequest) {
}
}
export async function PUT() {
export async function PUT(request: NextRequest) {
try {
const slot = getSlot(request);
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies();
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value;
const refreshToken = cookieStore.get(cookieName)?.value;
if (!refreshToken) {
return NextResponse.json({ error: 'No refresh token' }, { status: 401 });
@@ -129,7 +142,7 @@ export async function PUT() {
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
logger.error('Token refresh failed', { status: tokenResponse.status, error: errorText });
cookieStore.delete(REFRESH_TOKEN_COOKIE);
cookieStore.delete(cookieName);
return NextResponse.json({ error: 'Refresh failed' }, { status: 401 });
}
@@ -141,7 +154,7 @@ export async function PUT() {
}
if (tokens.refresh_token) {
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
}
return NextResponse.json({
@@ -154,10 +167,39 @@ export async function PUT() {
}
}
export async function DELETE() {
export async function DELETE(request: NextRequest) {
try {
const all = request.nextUrl.searchParams.get('all') === 'true';
if (all) {
// Revoke and delete all refresh token cookies (slots 0-4)
const cookieStore = await cookies();
for (let i = 0; i <= 4; i++) {
const name = refreshTokenCookieName(i);
const token = cookieStore.get(name)?.value;
if (token) {
// Best-effort revocation
try {
const metadata = await getMetadata().catch(() => null);
if (metadata?.revocation_endpoint) {
const params = buildOAuthParams({ token, token_type_hint: 'refresh_token' });
await fetch(metadata.revocation_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
}).catch(() => {});
}
} catch { /* best effort */ }
cookieStore.delete(name);
}
}
return NextResponse.json({ ok: true });
}
const slot = getSlot(request);
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies();
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value;
const refreshToken = cookieStore.get(cookieName)?.value;
const metadata = await getMetadata().catch((err) => {
logger.warn('Failed to discover OAuth metadata during logout', {
error: err instanceof Error ? err.message : 'Unknown error',
@@ -186,7 +228,7 @@ export async function DELETE() {
}
}
cookieStore.delete(REFRESH_TOKEN_COOKIE);
cookieStore.delete(cookieName);
}
let end_session_url: string | undefined;
+103
View File
@@ -0,0 +1,103 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
interface DiscoveryAccountRequest {
key: string;
candidates: string[];
}
interface DiscoveryResult {
url: string | null;
resolvedAccount: string | null;
}
function buildPublicUrl(serverUrl: string, path: string): string {
return new URL(path, serverUrl).toString();
}
async function probeCalendarHome(serverUrl: string, authHeader: string, accountName: string): Promise<string | null> {
const targetUrl = buildPublicUrl(serverUrl, `/dav/cal/${encodeURIComponent(accountName)}`);
const response = await fetch(targetUrl, {
method: 'PROPFIND',
headers: {
Authorization: authHeader,
Depth: '0',
'Content-Type': 'application/xml; charset=utf-8',
},
body: `<?xml version="1.0" encoding="utf-8"?>
<D:propfind xmlns:D="DAV:">
<D:prop>
<D:resourcetype/>
<D:displayname/>
</D:prop>
</D:propfind>`,
redirect: 'manual',
});
if (response.status === 207) {
return targetUrl;
}
if (response.status >= 300 && response.status < 400) {
const location = response.headers.get('Location');
if (location) {
return new URL(location, targetUrl).toString();
}
}
return null;
}
export async function POST(request: NextRequest) {
try {
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json().catch(() => ({}));
const accounts = Array.isArray(body.accounts) ? body.accounts as DiscoveryAccountRequest[] : [];
const wellKnownUrl = buildPublicUrl(creds.serverUrl, '/.well-known/caldav');
const discovered: Record<string, DiscoveryResult> = {};
for (const account of accounts) {
if (!account?.key) continue;
const candidates = Array.from(new Set(
(account.candidates || [])
.map((candidate) => candidate?.trim())
.filter((candidate): candidate is string => Boolean(candidate))
));
let url: string | null = null;
let resolvedAccount: string | null = null;
for (const candidate of candidates) {
try {
url = await probeCalendarHome(creds.serverUrl, creds.authHeader, candidate);
if (url) {
resolvedAccount = candidate;
break;
}
} catch (error) {
logger.warn('CalDAV discovery probe failed', {
accountKey: account.key,
candidate,
error: error instanceof Error ? error.message : 'Unknown',
});
}
}
discovered[account.key] = { url, resolvedAccount };
}
return NextResponse.json({
wellKnownUrl,
accounts: discovered,
});
} catch (error) {
logger.error('CalDAV discovery failed', { error: error instanceof Error ? error.message : 'Unknown' });
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+26 -35
View File
@@ -1,10 +1,21 @@
import v8 from 'node:v8';
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
import { logger } from '@/lib/logger';
// Health check thresholds
const MEMORY_WARNING_THRESHOLD = 0.85; // 85% heap usage
const MEMORY_CRITICAL_THRESHOLD = 0.95; // 95% heap usage
const MEMORY_WARNING_THRESHOLD = 0.85;
const MEMORY_CRITICAL_THRESHOLD = 0.95;
function getHeapUsagePercent(heapUsed: number, heapTotal: number): number {
const heapSizeLimit = v8.getHeapStatistics().heap_size_limit;
const denominator = heapSizeLimit > 0 ? heapSizeLimit : heapTotal;
if (denominator <= 0) {
return 0;
}
return (heapUsed / denominator) * 100;
}
interface HealthStatus {
status: 'healthy' | 'degraded' | 'unhealthy';
@@ -14,6 +25,7 @@ interface HealthStatus {
memory?: {
heapUsed: number;
heapTotal: number;
heapSizeLimit: number;
rss: number;
external: number;
heapUsagePercent: number;
@@ -27,14 +39,9 @@ interface HealthStatus {
/**
* Health check endpoint for container orchestration
*
* GET /api/health - Basic health check (returns 200 OK or 503 Service Unavailable)
* GET /api/health?detailed=true - Detailed diagnostics with memory stats
* HEAD /api/health - Lightweight health check (status code only)
*
* Health status based on Node.js heap usage:
* - Healthy (200): < 85% heap usage
* - Degraded (200): 85-95% heap usage (warnings in detailed mode)
* - Unhealthy (503): > 95% heap usage
* GET /api/health - Liveness probe for container orchestration
* GET /api/health?detailed=true - Diagnostics with advisory memory warnings
* HEAD /api/health - Lightweight liveness probe (status code only)
*/
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
@@ -43,38 +50,31 @@ export async function GET(request: NextRequest) {
try {
const timestamp = new Date().toISOString();
const memUsage = process.memoryUsage();
const heapUsagePercent = (memUsage.heapUsed / memUsage.heapTotal) * 100;
// Determine health status based on memory usage
const heapSizeLimit = v8.getHeapStatistics().heap_size_limit;
const heapUsagePercent = getHeapUsagePercent(memUsage.heapUsed, memUsage.heapTotal);
let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
const warnings: string[] = [];
let httpStatus = 200;
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
status = 'unhealthy';
httpStatus = 503;
status = 'degraded';
warnings.push(`V8 heap usage is very high: ${heapUsagePercent.toFixed(1)}% of heap limit`);
} else if (heapUsagePercent >= MEMORY_WARNING_THRESHOLD * 100) {
status = 'degraded';
warnings.push(`Memory usage high: ${heapUsagePercent.toFixed(1)}%`);
warnings.push(`V8 heap usage is high: ${heapUsagePercent.toFixed(1)}% of heap limit`);
}
// Build response
const response: HealthStatus = {
status,
status: detailed ? status : 'healthy',
timestamp,
};
if (status === 'unhealthy') {
response.reason = `Memory usage critical: ${heapUsagePercent.toFixed(1)}%`;
}
// Add detailed information if requested
if (detailed) {
response.uptime = process.uptime();
response.version = process.env.npm_package_version || '0.1.0';
response.memory = {
heapUsed: memUsage.heapUsed,
heapTotal: memUsage.heapTotal,
heapSizeLimit,
rss: memUsage.rss,
external: memUsage.external,
heapUsagePercent: Number(heapUsagePercent.toFixed(2)),
@@ -87,10 +87,8 @@ export async function GET(request: NextRequest) {
}
}
logger.info('Health check', { status, detailed });
return NextResponse.json(response, {
status: httpStatus,
status: 200,
headers: {
'Cache-Control': 'no-store, no-cache, must-revalidate',
'Pragma': 'no-cache',
@@ -116,13 +114,6 @@ export async function GET(request: NextRequest) {
*/
export async function HEAD() {
try {
const memUsage = process.memoryUsage();
const heapUsagePercent = (memUsage.heapUsed / memUsage.heapTotal) * 100;
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
return new Response(null, { status: 503 });
}
return new Response(null, { status: 200 });
} catch {
return new Response(null, { status: 503 });
+26 -11
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
import { sessionCookieName } from '@/lib/auth/session-cookie';
import { saveUserSettings, loadUserSettings, deleteUserSettings } from '@/lib/settings-sync';
function isEnabled(): boolean {
@@ -10,19 +10,30 @@ function isEnabled(): boolean {
}
/**
* Verify identity against the session cookie if available.
* Returns true if no session cookie exists (can't verify) or if identity matches.
* Returns false if session cookie exists but identity doesn't match.
* Verify identity against session cookies across all account slots.
* With multi-account, the requesting account may be on any slot (0-4).
* Returns true if any slot matches OR if no session cookies exist at all.
*/
async function verifyIdentity(username: string, serverUrl: string): Promise<boolean> {
const cookieStore = await cookies();
const sessionToken = cookieStore.get(SESSION_COOKIE)?.value;
if (!sessionToken) return true; // No session cookie, can't verify (same-origin protection applies)
let hasAnyCookie = false;
const session = decryptSession(sessionToken);
if (!session) return true; // Invalid session cookie, skip verification
for (let slot = 0; slot <= 4; slot++) {
const token = cookieStore.get(sessionCookieName(slot))?.value;
if (!token) continue;
hasAnyCookie = true;
return session.username === username && session.serverUrl === serverUrl;
const session = decryptSession(token);
if (session && session.username === username && session.serverUrl === serverUrl) {
return true; // Found a matching slot
}
}
// No cookies at all → can't verify, allow (same-origin protection applies)
if (!hasAnyCookie) return true;
// Cookies exist but none matched → identity mismatch
return false;
}
export async function GET(request: NextRequest) {
@@ -47,7 +58,9 @@ export async function GET(request: NextRequest) {
}
return NextResponse.json({ settings });
} catch (error) {
logger.error('Settings load error', { error: error instanceof Error ? error.message : 'Unknown error' });
const message = error instanceof Error ? error.message : 'Unknown error';
const code = (error as NodeJS.ErrnoException).code;
logger.error('Settings load error', { error: message, code });
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
@@ -74,7 +87,9 @@ export async function POST(request: NextRequest) {
await saveUserSettings(username, serverUrl, settings);
return NextResponse.json({ ok: true });
} catch (error) {
logger.error('Settings save error', { error: error instanceof Error ? error.message : 'Unknown error' });
const message = error instanceof Error ? error.message : 'Unknown error';
const code = (error as NodeJS.ErrnoException).code;
logger.error('Settings save error', { error: message, code });
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+6
View File
@@ -20,6 +20,8 @@
--color-accent-foreground: #1e40af;
--color-destructive: #ef4444;
--color-destructive-foreground: #ffffff;
--color-popover: #ffffff;
--color-popover-foreground: #0f172a;
/* Settings variables */
--font-size-base: 16px;
@@ -50,6 +52,8 @@
--color-accent-foreground: #dbeafe;
--color-destructive: #ef4444;
--color-destructive-foreground: #fafafa;
--color-popover: #1c1c1c;
--color-popover-foreground: #fafafa;
}
@theme inline {
@@ -68,6 +72,8 @@
--color-accent-foreground: var(--color-accent-foreground);
--color-destructive: var(--color-destructive);
--color-destructive-foreground: var(--color-destructive-foreground);
--color-popover: var(--color-popover);
--color-popover-foreground: var(--color-popover-foreground);
}
* {
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useEffect } from "react";
import { useAuthStore } from "@/stores/auth-store";
export default function NotFound() {
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
useEffect(() => {
if (!isAuthenticated) {
window.location.href = "/login";
}
}, [isAuthenticated]);
if (!isAuthenticated) {
return null;
}
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center max-w-md px-4">
<h1 className="text-4xl font-bold text-foreground mb-2">404</h1>
<p className="text-muted-foreground mb-6">This page could not be found.</p>
<a
href="/"
className="inline-flex items-center px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity"
>
Go home
</a>
</div>
</div>
);
}
+45 -16
View File
@@ -1,12 +1,12 @@
"use client";
import { useMemo } from "react";
import { useMemo, useRef, useEffect, useCallback } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { format, parseISO, isToday, isTomorrow } from "date-fns";
import { format, parseISO, isToday, isTomorrow, startOfDay } from "date-fns";
import { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
import { cn } from "@/lib/utils";
import { parseDuration, getEventColor } from "./event-card";
import { getEventDayBounds } from "@/lib/calendar-utils";
import { getEventDayBounds, getPrimaryCalendarId } from "@/lib/calendar-utils";
import { getParticipantCount } from "@/lib/calendar-participants";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
@@ -27,6 +27,7 @@ interface DayGroup {
}
export function CalendarAgendaView({
selectedDate,
events,
calendars,
onSelectEvent,
@@ -43,6 +44,9 @@ export function CalendarAgendaView({
return map;
}, [calendars]);
const todayRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const grouped = useMemo(() => {
const sorted = [...events].sort((a, b) =>
new Date(a.start).getTime() - new Date(b.start).getTime()
@@ -69,10 +73,38 @@ export function CalendarAgendaView({
} catch { /* skip invalid dates */ }
});
// Always include today's date in the groups so the view has a "Today" anchor
const todayKey = format(new Date(), "yyyy-MM-dd");
if (!groupMap.has(todayKey)) {
const todayGroup = { date: startOfDay(new Date()), dateKey: todayKey, events: [] as CalendarEvent[] };
groupMap.set(todayKey, todayGroup);
groups.push(todayGroup);
}
groups.sort((a, b) => a.date.getTime() - b.date.getTime());
return groups;
}, [events]);
// Auto-scroll to today's section on mount and when selectedDate changes to today
const scrollToToday = useCallback(() => {
if (todayRef.current) {
todayRef.current.scrollIntoView({ block: "start" });
}
}, []);
useEffect(() => {
// Scroll to today on mount
const frame = requestAnimationFrame(scrollToToday);
return () => cancelAnimationFrame(frame);
}, [scrollToToday]);
useEffect(() => {
// Scroll to today when selectedDate changes to today
if (isToday(selectedDate)) {
scrollToToday();
}
}, [selectedDate, scrollToToday]);
const formatDateHeader = (date: Date): string => {
if (isToday(date)) return t("events.today_header");
if (isTomorrow(date)) return t("events.tomorrow_header");
@@ -86,19 +118,10 @@ export function CalendarAgendaView({
return format(date, "HH:mm");
};
if (grouped.length === 0) {
return (
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground">
<CalendarIcon className="w-12 h-12 mb-3 opacity-30" />
<p className="text-sm">{t("events.no_events")}</p>
</div>
);
}
return (
<div className="flex-1 overflow-y-auto">
<div className="flex-1 overflow-y-auto" ref={scrollContainerRef}>
{grouped.map((group) => (
<div key={group.dateKey}>
<div key={group.dateKey} ref={isToday(group.date) ? todayRef : undefined}>
<div className="sticky top-0 bg-muted/80 backdrop-blur-sm px-4 py-2 border-b border-border">
<span className={cn(
"text-sm font-medium",
@@ -111,10 +134,15 @@ export function CalendarAgendaView({
</span>
</div>
{group.events.length === 0 ? (
<div className="px-4 py-6 text-center text-sm text-muted-foreground">
{t("events.no_events")}
</div>
) : (
<div className="divide-y divide-border">
{group.events.map((ev) => {
const calId = Object.keys(ev.calendarIds)[0];
const calendar = calendarMap.get(calId);
const calId = getPrimaryCalendarId(ev);
const calendar = calId ? calendarMap.get(calId) : undefined;
const color = getEventColor(ev, calendar);
const start = parseISO(ev.start);
const durMin = parseDuration(ev.duration);
@@ -176,6 +204,7 @@ export function CalendarAgendaView({
);
})}
</div>
)}
</div>
))}
</div>
+37 -6
View File
@@ -2,13 +2,14 @@
import { useMemo, useEffect, useRef, useState } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { format, isToday, parseISO } from "date-fns";
import { format, isSameDay, isToday, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
import { getEventDayBounds, layoutOverlappingEvents, formatSnapTime } from "@/lib/calendar-utils";
import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
interface CalendarDayViewProps {
selectedDate: Date;
@@ -20,6 +21,7 @@ interface CalendarDayViewProps {
onCreateAtTime: (date: Date, endDate?: Date) => void;
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
}
const HOUR_HEIGHT = 64;
@@ -35,6 +37,7 @@ export function CalendarDayView({
onCreateAtTime,
timeFormat = "24h",
isMobile,
pendingPreview,
}: CalendarDayViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -127,12 +130,12 @@ export function CalendarDayView({
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
<div className="space-y-1">
{allDayEvents.map((ev) => {
const calId = Object.keys(ev.calendarIds)[0];
const calId = getPrimaryCalendarId(ev);
return (
<EventCard
key={ev.id}
event={ev}
calendar={calendarMap.get(calId)}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="chip"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
@@ -192,7 +195,7 @@ export function CalendarDayView({
const top = (startMin / 60) * HOUR_HEIGHT;
const baseHeight = Math.max(24, (durMin / 60) * HOUR_HEIGHT);
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
const calId = Object.keys(ev.calendarIds)[0];
const calId = getPrimaryCalendarId(ev);
const leftPct = (column / totalColumns) * 100;
const widthPct = (1 / totalColumns) * 100;
@@ -205,7 +208,7 @@ export function CalendarDayView({
>
<EventCard
event={ev}
calendar={calendarMap.get(calId)}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="block"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
@@ -274,6 +277,34 @@ export function CalendarDayView({
</div>
</div>
)}
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, selectedDate) && (
(() => {
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
const endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
const durationMin = Math.max(15, endMin - startMin);
const cal = calendars.find(c => c.id === pendingPreview.calendarId);
const color = cal?.color || "hsl(var(--primary))";
return (
<div
className="absolute left-2 right-2 z-10 rounded-md pointer-events-none border-2 border-dashed overflow-hidden"
style={{
top: (startMin / 60) * HOUR_HEIGHT,
height: Math.max(24, (durationMin / 60) * HOUR_HEIGHT),
borderColor: color,
backgroundColor: `${color}10`,
}}
>
<div className="text-[10px] font-medium px-1.5 py-0.5 truncate" style={{ color }}>
{pendingPreview.title}
</div>
<div className="text-[9px] px-1.5 opacity-70" style={{ color }}>
{formatSnapTime(startMin, timeFormat)} {formatSnapTime(startMin + durationMin, timeFormat)}
</div>
</div>
);
})()
)}
</div>
</div>
</div>
+57 -22
View File
@@ -8,10 +8,11 @@ import {
} from "date-fns";
import { cn } from "@/lib/utils";
import { EventCard } from "./event-card";
import { buildWeekSegments, getEventDayBounds } from "@/lib/calendar-utils";
import { buildWeekSegments, getEventDayBounds, getPrimaryCalendarId } from "@/lib/calendar-utils";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import { useAuthStore } from "@/stores/auth-store";
import { useCalendarStore } from "@/stores/calendar-store";
import type { PendingEventPreview } from "./event-modal";
import { toast } from "@/stores/toast-store";
interface CalendarMonthViewProps {
@@ -25,6 +26,7 @@ interface CalendarMonthViewProps {
onCreateAtTime?: (date: Date) => void;
firstDayOfWeek?: number;
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
}
export function CalendarMonthView({
@@ -38,6 +40,7 @@ export function CalendarMonthView({
onCreateAtTime,
firstDayOfWeek = 1,
isMobile,
pendingPreview,
}: CalendarMonthViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -194,35 +197,67 @@ export function CalendarMonthView({
</span>
</div>
{isMobile ? (
dayEvents.length > 0 && (
<div className="flex items-center justify-center gap-0.5 flex-wrap">
{dayEvents.slice(0, 3).map((ev) => {
const calId = Object.keys(ev.calendarIds)[0];
const cal = calendarMap.get(calId);
const evColor = ev.color || cal?.color || "#3b82f6";
return (
<span
key={ev.id}
className="w-1.5 h-1.5 rounded-full"
style={{ backgroundColor: evColor }}
/>
);
})}
{dayEvents.length > 3 && (
<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
)}
</div>
)
<div className="flex items-center justify-center gap-0.5 flex-wrap">
{dayEvents.slice(0, 3).map((ev) => {
const calId = getPrimaryCalendarId(ev);
const cal = calId ? calendarMap.get(calId) : undefined;
const evColor = ev.color || cal?.color || "#3b82f6";
return (
<span
key={ev.id}
className="w-1.5 h-1.5 rounded-full"
style={{ backgroundColor: evColor }}
/>
);
})}
{dayEvents.length > 3 && (
<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
)}
{pendingPreview && isSameDay(pendingPreview.start, day) && (
<span
className="w-1.5 h-1.5 rounded-full border border-dashed"
style={{ borderColor: calendarMap.get(pendingPreview.calendarId)?.color || "#3b82f6" }}
/>
)}
</div>
) : null}
</div>
);
})}
</div>
{!isMobile && pendingPreview && (() => {
const previewDayIdx = week.findIndex(d => isSameDay(d, pendingPreview.start));
if (previewDayIdx === -1) return null;
const previewRow = rowCount;
const cal = calendarMap.get(pendingPreview.calendarId);
const color = cal?.color || "#3b82f6";
return (
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
<div
className="absolute px-0.5"
style={{
left: `calc(${(previewDayIdx / 7) * 100}% + 1px)`,
width: `calc(${(1 / 7) * 100}% - 2px)`,
top: previewRow * 22,
height: 20,
}}
>
<div
className="h-full rounded text-[10px] leading-[20px] font-medium px-1.5 truncate border-2 border-dashed"
style={{ borderColor: color, color, backgroundColor: `${color}10` }}
>
{pendingPreview.title}
</div>
</div>
</div>
);
})()}
{!isMobile && segments.length > 0 && (
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
{segments.map((segment) => {
const calId = Object.keys(segment.event.calendarIds)[0];
const calId = getPrimaryCalendarId(segment.event);
return (
<div
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
@@ -236,7 +271,7 @@ export function CalendarMonthView({
>
<EventCard
event={segment.event}
calendar={calendarMap.get(calId)}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="span"
continuesBefore={segment.continuesBefore}
continuesAfter={segment.continuesAfter}
@@ -47,7 +47,7 @@ export function CalendarSidebarPanel({
const shared = calendars.filter(c => c.isShared);
const groups = new Map<string, { accountName: string; calendars: Calendar[] }>();
for (const cal of shared) {
const key = cal.accountId!;
const key = cal.accountId || cal.accountName || cal.id;
if (!groups.has(key)) {
groups.set(key, { accountName: cal.accountName || key, calendars: [] });
}
+15 -1
View File
@@ -136,6 +136,20 @@ export function CalendarToolbar({
{t("views.today")}
</Button>
{!isMobile && (
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onPrev} aria-label={t("nav_prev")}>
<ChevronLeft className="w-4 h-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onNext} aria-label={t("nav_next")}>
<ChevronRight className="w-4 h-4" />
</Button>
<span className="text-base font-semibold ml-2 select-none">
{getDateLabel()}
</span>
</div>
)}
{isMobile && calendars && selectedCalendarIds && onToggleVisibility && (
<div className="relative" ref={dropdownRef}>
<Button
@@ -183,7 +197,7 @@ export function CalendarToolbar({
const shared = calendars.filter(c => c.isShared);
const groups = new Map<string, { accountName: string; cals: typeof shared }>();
for (const c of shared) {
const key = c.accountId!;
const key = c.accountId || c.accountName || c.id;
if (!groups.has(key)) groups.set(key, { accountName: c.accountName || key, cals: [] });
groups.get(key)!.cals.push(c);
}
+36 -5
View File
@@ -8,9 +8,10 @@ import {
import { cn } from "@/lib/utils";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
import { buildWeekSegments, getEventDayBounds, layoutOverlappingEvents, formatSnapTime } from "@/lib/calendar-utils";
import { buildWeekSegments, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
interface CalendarWeekViewProps {
selectedDate: Date;
@@ -24,6 +25,7 @@ interface CalendarWeekViewProps {
firstDayOfWeek?: number;
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
}
const HOUR_HEIGHT = 60;
@@ -41,6 +43,7 @@ export function CalendarWeekView({
firstDayOfWeek = 1,
timeFormat = "24h",
isMobile,
pendingPreview,
}: CalendarWeekViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -162,7 +165,7 @@ export function CalendarWeekView({
<div className="absolute inset-0 pointer-events-none">
{allDaySegments.map((segment) => {
const calId = Object.keys(segment.event.calendarIds)[0];
const calId = getPrimaryCalendarId(segment.event);
return (
<div
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
@@ -176,7 +179,7 @@ export function CalendarWeekView({
>
<EventCard
event={segment.event}
calendar={calendarMap.get(calId)}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="span"
continuesBefore={segment.continuesBefore}
continuesAfter={segment.continuesAfter}
@@ -284,7 +287,7 @@ export function CalendarWeekView({
const top = (startMin / 60) * HOUR_HEIGHT;
const baseHeight = Math.max(20, (durMin / 60) * HOUR_HEIGHT);
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight;
const calId = Object.keys(ev.calendarIds)[0];
const calId = getPrimaryCalendarId(ev);
const leftPct = (column / totalColumns) * 100;
const widthPct = (1 / totalColumns) * 100;
@@ -297,7 +300,7 @@ export function CalendarWeekView({
>
<EventCard
event={ev}
calendar={calendarMap.get(calId)}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="block"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
@@ -366,6 +369,34 @@ export function CalendarWeekView({
</div>
</div>
)}
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && (
(() => {
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
const endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
const durationMin = Math.max(15, endMin - startMin);
const cal = calendars.find(c => c.id === pendingPreview.calendarId);
const color = cal?.color || "hsl(var(--primary))";
return (
<div
className="absolute left-1 right-1 z-10 rounded-md pointer-events-none border-2 border-dashed overflow-hidden"
style={{
top: (startMin / 60) * HOUR_HEIGHT,
height: Math.max(20, (durationMin / 60) * HOUR_HEIGHT),
borderColor: color,
backgroundColor: `${color}10`,
}}
>
<div className="text-[10px] font-medium px-1.5 py-0.5 truncate" style={{ color }}>
{pendingPreview.title}
</div>
<div className="text-[9px] px-1.5 opacity-70" style={{ color }}>
{formatSnapTime(startMin, timeFormat)} {formatSnapTime(startMin + durationMin, timeFormat)}
</div>
</div>
);
})()
)}
</div>
);
})}
+4
View File
@@ -70,6 +70,7 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
const color = getEventColor(event, calendar);
const startDate = parseISO(event.start);
const timeFormat = useSettingsStore((state) => state.timeFormat);
const showTimeInMonthView = useSettingsStore((state) => state.showTimeInMonthView);
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
const calendarName = calendar?.name || "";
@@ -156,6 +157,9 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
style={{ backgroundColor: `${color}24`, borderLeft: `3px solid ${color}`, color, ...style }}
>
<div className="flex items-center gap-1 min-w-0">
{showTimeInMonthView && !event.showWithoutTime && (
<span className="flex-shrink-0 opacity-80">{format(startDate, timeFmt)}</span>
)}
<span className="truncate font-medium">{event.title || t("events.no_title")}</span>
</div>
</button>
+36 -8
View File
@@ -8,7 +8,7 @@ import { X, Trash2, Check, Users, CalendarDays, Copy, Pencil, Clock, MapPin, Vid
import { format, parseISO, addHours, addDays } from "date-fns";
import type { CalendarEvent, Calendar, CalendarParticipant } from "@/lib/jmap/types";
import { parseDuration, getEventColor } from "./event-card";
import { buildAllDayDuration, getEventDisplayEndDate } from "@/lib/calendar-utils";
import { buildAllDayDuration, getEventDisplayEndDate, getPrimaryCalendarId } from "@/lib/calendar-utils";
import { ParticipantInput } from "./participant-input";
import {
isOrganizer,
@@ -20,16 +20,25 @@ import {
} from "@/lib/calendar-participants";
import { useSettingsStore } from "@/stores/settings-store";
export interface PendingEventPreview {
start: Date;
end: Date;
title: string;
allDay: boolean;
calendarId: string;
}
interface EventModalProps {
event?: CalendarEvent | null;
calendars: Calendar[];
defaultDate?: Date;
defaultEndDate?: Date;
onSave: (data: Partial<CalendarEvent>, sendSchedulingMessages?: boolean) => void;
onSave: (data: Partial<CalendarEvent>, sendSchedulingMessages?: boolean) => void | Promise<void>;
onDelete?: (id: string, sendSchedulingMessages?: boolean) => void;
onDuplicate?: (data: Partial<CalendarEvent>) => void;
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
onClose: () => void;
onPreviewChange?: (preview: PendingEventPreview | null) => void;
currentUserEmails?: string[];
isMobile?: boolean;
}
@@ -105,6 +114,7 @@ export function EventModal({
onDuplicate,
onRsvp,
onClose,
onPreviewChange,
currentUserEmails = [],
isMobile = false,
}: EventModalProps) {
@@ -184,7 +194,7 @@ export function EventModal({
const [endTime, setEndTime] = useState(formatTimeInput(getInitialEnd()));
const [allDay, setAllDay] = useState(event?.showWithoutTime || false);
const [calendarId, setCalendarId] = useState<string>(() => {
if (event?.calendarIds) return Object.keys(event.calendarIds)[0] || calendars[0]?.id || "";
if (event?.calendarIds) return getPrimaryCalendarId(event) || calendars[0]?.id || "";
const defaultCal = calendars.find(c => c.isDefault);
return defaultCal?.id || calendars[0]?.id || "";
});
@@ -209,6 +219,7 @@ export function EventModal({
return "none";
});
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [attendees, setAttendees] = useState<{ name: string; email: string }[]>(() => {
if (!event?.participants) return [];
@@ -218,6 +229,18 @@ export function EventModal({
});
const [sendInvitations, setSendInvitations] = useState(true);
// Report live preview to parent for grid outline
useEffect(() => {
if (!onPreviewChange || isEdit) return;
const startStr = allDay ? `${startDate}T00:00:00` : `${startDate}T${startTime}:00`;
const endStr = allDay ? `${endDate}T23:59:59` : `${endDate}T${endTime}:00`;
const s = new Date(startStr);
const e = new Date(endStr);
if (isNaN(s.getTime()) || isNaN(e.getTime())) return;
onPreviewChange({ start: s, end: e, title: title || "(No title)", allDay, calendarId });
return () => onPreviewChange(null);
}, [startDate, startTime, endDate, endTime, allDay, title, calendarId, isEdit, onPreviewChange]);
const statusCounts = useMemo(() => {
if (!event?.participants) return null;
return getStatusCounts(event);
@@ -231,9 +254,9 @@ export function EventModal({
setAttendees(prev => prev.filter(a => a.email.toLowerCase() !== email.toLowerCase()));
}, []);
const handleSave = useCallback(() => {
const handleSave = useCallback(async () => {
const trimmedTitle = title.trim();
if (!trimmedTitle) return;
if (!trimmedTitle || isSaving) return;
if (trimmedTitle.length > 500 || description.trim().length > 10000 || location.trim().length > 500) return;
const startStr = allDay
@@ -343,8 +366,13 @@ export function EventModal({
}
const shouldSendScheduling = attendees.length > 0 && sendInvitations;
onSave(data, shouldSendScheduling);
}, [title, description, location, startDate, startTime, endDate, endTime, allDay, calendarId, recurrence, alert, attendees, sendInvitations, currentUserEmails, existingParticipants, event, onSave]);
setIsSaving(true);
try {
await onSave(data, shouldSendScheduling);
} finally {
setIsSaving(false);
}
}, [title, description, location, startDate, startTime, endDate, endTime, allDay, calendarId, recurrence, alert, attendees, sendInvitations, currentUserEmails, existingParticipants, event, onSave, isSaving]);
const handleRsvp = useCallback((status: CalendarParticipant['participationStatus']) => {
if (!event || !userParticipantId || !onRsvp) return;
@@ -945,7 +973,7 @@ export function EventModal({
<Button variant="outline" onClick={isEdit ? () => setMode("view") : onClose}>
{t("form.cancel")}
</Button>
<Button onClick={handleSave} disabled={!title.trim()}>
<Button onClick={handleSave} disabled={!title.trim() || isSaving}>
{t("form.save")}
</Button>
</div>
+21 -8
View File
@@ -6,7 +6,7 @@ import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Co
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { ContactCard } from "@/lib/jmap/types";
import type { ContactCard, AnniversaryDate, PartialDate } from "@/lib/jmap/types";
import { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
import { useSmimeStore } from "@/stores/smime-store";
import { parseCertificatePemOrDer, extractCertificateInfo } from "@/lib/smime/certificate-utils";
@@ -26,12 +26,23 @@ function formatPhoneFeatures(features?: Record<string, boolean>): string {
return Object.keys(features).filter(k => features[k]).join(", ");
}
function formatDate(dateInput: string | Record<string, unknown>): string {
function formatDate(dateInput: AnniversaryDate): string {
// Handle RFC 9553 PartialDate objects: { year?, month?, day?, calendarScale? }
// Handle RFC 9553 Timestamp objects: { "@type": "Timestamp", utc: "..." }
if (typeof dateInput === 'object' && dateInput !== null) {
const year = dateInput.year as number | undefined;
const month = dateInput.month as number | undefined;
const day = dateInput.day as number | undefined;
if (dateInput['@type'] === 'Timestamp' && typeof dateInput.utc === 'string') {
try {
const d = new Date(dateInput.utc as string);
if (!isNaN(d.getTime())) {
return d.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
}
} catch { /* fallback */ }
return String(dateInput.utc);
}
const pd = dateInput as PartialDate;
const year = pd.year;
const month = pd.month;
const day = pd.day;
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const parts: string[] = [];
if (month && monthNames[month - 1]) parts.push(monthNames[month - 1]);
@@ -282,9 +293,11 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
{addresses.map((a, i) => (
<div key={i} className="text-sm space-y-0.5 rounded-md border border-border/60 bg-muted/30 p-3">
<div>
{a.fullAddress
? a.fullAddress
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
{a.full || a.fullAddress
? (a.full || a.fullAddress)
: a.components && a.components.length > 0
? a.components.filter(c => c.kind !== 'separator').map(c => c.value).filter(Boolean).join(", ")
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
{a.contexts && <ContextBadge contexts={a.contexts} />}
</div>
{a.timeZone && (
+72 -17
View File
@@ -6,7 +6,7 @@ import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo, AddressBook } from "@/lib/jmap/types";
import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo, AddressBook, AnniversaryDate, PartialDate, ContactAddress } from "@/lib/jmap/types";
interface EmailEntry {
address: string;
@@ -129,6 +129,67 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
const findComponent = (kind: string) => contact?.name?.components?.find(c => c.kind === kind)?.value || "";
// Convert RFC 9553 AnniversaryDate to ISO date string for HTML date input
function anniversaryDateToString(date: AnniversaryDate): string {
if (typeof date === 'string') return date;
if (date && typeof date === 'object') {
if ('@type' in date && date['@type'] === 'Timestamp' && 'utc' in date) {
return (date as { utc: string }).utc.split('T')[0];
}
const pd = date as PartialDate;
if (pd.year && pd.month && pd.day) {
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
}
if (pd.month && pd.day) {
return `--${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
}
if (pd.year && pd.month) {
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}`;
}
if (pd.year) return String(pd.year);
}
return String(date);
}
// Convert ISO date string back to RFC 9553 PartialDate for the server
function stringToPartialDate(str: string): PartialDate {
if (str.startsWith('--')) {
const parts = str.substring(2).split('-');
const pd: PartialDate = { month: parseInt(parts[0], 10) };
if (parts[1]) pd.day = parseInt(parts[1], 10);
return pd;
}
const parts = str.split('-');
const pd: PartialDate = {};
if (parts[0]) pd.year = parseInt(parts[0], 10);
if (parts[1]) pd.month = parseInt(parts[1], 10);
if (parts[2]) pd.day = parseInt(parts[2], 10);
return pd;
}
// Extract flat address fields from RFC 9553 components format
function addressToFlat(a: ContactAddress): AddressEntry {
if (a.components && a.components.length > 0) {
const findComp = (kind: string) => a.components!.filter(c => c.kind === kind).map(c => c.value).join(' ');
return {
street: findComp('name') || findComp('number') ? [findComp('number'), findComp('name')].filter(Boolean).join(' ') : '',
locality: findComp('locality'),
region: findComp('region'),
postcode: findComp('postcode'),
country: findComp('country'),
context: a.contexts?.work ? 'work' : a.contexts?.private ? 'private' : '',
};
}
return {
street: a.street || '',
locality: a.locality || '',
region: a.region || '',
postcode: a.postcode || '',
country: a.country || '',
context: a.contexts?.work ? 'work' : a.contexts?.private ? 'private' : '',
};
}
const [prefix, setPrefix] = useState(findComponent("prefix"));
const [givenName, setGivenName] = useState(findComponent("given"));
const [additionalName, setAdditionalName] = useState(findComponent("additional"));
@@ -184,14 +245,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
const [addresses, setAddresses] = useState<AddressEntry[]>(() => {
if (contact?.addresses) {
return Object.values(contact.addresses).map(a => ({
street: a.street || "",
locality: a.locality || "",
region: a.region || "",
postcode: a.postcode || "",
country: a.country || "",
context: a.contexts?.work ? "work" : a.contexts?.private ? "private" : "",
}));
return Object.values(contact.addresses).map(a => addressToFlat(a));
}
return [];
});
@@ -210,7 +264,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
const [anniversaries, setAnniversaries] = useState<AnniversaryEntry[]>(() => {
if (contact?.anniversaries) {
return Object.values(contact.anniversaries).map(a => ({
date: a.date,
date: anniversaryDateToString(a.date),
kind: a.kind,
}));
}
@@ -336,12 +390,13 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
const addressesMap: Record<string, ContactCard["addresses"] extends Record<string, infer V> ? V : never> = {};
addresses.filter(a => a.street.trim() || a.locality.trim() || a.country.trim()).forEach((a, i) => {
const obj: Record<string, unknown> = {};
if (a.street.trim()) obj.street = a.street.trim();
if (a.locality.trim()) obj.locality = a.locality.trim();
if (a.region.trim()) obj.region = a.region.trim();
if (a.postcode.trim()) obj.postcode = a.postcode.trim();
if (a.country.trim()) obj.country = a.country.trim();
const components: Array<{ kind: string; value: string }> = [];
if (a.street.trim()) components.push({ kind: "name", value: a.street.trim() });
if (a.locality.trim()) components.push({ kind: "locality", value: a.locality.trim() });
if (a.region.trim()) components.push({ kind: "region", value: a.region.trim() });
if (a.postcode.trim()) components.push({ kind: "postcode", value: a.postcode.trim() });
if (a.country.trim()) components.push({ kind: "country", value: a.country.trim() });
const obj: Record<string, unknown> = { components, isOrdered: true, defaultSeparator: ", " };
if (a.context) obj.contexts = { [a.context]: true };
// @ts-expect-error - dynamic build
addressesMap[`a${i}`] = obj;
@@ -357,7 +412,7 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
const anniversariesMap: Record<string, ContactAnniversary> = {};
anniversaries.filter(a => a.date.trim()).forEach((a, i) => {
anniversariesMap[`an${i}`] = { date: a.date.trim(), kind: a.kind };
anniversariesMap[`an${i}`] = { date: stringToPartialDate(a.date.trim()), kind: a.kind };
});
const personalInfoMap: Record<string, ContactPersonalInfo> = {};
+245 -48
View File
@@ -1,14 +1,16 @@
"use client";
import { useMemo, useState, useCallback, type DragEvent } from "react";
import { useMemo, useState, useCallback, useEffect, useRef, type DragEvent } from "react";
import { useTranslations } from "next-intl";
import { BookUser, Users, Plus, UserPlus, Share2, Book } from "lucide-react";
import { BookUser, Users, Plus, Share2, Book, ChevronRight, ChevronDown, UserPlus, UsersRound, Upload, Tag, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ContextMenu, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu";
import { useContextMenu } from "@/hooks/use-context-menu";
import { cn } from "@/lib/utils";
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
import { getContactDisplayName } from "@/stores/contact-store";
export type ContactCategory = "all" | { groupId: string } | { addressBookId: string };
export type ContactCategory = "all" | { groupId: string } | { addressBookId: string } | { keyword: string };
interface ContactsSidebarProps {
groups: ContactCard[];
@@ -18,10 +20,30 @@ interface ContactsSidebarProps {
onSelectCategory: (category: ContactCategory) => void;
onCreateGroup: () => void;
onCreateContact: () => void;
onImport?: () => void;
onEditGroup?: (groupId: string) => void;
onDeleteGroup?: (groupId: string) => void;
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
className?: string;
}
const COLLAPSED_KEY = "contacts-sidebar-collapsed";
function loadCollapsed(): Record<string, boolean> {
try {
const v = localStorage.getItem(COLLAPSED_KEY);
return v ? JSON.parse(v) : {};
} catch {
return {};
}
}
function saveCollapsed(state: Record<string, boolean>) {
try {
localStorage.setItem(COLLAPSED_KEY, JSON.stringify(state));
} catch { /* ignore */ }
}
export function ContactsSidebar({
groups,
individuals,
@@ -30,10 +52,42 @@ export function ContactsSidebar({
onSelectCategory,
onCreateGroup,
onCreateContact,
onImport,
onEditGroup,
onDeleteGroup,
onDropContacts,
className,
}: ContactsSidebarProps) {
const t = useTranslations("contacts");
const { contextMenu: groupContextMenu, openContextMenu: openGroupContextMenu, closeContextMenu: closeGroupContextMenu, menuRef: groupMenuRef } = useContextMenu<ContactCard>();
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(loadCollapsed);
const [showMenu, setShowMenu] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const menuBtnRef = useRef<HTMLButtonElement>(null);
const toggleSection = useCallback((key: string) => {
setCollapsed(prev => {
const next = { ...prev, [key]: !prev[key] };
saveCollapsed(next);
return next;
});
}, []);
// Close dropdown on outside click
useEffect(() => {
if (!showMenu) return;
const handler = (e: MouseEvent) => {
if (
menuRef.current && !menuRef.current.contains(e.target as Node) &&
menuBtnRef.current && !menuBtnRef.current.contains(e.target as Node)
) {
setShowMenu(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [showMenu]);
const sortedGroups = useMemo(() => {
return [...groups].sort((a, b) =>
@@ -73,25 +127,96 @@ export function ContactsSidebar({
if (!contact.addressBookIds) continue;
for (const bookId of Object.keys(contact.addressBookIds)) {
if (!contact.addressBookIds[bookId]) continue;
// Build the full namespaced key
const key = contact.isShared && contact.accountId ? `${contact.accountId}:${bookId}` : bookId;
counts[key] = (counts[key] || 0) + 1;
counts[bookId] = (counts[bookId] || 0) + 1;
}
}
return counts;
}, [individuals]);
// Auto-collect keywords from all contacts
const allKeywords = useMemo(() => {
const counts: Record<string, number> = {};
for (const contact of individuals) {
if (!contact.keywords) continue;
for (const [kw, active] of Object.entries(contact.keywords)) {
if (!active) continue;
counts[kw] = (counts[kw] || 0) + 1;
}
}
return Object.entries(counts).sort(([a], [b]) => a.localeCompare(b));
}, [individuals]);
// Resolve actual group member counts against living contacts
const memberCountByGroup = useMemo(() => {
const counts: Record<string, number> = {};
for (const group of groups) {
if (!group.members) {
counts[group.id] = 0;
continue;
}
const memberKeys = Object.keys(group.members).filter(k => group.members![k]);
const normalizedKeys = memberKeys.map(k => k.startsWith('urn:uuid:') ? k.slice(9) : k);
counts[group.id] = individuals.filter(c => {
if (memberKeys.includes(c.id) || normalizedKeys.includes(c.id)) return true;
if (c.uid) {
const bareUid = c.uid.startsWith('urn:uuid:') ? c.uid.slice(9) : c.uid;
return memberKeys.includes(c.uid) || normalizedKeys.includes(bareUid);
}
return false;
}).length;
}
return counts;
}, [groups, individuals]);
return (
<div className={cn("flex flex-col h-full bg-secondary", className)}>
{/* Header */}
<div className="px-3 border-b border-border flex items-center justify-between" style={{ paddingBlock: 'var(--density-header-py)' }}>
<span className="text-sm font-semibold truncate">{t("title")}</span>
<Button size="icon" variant="ghost" onClick={onCreateContact} className="h-7 w-7 flex-shrink-0">
<UserPlus className="w-4 h-4" />
</Button>
<div className="relative flex-shrink-0">
<Button
ref={menuBtnRef}
size="icon"
variant="ghost"
onClick={() => setShowMenu(v => !v)}
className="h-7 w-7"
>
<Plus className="w-4 h-4" />
</Button>
{showMenu && (
<div
ref={menuRef}
className="absolute right-0 top-full mt-1 w-44 rounded-md border border-border bg-background text-foreground shadow-md z-50 py-1"
>
<button
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
onClick={() => { setShowMenu(false); onCreateContact(); }}
>
<UserPlus className="w-4 h-4" />
{t("create_new")}
</button>
<button
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
onClick={() => { setShowMenu(false); onCreateGroup(); }}
>
<UsersRound className="w-4 h-4" />
{t("groups.create")}
</button>
{onImport && (
<button
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
onClick={() => { setShowMenu(false); onImport(); }}
>
<Upload className="w-4 h-4" />
{t("import.title")}
</button>
)}
</div>
)}
</div>
</div>
{/* Categories */}
{/* Navigation */}
<div className="flex-1 overflow-y-auto py-1">
{/* All contacts */}
<button
@@ -107,19 +232,27 @@ export function ContactsSidebar({
<BookUser className="w-4 h-4 flex-shrink-0" />
<span className="truncate">{t("tabs.all")}</span>
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
{individuals.filter(c => !c.isShared).length}
{individuals.length}
</span>
</button>
{/* Personal address books */}
{/* My Address Books */}
{personalBooks.length > 0 && (
<div className="mt-2">
<div className="flex items-center justify-between px-3 py-1">
<button
onClick={() => toggleSection("addressBooks")}
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
>
{collapsed.addressBooks ? (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
)}
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("address_books.title")}
</span>
</div>
{personalBooks.map((book) => (
</button>
{!collapsed.addressBooks && personalBooks.map((book) => (
<AddressBookItem
key={book.id}
book={book}
@@ -133,29 +266,33 @@ export function ContactsSidebar({
)}
{/* Groups section */}
{(sortedGroups.length > 0) && (
{sortedGroups.length > 0 && (
<div className="mt-2">
<div className="flex items-center justify-between px-3 py-1">
<button
onClick={() => toggleSection("groups")}
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
>
{collapsed.groups ? (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
)}
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("tabs.groups")}
</span>
<Button size="icon" variant="ghost" onClick={onCreateGroup} className="h-5 w-5">
<Plus className="w-3 h-3" />
</Button>
</div>
</button>
{sortedGroups.map((group) => {
{!collapsed.groups && sortedGroups.map((group) => {
const isActive = typeof activeCategory === "object" && "groupId" in activeCategory && activeCategory.groupId === group.id;
const memberCount = group.members
? Object.values(group.members).filter(Boolean).length
: 0;
const memberCount = memberCountByGroup[group.id] || 0;
return (
<button
key={group.id}
onClick={() => onSelectCategory({ groupId: group.id })}
onContextMenu={(e) => openGroupContextMenu(e, group)}
className={cn(
"w-full flex items-center gap-2 px-3 text-sm transition-colors",
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
isActive
? "bg-accent text-accent-foreground font-medium"
: "text-foreground/80 hover:bg-muted"
@@ -173,35 +310,66 @@ export function ContactsSidebar({
</div>
)}
{sortedGroups.length === 0 && (
<div className="mt-2 px-3">
<div className="flex items-center justify-between py-1">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("tabs.groups")}
</span>
</div>
<Button
size="sm"
variant="ghost"
onClick={onCreateGroup}
className="w-full justify-start text-xs text-muted-foreground h-7"
{/* Categories section (from contact keywords) */}
{allKeywords.length > 0 && (
<div className="mt-2">
<button
onClick={() => toggleSection("categories")}
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
>
<Plus className="w-3 h-3 mr-1.5" />
{t("groups.create")}
</Button>
{collapsed.categories ? (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
)}
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("detail.categories")}
</span>
</button>
{!collapsed.categories && allKeywords.map(([keyword, count]) => {
const isActive = typeof activeCategory === "object" && "keyword" in activeCategory && activeCategory.keyword === keyword;
return (
<button
key={keyword}
onClick={() => onSelectCategory({ keyword })}
className={cn(
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
isActive
? "bg-accent text-accent-foreground font-medium"
: "text-foreground/80 hover:bg-muted"
)}
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
>
<Tag className="w-3.5 h-3.5 flex-shrink-0" />
<span className="truncate">{keyword}</span>
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
{count}
</span>
</button>
);
})}
</div>
)}
{/* Shared accounts with address books */}
{sharedBookGroups.map((group) => (
<div key={group.accountId} className="mt-2">
<div className="flex items-center justify-between px-3 py-1">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-1">
<Share2 className="w-3 h-3" />
{group.accountName}
<button
onClick={() => toggleSection(`shared-${group.accountId}`)}
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
>
{collapsed[`shared-${group.accountId}`] ? (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
)}
<Share2 className="w-3 h-3 text-muted-foreground" />
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider truncate">
{t("address_books.shared_prefix", { name: group.accountName })}
</span>
</div>
{group.books.map((book) => (
</button>
{!collapsed[`shared-${group.accountId}`] && group.books.map((book) => (
<AddressBookItem
key={book.id}
book={book}
@@ -214,6 +382,35 @@ export function ContactsSidebar({
</div>
))}
</div>
{/* Group context menu */}
{groupContextMenu.data && (
<ContextMenu
ref={groupMenuRef}
isOpen={groupContextMenu.isOpen}
position={groupContextMenu.position}
onClose={closeGroupContextMenu}
>
<ContextMenuItem
icon={Pencil}
label={t("groups.edit")}
onClick={() => {
closeGroupContextMenu();
onEditGroup?.(groupContextMenu.data!.id);
}}
/>
<ContextMenuSeparator />
<ContextMenuItem
icon={Trash2}
label={t("form.delete")}
onClick={() => {
closeGroupContextMenu();
onDeleteGroup?.(groupContextMenu.data!.id);
}}
destructive
/>
</ContextMenu>
)}
</div>
);
}
@@ -266,7 +463,7 @@ function AddressBookItem({
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={cn(
"w-full flex items-center gap-2 px-3 text-sm transition-colors",
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
isActive
? "bg-accent text-accent-foreground font-medium"
: "text-foreground/80 hover:bg-muted",
+17 -12
View File
@@ -27,6 +27,7 @@ import { substitutePlaceholders } from "@/lib/template-utils";
import { TemplatePicker } from "@/components/templates/template-picker";
import { TemplateForm } from "@/components/templates/template-form";
import type { EmailTemplate } from "@/lib/template-types";
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
export interface ComposerDraftData {
to: string;
@@ -199,6 +200,14 @@ export function EmailComposer({
const { client } = useAuthStore();
const identities = useIdentityStore((s) => s.identities);
const primaryIdentity = identities[0] ?? null;
const currentIdentity = selectedIdentityId
? identities.find((identity) => identity.id === selectedIdentityId) || primaryIdentity
: primaryIdentity;
const composerSignatureHtml = currentIdentity?.htmlSignature
? `<div>${sanitizeEmailHtml(currentIdentity.htmlSignature)}</div>`
: currentIdentity?.textSignature
? `<div>${getPlainTextSignature(currentIdentity).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</div>`
: '';
const getAutocomplete = useContactStore((s) => s.getAutocomplete);
const addTemplate = useTemplateStore((s) => s.addTemplate);
const sendRawEmail = useEmailStore((s) => s.sendRawEmail);
@@ -527,10 +536,6 @@ export function EmailComposer({
setSaveStatus('saving');
// Get the selected identity or primary identity
const currentIdentity = selectedIdentityId
? identities.find(id => id.id === selectedIdentityId)
: primaryIdentity;
// Generate sub-addressed email if tag is set
const fromEmail = currentIdentity?.email
? subAddressTag
@@ -649,10 +654,6 @@ export function EmailComposer({
}
}
const currentIdentity = selectedIdentityId
? identities.find(id => id.id === selectedIdentityId)
: primaryIdentity;
const fromEmail = currentIdentity?.email
? subAddressTag
? generateSubAddress(currentIdentity.email, subAddressTag)
@@ -660,10 +661,7 @@ export function EmailComposer({
: undefined;
// Append signature from the selected identity
let finalBody = body;
if (currentIdentity?.textSignature) {
finalBody = body + '\n\n-- \n' + currentIdentity.textSignature;
}
let finalBody = appendPlainTextSignature(body, currentIdentity);
// Append quoted original text for the plain text part in reply/forward
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
@@ -1126,6 +1124,13 @@ export function EmailComposer({
/>
</div>
{composerSignatureHtml && (
<div
className="px-4 pb-3 text-sm leading-6 text-foreground break-words [&_a]:text-primary [&_a]:underline-offset-2 [&_a:hover]:underline"
dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
/>
)}
{/* Quoted original HTML */}
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && (
<div className="border-t border-border">
+437 -139
View File
@@ -5,6 +5,7 @@ import ReactDOM from "react-dom";
import DOMPurify from "dompurify";
import { Email, ContactCard, Mailbox } from "@/lib/jmap/types";
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
import { hasMeaningfulHtmlBody } from "@/lib/signature-utils";
import { Button } from "@/components/ui/button";
import { Avatar } from "@/components/ui/avatar";
import { formatFileSize, cn, buildMailboxTree, MailboxNode, formatDateTime } from "@/lib/utils";
@@ -104,7 +105,7 @@ interface EmailViewerProps {
onToggleStar?: () => void;
onMarkAsRead?: (emailId: string, read: boolean) => void;
onSetColorTag?: (emailId: string, color: string | null) => void;
onDownloadAttachment?: (blobId: string, name: string, type?: string) => void;
onDownloadAttachment?: (blobId: string, name: string, type?: string, forceDownload?: boolean) => void;
onQuickReply?: (body: string) => Promise<void>;
onMarkAsSpam?: () => void;
onUndoSpam?: () => void;
@@ -148,6 +149,42 @@ const getFileIcon = (name?: string, type?: string) => {
return File;
};
const MIME_TYPE_LABELS: Record<string, string> = {
'application/pdf': 'Document.pdf',
'application/zip': 'Archive.zip',
'application/x-zip-compressed': 'Archive.zip',
'application/gzip': 'Archive.gz',
'application/x-rar-compressed': 'Archive.rar',
'application/x-7z-compressed': 'Archive.7z',
'application/msword': 'Document.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Document.docx',
'application/vnd.ms-excel': 'Spreadsheet.xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Spreadsheet.xlsx',
'application/vnd.ms-powerpoint': 'Presentation.ppt',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'Presentation.pptx',
'text/plain': 'Text.txt',
'text/html': 'Document.html',
'text/csv': 'Data.csv',
'application/json': 'Data.json',
'application/xml': 'Data.xml',
'application/octet-stream': 'Attachment',
'message/rfc822': 'Email.eml',
};
const getAttachmentDisplayName = (name: string | null | undefined, mimeType?: string): string => {
if (name) return name;
if (mimeType) {
const label = MIME_TYPE_LABELS[mimeType.toLowerCase()];
if (label) return label;
const sub = mimeType.split('/')[1];
if (sub) {
const clean = sub.replace(/^x-/, '').replace(/^vnd\./, '');
return `Attachment.${clean}`;
}
}
return 'Attachment';
};
const getCurrentColor = (keywords: Record<string, boolean> | undefined) => {
if (!keywords) return null;
for (const key of Object.keys(keywords)) {
@@ -706,7 +743,11 @@ function ContactSidebarPanel({
<SidebarSection icon={MapPin} title="Addresses">
{addresses.map((a, i) => (
<div key={i} className="text-sm text-muted-foreground">
{[a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
{a.full || a.fullAddress
? (a.full || a.fullAddress)
: a.components && a.components.length > 0
? a.components.filter(c => c.kind !== 'separator').map(c => c.value).filter(Boolean).join(", ")
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")}
</div>
))}
</SidebarSection>
@@ -832,6 +873,7 @@ export function EmailViewer({
const tFiles = useTranslations('files');
const externalContentPolicy = useSettingsStore((state) => state.externalContentPolicy);
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
const attachmentPosition = useSettingsStore((state) => state.attachmentPosition);
const addTrustedSender = useSettingsStore((state) => state.addTrustedSender);
const isSenderTrusted = useSettingsStore((state) => state.isSenderTrusted);
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
@@ -859,6 +901,8 @@ export function EmailViewer({
const { identities, client } = useAuthStore();
const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
const [showFullHeaders, setShowFullHeaders] = useState(false);
const [showAllBesideAttachments, setShowAllBesideAttachments] = useState(false);
const [showAllMobileAttachments, setShowAllMobileAttachments] = useState(false);
const [allowExternalContent, setAllowExternalContent] = useState(false);
const [hasBlockedContent, setHasBlockedContent] = useState(false);
const [cidBlobUrls, setCidBlobUrls] = useState<Record<string, string>>({});
@@ -2144,9 +2188,7 @@ export function EmailViewer({
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
if (hasTextBody && htmlContent) {
const stripped = htmlContent.replace(/<\/?(html|head|body|meta|!doctype|!DOCTYPE|br\s*\/?)[^>]*>/gi, '').trim();
const hasRichContent = /<(table|tr|td|th|img|style|link|div\s+[^>]*class|span\s+[^>]*class|font|center|blockquote|ul|ol|li|h[1-6])\b/i.test(stripped);
useHtmlVersion = hasRichContent;
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
} else {
useHtmlVersion = !!htmlContent;
}
@@ -2391,6 +2433,44 @@ export function EmailViewer({
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
}, [mailAttachmentAction, onDownloadAttachment]);
const handleEffectiveAttachmentDownload = useCallback((attachment: EffectiveAttachment) => {
if (attachment.blobId && onDownloadAttachment) {
onDownloadAttachment(attachment.blobId, attachment.name || 'download', attachment.type, true);
return;
}
if (attachment.tnefData) {
const buffer = attachment.tnefData.buffer.slice(
attachment.tnefData.byteOffset,
attachment.tnefData.byteOffset + attachment.tnefData.byteLength,
) as ArrayBuffer;
const blob = new Blob([buffer], { type: attachment.type || 'application/octet-stream' });
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = attachment.name || 'download';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(objectUrl), 60000);
return;
}
if (!attachment.decryptedAttachment) return;
const bytes = getAttachmentContentBytes(attachment.decryptedAttachment);
if (!bytes || bytes.byteLength === 0) return;
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
const blob = new Blob([buffer], { type: attachment.type || 'application/octet-stream' });
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = attachment.name || 'download';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
}, [onDownloadAttachment]);
// Iframe for rendering HTML emails true-to-life
const iframeRef = useRef<HTMLIFrameElement>(null);
@@ -2910,6 +2990,21 @@ export function EmailViewer({
<Code className="w-4 h-4" />
</Button>
{/* Dark/light mode toggle for HTML emails */}
{effectiveEmailContent.isHtml && (
<Button
variant="ghost"
size="sm"
onClick={() => setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev)}
data-overflow-item
data-overflow-priority="11"
className="hidden sm:inline-flex h-8 gap-1.5"
title={isDark ? 'View in light mode' : 'View in dark mode'}
>
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
</Button>
)}
{/* More menu — click-based */}
<div ref={moreMenuRef} className="relative">
<Button
@@ -3092,6 +3187,16 @@ export function EmailViewer({
<Code className="w-4 h-4" />
{t('view_source')}
</button>
{/* Overflow: dark/light mode toggle */}
{effectiveEmailContent.isHtml && (
<button
onClick={() => { setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev); setMoreMenuOpen(false); setMoreMenuSub(null); }}
className={cn("w-full px-3 py-1.5 text-sm text-left hover:bg-muted text-foreground flex items-center gap-2", hiddenPriorities.has(11) ? "" : "sm:hidden")}
>
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
{isDark ? 'View in light mode' : 'View in dark mode'}
</button>
)}
<div className="h-px bg-border my-1" />
{/* Export email */}
<button
@@ -3265,6 +3370,15 @@ export function EmailViewer({
<Code className="w-5 h-5" />
{t('view_source')}
</button>
{effectiveEmailContent.isHtml && (
<button
onClick={() => { setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev); setMoreMenuOpen(false); }}
className="w-full px-4 py-3 min-h-[44px] text-sm text-left hover:bg-muted text-foreground flex items-center gap-3"
>
{isDark ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
{isDark ? 'View in light mode' : 'View in dark mode'}
</button>
)}
<div className="h-px bg-border my-1" />
<button
onClick={() => { handleExportEmail(); setMoreMenuOpen(false); }}
@@ -3338,7 +3452,7 @@ export function EmailViewer({
)}
<div className="flex-1 min-w-0">
<div className="flex items-start gap-2">
<h1 className="text-lg lg:text-2xl font-bold text-foreground tracking-tight break-words min-w-0">
<h1 className="text-lg lg:text-xl font-bold text-foreground tracking-tight break-words min-w-0">
{email.subject || t('no_subject')}
</h1>
{/* Star inline with subject (top toolbar mode) */}
@@ -3362,19 +3476,24 @@ export function EmailViewer({
<span className={cn("w-2.5 h-2.5 rounded-full flex-shrink-0", dotClass)} title={kw!.label} />
) : null;
})()}
</div>
<div className="flex items-center gap-2 lg:gap-3 mt-1 lg:mt-1.5 text-xs lg:text-sm text-muted-foreground">
<span className="flex items-center gap-1 lg:gap-1.5 whitespace-nowrap">
<Clock className="w-3.5 h-3.5 lg:w-4 lg:h-4" />
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
</span>
{isImportant && (
<span className="px-1.5 lg:px-2 py-0.5 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-full text-xs font-medium whitespace-nowrap">
<span className="px-1.5 lg:px-2 py-0.5 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-full text-xs font-medium whitespace-nowrap flex-shrink-0 self-center">
{t('important')}
</span>
)}
</div>
</div>
{/* Date/time on the right of subject row */}
<div className="flex-shrink-0 text-right">
<span className="text-xs lg:text-sm text-muted-foreground whitespace-nowrap">
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
</span>
{email.size > 0 && (
<div className="text-xs text-muted-foreground/60">
{formatFileSize(email.size)}
</div>
)}
</div>
</div>
</div>
</div>
@@ -3405,13 +3524,14 @@ export function EmailViewer({
name={sender?.name}
email={sender?.email}
size="lg"
className="shadow-sm w-12 h-12 group-hover:ring-2 group-hover:ring-primary/30 transition-all"
className="shadow-sm w-10 h-10 group-hover:ring-2 group-hover:ring-primary/30 transition-all"
/>
</button>
<div className="flex-1 min-w-0">
{/* Sender line with email and badges */}
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0 flex gap-4">
<div className="flex-1 min-w-0">
{/* Row 1: Sender name + badges */}
<div>
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<button
@@ -3422,103 +3542,80 @@ export function EmailViewer({
{sender?.name || sender?.email || t('unknown_sender')}
</button>
<EmailIdentityBadge email={email} identities={identities} />
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
listUnsubscribe={listHeaders.listUnsubscribe}
senderEmail={email?.from?.[0]?.email || ''}
onDismiss={() => {
const messageId = email?.messageId || '';
const newSet = new Set(dismissedUnsubBanners).add(messageId);
setDismissedUnsubBanners(newSet);
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
}}
/>
)}
</div>
{sender?.email && (
<div className="text-sm text-muted-foreground mt-0.5 flex items-center min-w-0">
<span className="truncate">{sender.email}</span>
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
listUnsubscribe={listHeaders.listUnsubscribe}
senderEmail={email?.from?.[0]?.email || ''}
onDismiss={() => {
const messageId = email?.messageId || '';
const newSet = new Set(dismissedUnsubBanners).add(messageId);
setDismissedUnsubBanners(newSet);
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
}}
/>
)}
</div>
)}
</div>
{/* Date and size on the right */}
<div className="text-right flex-shrink-0">
<div className="text-sm text-muted-foreground whitespace-nowrap">
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
</div>
{email.size > 0 && (
<div className="text-xs text-muted-foreground/70 mt-0.5">
{formatFileSize(email.size)}
</div>
)}
{effectiveEmailContent.isHtml && (
<button
onClick={() => setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev)}
className="inline-flex items-center rounded-full p-1 mt-1 text-muted-foreground/70 hover:text-foreground transition-colors hover:bg-muted"
title={isDark ? 'View in light mode' : 'View in dark mode'}
>
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
</button>
{/* Email address under name */}
{sender?.email && sender?.name && (
<div className="text-sm text-muted-foreground mt-0.5 truncate">{sender.email}</div>
)}
</div>
</div>
{/* Recipient section - separate line */}
<div className="mt-2 space-y-1">
{/* Row 2: Recipients + Show details */}
<div className="mt-1 flex items-center gap-2 text-sm text-muted-foreground flex-wrap">
{email.to && email.to.length > 0 && (
<div className="flex flex-wrap items-center gap-1 text-sm">
<span className="text-muted-foreground">{t('recipient_to_prefix')}</span>
<>
<span>{t('recipient_to_prefix')}</span>
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
{email.to.length > 2 && (
<button
onClick={() => setShowFullHeaders(!showFullHeaders)}
className="ml-1 text-blue-600 dark:text-blue-400 hover:underline text-sm"
className="text-blue-600 dark:text-blue-400 hover:underline text-sm"
>
{t('more_count', { count: email.to.length - 2 })}
</button>
)}
</div>
</>
)}
{email.cc && email.cc.length > 0 && (
<div className="flex flex-wrap items-center gap-1 text-sm">
<span className="text-muted-foreground">CC:</span>
<>
<span className="text-muted-foreground/50">|</span>
<span>CC:</span>
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
{email.cc.length > 2 && (
<span className="text-muted-foreground text-sm">+{email.cc.length - 2}</span>
<span className="text-muted-foreground">+{email.cc.length - 2}</span>
)}
</div>
</>
)}
{email.bcc && email.bcc.length > 0 && (
<div className="flex flex-wrap items-center gap-1 text-sm">
<span className="text-muted-foreground">{t('bcc')}:</span>
<>
<span className="text-muted-foreground/50">|</span>
<span>{t('bcc')}:</span>
{renderClickableRecipients(email.bcc, currentUserEmail, t, handleViewContactSidebar)}
{email.bcc.length > 2 && (
<span className="text-muted-foreground text-sm">+{email.bcc.length - 2}</span>
<span className="text-muted-foreground">+{email.bcc.length - 2}</span>
)}
</div>
</>
)}
<button
onClick={() => setShowFullHeaders(!showFullHeaders)}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-0.5 transition-colors ml-1"
>
{showFullHeaders ? (
<>
<ChevronUp className="w-3 h-3" />
{t('hide_details')}
</>
) : (
<>
<ChevronDown className="w-3 h-3" />
{t('show_details')}
</>
)}
</button>
</div>
{/* Details toggle - stays in place when expanded */}
<button
onClick={() => setShowFullHeaders(!showFullHeaders)}
className="mt-3 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
>
{showFullHeaders ? (
<>
<ChevronUp className="w-3 h-3" />
{t('hide_details')}
</>
) : (
<>
<ChevronDown className="w-3 h-3" />
{t('show_details')}
</>
)}
</button>
{/* Expandable Details */}
{showFullHeaders && (
<div className="mt-3 space-y-3">
@@ -3890,46 +3987,248 @@ export function EmailViewer({
</div>
)}
</div>
{/* Attachments on the right (beside-sender mode) */}
{attachmentPosition === 'beside-sender' && effectiveAttachments.length > 0 && (
<div className="relative flex flex-col items-end justify-start gap-1 flex-shrink-0 max-w-[50%]">
{effectiveAttachments.slice(0, 2).map((attachment) => {
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
return (
<div
key={attachment.id}
className="inline-flex items-center gap-1.5 px-2 py-1 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
>
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
<span className="text-xs text-foreground truncate max-w-[140px]">
{getAttachmentDisplayName(attachment.name, attachment.type)}
</span>
<span className="text-[10px] text-muted-foreground">
{formatFileSize(attachment.size)}
</span>
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={t('download')}
onClick={() => handleEffectiveAttachmentDownload(attachment)}
>
<Download className="w-3.5 h-3.5 text-foreground" />
</button>
{opensPreview && (
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={tFiles('preview')}
onClick={() => handleEffectiveAttachmentOpen(attachment)}
>
<Eye className="w-3.5 h-3.5 text-foreground" />
</button>
)}
</div>
</div>
);
})}
{effectiveAttachments.length > 2 && (
<button
onClick={() => setShowAllBesideAttachments(!showAllBesideAttachments)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-0.5"
>
+{effectiveAttachments.length - 2} {t('more')}
</button>
)}
{/* Floating popup for remaining attachments */}
{showAllBesideAttachments && effectiveAttachments.length > 2 && (
<>
<div className="fixed inset-0 z-40" onClick={() => setShowAllBesideAttachments(false)} />
<div className="absolute top-full right-0 mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-2 flex flex-col gap-1 min-w-[220px]">
{effectiveAttachments.slice(2).map((attachment) => {
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
return (
<div
key={attachment.id}
className="flex items-center gap-1.5 px-2 py-1 rounded-md group relative cursor-default w-full"
>
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
<span className="text-xs text-foreground truncate max-w-[180px]">
{getAttachmentDisplayName(attachment.name, attachment.type)}
</span>
<span className="text-[10px] text-muted-foreground ml-auto flex-shrink-0">
{formatFileSize(attachment.size)}
</span>
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={t('download')}
onClick={() => { handleEffectiveAttachmentDownload(attachment); setShowAllBesideAttachments(false); }}
>
<Download className="w-3.5 h-3.5 text-foreground" />
</button>
{opensPreview && (
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={tFiles('preview')}
onClick={() => { handleEffectiveAttachmentOpen(attachment); setShowAllBesideAttachments(false); }}
>
<Eye className="w-3.5 h-3.5 text-foreground" />
</button>
)}
</div>
</div>
);
})}
</div>
</>
)}
</div>
)}
</div>
</div>
</div>
{/* === ATTACHMENTS (integrated into header) === */}
{effectiveAttachments.length > 0 && (
<div className="bg-background border-b border-border px-4 lg:px-6 py-3">
<div className="flex items-start gap-2 flex-wrap">
{/* === ATTACHMENTS below header (below-header mode, desktop only) === */}
{attachmentPosition === 'below-header' && effectiveAttachments.length > 0 && (
<div className="hidden lg:block bg-background border-b border-border px-4 lg:px-6 py-2">
<div className="flex items-center gap-2 flex-wrap">
{effectiveAttachments.map((attachment) => {
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
return (
<button
<div
key={attachment.id}
className="inline-flex items-center gap-2 px-3 py-2 bg-muted/60 hover:bg-accent rounded-lg transition-colors group border border-border/50"
title={`${opensPreview ? tFiles('preview') : t('download')} ${attachment.name || 'Unnamed'} (${formatFileSize(attachment.size)})`}
onClick={() => handleEffectiveAttachmentOpen(attachment)}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
>
<FileIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
<div className="flex flex-col items-start min-w-0">
<span className="text-sm text-foreground truncate max-w-[200px]">
{attachment.name || "Unnamed"}
</span>
<span className="text-xs text-muted-foreground">
{formatFileSize(attachment.size)}
</span>
<span className="text-sm text-foreground truncate max-w-[200px]">
{getAttachmentDisplayName(attachment.name, attachment.type)}
</span>
<span className="text-xs text-muted-foreground">
{formatFileSize(attachment.size)}
</span>
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={t('download')}
onClick={() => handleEffectiveAttachmentDownload(attachment)}
>
<Download className="w-4 h-4 text-foreground" />
</button>
{opensPreview && (
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={tFiles('preview')}
onClick={() => handleEffectiveAttachmentOpen(attachment)}
>
<Eye className="w-4 h-4 text-foreground" />
</button>
)}
</div>
{opensPreview ? (
<Eye className="w-3.5 h-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
) : (
<Download className="w-3.5 h-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
)}
</button>
</div>
);
})}
</div>
</div>
)}
{/* Mobile/Tablet Attachments */}
{effectiveAttachments.length > 0 && (
<div className="lg:hidden bg-background border-b border-border px-4 py-2">
<div className="relative flex items-center gap-1.5 flex-wrap">
{effectiveAttachments.slice(0, 2).map((attachment) => {
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
return (
<div
key={attachment.id}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
>
<FileIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
<span className="text-sm text-foreground truncate max-w-[200px]">
{getAttachmentDisplayName(attachment.name, attachment.type)}
</span>
<span className="text-xs text-muted-foreground">
{formatFileSize(attachment.size)}
</span>
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={t('download')}
onClick={() => handleEffectiveAttachmentDownload(attachment)}
>
<Download className="w-4 h-4 text-foreground" />
</button>
{opensPreview && (
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={tFiles('preview')}
onClick={() => handleEffectiveAttachmentOpen(attachment)}
>
<Eye className="w-4 h-4 text-foreground" />
</button>
)}
</div>
</div>
);
})}
{effectiveAttachments.length > 2 && (
<button
onClick={() => setShowAllMobileAttachments(!showAllMobileAttachments)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-0.5"
>
+{effectiveAttachments.length - 2} {t('more')}
</button>
)}
{showAllMobileAttachments && effectiveAttachments.length > 2 && (
<>
<div className="fixed inset-0 z-40" onClick={() => setShowAllMobileAttachments(false)} />
<div className="absolute top-full left-0 mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-2 flex flex-col gap-1 min-w-[220px]">
{effectiveAttachments.slice(2).map((attachment) => {
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
return (
<div
key={attachment.id}
className="flex items-center gap-1.5 px-2 py-1 rounded-md group relative cursor-default w-full"
>
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
<span className="text-xs text-foreground truncate max-w-[180px]">
{getAttachmentDisplayName(attachment.name, attachment.type)}
</span>
<span className="text-[10px] text-muted-foreground ml-auto flex-shrink-0">
{formatFileSize(attachment.size)}
</span>
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={t('download')}
onClick={() => { handleEffectiveAttachmentDownload(attachment); setShowAllMobileAttachments(false); }}
>
<Download className="w-3.5 h-3.5 text-foreground" />
</button>
{opensPreview && (
<button
className="p-1 hover:bg-accent rounded transition-colors"
title={tFiles('preview')}
onClick={() => { handleEffectiveAttachmentOpen(attachment); setShowAllMobileAttachments(false); }}
>
<Eye className="w-3.5 h-3.5 text-foreground" />
</button>
)}
</div>
</div>
);
})}
</div>
</>
)}
</div>
</div>
)}
{/* Mobile/Tablet Sender Info - scrolls with content */}
<div className="lg:hidden bg-background border-b border-border px-4" style={{ paddingBlock: 'var(--density-header-py)' }}>
<div className="flex items-start" style={{ gap: 'var(--density-item-gap)' }}>
@@ -3946,8 +4245,8 @@ export function EmailViewer({
/>
</button>
<div className="flex-1 min-w-0">
{/* Mobile 2-line layout */}
<div className="flex items-center gap-2 flex-wrap">
{/* Row 1: Sender name + badges */}
<div className="flex items-center gap-1.5 flex-wrap">
<button
onClick={() => sender?.email && handleViewContactSidebar(null, sender.email)}
className="text-sm font-semibold text-foreground hover:text-primary hover:underline transition-colors cursor-pointer text-left"
@@ -3955,43 +4254,42 @@ export function EmailViewer({
{sender?.name || sender?.email || t('unknown_sender')}
</button>
<EmailIdentityBadge email={email} identities={identities} />
</div>
<div className="mt-1 flex items-center gap-1 text-sm text-muted-foreground flex-wrap">
{sender?.email && sender?.name && (
<>
<span className="truncate">{sender.email}</span>
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
listUnsubscribe={listHeaders.listUnsubscribe}
senderEmail={email?.from?.[0]?.email || ''}
onDismiss={() => {
const messageId = email?.messageId || '';
const newSet = new Set(dismissedUnsubBanners).add(messageId);
setDismissedUnsubBanners(newSet);
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
}}
/>
)}
<span>·</span>
</>
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
<UnsubscribeBanner
listUnsubscribe={listHeaders.listUnsubscribe}
senderEmail={email?.from?.[0]?.email || ''}
onDismiss={() => {
const messageId = email?.messageId || '';
const newSet = new Set(dismissedUnsubBanners).add(messageId);
setDismissedUnsubBanners(newSet);
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
}}
/>
)}
</div>
{/* Email address under name */}
{sender?.email && sender?.name && (
<div className="text-xs text-muted-foreground mt-0.5 truncate">{sender.email}</div>
)}
{/* Row 2: Recipients */}
<div className="mt-0.5 flex items-center gap-1 text-sm text-muted-foreground flex-wrap">
{email.to && email.to.length > 0 && (
<>
<span> {t('recipient_to_prefix')}</span>
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
</>
)}
{email.cc && email.cc.length > 0 && (
<>
<span className="text-muted-foreground/50">|</span>
<span>CC:</span>
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
{email.cc.length > 2 && (
<span>+{email.cc.length - 2}</span>
)}
</>
)}
</div>
{/* CC line (mobile - only if present) */}
{email.cc && email.cc.length > 0 && (
<div className="mt-1 flex items-center gap-1 text-sm">
<span className="text-muted-foreground">CC:</span>
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
{email.cc.length > 2 && (
<span className="text-muted-foreground">+{email.cc.length - 2}</span>
)}
</div>
)}
</div>
</div>
</div>
@@ -4,6 +4,7 @@ import { useState, useEffect, useMemo } from "react";
import DOMPurify from "dompurify";
import { Email, ThreadGroup } from "@/lib/jmap/types";
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
import { hasMeaningfulHtmlBody } from "@/lib/signature-utils";
import { transformInlineStyles, transformColorForDarkMode, transformBgColorForDarkMode } from "@/lib/color-transform";
import { useThemeStore } from "@/stores/theme-store";
import { Avatar } from "@/components/ui/avatar";
@@ -320,9 +321,7 @@ function EmailCard({
// Server-generated HTML from text/plain emails often lacks <br> tags, collapsing newlines.
const hasTextBody = email.textBody?.[0]?.partId && email.bodyValues[email.textBody[0].partId];
if (hasTextBody && htmlContent) {
const stripped = htmlContent.replace(/<\/?(html|head|body|meta|!doctype|!DOCTYPE|br\s*\/?)[^>]*>/gi, '').trim();
const hasRichContent = /<(table|tr|td|th|img|style|link|div\s+[^>]*class|span\s+[^>]*class|font|center|blockquote|ul|ol|li|h[1-6])\b/i.test(stripped);
useHtmlVersion = hasRichContent;
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
} else {
useHtmlVersion = !!htmlContent;
}
+1 -1
View File
@@ -135,7 +135,7 @@ export function SubAddressHelper({
<div
ref={popoverRef}
className={cn(
'absolute top-full left-0 mt-1 z-50',
'absolute top-full right-0 mt-1 z-50',
'bg-background border border-border rounded-lg shadow-lg',
'w-80 p-4 animate-in fade-in zoom-in-95 duration-150'
)}
+273
View File
@@ -0,0 +1,273 @@
"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { Check, Plus, LogOut, Star, ChevronDown, AlertCircle } from "lucide-react";
import { useTranslations } from "next-intl";
import { useAccountStore, type AccountEntry } from "@/stores/account-store";
import { useAuthStore } from "@/stores/auth-store";
import { getInitials, MAX_ACCOUNTS } from "@/lib/account-utils";
import { cn } from "@/lib/utils";
import { useRouter } from "@/i18n/navigation";
interface AccountSwitcherProps {
/** "rail" = small avatar only (NavigationRail), "expanded" = avatar + name + email (Sidebar) */
variant?: "rail" | "expanded";
className?: string;
}
function AccountAvatar({ account, size = "sm" }: { account: AccountEntry; size?: "sm" | "md" }) {
const initials = getInitials(account.displayName || account.label, account.email || account.username);
const sizeClasses = size === "sm" ? "w-8 h-8 text-xs" : "w-9 h-9 text-sm";
return (
<div
className={cn("rounded-full flex items-center justify-center text-white font-medium flex-shrink-0", sizeClasses)}
style={{ backgroundColor: account.avatarColor }}
title={account.label}
>
{initials}
</div>
);
}
export function AccountSwitcher({ variant = "rail", className }: AccountSwitcherProps) {
const t = useTranslations("sidebar");
const router = useRouter();
const [open, setOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>(null);
const popoverRef = useRef<HTMLDivElement>(null);
const [popoverStyle, setPopoverStyle] = useState<React.CSSProperties>({});
const accounts = useAccountStore((s) => s.accounts);
const activeAccountId = useAccountStore((s) => s.activeAccountId);
const setDefaultAccount = useAccountStore((s) => s.setDefaultAccount);
const activeAccount = accounts.find((a) => a.id === activeAccountId);
const switchAccount = useAuthStore((s) => s.switchAccount);
const logout = useAuthStore((s) => s.logout);
const logoutAll = useAuthStore((s) => s.logoutAll);
const primaryIdentity = useAuthStore((s) => s.primaryIdentity);
const updatePosition = useCallback(() => {
if (!buttonRef.current) return;
const rect = buttonRef.current.getBoundingClientRect();
if (variant === "rail") {
setPopoverStyle({
position: "fixed",
left: rect.right + 8,
bottom: Math.max(8, window.innerHeight - rect.bottom),
});
} else {
setPopoverStyle({
position: "fixed",
left: rect.left,
top: rect.bottom + 4,
});
}
}, [variant]);
useEffect(() => {
if (!open) return;
updatePosition();
const handleClickOutside = (e: MouseEvent) => {
if (
buttonRef.current?.contains(e.target as Node) ||
popoverRef.current?.contains(e.target as Node)
) return;
setOpen(false);
};
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false);
};
document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("keydown", handleEscape);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleEscape);
};
}, [open, updatePosition]);
const handleSwitch = async (accountId: string) => {
if (accountId === activeAccountId) return;
setOpen(false);
await switchAccount(accountId);
};
const handleAddAccount = () => {
setOpen(false);
router.push(`/login?mode=add-account` as never);
};
const handleLogout = () => {
setOpen(false);
logout();
if (useAccountStore.getState().accounts.length === 0) {
router.push("/login" as never);
}
};
const handleLogoutAll = () => {
setOpen(false);
logoutAll();
router.push("/login" as never);
};
const handleSetDefault = (accountId: string) => {
setDefaultAccount(accountId);
};
// Display name for the active account
const displayName = primaryIdentity?.name || activeAccount?.displayName || activeAccount?.label || "";
const displayEmail = primaryIdentity?.email || activeAccount?.email || activeAccount?.username || "";
return (
<>
<button
ref={buttonRef}
onClick={() => setOpen(!open)}
className={cn(
"flex items-center gap-2 rounded-md transition-colors",
variant === "rail"
? "justify-center w-10 h-10 hover:bg-muted"
: "w-full px-2 py-1.5 hover:bg-muted text-left min-w-0",
className
)}
title={variant === "rail" ? (displayName || displayEmail) : undefined}
aria-expanded={open}
aria-haspopup="true"
>
{activeAccount ? (
<>
<AccountAvatar account={activeAccount} size={variant === "rail" ? "sm" : "md"} />
{variant === "expanded" && (
<>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-foreground truncate">{displayName}</p>
<p className="text-xs text-muted-foreground truncate">{displayEmail}</p>
</div>
<ChevronDown className={cn("w-3.5 h-3.5 text-muted-foreground flex-shrink-0 transition-transform", open && "rotate-180")} />
</>
)}
</>
) : (
<div className={cn(
"rounded-full bg-muted flex items-center justify-center text-muted-foreground",
variant === "rail" ? "w-8 h-8 text-xs" : "w-9 h-9 text-sm"
)}>
?
</div>
)}
</button>
{open && createPortal(
<div
ref={popoverRef}
style={popoverStyle}
className="w-72 rounded-lg border border-border bg-background text-foreground shadow-lg z-50 overflow-hidden"
role="menu"
>
{/* Account List */}
<div className="py-1 max-h-64 overflow-y-auto">
{accounts.map((account) => {
const isActive = account.id === activeAccountId;
return (
<button
key={account.id}
onClick={() => handleSwitch(account.id)}
className={cn(
"w-full flex items-start gap-3 px-3 py-2.5 text-left transition-colors",
isActive ? "bg-accent/50" : "hover:bg-muted"
)}
role="menuitem"
disabled={isActive}
>
<div className="relative flex-shrink-0">
<AccountAvatar account={account} size="md" />
{isActive && (
<div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full bg-primary flex items-center justify-center">
<Check className="w-2.5 h-2.5 text-primary-foreground" />
</div>
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1">
<span className="text-sm font-medium truncate">
{account.displayName || account.label}
</span>
{account.isDefault && (
<Star className="w-3 h-3 text-amber-500 flex-shrink-0 fill-amber-500" />
)}
</div>
<p className="text-xs text-muted-foreground truncate">
{account.email || account.username}
</p>
<div className="flex items-center gap-1 mt-0.5">
{account.hasError ? (
<AlertCircle className="w-3 h-3 text-destructive" />
) : (
<span className={cn(
"w-1.5 h-1.5 rounded-full",
account.isConnected ? "bg-green-500" : "bg-muted-foreground/40"
)} />
)}
<span className="text-[10px] text-muted-foreground truncate">
{new URL(account.serverUrl).hostname}
</span>
</div>
</div>
</button>
);
})}
</div>
{/* Separator + Add Account */}
{accounts.length < MAX_ACCOUNTS && (
<div className="border-t border-border">
<button
onClick={handleAddAccount}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
role="menuitem"
>
<Plus className="w-4 h-4" />
{t("add_account")}
</button>
</div>
)}
{/* Separator + Actions */}
<div className="border-t border-border">
{activeAccount && !activeAccount.isDefault && accounts.length > 1 && (
<button
onClick={() => handleSetDefault(activeAccount.id)}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
role="menuitem"
>
<Star className="w-4 h-4" />
{t("set_as_default")}
</button>
)}
<button
onClick={handleLogout}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-muted transition-colors"
role="menuitem"
>
<LogOut className="w-4 h-4" />
{t("sign_out_of", { account: displayEmail })}
</button>
{accounts.length > 1 && (
<button
onClick={handleLogoutAll}
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-destructive hover:bg-muted transition-colors"
role="menuitem"
>
<LogOut className="w-4 h-4" />
{t("sign_out_all")}
</button>
)}
</div>
</div>,
document.body
)}
</>
);
}
+25 -19
View File
@@ -3,6 +3,7 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { Mail, Calendar, BookUser, HardDrive, Settings, LogOut, Keyboard, Plus } from "lucide-react";
import { AccountSwitcher } from "./account-switcher";
import { icons as lucideIcons, type LucideIcon } from "lucide-react";
import { usePathname, Link } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
@@ -216,8 +217,8 @@ export function NavigationRail({
);
})}
{/* Custom sidebar apps */}
{sidebarApps.map((app) => {
{/* Custom sidebar apps (per-app mobile visibility) */}
{sidebarApps.filter((app) => app.showOnMobile).map((app) => {
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
const isActive = activeAppId === app.id;
return (
@@ -251,16 +252,27 @@ export function NavigationRail({
);
})}
{/* Manage apps button */}
{onManageApps && (
<button
onClick={onManageApps}
className="flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px] transition-colors duration-150 text-muted-foreground hover:text-foreground"
>
<Plus className="w-5 h-5" />
<span className="text-[10px] font-medium leading-tight">{t("add_app")}</span>
</button>
)}
{/* Settings */}
<Link
href="/settings"
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
className={cn(
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
"transition-colors duration-150",
isSettingsActive
? "text-primary"
: "text-muted-foreground hover:text-foreground"
)}
aria-current={isSettingsActive ? "page" : undefined}
>
<div className="relative">
<Settings className="w-5 h-5" />
{isSettingsActive && (
<span className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-4 h-0.5 rounded-full bg-primary" />
)}
</div>
<span className="text-[10px] font-medium leading-tight">{t("settings")}</span>
</Link>
</nav>
);
}
@@ -432,13 +444,7 @@ export function NavigationRail({
)}
{onLogout && (
<button
onClick={onLogout}
className="flex items-center justify-center w-10 h-10 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
title={t("sign_out")}
>
<LogOut className="w-[18px] h-[18px]" />
</button>
<AccountSwitcher variant="rail" />
)}
</div>
</div>
+3 -9
View File
@@ -39,6 +39,7 @@ import { toast } from "@/stores/toast-store";
import { debug } from "@/lib/debug";
import { useConfig } from "@/hooks/use-config";
import { useThemeStore } from "@/stores/theme-store";
import { AccountSwitcher } from "./account-switcher";
interface SidebarProps {
mailboxes: Mailbox[];
@@ -485,15 +486,8 @@ export function Sidebar({
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
</Button>
{!isCollapsed && primaryIdentity && (
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate" title={primaryIdentity.name}>
{primaryIdentity.name}
</p>
<p className="text-xs text-muted-foreground truncate" title={primaryIdentity.email}>
{primaryIdentity.email}
</p>
</div>
{!isCollapsed && (
<AccountSwitcher variant="expanded" className="flex-1" />
)}
</div>
@@ -153,6 +153,9 @@ export function CalendarManagementSettings() {
const { client, serverUrl, username } = useAuthStore();
const { calendars, updateCalendar, createCalendar, removeCalendar, clearCalendarEvents, fetchCalendars, icalSubscriptions, removeICalSubscription, refreshICalSubscription, isSubscriptionCalendar } = useCalendarStore();
const [discoveredCalDavUrls, setDiscoveredCalDavUrls] = useState<Record<string, string | null>>({});
const [wellKnownCalDavUrl, setWellKnownCalDavUrl] = useState<string | null>(null);
const [isCreating, setIsCreating] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
@@ -175,6 +178,60 @@ export function CalendarManagementSettings() {
}
}, [client, calendars.length, fetchCalendars]);
useEffect(() => {
if (!client || !serverUrl || !username) {
setDiscoveredCalDavUrls({});
setWellKnownCalDavUrl(null);
return;
}
const primaryKey = username;
const accounts = new Map<string, string[]>();
accounts.set(primaryKey, [username]);
for (const calendar of calendars) {
if (!calendar.isShared) continue;
const key = calendar.accountId || calendar.accountName || calendar.id;
const candidates = accounts.get(key) || [];
if (calendar.accountId) candidates.push(calendar.accountId);
if (calendar.accountName) candidates.push(calendar.accountName);
accounts.set(key, candidates);
}
const controller = new AbortController();
fetch('/api/caldav/discover', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
accounts: Array.from(accounts.entries()).map(([key, candidates]) => ({ key, candidates })),
}),
signal: controller.signal,
})
.then(async (response) => {
if (!response.ok) throw new Error(`CalDAV discovery failed: ${response.status}`);
return response.json() as Promise<{
wellKnownUrl?: string;
accounts?: Record<string, { url: string | null }>;
}>;
})
.then((payload) => {
setWellKnownCalDavUrl(payload.wellKnownUrl || null);
const next: Record<string, string | null> = {};
for (const [key, value] of Object.entries(payload.accounts || {})) {
next[key] = value?.url || null;
}
setDiscoveredCalDavUrls(next);
})
.catch(() => {
const fallbackWellKnown = new URL('/.well-known/caldav', serverUrl).toString();
setDiscoveredCalDavUrls({});
setWellKnownCalDavUrl(fallbackWellKnown);
});
return () => controller.abort();
}, [client, calendars, serverUrl, username]);
const handleRefreshSubscription = async (subId: string) => {
if (!client) return;
setRefreshingSubId(subId);
@@ -295,8 +352,10 @@ export function CalendarManagementSettings() {
const buildCalDavUrl = (calendarId: string) => {
if (!serverUrl || !username) return null;
const base = serverUrl.replace(/\/$/, '');
return `${base}/dav/calendars/user/${encodeURIComponent(username)}/${encodeURIComponent(calendarId)}/`;
const calendar = calendars.find((entry) => entry.id === calendarId);
if (!calendar) return null;
const accountKey = calendar.isShared ? (calendar.accountId || calendar.accountName || calendar.id) : username;
return discoveredCalDavUrls[accountKey] || wellKnownCalDavUrl;
};
const handleCopyUrl = async (url: string) => {
+11
View File
@@ -14,6 +14,7 @@ export function CalendarSettings() {
const {
timeFormat,
firstDayOfWeek,
showTimeInMonthView,
calendarNotificationsEnabled,
calendarNotificationSound,
calendarInvitationParsingEnabled,
@@ -57,6 +58,16 @@ export function CalendarSettings() {
/>
</SettingItem>
<SettingItem
label={t('show_time_in_month_view')}
description={t('show_time_in_month_view_desc')}
>
<ToggleSwitch
checked={showTimeInMonthView}
onChange={(checked) => updateSetting('showTimeInMonthView', checked)}
/>
</SettingItem>
<SettingItem
label={t('notifications_enabled')}
description={t('notifications_enabled_desc')}
+12
View File
@@ -24,6 +24,7 @@ export function EmailSettings() {
emailsPerPage,
externalContentPolicy,
mailAttachmentAction,
attachmentPosition,
emailAlwaysLightMode,
archiveMode,
trustedSenders,
@@ -195,6 +196,17 @@ export function EmailSettings() {
/>
</SettingItem>
<SettingItem label={t('attachment_position.label')} description={t('attachment_position.description')}>
<Select
value={attachmentPosition}
onChange={(value) => updateSetting('attachmentPosition', value as 'beside-sender' | 'below-header')}
options={[
{ value: 'beside-sender', label: t('attachment_position.beside-sender') },
{ value: 'below-header', label: t('attachment_position.below-header') },
]}
/>
</SettingItem>
{/* Emails Per Page */}
<SettingItem label={t('emails_per_page.label')} description={t('emails_per_page.description')}>
<Select
+28 -15
View File
@@ -490,21 +490,34 @@ export function FolderSettings() {
{/* Standard Folder Roles — advanced section */}
<SettingsSection title={t('standard_roles')} description={t('standard_roles_description')}>
{STANDARD_ROLES.map((role) => (
<SettingItem key={role} label={t(`role_${role}`)}>
<Select
value={getRoleMailboxId(role)}
onChange={(value) => handleRoleChange(role, value)}
options={[
{ value: '', label: t('role_none') },
...ownMailboxes.map(mb => ({
value: mb.id,
label: mb.name,
})),
]}
/>
</SettingItem>
))}
{STANDARD_ROLES.map((role) => {
// Disambiguate duplicate folder names by appending parent path
const nameCounts = new Map<string, number>();
ownMailboxes.forEach(mb => nameCounts.set(mb.name, (nameCounts.get(mb.name) || 0) + 1));
const getParentPath = (mb: { parentId?: string; name: string }) => {
if (!mb.parentId) return '';
const parent = ownMailboxes.find(p => p.id === mb.parentId);
return parent ? `${parent.name}/` : '';
};
return (
<SettingItem key={role} label={t(`role_${role}`)}>
<Select
value={getRoleMailboxId(role)}
onChange={(value) => handleRoleChange(role, value)}
options={[
{ value: '', label: t('role_none') },
...ownMailboxes.map(mb => ({
value: mb.id,
label: (nameCounts.get(mb.name) || 0) > 1
? `${getParentPath(mb)}${mb.name} (${mb.id.slice(-6)})`
: mb.name,
})),
]}
/>
</SettingItem>
);
})}
</SettingsSection>
</div>
);
@@ -18,6 +18,7 @@ interface SidebarAppFormData {
url: string;
icon: string;
openMode: "tab" | "inline";
showOnMobile: boolean;
}
function AppForm({
@@ -37,6 +38,7 @@ function AppForm({
url: app?.url || "",
icon: app?.icon || "Globe",
openMode: app?.openMode || "tab",
showOnMobile: app?.showOnMobile ?? false,
});
const [errors, setErrors] = useState<Record<string, string>>({});
@@ -144,6 +146,25 @@ function AppForm({
</div>
</div>
<div className="flex items-center justify-between">
<label className="text-sm font-medium">{t("show_on_mobile")}</label>
<button
type="button"
onClick={() => setFormData({ ...formData, showOnMobile: !formData.showOnMobile })}
className={cn(
"relative inline-flex h-5 w-9 items-center rounded-full transition-colors",
formData.showOnMobile ? "bg-primary" : "bg-muted-foreground/30"
)}
>
<span
className={cn(
"inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",
formData.showOnMobile ? "translate-x-4.5" : "translate-x-0.5"
)}
/>
</button>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
{t("cancel")}
+9 -5
View File
@@ -28,15 +28,18 @@ export default [
},
plugins: {
"@typescript-eslint": tseslint,
"react": reactPlugin,
react: reactPlugin,
"react-hooks": reactHooksPlugin,
},
rules: {
...tseslint.configs.recommended.rules,
"@typescript-eslint/no-unused-vars": ["warn", {
argsIgnorePattern: "^_",
varsIgnorePattern: "^_"
}],
"@typescript-eslint/no-unused-vars": [
"warn",
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
},
],
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-empty-object-type": "off",
"react-hooks/rules-of-hooks": "error",
@@ -70,6 +73,7 @@ export default [
"*.config.js",
"*.config.mjs",
"e2e/**",
"local-data/**/*.mjs",
],
},
];
+98
View File
@@ -0,0 +1,98 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const loggerError = vi.fn();
vi.mock('next/server', () => ({
NextResponse: {
json: (data: unknown, init?: { status?: number; headers?: unknown }) => ({
status: init?.status ?? 200,
headers: init?.headers,
json: async () => data,
}),
},
}));
vi.mock('@/lib/logger', () => ({
logger: {
error: loggerError,
},
}));
describe('health route', () => {
beforeEach(() => {
vi.restoreAllMocks();
loggerError.mockReset();
});
it('returns healthy for the basic liveness probe even when heap usage is high', async () => {
vi.spyOn(process, 'memoryUsage').mockReturnValue({
rss: 120_000_000,
heapTotal: 45_000_000,
heapUsed: 43_000_000,
external: 8_000_000,
arrayBuffers: 1_000_000,
});
const { GET } = await import('@/app/api/health/route');
const response = await GET({ nextUrl: new URL('http://localhost/api/health') } as never);
const payload = await response.json();
expect(response.status).toBe(200);
expect(payload).toMatchObject({
status: 'healthy',
});
expect(payload.warnings).toBeUndefined();
});
it('returns degraded diagnostics in detailed mode without failing the probe', async () => {
vi.spyOn(process, 'memoryUsage').mockReturnValue({
rss: 120_000_000,
heapTotal: 4_100_000_000,
heapUsed: 4_000_000_000,
external: 8_000_000,
arrayBuffers: 1_000_000,
});
vi.spyOn(process, 'uptime').mockReturnValue(123.45);
const { GET } = await import('@/app/api/health/route');
const response = await GET({ nextUrl: new URL('http://localhost/api/health?detailed=true') } as never);
const payload = await response.json();
expect(response.status).toBe(200);
expect(payload.status).toBe('degraded');
expect(payload.memory).toMatchObject({
heapUsed: 4_000_000_000,
heapTotal: 4_100_000_000,
rss: 120_000_000,
external: 8_000_000,
});
expect(payload.memory.heapSizeLimit).toBeGreaterThan(0);
expect(payload.warnings).toEqual([
expect.stringContaining('V8 heap usage is high'),
]);
});
it('keeps HEAD as a stable liveness probe', async () => {
const { HEAD } = await import('@/app/api/health/route');
const response = await HEAD();
expect(response.status).toBe(200);
});
it('returns 503 when collecting health diagnostics throws', async () => {
vi.spyOn(process, 'memoryUsage').mockImplementation(() => {
throw new Error('boom');
});
const { GET } = await import('@/app/api/health/route');
const response = await GET({ nextUrl: new URL('http://localhost/api/health') } as never);
const payload = await response.json();
expect(response.status).toBe(503);
expect(payload).toMatchObject({
status: 'unhealthy',
reason: 'boom',
});
expect(loggerError).toHaveBeenCalledWith('Health check failed', { error: 'boom' });
});
});
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest';
import {
appendPlainTextSignature,
getPlainTextSignature,
hasMeaningfulHtmlBody,
} from '../signature-utils';
describe('signature-utils', () => {
describe('getPlainTextSignature', () => {
it('prefers text signatures when present', () => {
expect(getPlainTextSignature({ textSignature: 'Regards,\nAlice', htmlSignature: '<p>Ignored</p>' })).toBe('Regards,\nAlice');
});
it('converts html-only signatures into plain text', () => {
expect(getPlainTextSignature({ htmlSignature: '<p>Alice Example<br><a href="mailto:alice@example.com">alice@example.com</a></p>' })).toBe('Alice Example\nalice@example.com');
});
});
describe('appendPlainTextSignature', () => {
it('appends a converted html signature to the text body', () => {
expect(appendPlainTextSignature('Hello there', { htmlSignature: '<p>Alice<br>Engineering</p>' })).toBe('Hello there\n\n-- \nAlice\nEngineering');
});
it('leaves the body untouched when no signature exists', () => {
expect(appendPlainTextSignature('Hello there', {})).toBe('Hello there');
});
});
describe('hasMeaningfulHtmlBody', () => {
it('prefers html bodies that preserve signature formatting', () => {
expect(hasMeaningfulHtmlBody('<div>Hello</div><br><p>Alice</p>')).toBe(true);
});
it('ignores minimal wrapper html with a single block', () => {
expect(hasMeaningfulHtmlBody('<div>Hello world</div>')).toBe(false);
});
});
});
+130
View File
@@ -0,0 +1,130 @@
/**
* Manages per-account state snapshots for fast switching.
* When user switches from Account A B, we snapshot A's store state
* into memory, clear stores, then restore B's cached state.
*/
import { useEmailStore } from '@/stores/email-store';
import { useContactStore } from '@/stores/contact-store';
import { useCalendarStore } from '@/stores/calendar-store';
import { useFilterStore } from '@/stores/filter-store';
import { DEFAULT_SEARCH_FILTERS } from '@/lib/jmap/search-utils';
import { useIdentityStore } from '@/stores/identity-store';
import { useVacationStore } from '@/stores/vacation-store';
// Minimal snapshot shapes — we only capture what we need
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type StoreSnapshot = Record<string, any>;
interface AccountSnapshot {
email: StoreSnapshot;
contact: StoreSnapshot;
calendar: StoreSnapshot;
filter: StoreSnapshot;
identity: StoreSnapshot;
vacation: StoreSnapshot;
}
const cache = new Map<string, AccountSnapshot>();
/** Capture current store states for the given account */
export function snapshotAccount(accountId: string): void {
const emailState = useEmailStore.getState();
const contactState = useContactStore.getState();
const calendarState = useCalendarStore.getState();
const filterState = useFilterStore.getState();
const identityState = useIdentityStore.getState();
const vacationState = useVacationStore.getState();
cache.set(accountId, {
email: {
emails: emailState.emails,
mailboxes: emailState.mailboxes,
selectedEmail: emailState.selectedEmail,
selectedMailbox: emailState.selectedMailbox,
searchQuery: emailState.searchQuery,
quota: emailState.quota,
},
contact: {
contacts: contactState.contacts,
addressBooks: contactState.addressBooks,
supportsSync: contactState.supportsSync,
},
calendar: {
calendars: calendarState.calendars,
events: calendarState.events,
selectedCalendarIds: calendarState.selectedCalendarIds,
viewMode: calendarState.viewMode,
supportsCalendar: calendarState.supportsCalendar,
},
filter: {
rules: filterState.rules,
isSupported: filterState.isSupported,
},
identity: {
identities: identityState.identities,
preferredPrimaryId: identityState.preferredPrimaryId,
},
vacation: {
isEnabled: vacationState.isEnabled,
isSupported: vacationState.isSupported,
},
});
}
/** Restore cached store states for the given account. Returns false if no cache exists. */
export function restoreAccount(accountId: string): boolean {
const snapshot = cache.get(accountId);
if (!snapshot) return false;
useEmailStore.setState(snapshot.email);
useContactStore.setState(snapshot.contact);
useCalendarStore.setState(snapshot.calendar);
useFilterStore.setState(snapshot.filter);
useIdentityStore.setState(snapshot.identity);
useVacationStore.setState(snapshot.vacation);
return true;
}
/** Clear all stores (used before restoring a different account) */
export function clearAllStores(): void {
useEmailStore.setState({
emails: [],
mailboxes: [],
selectedEmail: null,
selectedMailbox: '',
isLoading: false,
error: null,
searchQuery: '',
quota: null,
isPushConnected: false,
lastPushUpdate: null,
newEmailNotification: null,
selectedEmailIds: new Set<string>(),
hasMoreEmails: false,
totalEmails: 0,
expandedThreadIds: new Set<string>(),
threadEmailsCache: new Map(),
isLoadingThread: null,
selectedKeyword: null,
tagCounts: {},
searchFilters: { ...DEFAULT_SEARCH_FILTERS },
isAdvancedSearchOpen: false,
});
useIdentityStore.getState().clearIdentities();
useContactStore.getState().clearContacts();
useVacationStore.getState().clearState();
useCalendarStore.getState().clearState();
useFilterStore.getState().clearState();
}
/** Evict cached state for one account */
export function evictAccount(accountId: string): void {
cache.delete(accountId);
}
/** Evict all cached states */
export function evictAll(): void {
cache.clear();
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Utilities for multi-account support:
* - Account ID generation
* - Deterministic avatar colors
* - Account-scoped localStorage keys
*/
/** Generate a unique, deterministic account ID from username and server URL */
export function generateAccountId(username: string, serverUrl: string): string {
const host = new URL(serverUrl).hostname;
return `${username}@${host}`;
}
/** Deterministic avatar/accent color from an email string */
export function generateAvatarColor(email: string): string {
let hash = 0;
for (let i = 0; i < email.length; i++) {
hash = ((hash << 5) - hash + email.charCodeAt(i)) | 0;
}
// 12 distinct, accessible hues
const colors = [
'#2563eb', // blue
'#7c3aed', // violet
'#db2777', // pink
'#dc2626', // red
'#ea580c', // orange
'#d97706', // amber
'#65a30d', // lime
'#16a34a', // green
'#0d9488', // teal
'#0891b2', // cyan
'#6366f1', // indigo
'#9333ea', // purple
];
return colors[Math.abs(hash) % colors.length];
}
/** Get initials for an avatar from a display name or email */
export function getInitials(name: string, email?: string): string {
if (name) {
const parts = name.trim().split(/\s+/);
if (parts.length >= 2) {
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
return parts[0][0]?.toUpperCase() ?? '?';
}
if (email) {
return email[0]?.toUpperCase() ?? '?';
}
return '?';
}
/** Build an account-scoped localStorage key */
export function getAccountScopedKey(baseKey: string, accountId: string): string {
return `${baseKey}::${accountId}`;
}
/** Maximum number of accounts allowed */
export const MAX_ACCOUNTS = 5;
+5
View File
@@ -1,2 +1,7 @@
export const SESSION_COOKIE = 'jmap_session';
export const SESSION_COOKIE_MAX_AGE = 30 * 24 * 60 * 60;
/** Get the cookie name for a given account slot (0-4). Slot 0 uses the legacy name. */
export function sessionCookieName(slot: number): string {
return slot === 0 ? SESSION_COOKIE : `${SESSION_COOKIE}_${slot}`;
}
+7
View File
@@ -0,0 +1,7 @@
export function replaceWindowLocation(url: string): void {
if (typeof window === 'undefined') {
return;
}
window.location.replace(url);
}
+4
View File
@@ -142,3 +142,7 @@ export function formatSnapTime(minutes: number, timeFormat: "12h" | "24h"): stri
}
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
}
export function getPrimaryCalendarId(event: Pick<CalendarEvent, 'calendarIds'>): string | undefined {
return Object.keys(event.calendarIds || {})[0];
}
+74 -36
View File
@@ -2066,6 +2066,11 @@ export class JMAPClient {
return coreCapability?.maxCallsInRequest || 50;
}
getMaxObjectsInGet(): number {
const coreCapability = this.capabilities["urn:ietf:params:jmap:core"] as { maxObjectsInGet?: number } | undefined;
return coreCapability?.maxObjectsInGet || 500;
}
getEventSourceUrl(): string | null {
if (!this.session) return null;
@@ -2428,26 +2433,62 @@ export class JMAPClient {
}
}
async getContacts(addressBookId?: string): Promise<ContactCard[]> {
try {
const accountId = this.getContactsAccountId();
const queryArgs: Record<string, unknown> = { accountId, limit: 1000 };
if (addressBookId) {
queryArgs.filter = { inAddressBook: addressBookId };
private async fetchPaginatedContacts(
accountId: string,
filter?: Record<string, unknown>,
): Promise<ContactCard[]> {
const batchSize = this.getMaxObjectsInGet();
const allIds: string[] = [];
let position = 0;
// Paginate ContactCard/query to collect all IDs
for (;;) {
const queryArgs: Record<string, unknown> = { accountId, position, limit: batchSize };
if (filter) {
queryArgs.filter = filter;
}
const response = await this.request([
["ContactCard/query", queryArgs, "0"],
["ContactCard/get", {
accountId,
"#ids": { resultOf: "0", name: "ContactCard/query", path: "/ids" },
}, "1"],
["ContactCard/query", queryArgs, "q"],
], this.contactUsing());
if (response.methodResponses?.[1]?.[0] === "ContactCard/get") {
return (response.methodResponses[1][1].list || []) as ContactCard[];
const queryResult = response.methodResponses?.[0];
if (queryResult?.[0] !== "ContactCard/query") break;
const ids: string[] = queryResult[1].ids || [];
allIds.push(...ids);
const total: number = queryResult[1].total ?? -1;
if (ids.length < batchSize || (total > 0 && allIds.length >= total)) {
break;
}
return [];
position += ids.length;
}
if (allIds.length === 0) return [];
// Batch ContactCard/get to respect maxObjectsInGet
const allContacts: ContactCard[] = [];
for (let i = 0; i < allIds.length; i += batchSize) {
const chunk = allIds.slice(i, i + batchSize);
const response = await this.request([
["ContactCard/get", { accountId, ids: chunk }, "g"],
], this.contactUsing());
if (response.methodResponses?.[0]?.[0] === "ContactCard/get") {
const list = (response.methodResponses[0][1].list || []) as ContactCard[];
allContacts.push(...list);
}
}
return allContacts;
}
async getContacts(addressBookId?: string): Promise<ContactCard[]> {
try {
const accountId = this.getContactsAccountId();
const filter = addressBookId ? { inAddressBook: addressBookId } : undefined;
return await this.fetchPaginatedContacts(accountId, filter);
} catch (error) {
console.error('Failed to get contacts:', error);
return [];
@@ -2465,26 +2506,19 @@ export class JMAPClient {
const account = this.accounts[accountId];
try {
const response = await this.request([
["ContactCard/query", { accountId, limit: 1000 }, "0"],
["ContactCard/get", {
accountId,
"#ids": { resultOf: "0", name: "ContactCard/query", path: "/ids" },
}, "1"],
], this.contactUsing());
if (response.methodResponses?.[1]?.[0] === "ContactCard/get") {
const rawContacts = (response.methodResponses[1][1].list || []) as ContactCard[];
const contacts = rawContacts.map((contact) => ({
...contact,
id: isPrimary ? contact.id : `${accountId}:${contact.id}`,
originalId: contact.id,
accountId,
accountName: account?.name || (isPrimary ? this.username : accountId),
isShared: !isPrimary,
}));
allContacts.push(...contacts);
}
const rawContacts = await this.fetchPaginatedContacts(accountId);
const contacts = rawContacts.map((contact) => ({
...contact,
id: isPrimary ? contact.id : `${accountId}:${contact.id}`,
originalId: contact.id,
addressBookIds: isPrimary ? contact.addressBookIds : (contact.addressBookIds ? Object.fromEntries(
Object.entries(contact.addressBookIds).map(([bookId, v]) => [`${accountId}:${bookId}`, v])
) : contact.addressBookIds),
accountId,
accountName: account?.name || (isPrimary ? this.username : accountId),
isShared: !isPrimary,
}));
allContacts.push(...contacts);
} catch (error) {
console.error(`Failed to fetch contacts for account ${accountId}:`, error);
}
@@ -2851,8 +2885,8 @@ export class JMAPClient {
id: isPrimary ? event.id : `${accountId}:${event.id}`,
originalId: event.id,
originalCalendarIds: event.calendarIds,
calendarIds: isPrimary ? event.calendarIds : Object.fromEntries(
Object.entries(event.calendarIds).map(([calId, v]) => [`${accountId}:${calId}`, v])
calendarIds: isPrimary ? (event.calendarIds || {}) : Object.fromEntries(
Object.entries(event.calendarIds || {}).map(([calId, v]) => [`${accountId}:${calId}`, v])
),
accountId,
accountName: account?.name || (isPrimary ? this.username : accountId),
@@ -2885,6 +2919,10 @@ export class JMAPClient {
filter,
limit: limit || 1000,
};
// Expand recurring events into individual occurrences when a date range is provided
if (filter.after || filter.before) {
queryArgs.expandRecurrences = true;
}
if (sort) {
queryArgs.sort = sort;
}
+32 -1
View File
@@ -252,7 +252,20 @@ export interface ContactTitle {
organizationId?: string;
}
// RFC 9553 AddressComponent
export interface AddressComponent {
kind: 'room' | 'apartment' | 'floor' | 'building' | 'number' | 'name' | 'block' | 'subDistrict' | 'district' | 'locality' | 'region' | 'postcode' | 'country' | 'direction' | 'landmark' | 'postOfficeBox' | 'separator' | string;
value: string;
phonetic?: string;
}
export interface ContactAddress {
// RFC 9553 format
components?: AddressComponent[];
full?: string;
isOrdered?: boolean;
defaultSeparator?: string;
// Legacy flat fields (from vCard import)
street?: string;
locality?: string;
region?: string;
@@ -284,9 +297,27 @@ export interface ContactMedia {
mediaType?: string;
}
// RFC 9553 PartialDate
export interface PartialDate {
'@type'?: 'PartialDate';
year?: number;
month?: number;
day?: number;
calendarScale?: string;
}
// RFC 9553 Timestamp
export interface Timestamp {
'@type': 'Timestamp';
utc: string;
}
export type AnniversaryDate = string | PartialDate | Timestamp;
export interface ContactAnniversary {
'@type'?: 'Anniversary';
kind: 'birth' | 'death' | 'wedding' | 'other';
date: string;
date: AnniversaryDate;
place?: ContactAddress;
}
+5
View File
@@ -1,2 +1,7 @@
export const OAUTH_SCOPES = 'openid email profile';
export const REFRESH_TOKEN_COOKIE = 'jmap_rt';
/** Get the cookie name for a given account slot (0-4). Slot 0 uses the legacy name. */
export function refreshTokenCookieName(slot: number): string {
return slot === 0 ? REFRESH_TOKEN_COOKIE : `${REFRESH_TOKEN_COOKIE}_${slot}`;
}
+5 -2
View File
@@ -1,5 +1,5 @@
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
import { readFile, writeFile, unlink, mkdir } from 'node:fs/promises';
import { readFile, writeFile, unlink, mkdir, rename } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { logger } from '@/lib/logger';
@@ -45,7 +45,10 @@ export async function saveUserSettings(username: string, serverUrl: string, sett
const tag = cipher.getAuthTag();
const data = Buffer.concat([iv, tag, encrypted]);
await writeFile(getSettingsPath(username, serverUrl), data);
const targetPath = getSettingsPath(username, serverUrl);
const tmpPath = targetPath + '.tmp';
await writeFile(tmpPath, data);
await rename(tmpPath, targetPath);
}
export async function loadUserSettings(username: string, serverUrl: string): Promise<Record<string, unknown> | null> {
+158
View File
@@ -0,0 +1,158 @@
import { parseHtmlSafely, sanitizeSignatureHtml } from '@/lib/email-sanitization';
type SignatureSource = {
textSignature?: string;
htmlSignature?: string;
};
const BLOCK_TAGS = new Set([
'address',
'article',
'aside',
'blockquote',
'div',
'footer',
'header',
'li',
'nav',
'p',
'section',
'tr',
]);
function normalizeSignatureLineBreaks(value: string): string {
return value
.replace(/\r\n?/g, '\n')
.replace(/\u00a0/g, ' ')
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function htmlToPlainText(html: string): string {
const document = parseHtmlSafely(html);
const chunks: string[] = [];
const appendText = (value: string) => {
if (!value) return;
const normalized = value.replace(/\s+/g, ' ');
if (!normalized.trim()) return;
const previous = chunks[chunks.length - 1];
if (previous && !previous.endsWith('\n') && !previous.endsWith(' ')) {
chunks.push(' ');
}
chunks.push(normalized);
};
const appendNewline = () => {
const previous = chunks[chunks.length - 1];
if (previous === '\n') return;
if (previous?.endsWith('\n')) return;
chunks.push('\n');
};
const walk = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
appendText(node.textContent || '');
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
const element = node as HTMLElement;
const tagName = element.tagName.toLowerCase();
if (tagName === 'br') {
appendNewline();
return;
}
if (tagName === 'a') {
const text = element.textContent?.replace(/\s+/g, ' ').trim() || '';
const href = element.getAttribute('href')?.trim() || '';
const normalizedHref = href.replace(/^mailto:/i, '');
if (text && normalizedHref && text === normalizedHref) {
appendText(text);
return;
}
if (text && href && text !== href) {
appendText(`${text} <${href}>`);
return;
}
}
if (BLOCK_TAGS.has(tagName) && chunks.length > 0) {
appendNewline();
}
Array.from(element.childNodes).forEach(walk);
if (BLOCK_TAGS.has(tagName)) {
appendNewline();
}
};
Array.from(document.body.childNodes).forEach(walk);
return normalizeSignatureLineBreaks(chunks.join(''));
}
export function getPlainTextSignature(signature?: SignatureSource | null): string {
if (signature?.textSignature?.trim()) {
return normalizeSignatureLineBreaks(signature.textSignature);
}
if (signature?.htmlSignature?.trim()) {
return htmlToPlainText(sanitizeSignatureHtml(signature.htmlSignature));
}
return '';
}
export function appendPlainTextSignature(body: string, signature?: SignatureSource | null): string {
const plainTextSignature = getPlainTextSignature(signature);
if (!plainTextSignature) {
return body;
}
return `${body}\n\n-- \n${plainTextSignature}`;
}
export function hasMeaningfulHtmlBody(html: string): boolean {
if (!html.trim()) return false;
const document = parseHtmlSafely(html);
const richSelector = [
'table',
'img',
'style',
'b',
'strong',
'i',
'em',
'u',
'font',
'a[href]',
'div[style]',
'span[style]',
'p[style]',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'ul',
'ol',
'blockquote',
'br',
].join(', ');
if (document.querySelector(richSelector)) {
return true;
}
const blockElements = document.body.querySelectorAll('p, div, blockquote, li');
return blockElements.length > 1;
}
+10 -6
View File
@@ -97,17 +97,19 @@ const ROLE_PRIORITY: Record<string, number> = {
// Deduplicate mailboxes (e.g., "Sent" vs "Sent Mail")
function deduplicateMailboxes(mailboxes: Mailbox[]): Mailbox[] {
const roleMap = new Map<string, Mailbox>();
const result: Mailbox[] = [];
// First pass: collect mailboxes with roles
// Group role mailboxes by account so deduplication is scoped per-account
const rolesByAccount = new Map<string, Mailbox[]>();
mailboxes.forEach(mb => {
if (mb.role) {
roleMap.set(mb.role, mb);
const key = mb.accountId || '';
if (!rolesByAccount.has(key)) rolesByAccount.set(key, []);
rolesByAccount.get(key)!.push(mb);
}
});
// Second pass: filter out duplicates
// Filter out duplicates scoped to the same account
mailboxes.forEach(mb => {
// If this mailbox has a role, always keep it
if (mb.role) {
@@ -115,9 +117,11 @@ function deduplicateMailboxes(mailboxes: Mailbox[]): Mailbox[] {
return;
}
// Check if this is a duplicate of a role-based mailbox
// Check if this is a duplicate of a role-based mailbox in the SAME account
const accountKey = mb.accountId || '';
const accountRoles = rolesByAccount.get(accountKey) || [];
const lowerName = mb.name.toLowerCase();
const isDuplicate = Array.from(roleMap.values()).some(roleMb => {
const isDuplicate = accountRoles.some(roleMb => {
const roleLowerName = roleMb.name.toLowerCase();
// Check for common duplicates: "Sent Mail" vs "Sent", etc.
return lowerName.includes(roleLowerName) || roleLowerName.includes(lowerName);
+48 -9
View File
@@ -1,4 +1,26 @@
import type { ContactCard, NameComponent, ContactMedia, ContactOnlineService } from "@/lib/jmap/types";
import type { ContactCard, NameComponent, ContactMedia, ContactOnlineService, AnniversaryDate, PartialDate } from "@/lib/jmap/types";
// Convert RFC 9553 AnniversaryDate (PartialDate|Timestamp|string) to vCard date string
function anniversaryDateToVcardString(date: AnniversaryDate): string {
if (typeof date === 'string') return date;
if (date && typeof date === 'object') {
if ('@type' in date && date['@type'] === 'Timestamp' && 'utc' in date) {
return (date as { utc: string }).utc.split('T')[0];
}
const pd = date as PartialDate;
if (pd.year && pd.month && pd.day) {
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
}
if (pd.month && pd.day) {
return `--${String(pd.month).padStart(2, '0')}-${String(pd.day).padStart(2, '0')}`;
}
if (pd.year && pd.month) {
return `${String(pd.year).padStart(4, '0')}-${String(pd.month).padStart(2, '0')}`;
}
if (pd.year) return String(pd.year);
}
return String(date);
}
const VCARD_SEX_TO_GENDER: Record<string, string> = {
M: "masculine",
@@ -598,14 +620,30 @@ function generateSingleVCard(contact: ContactCard): string {
for (const addr of Object.values(contact.addresses)) {
const type = contextToType(addr.contexts);
const typeParam = type ? `;TYPE=${type}` : "";
let street = addr.street || "";
let locality = addr.locality || "";
let region = addr.region || "";
let postcode = addr.postcode || "";
let country = addr.country || "";
// RFC 9553 components-based address: extract flat fields for vCard ADR
if (addr.components && addr.components.length > 0) {
const findComp = (kind: string) => addr.components!.filter(c => c.kind === kind).map(c => c.value).join(' ');
const number = findComp('number');
const name = findComp('name');
street = street || [number, name].filter(Boolean).join(' ');
locality = locality || findComp('locality');
region = region || findComp('region');
postcode = postcode || findComp('postcode');
country = country || findComp('country');
}
const parts = [
"",
"",
addr.street || "",
addr.locality || "",
addr.region || "",
addr.postcode || "",
addr.country || "",
street,
locality,
region,
postcode,
country,
];
lines.push(`ADR${typeParam}:${parts.map(encodeValue).join(";")}`);
}
@@ -613,12 +651,13 @@ function generateSingleVCard(contact: ContactCard): string {
if (contact.anniversaries) {
for (const ann of Object.values(contact.anniversaries)) {
const dateStr = anniversaryDateToVcardString(ann.date);
if (ann.kind === "birth") {
lines.push(`BDAY:${ann.date}`);
lines.push(`BDAY:${dateStr}`);
} else if (ann.kind === "wedding") {
lines.push(`ANNIVERSARY:${ann.date}`);
lines.push(`ANNIVERSARY:${dateStr}`);
} else if (ann.kind === "death") {
lines.push(`DEATHDATE:${ann.date}`);
lines.push(`DEATHDATE:${dateStr}`);
}
}
}
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "Schließen",
"or": "oder",
"sign_in_sso": "Mit SSO anmelden",
"add_account_title": "Konto hinzufügen",
"add_account_subtitle": "Mit einem anderen Konto anmelden",
"cancel": "Abbrechen",
"website": "Webseite",
"imprint": "Impressum",
"privacy_policy": "Datenschutz",
@@ -58,6 +61,11 @@
"storage_free": "Frei",
"storage_total": "Gesamt",
"sign_out": "Abmelden",
"sign_out_of": "Von {account} abmelden",
"sign_out_all": "Von allen Konten abmelden",
"add_account": "Konto hinzufügen",
"set_as_default": "Als Standard festlegen",
"switch_account": "Konto wechseln",
"contacts": "Kontakte",
"calendar": "Kalender",
"settings": "Einstellungen",
@@ -202,6 +210,7 @@
"attachments": "Anhänge",
"important": "Wichtig",
"download": "Herunterladen",
"download_all": "Alle herunterladen",
"from": "Von",
"to": "An",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Zurück",
"next": "Weiter",
"send": "Senden"
"send": "Senden",
"more": "mehr"
},
"email_composer": {
"new_message": "Neue Nachricht",
@@ -745,6 +755,12 @@
"preview": "Wenn möglich in Vorschau öffnen",
"download": "Sofort herunterladen"
},
"attachment_position": {
"label": "Anhangsposition",
"description": "Wo Anhänge im E-Mail-Header angezeigt werden",
"beside-sender": "Neben dem Absender",
"below-header": "Unter dem Header"
},
"emails_per_page": {
"25": "25 E-Mails",
"50": "50 E-Mails",
@@ -1473,11 +1489,12 @@
"title": "Geteilt"
},
"address_books": {
"title": "Verzeichnisse",
"title": "Meine Adressbücher",
"shared_prefix": "Geteilt: {name}",
"moved": "Kontakt verschoben nach {name}",
"moved_plural": "{count} Kontakte verschoben nach {name}",
"move_failed": "Kontakt konnte nicht verschoben werden",
"address_book": "Verzeichnis"
"address_book": "Adressbuch"
},
"detail": {
"emails": "E-Mail-Adressen",
@@ -1938,6 +1955,12 @@
"deleted": "Abonnement entfernt",
"delete_error": "Abonnement konnte nicht entfernt werden",
"last_refreshed": "Zuletzt aktualisiert: {time}"
},
"tasks": {
"no_tasks": "Keine Aufgaben",
"no_title": "(Kein Titel)",
"mark_complete": "Als erledigt markieren",
"mark_incomplete": "Als unerledigt markieren"
}
},
"advanced_search": {
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "Dismiss",
"or": "or",
"sign_in_sso": "Sign in with SSO",
"add_account_title": "Add Account",
"add_account_subtitle": "Sign in with another account",
"cancel": "Cancel",
"website": "Website",
"imprint": "Imprint",
"privacy_policy": "Privacy Policy",
@@ -58,6 +61,11 @@
"storage_free": "Free",
"storage_total": "Total",
"sign_out": "Sign out",
"sign_out_of": "Sign out of {account}",
"sign_out_all": "Sign out of all accounts",
"add_account": "Add account",
"set_as_default": "Set as default",
"switch_account": "Switch account",
"contacts": "Contacts",
"calendar": "Calendar",
"settings": "Settings",
@@ -202,6 +210,7 @@
"attachments": "Attachments",
"important": "Important",
"download": "Download",
"download_all": "Download all",
"from": "From",
"to": "To",
"cc": "CC",
@@ -393,7 +402,8 @@
"event_status_tentative": "Tentative",
"event_status_cancelled": "Cancelled"
},
"send": "Send"
"send": "Send",
"more": "more"
},
"email_composer": {
"new_message": "New Message",
@@ -745,6 +755,12 @@
"preview": "Preview when possible",
"download": "Download immediately"
},
"attachment_position": {
"label": "Attachment Position",
"description": "Where to display attachments in the email header",
"beside-sender": "Next to sender",
"below-header": "Below header"
},
"emails_per_page": {
"25": "25 emails",
"50": "50 emails",
@@ -1473,11 +1489,12 @@
"title": "Shared"
},
"address_books": {
"title": "Directories",
"title": "My Address Books",
"shared_prefix": "Shared: {name}",
"moved": "Contact moved to {name}",
"moved_plural": "{count} contacts moved to {name}",
"move_failed": "Failed to move contact",
"address_book": "Directory"
"address_book": "Address Book"
},
"detail": {
"emails": "Email Addresses",
@@ -1938,6 +1955,12 @@
"deleted": "Subscription removed",
"delete_error": "Failed to remove subscription",
"last_refreshed": "Last updated: {time}"
},
"tasks": {
"no_tasks": "No tasks",
"no_title": "(No title)",
"mark_complete": "Mark as complete",
"mark_incomplete": "Mark as incomplete"
}
},
"advanced_search": {
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "Cerrar",
"or": "o",
"sign_in_sso": "Iniciar sesión con SSO",
"add_account_title": "Agregar cuenta",
"add_account_subtitle": "Iniciar sesión con otra cuenta",
"cancel": "Cancelar",
"website": "Sitio web",
"imprint": "Aviso legal",
"privacy_policy": "Política de privacidad",
@@ -58,6 +61,11 @@
"storage_free": "Libre",
"storage_total": "Total",
"sign_out": "Cerrar sesión",
"sign_out_of": "Cerrar sesión de {account}",
"sign_out_all": "Cerrar sesión de todas las cuentas",
"add_account": "Agregar cuenta",
"set_as_default": "Establecer como predeterminada",
"switch_account": "Cambiar cuenta",
"contacts": "Contactos",
"calendar": "Calendario",
"settings": "Configuración",
@@ -202,6 +210,7 @@
"attachments": "Archivos adjuntos",
"important": "Importante",
"download": "Descargar",
"download_all": "Descargar todo",
"from": "De",
"to": "Para",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Anterior",
"next": "Siguiente",
"send": "Enviar"
"send": "Enviar",
"more": "más"
},
"email_composer": {
"new_message": "Nuevo Mensaje",
@@ -745,6 +755,12 @@
"preview": "Mostrar vista previa cuando sea posible",
"download": "Descargar inmediatamente"
},
"attachment_position": {
"label": "Posición del adjunto",
"description": "Dónde mostrar los adjuntos en el encabezado del correo",
"beside-sender": "Junto al remitente",
"below-header": "Debajo del encabezado"
},
"emails_per_page": {
"25": "25 correos",
"50": "50 correos",
@@ -1473,11 +1489,12 @@
"title": "Compartidos"
},
"address_books": {
"title": "Directorios",
"title": "Mis Libretas de Direcciones",
"shared_prefix": "Compartido: {name}",
"moved": "Contacto movido a {name}",
"moved_plural": "{count} contactos movidos a {name}",
"move_failed": "Error al mover el contacto",
"address_book": "Directorio"
"address_book": "Libreta de direcciones"
},
"detail": {
"emails": "Direcciones de correo",
@@ -1938,6 +1955,12 @@
"deleted": "Suscripción eliminada",
"delete_error": "No se pudo eliminar la suscripción",
"last_refreshed": "Última actualización: {time}"
},
"tasks": {
"no_tasks": "Sin tareas",
"no_title": "(Sin título)",
"mark_complete": "Marcar como completada",
"mark_incomplete": "Marcar como incompleta"
}
},
"advanced_search": {
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "Fermer",
"or": "ou",
"sign_in_sso": "Se connecter avec SSO",
"add_account_title": "Ajouter un compte",
"add_account_subtitle": "Se connecter avec un autre compte",
"cancel": "Annuler",
"website": "Site web",
"imprint": "Mentions légales",
"privacy_policy": "Politique de confidentialité",
@@ -58,6 +61,11 @@
"storage_free": "Libre",
"storage_total": "Total",
"sign_out": "Se déconnecter",
"sign_out_of": "Se déconnecter de {account}",
"sign_out_all": "Se déconnecter de tous les comptes",
"add_account": "Ajouter un compte",
"set_as_default": "Définir par défaut",
"switch_account": "Changer de compte",
"contacts": "Contacts",
"calendar": "Calendrier",
"settings": "Paramètres",
@@ -202,6 +210,7 @@
"attachments": "Pièces jointes",
"important": "Important",
"download": "Télécharger",
"download_all": "Tout télécharger",
"from": "De",
"to": "À",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Précédent",
"next": "Suivant",
"send": "Envoyer"
"send": "Envoyer",
"more": "plus"
},
"email_composer": {
"new_message": "Nouveau message",
@@ -745,6 +755,12 @@
"preview": "Aperçu si possible",
"download": "Télécharger immédiatement"
},
"attachment_position": {
"label": "Position des pièces jointes",
"description": "Où afficher les pièces jointes dans l'en-tête de l'email",
"beside-sender": "À côté de l'expéditeur",
"below-header": "Sous l'en-tête"
},
"emails_per_page": {
"25": "25 emails",
"50": "50 emails",
@@ -1473,11 +1489,12 @@
"title": "Partagés"
},
"address_books": {
"title": "Répertoires",
"title": "Mes Carnets d'adresses",
"shared_prefix": "Partagé : {name}",
"moved": "Contact déplacé vers {name}",
"moved_plural": "{count} contacts déplacés vers {name}",
"move_failed": "Échec du déplacement du contact",
"address_book": "Répertoire"
"address_book": "Carnet d'adresses"
},
"detail": {
"emails": "Adresses e-mail",
@@ -1938,6 +1955,12 @@
"deleted": "Abonnement supprimé",
"delete_error": "Impossible de supprimer l'abonnement",
"last_refreshed": "Dernière mise à jour : {time}"
},
"tasks": {
"no_tasks": "Aucune tâche",
"no_title": "(Sans titre)",
"mark_complete": "Marquer comme terminée",
"mark_incomplete": "Marquer comme non terminée"
}
},
"advanced_search": {
+25 -2
View File
@@ -34,6 +34,9 @@
"dismiss": "Chiudi",
"or": "o",
"sign_in_sso": "Accedi con SSO",
"add_account_title": "Aggiungi account",
"add_account_subtitle": "Accedi con un altro account",
"cancel": "Annulla",
"website": "Sito web",
"imprint": "Note legali",
"privacy_policy": "Informativa sulla privacy",
@@ -58,6 +61,11 @@
"storage_free": "Libero",
"storage_total": "Totale",
"sign_out": "Esci",
"sign_out_of": "Disconnetti da {account}",
"sign_out_all": "Disconnetti da tutti gli account",
"add_account": "Aggiungi account",
"set_as_default": "Imposta come predefinito",
"switch_account": "Cambia account",
"contacts": "Contatti",
"calendar": "Calendario",
"settings": "Impostazioni",
@@ -202,6 +210,7 @@
"attachments": "Allegati",
"important": "Importante",
"download": "Scarica",
"download_all": "Scarica tutto",
"from": "Da",
"to": "A",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Precedente",
"next": "Successivo",
"send": "Invia"
"send": "Invia",
"more": "altri"
},
"email_composer": {
"new_message": "Nuovo messaggio",
@@ -745,6 +755,12 @@
"preview": "Anteprima quando possibile",
"download": "Scarica immediatamente"
},
"attachment_position": {
"label": "Posizione degli allegati",
"description": "Dove visualizzare gli allegati nell'intestazione dell'email",
"beside-sender": "Accanto al mittente",
"below-header": "Sotto l'intestazione"
},
"emails_per_page": {
"25": "25 messaggi",
"50": "50 messaggi",
@@ -1473,7 +1489,8 @@
"title": "Condivisi"
},
"address_books": {
"title": "Rubriche",
"title": "Le mie Rubriche",
"shared_prefix": "Condiviso: {name}",
"moved": "Contatto spostato in {name}",
"moved_plural": "{count} contatti spostati in {name}",
"move_failed": "Impossibile spostare il contatto",
@@ -1938,6 +1955,12 @@
"deleted": "Abbonamento rimosso",
"delete_error": "Impossibile rimuovere l'abbonamento",
"last_refreshed": "Ultimo aggiornamento: {time}"
},
"tasks": {
"no_tasks": "Nessuna attività",
"no_title": "(Senza titolo)",
"mark_complete": "Segna come completata",
"mark_incomplete": "Segna come non completata"
}
},
"advanced_search": {
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "閉じる",
"or": "または",
"sign_in_sso": "SSOでサインイン",
"add_account_title": "アカウントを追加",
"add_account_subtitle": "別のアカウントでサインイン",
"cancel": "キャンセル",
"website": "ウェブサイト",
"imprint": "サイト運営者情報",
"privacy_policy": "プライバシーポリシー",
@@ -58,6 +61,11 @@
"storage_free": "空き",
"storage_total": "合計",
"sign_out": "サインアウト",
"sign_out_of": "{account} からサインアウト",
"sign_out_all": "すべてのアカウントからサインアウト",
"add_account": "アカウントを追加",
"set_as_default": "デフォルトに設定",
"switch_account": "アカウントを切り替え",
"contacts": "連絡先",
"calendar": "カレンダー",
"settings": "設定",
@@ -202,6 +210,7 @@
"attachments": "添付ファイル",
"important": "重要",
"download": "ダウンロード",
"download_all": "すべてダウンロード",
"from": "送信者",
"to": "宛先",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "前へ",
"next": "次へ",
"send": "送信"
"send": "送信",
"more": "他"
},
"email_composer": {
"new_message": "新規メッセージ",
@@ -745,6 +755,12 @@
"preview": "可能ならプレビューを開く",
"download": "すぐにダウンロード"
},
"attachment_position": {
"label": "添付ファイルの位置",
"description": "メールヘッダー内での添付ファイルの表示位置",
"beside-sender": "送信者の横",
"below-header": "ヘッダーの下"
},
"emails_per_page": {
"25": "25件",
"50": "50件",
@@ -1473,11 +1489,12 @@
"title": "共有"
},
"address_books": {
"title": "ディレクトリ",
"title": "マイアドレス帳",
"shared_prefix": "共有: {name}",
"moved": "連絡先を {name} に移動しました",
"moved_plural": "{count} 件の連絡先を {name} に移動しました",
"move_failed": "連絡先の移動に失敗しました",
"address_book": "ディレクトリ"
"address_book": "アドレス帳"
},
"detail": {
"emails": "メールアドレス",
@@ -1938,6 +1955,12 @@
"deleted": "購読を解除しました",
"delete_error": "購読の解除に失敗しました",
"last_refreshed": "最終更新: {time}"
},
"tasks": {
"no_tasks": "タスクなし",
"no_title": "(タイトルなし)",
"mark_complete": "完了にする",
"mark_incomplete": "未完了にする"
}
},
"advanced_search": {
+25 -2
View File
@@ -34,6 +34,9 @@
"dismiss": "Sluiten",
"or": "of",
"sign_in_sso": "Inloggen met SSO",
"add_account_title": "Account toevoegen",
"add_account_subtitle": "Inloggen met een ander account",
"cancel": "Annuleren",
"website": "Website",
"imprint": "Colofon",
"privacy_policy": "Privacybeleid",
@@ -58,6 +61,11 @@
"storage_free": "Vrij",
"storage_total": "Totaal",
"sign_out": "Afmelden",
"sign_out_of": "Uitloggen van {account}",
"sign_out_all": "Uitloggen van alle accounts",
"add_account": "Account toevoegen",
"set_as_default": "Als standaard instellen",
"switch_account": "Account wisselen",
"contacts": "Contacten",
"calendar": "Agenda",
"settings": "Instellingen",
@@ -202,6 +210,7 @@
"attachments": "Bijlagen",
"important": "Belangrijk",
"download": "Downloaden",
"download_all": "Alles downloaden",
"from": "Van",
"to": "Aan",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Vorige",
"next": "Volgende",
"send": "Verzenden"
"send": "Verzenden",
"more": "meer"
},
"email_composer": {
"new_message": "Nieuw bericht",
@@ -745,6 +755,12 @@
"preview": "Voorbeeld tonen indien mogelijk",
"download": "Direct downloaden"
},
"attachment_position": {
"label": "Positie van bijlagen",
"description": "Waar bijlagen in de e-mailkop worden weergegeven",
"beside-sender": "Naast de afzender",
"below-header": "Onder de kop"
},
"emails_per_page": {
"25": "25 e-mails",
"50": "50 e-mails",
@@ -1473,7 +1489,8 @@
"title": "Gedeeld"
},
"address_books": {
"title": "Adresboeken",
"title": "Mijn Adresboeken",
"shared_prefix": "Gedeeld: {name}",
"moved": "Contact verplaatst naar {name}",
"moved_plural": "{count} contacten verplaatst naar {name}",
"move_failed": "Verplaatsen van contact mislukt",
@@ -1938,6 +1955,12 @@
"deleted": "Abonnement verwijderd",
"delete_error": "Kan abonnement niet verwijderen",
"last_refreshed": "Laatst bijgewerkt: {time}"
},
"tasks": {
"no_tasks": "Geen taken",
"no_title": "(Geen titel)",
"mark_complete": "Markeren als voltooid",
"mark_incomplete": "Markeren als onvoltooid"
}
},
"advanced_search": {
+26 -3
View File
@@ -34,6 +34,9 @@
"dismiss": "Fechar",
"or": "ou",
"sign_in_sso": "Entrar com SSO",
"add_account_title": "Adicionar conta",
"add_account_subtitle": "Entrar com outra conta",
"cancel": "Cancelar",
"website": "Site",
"imprint": "Informações legais",
"privacy_policy": "Política de privacidade",
@@ -58,6 +61,11 @@
"storage_free": "Livre",
"storage_total": "Total",
"sign_out": "Sair",
"sign_out_of": "Sair de {account}",
"sign_out_all": "Sair de todas as contas",
"add_account": "Adicionar conta",
"set_as_default": "Definir como padrão",
"switch_account": "Trocar conta",
"contacts": "Contatos",
"calendar": "Calendário",
"settings": "Configurações",
@@ -202,6 +210,7 @@
"attachments": "Anexos",
"important": "Importante",
"download": "Baixar",
"download_all": "Baixar tudo",
"from": "De",
"to": "Para",
"cc": "CC",
@@ -393,7 +402,8 @@
},
"previous": "Anterior",
"next": "Próximo",
"send": "Enviar"
"send": "Enviar",
"more": "mais"
},
"email_composer": {
"new_message": "Nova Mensagem",
@@ -745,6 +755,12 @@
"preview": "Visualizar quando possível",
"download": "Baixar imediatamente"
},
"attachment_position": {
"label": "Posição dos anexos",
"description": "Onde exibir os anexos no cabeçalho do e-mail",
"beside-sender": "Ao lado do remetente",
"below-header": "Abaixo do cabeçalho"
},
"emails_per_page": {
"25": "25 e-mails",
"50": "50 e-mails",
@@ -1473,11 +1489,12 @@
"title": "Compartilhados"
},
"address_books": {
"title": "Diretórios",
"title": "Meus Catálogos de Endereços",
"shared_prefix": "Compartilhado: {name}",
"moved": "Contato movido para {name}",
"moved_plural": "{count} contatos movidos para {name}",
"move_failed": "Falha ao mover o contato",
"address_book": "Diretório"
"address_book": "Catálogo de endereços"
},
"detail": {
"emails": "Endereços de e-mail",
@@ -1938,6 +1955,12 @@
"deleted": "Assinatura removida",
"delete_error": "Falha ao remover assinatura",
"last_refreshed": "Última atualização: {time}"
},
"tasks": {
"no_tasks": "Sem tarefas",
"no_title": "(Sem título)",
"mark_complete": "Marcar como concluída",
"mark_incomplete": "Marcar como não concluída"
}
},
"advanced_search": {
+5 -5
View File
@@ -1,12 +1,12 @@
{
"name": "bulwark-webmail",
"version": "1.4.2",
"version": "1.4.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bulwark-webmail",
"version": "1.4.2",
"version": "1.4.4",
"license": "AGPL-3.0-only",
"dependencies": {
"@tanstack/react-virtual": "^3.13.18",
@@ -5480,9 +5480,9 @@
}
},
"node_modules/flatted": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz",
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
"version": "3.4.2",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
"dev": true,
"license": "ISC"
},
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bulwark-webmail",
"version": "1.4.2",
"version": "1.4.5",
"description": "Bulwark Webmail — a modern webmail client built for Stalwart Mail Server",
"author": "Bulwark Webmail <bulwark@rbm.systems>",
"license": "AGPL-3.0-only",
@@ -77,6 +77,7 @@
},
"overrides": {
"elliptic": "^6.6.1",
"flatted": "^3.4.2",
"undici": "^7.24.0"
}
}
@@ -0,0 +1,97 @@
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import * as browserNavigation from '@/lib/browser-navigation';
import { useAuthStore } from '../auth-store';
import { useAccountStore } from '../account-store';
type FetchInput = Parameters<typeof fetch>[0];
type FetchInit = Parameters<typeof fetch>[1];
describe('auth-store logout redirects', () => {
beforeEach(() => {
vi.restoreAllMocks();
sessionStorage.clear();
localStorage.clear();
window.history.pushState({}, '', '/en');
useAccountStore.setState({
accounts: [],
activeAccountId: null,
defaultAccountId: null,
});
useAuthStore.setState({
isAuthenticated: false,
isLoading: false,
error: null,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
activeAccountId: null,
});
});
afterEach(() => {
vi.useRealTimers();
});
it('redirects full logout to the locale login page', () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
vi.stubGlobal('fetch', fetchMock);
const replaceSpy = vi.spyOn(browserNavigation, 'replaceWindowLocation').mockImplementation(() => {});
window.history.pushState({}, '', '/fr/calendar');
useAuthStore.setState({ isAuthenticated: true, authMode: 'basic' });
useAuthStore.getState().logout();
expect(replaceSpy).toHaveBeenCalledWith('/fr/login');
expect(fetchMock).toHaveBeenCalledWith('/api/auth/session?slot=0', { method: 'DELETE', keepalive: true });
});
it('marks session expiry, preserves the current path, and redirects to login on refresh failure', async () => {
vi.useFakeTimers();
const fetchMock = vi.fn(async (input: FetchInput, init?: FetchInit) => {
const url = String(input);
const method = init?.method ?? 'GET';
if (url === '/api/auth/token?slot=0' && method === 'PUT') {
return { ok: false, json: async () => ({}) };
}
if (url === '/api/auth/token?slot=0' && method === 'DELETE') {
return { ok: true, json: async () => ({}) };
}
if (url === '/api/auth/session?slot=0' && method === 'DELETE') {
return { ok: true, json: async () => ({}) };
}
throw new Error(`Unexpected fetch call: ${method} ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
const replaceSpy = vi.spyOn(browserNavigation, 'replaceWindowLocation').mockImplementation(() => {});
window.history.pushState({}, '', '/en/calendar?view=day');
useAuthStore.setState({
isAuthenticated: true,
authMode: 'oauth',
activeAccountId: null,
});
await useAuthStore.getState().refreshAccessToken();
await vi.runAllTimersAsync();
expect(sessionStorage.getItem('session_expired')).toBe('true');
expect(sessionStorage.getItem('redirect_after_login')).toBe('/en/calendar?view=day');
expect(replaceSpy).toHaveBeenCalledWith('/en/login');
});
});
@@ -226,6 +226,34 @@ describe('email-store folder management', () => {
expect(client.updateMailbox).toHaveBeenCalledWith('trash-1', { role: 'trash' });
});
it('should clear role from ALL mailboxes with that role when reassigning', async () => {
// Simulate server anomaly: two mailboxes with role "trash"
const extraTrash = makeMailbox({ id: 'trash-2', name: 'Deleted Items', role: 'trash' });
useEmailStore.setState({
mailboxes: [inbox, sent, trash, custom, extraTrash],
});
const newMailboxes = [inbox, sent, custom,
makeMailbox({ id: 'trash-1', name: 'Trash', role: undefined }),
makeMailbox({ id: 'trash-2', name: 'Deleted Items', role: undefined }),
];
// custom-1 gets the trash role
newMailboxes[2] = { ...newMailboxes[2], role: 'trash' };
const client = makeMockClient({
getAllMailboxes: vi.fn().mockResolvedValue(newMailboxes),
});
await useEmailStore.getState().setMailboxRole(client, 'custom-1', 'trash');
// Should clear trash role from BOTH trash-1 and trash-2
expect(client.updateMailbox).toHaveBeenCalledWith('trash-1', { role: null });
expect(client.updateMailbox).toHaveBeenCalledWith('trash-2', { role: null });
// Then set trash role on custom-1
expect(client.updateMailbox).toHaveBeenCalledWith('custom-1', { role: 'trash' });
expect(client.updateMailbox).toHaveBeenCalledTimes(3);
});
it('should set error on failure', async () => {
const client = makeMockClient({
updateMailbox: vi.fn().mockRejectedValue(new Error('Role update failed')),
+201
View File
@@ -0,0 +1,201 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { generateAccountId, generateAvatarColor, MAX_ACCOUNTS } from '@/lib/account-utils';
export interface AccountEntry {
/** Unique key: `${username}@${serverHostname}` */
id: string;
/** Display label (defaults to email, user-editable) */
label: string;
/** Full server URL */
serverUrl: string;
/** Username / email used to authenticate */
username: string;
/** Authentication mode */
authMode: 'basic' | 'oauth';
/** Cookie slot index (04) for session/token cookies */
cookieSlot: number;
/** Whether "Remember Me" was checked (basic auth only) */
rememberMe: boolean;
/** Cached display info */
displayName: string;
email: string;
avatarColor: string;
/** Timestamp of last successful login */
lastLoginAt: number;
/** Whether this account is currently connected */
isConnected: boolean;
/** Whether this account had a connection error */
hasError: boolean;
errorMessage?: string;
/** Whether this is the default account (loaded on app start) */
isDefault: boolean;
}
interface AccountState {
accounts: AccountEntry[];
activeAccountId: string | null;
defaultAccountId: string | null;
addAccount: (entry: Omit<AccountEntry, 'id' | 'cookieSlot' | 'avatarColor'>) => string;
removeAccount: (accountId: string) => void;
setActiveAccount: (accountId: string) => void;
setDefaultAccount: (accountId: string) => void;
getDefaultAccount: () => AccountEntry | null;
updateAccount: (accountId: string, updates: Partial<AccountEntry>) => void;
getActiveAccount: () => AccountEntry | null;
getAccountById: (accountId: string) => AccountEntry | undefined;
getNextCookieSlot: () => number;
hasAccount: (username: string, serverUrl: string) => boolean;
}
export const useAccountStore = create<AccountState>()(
persist(
(set, get) => ({
accounts: [],
activeAccountId: null,
defaultAccountId: null,
addAccount: (entry) => {
const state = get();
const id = generateAccountId(entry.username, entry.serverUrl);
if (state.accounts.some((a) => a.id === id)) {
// Already exists — update mutable fields and return existing id
set((s) => ({
accounts: s.accounts.map((a) =>
a.id === id
? {
...a,
rememberMe: entry.rememberMe,
isConnected: entry.isConnected,
hasError: entry.hasError,
errorMessage: undefined,
lastLoginAt: entry.lastLoginAt,
authMode: entry.authMode,
}
: a
),
}));
return id;
}
if (state.accounts.length >= MAX_ACCOUNTS) {
throw new Error(`Maximum of ${MAX_ACCOUNTS} accounts reached`);
}
const cookieSlot = state.getNextCookieSlot();
const avatarColor = generateAvatarColor(entry.email || entry.username);
const isDefault = state.accounts.length === 0; // first account is default
const account: AccountEntry = {
...entry,
id,
cookieSlot,
avatarColor,
isDefault,
};
set((s) => ({
accounts: [...s.accounts, account],
// If there is no active account, activate this one
activeAccountId: s.activeAccountId ?? id,
defaultAccountId: isDefault ? id : s.defaultAccountId,
}));
return id;
},
removeAccount: (accountId) => {
set((s) => {
const remaining = s.accounts.filter((a) => a.id !== accountId);
const wasDefault = s.defaultAccountId === accountId;
const wasActive = s.activeAccountId === accountId;
let newDefault = s.defaultAccountId;
if (wasDefault) {
newDefault = remaining[0]?.id ?? null;
// Mark new default
if (newDefault) {
const idx = remaining.findIndex((a) => a.id === newDefault);
if (idx >= 0) {
remaining[idx] = { ...remaining[idx], isDefault: true };
}
}
}
return {
accounts: remaining,
activeAccountId: wasActive ? (remaining[0]?.id ?? null) : s.activeAccountId,
defaultAccountId: newDefault,
};
});
},
setActiveAccount: (accountId) => {
const account = get().accounts.find((a) => a.id === accountId);
if (!account) return;
set({ activeAccountId: accountId });
},
setDefaultAccount: (accountId) => {
const account = get().accounts.find((a) => a.id === accountId);
if (!account) return;
set((s) => ({
defaultAccountId: accountId,
accounts: s.accounts.map((a) => ({
...a,
isDefault: a.id === accountId,
})),
}));
},
getDefaultAccount: () => {
const state = get();
if (state.defaultAccountId) {
const account = state.accounts.find((a) => a.id === state.defaultAccountId);
if (account) return account;
}
return state.accounts[0] ?? null;
},
updateAccount: (accountId, updates) => {
set((s) => ({
accounts: s.accounts.map((a) =>
a.id === accountId ? { ...a, ...updates } : a
),
}));
},
getActiveAccount: () => {
const state = get();
return state.accounts.find((a) => a.id === state.activeAccountId) ?? null;
},
getAccountById: (accountId) => {
return get().accounts.find((a) => a.id === accountId);
},
getNextCookieSlot: () => {
const used = new Set(get().accounts.map((a) => a.cookieSlot));
for (let i = 0; i < MAX_ACCOUNTS; i++) {
if (!used.has(i)) return i;
}
return 0; // fallback, shouldn't happen if max is enforced
},
hasAccount: (username, serverUrl) => {
const id = generateAccountId(username, serverUrl);
return get().accounts.some((a) => a.id === id);
},
}),
{
name: 'account-registry',
partialize: (state) => ({
accounts: state.accounts,
activeAccountId: state.activeAccountId,
defaultAccountId: state.defaultAccountId,
}),
}
)
);
+767 -83
View File
File diff suppressed because it is too large Load Diff
+4 -18
View File
@@ -110,10 +110,12 @@ export const useCalendarStore = create<CalendarStore>()(
fetchEvents: async (client, start, end) => {
set({ isLoadingEvents: true, error: null });
try {
const events = await client.queryAllCalendarEvents({
const rawEvents = await client.queryAllCalendarEvents({
after: start,
before: end,
});
// Filter out malformed events missing required 'start' field
const events = rawEvents.filter(e => typeof e.start === 'string' && e.start);
set({ events, isLoadingEvents: false, dateRange: { start, end } });
} catch (error) {
debug.error('Failed to fetch events:', error);
@@ -142,13 +144,6 @@ export const useCalendarStore = create<CalendarStore>()(
}
const created = await client.createCalendarEvent(cleanEvent, sendSchedulingMessages, targetAccountId);
set((state) => ({ events: [...state.events, created] }));
if (sendSchedulingMessages && created.participants) {
try {
await client.sendImipInvitation(created);
} catch (e) {
debug.error('Failed to send invitation emails:', e);
}
}
return created;
} catch (error) {
debug.error('Failed to create event:', error);
@@ -178,16 +173,6 @@ export const useCalendarStore = create<CalendarStore>()(
set((state) => ({
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
}));
if (sendSchedulingMessages) {
try {
const updatedEvent = await client.getCalendarEvent(realId, targetAccountId);
if (updatedEvent?.participants) {
await client.sendImipInvitation(updatedEvent);
}
} catch (e) {
debug.error('Failed to send update notification emails:', e);
}
}
} catch (error) {
debug.error('Failed to update event:', error);
set({ error: 'Failed to update event' });
@@ -672,6 +657,7 @@ export const useCalendarStore = create<CalendarStore>()(
return {
...mergedState,
selectedDate: new Date(),
viewMode: getSafeCalendarViewMode(mergedState.viewMode),
};
},
+64 -17
View File
@@ -87,7 +87,39 @@ interface ContactStore {
export const useContactStore = create<ContactStore>()(
persist(
(set, get) => ({
(set, get) => {
// Clean group member references when contacts are removed
function cleanGroupMembers(contacts: ContactCard[], removedIds: Set<string>): ContactCard[] {
// Collect uid/id variants of removed contacts for matching
const removedKeys = new Set<string>();
for (const c of contacts) {
if (!removedIds.has(c.id)) continue;
removedKeys.add(c.id);
if (c.uid) {
removedKeys.add(c.uid);
const bare = c.uid.startsWith('urn:uuid:') ? c.uid.slice(9) : c.uid;
removedKeys.add(bare);
}
if (c.originalId) removedKeys.add(c.originalId);
}
return contacts.map(c => {
if (c.kind !== 'group' || !c.members) return c;
let changed = false;
const newMembers: Record<string, boolean> = {};
for (const [key, val] of Object.entries(c.members)) {
const bareKey = key.startsWith('urn:uuid:') ? key.slice(9) : key;
if (removedKeys.has(key) || removedKeys.has(bareKey)) {
changed = true;
} else {
newMembers[key] = val;
}
}
return changed ? { ...c, members: newMembers } : c;
});
}
return ({
contacts: [],
addressBooks: [],
selectedContactId: null,
@@ -170,10 +202,14 @@ export const useContactStore = create<ContactStore>()(
const originalId = contact?.originalId || id;
const accountId = contact?.isShared ? contact.accountId : undefined;
await client.deleteContact(originalId, accountId);
set((state) => ({
contacts: state.contacts.filter(c => c.id !== id),
selectedContactId: state.selectedContactId === id ? null : state.selectedContactId,
}));
set((state) => {
const removedIds = new Set([id]);
const cleaned = cleanGroupMembers(state.contacts, removedIds);
return {
contacts: cleaned.filter(c => c.id !== id),
selectedContactId: state.selectedContactId === id ? null : state.selectedContactId,
};
});
} catch (error) {
const msg = error instanceof Error ? error.message : 'Failed to delete contact';
set({ error: msg });
@@ -191,10 +227,14 @@ export const useContactStore = create<ContactStore>()(
),
})),
deleteLocalContact: (id) => set((state) => ({
contacts: state.contacts.filter(c => c.id !== id),
selectedContactId: state.selectedContactId === id ? null : state.selectedContactId,
})),
deleteLocalContact: (id) => set((state) => {
const removedIds = new Set([id]);
const cleaned = cleanGroupMembers(state.contacts, removedIds);
return {
contacts: cleaned.filter(c => c.id !== id),
selectedContactId: state.selectedContactId === id ? null : state.selectedContactId,
};
}),
setSelectedContact: (id) => set({ selectedContactId: id }),
setSearchQuery: (query) => set({ searchQuery: query }),
@@ -456,11 +496,14 @@ export const useContactStore = create<ContactStore>()(
}
}
set((state) => ({
contacts: state.contacts.filter(c => !deletedIds.has(c.id)),
selectedContactId: deletedIds.has(state.selectedContactId || '') ? null : state.selectedContactId,
selectedContactIds: new Set<string>(),
}));
set((state) => {
const cleaned = cleanGroupMembers(state.contacts, deletedIds);
return {
contacts: cleaned.filter(c => !deletedIds.has(c.id)),
selectedContactId: deletedIds.has(state.selectedContactId || '') ? null : state.selectedContactId,
selectedContactIds: new Set<string>(),
};
});
},
bulkAddToGroup: async (client, groupId, contactIds) => {
@@ -485,9 +528,11 @@ export const useContactStore = create<ContactStore>()(
// Same account: just update the addressBookIds
if ((sourceAccountId || primaryAccountId) === (targetAccountId || primaryAccountId)) {
await client.updateContact(originalId, { addressBookIds: { [targetBookOriginalId]: true } }, sourceAccountId);
const isTargetPrimary = !targetAccountId || targetAccountId === primaryAccountId;
const localBookId = isTargetPrimary ? targetBookOriginalId : `${targetAccountId}:${targetBookOriginalId}`;
set((state) => ({
contacts: state.contacts.map(c =>
c.id === id ? { ...c, addressBookIds: { [targetBookOriginalId]: true } } : c
c.id === id ? { ...c, addressBookIds: { [localBookId]: true } } : c
),
}));
} else {
@@ -501,6 +546,7 @@ export const useContactStore = create<ContactStore>()(
// Update local state
const isPrimary = !targetAccountId || targetAccountId === primaryAccountId;
const localBookId = isPrimary ? targetBookOriginalId : `${targetAccountId}:${targetBookOriginalId}`;
set((state) => ({
contacts: state.contacts.map(c => {
if (c.id !== id) return c;
@@ -511,7 +557,7 @@ export const useContactStore = create<ContactStore>()(
accountId: targetAccountId,
accountName: addressBook.accountName || targetAccountId,
isShared: !isPrimary,
addressBookIds: { [targetBookOriginalId]: true },
addressBookIds: { [localBookId]: true },
};
}),
}));
@@ -544,7 +590,8 @@ export const useContactStore = create<ContactStore>()(
return imported;
},
}),
});
},
{
name: 'contact-storage',
partialize: (state) => ({
+9 -7
View File
@@ -239,15 +239,17 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
try {
const mailboxes = await client.getAllMailboxes();
// Auto-select inbox if no mailbox is currently selected
// Auto-select inbox if no mailbox is selected or the current selection
// doesn't exist in the fetched list (e.g. after an account switch)
const currentSelectedMailbox = get().selectedMailbox;
if (!currentSelectedMailbox) {
const selectionValid = currentSelectedMailbox && mailboxes.some(m => m.id === currentSelectedMailbox);
if (!selectionValid) {
// Find inbox from PRIMARY account (not shared accounts)
const inboxMailbox = mailboxes.find(m => m.role === 'inbox' && !m.isShared);
if (inboxMailbox) {
set({ mailboxes, selectedMailbox: inboxMailbox.id, isLoading: false });
} else {
set({ mailboxes, isLoading: false });
set({ mailboxes, selectedMailbox: '', isLoading: false });
}
} else {
set({ mailboxes, isLoading: false });
@@ -1298,11 +1300,11 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
setMailboxRole: async (client, mailboxId, role) => {
try {
// If assigning a role, first clear that role from any other mailbox
// If assigning a role, first clear that role from ALL other mailboxes that have it
if (role) {
const existingMailbox = get().mailboxes.find(mb => mb.role === role && !mb.isShared);
if (existingMailbox && existingMailbox.id !== mailboxId) {
await client.updateMailbox(existingMailbox.id, { role: null });
const existingMailboxes = get().mailboxes.filter(mb => mb.role === role && !mb.isShared && mb.id !== mailboxId);
for (const existing of existingMailboxes) {
await client.updateMailbox(existing.id, { role: null });
}
}
await client.updateMailbox(mailboxId, { role });
+27 -15
View File
@@ -29,6 +29,7 @@ export type TimeFormat = '12h' | '24h';
export type FirstDayOfWeek = 0 | 1; // 0 = Sunday, 1 = Monday
export type ExternalContentPolicy = 'ask' | 'block' | 'allow';
export type MailAttachmentAction = 'preview' | 'download';
export type AttachmentPosition = 'beside-sender' | 'below-header';
export type ToolbarPosition = 'top' | 'below-subject';
export type ArchiveMode = 'single' | 'year' | 'month';
@@ -92,6 +93,7 @@ interface SettingsState {
emailsPerPage: number;
externalContentPolicy: ExternalContentPolicy;
mailAttachmentAction: MailAttachmentAction;
attachmentPosition: AttachmentPosition;
emailAlwaysLightMode: boolean; // Always render email content in light mode
archiveMode: ArchiveMode; // How to organize archived emails: single folder, by year, or by year+month
@@ -186,6 +188,7 @@ const DEFAULT_SETTINGS = {
emailsPerPage: 50,
externalContentPolicy: 'ask' as ExternalContentPolicy,
mailAttachmentAction: 'preview' as MailAttachmentAction,
attachmentPosition: 'beside-sender' as AttachmentPosition,
emailAlwaysLightMode: false,
archiveMode: 'single' as ArchiveMode,
@@ -271,6 +274,7 @@ export const useSettingsStore = create<SettingsState>()(
emailsPerPage: state.emailsPerPage,
externalContentPolicy: state.externalContentPolicy,
mailAttachmentAction: state.mailAttachmentAction,
attachmentPosition: state.attachmentPosition,
archiveMode: state.archiveMode,
trustedSenders: state.trustedSenders,
autoSaveDraftInterval: state.autoSaveDraftInterval,
@@ -562,26 +566,34 @@ if (typeof window !== 'undefined') {
applyAnimations(store.animationsEnabled);
// Shared sync function used by all store subscribers
const syncToServer = async (retries = 1): Promise<void> => {
const settings = JSON.parse(useSettingsStore.getState().exportSettings());
syncLog('Syncing settings to server...');
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: syncUsername, serverUrl: syncServerUrl, settings }),
});
if (res.status === 404) {
syncWarn('Settings sync endpoint returned 404, disabling sync');
syncEnabled = false;
} else if (res.status >= 500 && retries > 0) {
syncWarn('Settings sync got server error, retrying...');
await new Promise((r) => setTimeout(r, 2000));
return syncToServer(retries - 1);
} else if (!res.ok) {
syncError('Settings sync failed with status', res.status);
} else {
syncLog('Settings synced to server successfully');
}
};
const triggerSync = () => {
if (!syncEnabled || !syncUsername || !syncServerUrl || isLoadingFromServer) return;
if (syncTimeout) clearTimeout(syncTimeout);
syncTimeout = setTimeout(async () => {
try {
const settings = JSON.parse(useSettingsStore.getState().exportSettings());
syncLog('Syncing settings to server...');
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: syncUsername, serverUrl: syncServerUrl, settings }),
});
if (res.status === 404) {
syncWarn('Settings sync endpoint returned 404, disabling sync');
syncEnabled = false;
} else if (!res.ok) {
syncError('Settings sync failed with status', res.status);
} else {
syncLog('Settings synced to server successfully');
}
await syncToServer();
} catch (error) {
syncError('Settings sync error:', error);
}