Compare commits

...
141 Commits
Author SHA1 Message Date
Linus Rath 97bc26a332 Merge dev into main - version 1.4.8 2026-03-23 17:08:19 +01:00
Linus Rath 55c8d430ca chore: update version to 1.4.8 2026-03-23 16:59:24 +01:00
Linus Rath ef45140d32 fix: enhance account settings with username and authentication method display #90 2026-03-23 16:37:56 +01:00
Linus Rath 0effb97691 refactor: fix bugs in calendar logic across duration parsing, RFC compliance, and event handling
- Fix buildDuration() trailing "T" producing invalid ISO 8601 durations
- Fix DURATION_RE missing week (W) support in alerts and invitation parsing
- Fix computeFireTime() end fallback when utcEnd is missing
- Fix recurrenceOverrides patch escaping per RFC 6901 (updateEvent/rsvpEvent)
- Fix layoutOverlappingEvents endMin overflow past 1440
- Fix addDurationToDate() to support weeks and use UTC methods for UTC inputs
- Fix getEffectiveAlerts() null guard on calendarIds
- Fix buildAllDayDuration() DST-safe day calculation using differenceInCalendarDays
- Fix participant matching to check calendarAddress and sendTo (not just email)
- Fix buildParticipantMap() using crypto.randomUUID() instead of hardcoded IDs
- Fix overnight preview negative endMin in week view
- Fix sendImipInvitation() to emit DURATION when utcEnd is absent
- Fix sendImipCancellation() to validate status before sending
- Fix createEvent() to remap all calendarIds for shared calendars
- Fix getCalendarTasks() to clone before mutating @type
- Fix importEvents() error matching to include 'duplicate' and 'conflict'
- Fix looksLikeReply() false positive by requiring organizer + responded attendee
- Fix alert offset regex to require T before minutes
- Fix handleDuplicate() to generate new UID
- Fix formatSnapTime() input clamping
- Replace console.log/error with debug.log/error/warn in iMIP functions
2026-03-23 16:22:15 +01:00
Linus Rath f7ee204262 feat: add support for marking emails as answered or forwarded and update UI accordingly 2026-03-23 15:45:37 +01:00
Linus Rath 0c1f182b6b fix: detect tasks created by external CalDAV clients (Thunderbird)
Tasks created in Thunderbird via CalDAV were not visible because
getCalendarTasks() used a strict @type === 'Task' check. Stalwart
may not set @type when converting VTODO from CalDAV to JMAP.

- Use case-insensitive @type matching for server variations
- Add fallback heuristic: detect tasks by presence of 'progress'
  property (exclusive to JSCalendar Task, never on Event objects)
- Normalize @type to 'Task' on detected tasks for consistent
  downstream handling
- Refresh task store on CalendarEvent state changes so tasks
  created externally appear without manual page refresh

Fixes #84
2026-03-24 14:54:37 +01:00
Linus Rath 13010c158d feat: implement path prefix handling for OAuth and login redirects 2026-03-24 14:44:42 +01:00
Linus Rath de26e6da2e feat: enhance identity selection by supporting sub-addressing in email options 2026-03-24 14:33:50 +01:00
Linus Rath ddb3422852 feat: add default mail program settings with localization support 2026-03-23 23:07:19 +01:00
Linus RathandGitHub d9a2529261 Update badge links in README.md 2026-03-22 17:25:29 +01:00
Linus RathandGitHub e70224317d Update Discord badge link in README.md 2026-03-22 17:16:10 +01:00
Linus RathandGitHub a9ecf164ab Add Discord badge to README 2026-03-22 17:15:47 +01:00
Linus RathandGitHub 0db3cbc959 Merge pull request #82 from harrytang/feature/new-email-per-page-option
feat: add 10 as an additional Emails Per Page option
2026-03-22 12:39:15 +01:00
Harry Tang 387273288c feat: add 10 as an additional Emails Per Page option 2026-03-22 13:15:23 +02:00
Linus Rath 8eff9fdfab feat: add notification settings with sound picker and preview 2026-03-22 01:55:21 +01:00
Linus Rath d915e5fb64 feat: add all multi-part TLDs for domain validation #81 2026-03-21 21:33:55 +01:00
Linus Rath 5530cfe7fe Merge dev into main - version 1.4.7 2026-03-21 20:46:33 +01:00
Linus Rath 31eee4bab9 chore: bump version to 1.4.7 2026-03-21 20:45:57 +01:00
Linus Rath f04b97d52a fix: handle updates and deletions for synthetic JMAP IDs in calendar events 2026-03-21 20:45:23 +01:00
Linus Rath df272e38ef feat: add resizable image component and rich text editor with image upload support 2026-03-21 20:45:23 +01:00
Linus Rath a835af2d71 fix: update .env.example to clarify Docker volume mounting for settings data directory 2026-03-21 20:45:22 +01:00
Linus Rath 30284859c7 feat: add task management features to calendar 2026-03-21 20:45:22 +01:00
Linus Rath 64c3d7e384 fix: update getContacts test to use mockFetchOnce 2026-03-21 20:45:20 +01:00
Linus Rath e6d09546b1 fix: extend CryptoEngine to support legacy algorithms and integrate with LinerEngine for decryption 2026-03-21 20:45:20 +01:00
Linus Rath 83a0a1e235 feat: add non-interactive SSO login flow for embedded/iframe deployments (closes #69) 2026-03-21 20:45:19 +01:00
Linus Rath 7c3c3b5f7b fix: handle synthetic ID errors when updating calendar events with fallback to destroy and recreate 2026-03-21 20:45:18 +01:00
Linus Rath 8b1b3ad57b fix: update iframe sandbox attributes to allow popups to escape sandbox 2026-03-21 20:45:18 +01:00
Linus Rath afefbb8d46 feat: add expanded visual view for filter rules
- Add VisualRuleSummary component showing conditions and actions as
  labeled inline pills with IF/THEN flow layout
- Add expandedFilterView toggle to settings store (persisted)
- Fix RuleSummary to allow multi-line wrapping instead of truncating
- Use items-start on rule cards so drag handle and toggle align to top
- Add translations for expanded view keys in all 8 locales
2026-03-21 20:45:17 +01:00
Linus Rath 4c2d185be4 fix: refactor logout to use synchronous flow with full page redirect
- Rewrite logout() from async to synchronous to prevent React re-renders with stale state
- Replace router.push('/login') with redirectToLogin() (window.location.replace) in all page auth guards for reliable navigation in Edge/Safari
- Add performFullLogout() helper that clears auth state, feature stores, and localStorage
- Fix persist middleware partialize to return {} when not authenticated, preventing state resurrection
- Use keepalive fetch for background cookie/token cleanup so redirect fires immediately
- Remove unused useRouter imports from page.tsx and contacts/page.tsx
- Simplify all page logout handlers to directly call logout()

Fixes #63
2026-03-21 20:45:17 +01:00
Linus Rath c73940e22a feat: add option to show week numbers in mini-calendar 2026-03-21 20:45:16 +01:00
Linus Rath 09eda86d3f fix: add missing translation keys across all locales 2026-03-21 20:45:15 +01:00
Linus Rath 0d28d811a8 feat: support uploading folders via drag-and-drop and toolbar button 2026-03-21 20:45:14 +01:00
Linus RathandGitHub 45a485a1fa Merge pull request #71 from xnilsit/workflow-on-release
feat: re-add release workflow
2026-03-21 11:20:58 +01:00
xnilsit bc202498d5 feat: re-add release workflow 2026-03-21 11:06:14 +01:00
Linus RathandGitHub 721556e777 Update version badge to 1.4.6 2026-03-21 03:29:43 +01:00
Linus RathandGitHub 8c9cf3a66b Bump app version from 1.4.3 to 1.4.6 2026-03-21 03:29:17 +01:00
Linus Rath b88026de82 Merge dev into main - version 1.4.6 2026-03-21 03:08:47 +01:00
Linus Rath 6ed8ae5812 chore: bump version to 1.4.6 2026-03-21 03:08:19 +01:00
Linus Rath 089583a9ef feat(contacts): add no-category filter, drag-drop to category, and category combo box
- Add 'No Category' sidebar item to filter uncategorized contacts
- Categories section now always visible (not just when keywords exist)
- Add drag-and-drop support on category items in sidebar to assign keywords
- Fix effectAllowed mismatch (move -> copyMove) for category drop targets
- Replace plain text categories input with combo box in contact edit form
  - Shows existing categories as clickable suggestions
  - Displays assigned categories as removable badges
  - Supports adding new categories inline
- Add translations for all 8 locales
2026-03-21 03:04:36 +01:00
Linus Rath 2d834213ee feat: enhance certificate extraction and legacy PBE support in crypto engine 2026-03-21 02:48:12 +01:00
Linus Rath 439a4dbe8a feat: add hover actions for emails and update settings for quick actions 2026-03-21 02:31:42 +01:00
Linus Rath 8350bad2a6 fix: adjust padding and size of sidebar buttons for improved layout 2026-03-21 02:06:52 +01:00
Linus Rath 2d56cc9be9 feat: implement keyword migration functionality and update related components 2026-03-21 01:58:48 +01:00
Linus Rath 2547c10060 feat: add demo data for emails, files, filters, identities, mailboxes, vacation responses, and JMAP client interface
- Created demo emails with various states (inbox, sent, drafts, trash, etc.) in `emails.ts`.
- Added demo file nodes representing directories and files in `files.ts`.
- Implemented demo Sieve capabilities and scripts in `filters.ts`.
- Defined demo identities for users in `identities.ts`.
- Established demo mailboxes with permissions and counts in `mailboxes.ts`.
- Created a demo vacation response in `vacation.ts`.
- Introduced a comprehensive JMAP client interface in `client-interface.ts` to standardize interactions with the JMAP API.
2026-03-21 01:38:42 +01:00
Linus RathandGitHub 01779fa59e Update SHA tag prefix in docker-publish.yml
Fix the tag prefix format for SHA in Docker publish workflow.
2026-03-21 00:15:01 +01:00
Linus RathandGitHub fc38427ed0 Merge pull request #68 from xnilsit/main
feat: add separate docker build for releases
2026-03-21 00:08:49 +01:00
xnilsit 3cbfb70860 feat: also build images for dev branch 2026-03-21 00:08:32 +01:00
xnilsit c32b740dac chore: rename release workflow 2026-03-20 23:11:41 +01:00
xnilsit a02091a7ad fix: don't tag releases with hash 2026-03-20 22:48:37 +01:00
xnilsit bc311adf6a feat: add separate docker build for releases 2026-03-20 22:35:37 +01:00
Linus Rath 8aca1623f4 Merge dev into main - version 1.4.5 (build fix) 2026-03-20 18:17:53 +01:00
Linus Rath a8be40579e fix: add missing showTimeInMonthView and showOnMobile type definitions to settings store 2026-03-20 18:17:31 +01:00
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
Linus Rath 0fe8e81dc7 Merge branch 'dev' 2026-03-19 01:43:11 +01:00
Linus Rath 267f7257cf chore: remove scripts directory (moved to local-data) 2026-03-19 01:43:11 +01:00
Linus Rath fb8c9db716 chore: bump version to 1.4.2 2026-03-19 01:38:23 +01:00
Linus Rath 2793d4b4af feat: add calendar task list view and shared calendar grouping
- Add TaskListView component for displaying calendar tasks
- Group shared calendars by account in sidebar panel
- Add task view toggle to calendar toolbar
- Extend calendar store with task-related state
2026-03-19 01:21:43 +01:00
Linus Rath 96c2ee9e13 chore: remove scripts already moved to local-data 2026-03-19 01:21:36 +01:00
Linus Rath af115e3245 feat: add address book directories with drag-and-drop and editor picker
- Show address books in sidebar organized by personal directories and
  shared accounts, replacing the flat shared accounts list
- Make contact list items draggable with multi-select support using
  native HTML5 drag-and-drop (application/x-contact-ids MIME type)
- Add drop targets on sidebar address book items with visual feedback
- Add moveContactToAddressBook store method supporting same-account
  updates and cross-account create+delete moves
- Add address book picker dropdown in contact create/edit form
- Update ContactCategory type from sharedAccountId to addressBookId
- Add address_books translations to all 8 locales
- Fix contact-list-item tests for new selectedContactIds prop
2026-03-19 01:13:34 +01:00
Linus Rath fc79bf4f9b fix: resolve default sender to canonical identity on local-part login
When authenticating with a local-part username (e.g. 'user' instead of
'user@domain.tld') on Stalwart 0.15.x, the default sender could resolve
to an alias identity instead of the canonical mailbox address.

- Add emailMatchesUsername() helper that matches local-part usernames
  against full email addresses (e.g. 'user' matches 'user@domain.tld')
- Prefer canonical identities (mayDelete=false) over aliases as tiebreaker
- Add preferredPrimaryId to identity store (persisted to localStorage)
  so users can explicitly set their default sender
- Add 'Set as Primary' star button in identity manager modal
- Fix sendEmail() fallback identity resolution for local-part usernames
- Add i18n strings for all 8 supported locales

Fixes #43
2026-03-18 20:05:35 +01:00
Linus Rath b844b88733 fix: enhance calendar event handling with IMIP invitation and cancellation support 2026-03-18 19:59:47 +01:00
Linus Rath bcdde9f454 fix: add support for email attachments in sendEmail functionality and update related components 2026-03-18 18:51:20 +01:00
Linus Rath bb72ac92ae fix: implement draft editing functionality across email components and add localization keys 2026-03-18 18:39:46 +01:00
Linus Rath 6457b27125 fix: enhance calendar event creation with double-click support and modal date handling 2026-03-18 18:13:33 +01:00
Linus Rath ef562bcaad fix: add email export/import localization keys for multiple languages 2026-03-18 18:00:51 +01:00
Linus Rath 9fdbb62205 fix: update gender handling to use speakToAs structure and adjust localization keys 2026-03-18 17:55:29 +01:00
Linus Rath 2edbf379e2 fix: implement unwrapping of embedded message/rfc822 attachments and enhance HTML body validation 2026-03-18 17:32:25 +01:00
Linus Rath cdc521b693 fix: add time-based sorting for events in buildWeekSegments function 2026-03-18 17:02:37 +01:00
Linus Rath e7249f8bd3 Merge dev into main 2026-03-18 16:58:00 +01:00
Linus Rath a57492d7c0 fix: refactor overflow handling in EmailViewer component to use hidden priorities and layout effects 2026-03-18 16:56:24 +01:00
Linus Rath 2b4ff2f3de fix: remove debugMode usage from EmailViewer component 2026-03-18 16:33:55 +01:00
Linus Rath 5a3f9faafe fix: update dompurify to version 3.3.3 and elliptic to version 6.6.1, add undici override 2026-03-18 16:10:47 +01:00
Linus Rath a74cd32364 Merge dev into main - version 1.4.1 2026-03-18 15:51:22 +01:00
Linus Rath 38c04099e2 Bump version to 1.4.1 2026-03-18 15:42:37 +01:00
Linus Rath ae14e09f66 fix: enforce image and table styling 2026-03-18 15:40:08 +01:00
Linus Rath ada356e440 fix: menu overvlow fixed with submenu support for move and tag actions 2026-03-18 15:35:17 +01:00
Linus Rath a886edda6f fix: deduplicate toolbar and fix overflow detection
Extract shared renderToolbarItems() function to eliminate ~850 lines of
duplicated toolbar code between 'top' and 'below-subject' positions.

Add overflow support to Reply, Reply All, and Forward buttons with
data-overflow-item attributes and corresponding More menu entries.

Fix overflow detection algorithm: temporarily disable flex-shrink on
child groups during measurement so scrollWidth reflects natural widths
instead of flex-compressed values. Add overflow-hidden to toolbar
container to prevent visual overflow during recalculation.
2026-03-18 15:29:16 +01:00
Linus Rath ff97d8bc4c feat: enhance TNEF parsing with detailed debug logging for better traceability 2026-03-18 15:00:53 +01:00
Linus Rath b1db100c3a feat: enhance email body handling by prioritizing textBody for minimal HTML and expanding JMAPClient properties 2026-03-18 14:53:08 +01:00
Linus Rath 19584cfef6 feat: add email import/export functionality with .eml support 2026-03-18 14:44:12 +01:00
Linus Rath 8a2ef5a6c5 feat: integrate webcrypto-liner for legacy algorithm support in S/MIME handling 2026-03-18 14:29:29 +01:00
Linus Rath 477fc8c885 Merge branch 'main' of https://github.com/bulwarkmail/webmail 2026-03-18 00:31:49 +01:00
Linus Rath 84abfe79dd feat: update changelog for version 1.4.0 with new features and fixes
feat: update README.md to reflect version 1.4.0 and new features
chore: bump version to 1.4.0 in VERSION and package files
feat: implement identity refresh behavior in identity management
feat: add TNEF support for Outlook emails and archive organization modes
feat: enhance UI with configurable sidebar apps and branding options
refactor: remove unused addon-plugin-theme-concept.md file
2026-03-18 00:18:48 +01:00
Linus Rath 8a92d53125 feat: improve calendar view mode handling with validation and defaulting 2026-03-17 23:56:10 +01:00
Linus Rath 6fe4a98b02 feat: add sidebar apps management feature
- Implemented sidebar apps functionality including adding, editing, and deleting apps.
- Created a modal for managing sidebar apps with forms for inputting app details.
- Added icon picker component for selecting app icons.
- Introduced inline app view for displaying apps within the sidebar.
- Updated translations for new sidebar apps feature in Dutch and Portuguese.
- Enhanced settings store to manage sidebar apps state.
- Added hooks for managing sidebar apps state and modal visibility.
2026-03-17 23:02:26 +01:00
Linus Rath 3186198fad feat: enhance identity management with identity refresh functionality and improved modal behavior 2026-03-17 21:50:35 +01:00
Linus Rath 5c933a595f feat: implement time format preference across calendar and email components 2026-03-17 21:39:59 +01:00
Linus Rath 828ad4df72 Remove unused files: ROADMAP.md and TNEF test outputs 2026-03-17 21:26:11 +01:00
Linus Rath f720cb3ef8 feat: add TNEF (winmail.dat) support for email attachments and parsing 2026-03-17 21:22:43 +01:00
Linus Rath 818a02428b Merge branch 'dev' of https://github.com/bulwarkmail/webmail into dev 2026-03-17 20:54:02 +01:00
Linus Rath 6ed30059e5 Merge branch 'dev' of https://github.com/bulwarkmail/webmail into dev 2026-03-17 20:53:53 +01:00
Linus Rath a2cb2b2c86 fix: proper support for all-day events 2026-03-17 20:51:47 +01:00
Linus Rath 1f7cd61fc7 feat: implement email archiving options and reorganize functionality 2026-03-17 20:37:57 +01:00
Linus Rath 070eeeecee feat: add translation key collection utility and update test for completeness 2026-03-17 20:20:44 +01:00
Linus Rath de35d1d8e8 feat: add S/MIME store for managing key records and public certificates
- Implemented Zustand store for S/MIME functionality, including state management for key records and public certificates.
- Added methods for importing PKCS#12 files and public certificates, binding identities to keys, and managing unlocked keys.
- Introduced session storage for remembering unlocked keys across sessions.
- Enhanced error handling and loading states during data operations.
2026-03-17 20:14:01 +01:00
Linus Rath 7c5785e9e8 feat: enhance branding options with custom favicon and logos in configuration 2026-03-17 15:25:06 +01:00
Linus Rath 54f4d37595 fix: update author information in package.json 2026-03-17 15:14:06 +01:00
Linus Rath 71cd826c6f fix: update vendor label in Dockerfile to correct value 2026-03-17 15:12:37 +01:00
Linus Rath e96b9a72e7 fix: update page title to use appName from configuration 2026-03-17 15:07:50 +01:00
Linus Rath ce4ebb3dc2 fix: correct formatting of HOSTNAME environment variable in docker-compose.yml 2026-03-17 15:00:34 +01:00
Linus Rath 6680b65863 feat: add server listen address configuration to .env and README 2026-03-17 14:58:12 +01:00
Linus RathandGitHub df64959e60 Fix formatting in README for consistency 2026-03-17 12:10:48 +01:00
Linus RathandGitHub 8641275bb4 Update version badge to 1.3.0 2026-03-17 08:49:28 +01:00
Linus Rath 6e78f2a09e feat: add 'Always Light Mode' setting for email display 2026-03-17 00:56:34 +01:00
Linus RathandGitHub d429652f72 Update image width in README.md 2026-03-17 00:39:00 +01:00
199 changed files with 45120 additions and 3954 deletions
-2
View File
@@ -5,9 +5,7 @@ node_modules
.env* .env*
!.env.example !.env.example
!.env.dev.example !.env.dev.example
.claude/
scripts/ scripts/
TODO.md TODO.md
CLAUDE.md
*.md *.md
!README.md !README.md
+34 -3
View File
@@ -64,9 +64,23 @@ JMAP_SERVER_URL=https://your-jmap-server.com
# SETTINGS_SYNC_ENABLED=true # SETTINGS_SYNC_ENABLED=true
# Directory for storing encrypted settings files (default: ./data/settings). # Directory for storing encrypted settings files (default: ./data/settings).
# For Docker, mount a persistent volume at this path. # For Docker, the working directory is /app, so the default resolves to
# /app/data/settings — mount a persistent volume there:
# volumes:
# - bulwark-settings:/app/data/settings
# SETTINGS_DATA_DIR=./data/settings # SETTINGS_DATA_DIR=./data/settings
# =============================================================================
# Server Listen Address
# =============================================================================
# Hostname the server binds to (default: 0.0.0.0)
# Set to "::" for dual-stack
# HOSTNAME=0.0.0.0
# Port the server listens on (default: 3000)
# PORT=3000
# ============================================================================= # =============================================================================
# Logging # Logging
# ============================================================================= # =============================================================================
@@ -78,10 +92,27 @@ JMAP_SERVER_URL=https://your-jmap-server.com
# LOG_LEVEL=info # LOG_LEVEL=info
# ============================================================================= # =============================================================================
# Login Page Customization (all optional) # Branding (all optional)
# ============================================================================= # =============================================================================
# Custom logo images for the login page (PNG, SVG, etc.) # Custom favicon for the browser tab.
# Supported formats: SVG (recommended), PNG, ICO.
# Recommended size: 32×32px minimum, 512×512px maximum (or SVG for best scaling).
# Can be an absolute URL or a path relative to the public/ directory.
# Defaults to the Bulwark favicon if not set.
# FAVICON_URL=/branding/my-favicon.svg
# Custom logos for the sidebar (shown in the main app after login).
# Supported formats: SVG (recommended), PNG, WebP.
# Recommended size: min 24×24px, max 128×128px
# Can be absolute URLs or paths relative to the public/ directory.
# If not set, no logo is shown in the sidebar.
# APP_LOGO_LIGHT_URL=/branding/my-logo-color.svg
# APP_LOGO_DARK_URL=/branding/my-logo-white.svg
# Custom logo images for the login page.
# Supported formats: SVG (recommended), PNG, WebP.
# Recommended size: min 32×32px, max 512×512px
# Can be absolute URLs or paths relative to the public/ directory. # Can be absolute URLs or paths relative to the public/ directory.
# Light mode logo (shown on light backgrounds), defaults to Bulwark logo. # Light mode logo (shown on light backgrounds), defaults to Bulwark logo.
LOGIN_LOGO_LIGHT_URL=/branding/Bulwark_Logo_Color.svg LOGIN_LOGO_LIGHT_URL=/branding/Bulwark_Logo_Color.svg
@@ -0,0 +1,118 @@
name: Publish Docker Image on Release
on:
release:
types: [published]
workflow_dispatch:
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
jobs:
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
steps:
- name: Checkout
uses: actions/checkout@v4
- 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 }}
- 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
type=semver,pattern=v{{version}}
type=semver,pattern={{version}}
type=semver,pattern=v{{major}}.{{minor}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern=v{{major}}
type=semver,pattern={{major}}
- 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 }}
+81 -20
View File
@@ -2,7 +2,9 @@ name: Publish Docker Image
on: on:
push: push:
branches: [main] branches:
- main
- dev
paths: paths:
- "Dockerfile" - "Dockerfile"
- ".dockerignore" - ".dockerignore"
@@ -17,12 +19,22 @@ on:
- "package.json" - "package.json"
- "package-lock.json" - "package-lock.json"
- ".github/workflows/docker-publish.yml" - ".github/workflows/docker-publish.yml"
tags: ["v*.*.*"]
workflow_dispatch: workflow_dispatch:
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
jobs: jobs:
build-and-push: build:
runs-on: ubuntu-latest 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: permissions:
contents: read contents: read
packages: write packages: write
@@ -31,9 +43,6 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v3
@@ -48,21 +57,73 @@ jobs:
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@v5
with: with:
images: | images: ${{ env.IMAGE_NAME }}
ghcr.io/${{ github.repository }}
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 - name: Build and push by digest
id: build
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64,linux/arm64 platforms: ${{ matrix.platform }}
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }} labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-to: type=gha,mode=max 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={{branch}}
type=sha,prefix={{branch}}-
- 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 *.tsbuildinfo
next-env.d.ts next-env.d.ts
# claude code
.claude/
# settings sync data # settings sync data
/data/ /data/
+159
View File
@@ -1,5 +1,164 @@
# Changelog # Changelog
## 1.4.8 (2026-03-23)
### Features
- **Email**: Add support for marking emails as answered or forwarded and display status icons in email list and thread views
- **Email**: Enhance identity selection by supporting sub-addressing (plus addressing) in email composer
- **Settings**: Add notification settings with sound picker, preview playback, and configurable alert sounds
- **Settings**: Add default mail program settings with localization support across all locales
- **Auth**: Implement path prefix handling for OAuth callbacks and login redirects, enabling reverse proxy deployments
- **Validation**: Add all multi-part TLDs for domain validation in favicon API (#81)
### Fixes
- **Calendar**: Fix bugs in duration parsing, RFC compliance, and event handling across calendar components
- **Calendar**: Detect tasks created by external CalDAV clients such as Thunderbird
- **Settings**: Enhance account settings with username and authentication method display (#90)
## 1.4.7 (2026-03-21)
### Features
- **Calendar**: Add task management features with task creation, editing, and status tracking
- **Calendar**: Add option to show week numbers in mini-calendar
- **Email**: Add resizable image component and rich text editor with image upload support
- **Files**: Support uploading folders via drag-and-drop and toolbar button
- **Filters**: Add expanded visual view for filter rules
- **Auth**: Add non-interactive SSO login flow for embedded/iframe deployments (#69)
- **DevOps**: Add separate Docker build workflow for releases and dev branch images
### Fixes
- **Calendar**: Handle updates and deletions for synthetic JMAP IDs in calendar events with fallback to destroy and recreate
- **Security**: Extend CryptoEngine to support legacy algorithms and integrate with LinerEngine for decryption
- **Auth**: Refactor logout to use synchronous flow with full page redirect
- **Email**: Update iframe sandbox attributes to allow popups to escape sandbox
- **i18n**: Add missing translation keys across all locales
- **Docker**: Update .env.example to clarify Docker volume mounting for settings data directory
## 1.4.6 (2026-03-21)
### Features
- **Demo**: Add full demo mode with fixture data for emails, calendars, contacts, files, filters, identities, mailboxes, and vacation responses
- **Demo**: Implement JMAP client interface abstraction to support demo and live backends
- **Contacts**: Add no-category filter, drag-and-drop to category, and category combo box in contact form
- **Email**: Add hover actions for emails with configurable quick-action buttons
- **Settings**: Implement keyword migration functionality for upgrading legacy email tags
- **Security**: Enhance S/MIME certificate extraction and add legacy PBE (password-based encryption) support
- **Tour**: Add interactive guided tour overlay for new user onboarding
### Fixes
- **Settings**: Add missing `showTimeInMonthView` and `showOnMobile` type definitions to settings store
- **UI**: Adjust padding and size of sidebar buttons for improved layout
## 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
- **Calendar**: Add task list view for calendar tasks with task details and management
- **Calendar**: Add shared calendar grouping with visual separation in sidebar
- **Calendar**: Support double-click to create events and improve modal date handling
- **Contacts**: Add address book directories with drag-and-drop and editor picker
- **Email**: Add email attachment support in sendEmail functionality
- **Email**: Implement draft editing functionality across email components
- **Email**: Implement unwrapping of embedded message/rfc822 attachments with enhanced HTML body validation
- **Email**: Add email export/import localization keys for multiple languages
- **Contacts**: Update gender handling to use speakToAs structure
### Fixes
- **Email**: Resolve default sender to canonical identity on local-part login
- **Email**: Refactor overflow handling in EmailViewer to use hidden priorities and layout effects
- **Email**: Remove debugMode usage from EmailViewer component
- **Calendar**: Enhance IMIP invitation and cancellation handling for calendar events
- **Calendar**: Add time-based sorting for events in buildWeekSegments function
- **Dependencies**: Update dompurify to 3.3.3 and elliptic to 6.6.1, add undici override
## 1.4.1 (2026-03-18)
### Features
- **Security**: Add S/MIME certificate management with identity bindings, signer auto-import, unlock controls, and compose/viewer sign, encrypt, decrypt, and verification flows
- **Email**: Add TNEF (`winmail.dat`) parsing to extract message bodies and attachments from Outlook rich-text emails
- **Email**: Add archive organization modes for archiving directly or into year/month subfolders
- **Email**: Add an "Always Show Emails in Light Mode" preference to avoid dark-mode conversion issues
- **Email**: Apply the 12-hour or 24-hour time format preference consistently across calendar and email surfaces
- **Identity**: Add identity refresh behavior in the identity manager so server-side changes stay in sync after edits
- **UI**: Add configurable sidebar apps with custom icons plus inline or new-tab launch modes
- **Branding**: Add runtime branding options for custom favicon, sidebar logos, and login logos
- **Deployment**: Add configurable server listen address support via `HOSTNAME`, including IPv6 and dual-stack guidance
### Fixes
- **Calendar**: Improve all-day event handling
- **Calendar**: Validate and default persisted calendar view mode values
- **UI**: Use configured app names more consistently in metadata and login branding surfaces
- **Docker**: Correct `HOSTNAME` formatting in the Docker Compose example
- **Metadata**: Correct package author and container vendor metadata
## 1.3.0 (2026-03-16) ## 1.3.0 (2026-03-16)
### Features ### Features
+1 -1
View File
@@ -13,7 +13,7 @@ LABEL org.opencontainers.image.description="Modern webmail client built with Nex
LABEL org.opencontainers.image.source="https://github.com/bulwarkmail/webmail" LABEL org.opencontainers.image.source="https://github.com/bulwarkmail/webmail"
LABEL org.opencontainers.image.url="https://github.com/bulwarkmail/webmail" LABEL org.opencontainers.image.url="https://github.com/bulwarkmail/webmail"
LABEL org.opencontainers.image.licenses="AGPL-3.0-only" LABEL org.opencontainers.image.licenses="AGPL-3.0-only"
LABEL org.opencontainers.image.vendor="root.cloud" LABEL org.opencontainers.image.vendor="rbm.systems"
WORKDIR /app WORKDIR /app
ENV NODE_ENV=production ENV NODE_ENV=production
+21 -5
View File
@@ -11,9 +11,10 @@
A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.art/).<br/> A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.art/).<br/>
Built with Next.js and the JMAP protocol. Built with Next.js and the JMAP protocol.
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg)](LICENSE) [![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg?logo=gnu&logoColor=white)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.2.4-green.svg)](CHANGELOG.md) [![Discord](https://img.shields.io/discord/1482128142939455674?color=7289da&label=discord&logo=discord&logoColor=white)](https://discord.gg/tYCujymGrT)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue)](https://ghcr.io/bulwarkmail/webmail) [![Version](https://img.shields.io/badge/version-1.4.7-green.svg?logo=git&logoColor=white)](CHANGELOG.md)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue?logo=docker&logoColor=white)](https://ghcr.io/bulwarkmail/webmail)
</div> </div>
@@ -99,12 +100,14 @@ Built with Next.js and the JMAP protocol.
- **Attachments** — upload, download, and inline preview - **Attachments** — upload, download, and inline preview
- **Search** — full-text with JMAP filter panel, search chips, cross-mailbox queries, wildcard support, and OR conditions - **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 - **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 - **Print** emails directly from the viewer
- **Color tags/labels** and star/unstar - **Color tags/labels** and star/unstar
- **Virtual scrolling** for large mailboxes - **Virtual scrolling** for large mailboxes
- **Quick reply** from the viewer - **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 - **Recipient popover** for quick contact interaction
- **TNEF support** — extract Outlook `winmail.dat` message bodies and attachments automatically
- **Folder management** — create, rename, delete folders with icon picker and subfolder support - **Folder management** — create, rename, delete folders with icon picker and subfolder support
- **Tag counts** — unread and total counts displayed in sidebar - **Tag counts** — unread and total counts displayed in sidebar
@@ -151,6 +154,7 @@ Built with Next.js and the JMAP protocol.
- **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 - **HTML sanitization** via DOMPurify with XSS prevention
- **S/MIME** — manage certificates, sign outgoing mail, encrypt to recipients, decrypt messages, and verify signatures
- **SPF/DKIM/DMARC** status indicators - **SPF/DKIM/DMARC** status indicators
- **OAuth2/OIDC with PKCE** for SSO (Keycloak, Authentik, or built-in), with OAuth-only mode - **OAuth2/OIDC with PKCE** for SSO (Keycloak, Authentik, or built-in), with OAuth-only mode
- **TOTP two-factor authentication** - **TOTP two-factor authentication**
@@ -163,12 +167,13 @@ Built with Next.js and the JMAP protocol.
- **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 - **Dark and light themes** with intelligent email color transformation
- **Always-light email rendering** option for problematic HTML messages in dark theme
- **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support - **Responsive** — desktop sidebar + mobile bottom tab bar with tablet support
- **Keyboard shortcuts** — full navigation without a mouse - **Keyboard shortcuts** — full navigation without a mouse
- **Drag-and-drop** email organization between mailboxes and tag assignment - **Drag-and-drop** email organization between mailboxes and tag assignment
- **Right-click context menus**, toast notifications with undo, form validation with shake feedback - **Right-click context menus**, toast notifications with undo, form validation with shake feedback
- **Customizable toolbar** position and login page branding - **Customizable toolbar** position, custom favicon, sidebar/login logos, and login page branding
- **Configurable logo** with light/dark mode variants - **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) - **Settings sync** — preferences synchronized with the server (encrypted)
- **Storage quota** display - **Storage quota** display
- **Shared folders** — multi-account access - **Shared folders** — multi-account access
@@ -183,6 +188,7 @@ Automatic browser detection with persistent preference.
### Identity Management ### Identity Management
- **Multiple sender identities** with per-identity signatures - **Multiple sender identities** with per-identity signatures
- **Identity refresh** — keep the identity manager aligned with server-side changes after edits
- **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions - **Sub-addressing** — `user+tag@domain.com` with contextual tag suggestions
- **Identity badges** in viewer and email list - **Identity badges** in viewer and email list
@@ -243,6 +249,16 @@ 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>
```env
HOSTNAME=0.0.0.0 # Default; use "::" for IPv6
PORT=3000 # Default listen port
```
</details>
<details> <details>
<summary>OAuth2/OIDC (SSO)</summary> <summary>OAuth2/OIDC (SSO)</summary>
-301
View File
@@ -1,301 +0,0 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="public/branding/Bulwark%20Logo%20with%20Lettering%20White%20and%20Color.svg" />
<source media="(prefers-color-scheme: light)" srcset="public/branding/Bulwark%20Logo%20with%20Lettering%20Dark%20Color.svg" />
<img src="public/branding/Bulwark%20Logo%20with%20Lettering%20Dark%20Color.svg" alt="Bulwark Webmail" width="220" />
</picture>
</div>
# Bulwark Webmail - Roadmap
This document tracks the development status and planned features for Bulwark Webmail.
## Completed Features
### Core Infrastructure
- [x] Next.js 16 with TypeScript and App Router
- [x] Tailwind CSS v4 with Oxide engine
- [x] Zustand state management
- [x] Custom JMAP client implementation (RFC 8620)
### Authentication
- [x] Login with JMAP server authentication
- [x] Session management (no password storage for security)
- [x] Username autocomplete with history
- [x] Logout functionality
- [x] Authentication error handling
- [x] JMAP identities for sender address
- [x] TOTP two-factor authentication (Stalwart-compatible)
- [x] OAuth2/OIDC with PKCE (opt-in SSO, session persistence, RP-initiated logout)
- [x] External IdP support via explicit issuer URL (Keycloak, Authentik, etc.)
- [x] "Remember me" session persistence for Basic Auth (AES-256-GCM encrypted httpOnly cookie)
### JMAP Server Connection
- [x] Session establishment and keep-alive
- [x] Connection error handling and retries
- [x] CORS error detection with actionable user guidance
- [x] Session URL origin rewriting (fixes Docker/reverse proxy deployments where server returns internal hostname)
- [x] Storage quota display
- [x] Server capability detection
- [x] Shared folders support (multi-account access)
### Email Operations
- [x] Email fetching and display
- [x] Full HTML email rendering
- [x] Compose, reply, reply-all, forward
- [x] Draft auto-save with discard confirmation
- [x] Mark as read/unread
- [x] Star/unstar emails
- [x] Delete and archive
- [x] Color tags/labels
- [x] Full-text search
- [x] Advanced search with JMAP filter panel, search chips, and cross-mailbox queries
- [x] Attachment upload and download
- [x] Batch operations (multi-select)
- [x] Quick reply form
- [x] Email threading (Gmail-style inline expansion)
### Real-time Updates
- [x] EventSource for JMAP push notifications
- [x] State synchronization
- [x] Email arrival notifications
- [x] Real-time unread counts
- [x] Mailbox change handling
### User Interface
- [x] Three-pane layout (sidebar, list, viewer)
- [x] Minimalist design system
- [x] Dark and light theme support
- [x] Custom scrollbars
- [x] Mobile responsive design
- [x] Keyboard shortcuts
- [x] Drag-and-drop email organization
- [x] Right-click context menus
- [x] Hierarchical mailbox display
- [x] Email list with avatars and visual hierarchy
- [x] Expandable email headers
- [x] External content warning banner
- [x] SPF/DKIM/DMARC status indicators
- [x] Loading states and skeletons
- [x] Smooth transitions and animations
- [x] Infinite scroll pagination
- [x] Virtual scrolling for large email lists
- [x] Error boundaries
- [x] Settings page with preferences
- [x] Navigation rail (desktop vertical icon sidebar + mobile bottom tab bar)
- [x] Welcome banner for first-time users (one-time display, localStorage persistence)
- [x] Confirmation dialog component with promise-based useConfirmDialog hook
- [x] Toast notifications with undo action support and typed durations
- [x] Inline form validation with shake animation (email composer, contact form)
- [x] Login UX polish (error shake, discreet 2FA toggle, password visibility toggle, session expired banner)
- [x] Empty state patterns for contacts (distinct "no data" vs "no search results" with contextual actions)
- [x] WCAG AA reduced-motion media query (global animation/transition reset)
- [x] Safe area inset utilities for notched devices
- [x] Screen reader live region announcements (sr-only)
### Internationalization
- [x] English language support
- [x] French language support
- [x] Japanese language support
- [x] Spanish language support
- [x] Italian language support
- [x] German language support
- [x] Dutch language support
- [x] Portuguese language support
- [x] Automatic browser language detection
- [x] Language preference persistence
### Security & Accessibility
- [x] External content blocked by default
- [x] HTML sanitization with DOMPurify
- [x] User control for loading external content
- [x] Trusted senders list for automatic image loading
- [x] Dark mode email readability (intelligent color transformation)
- [x] WCAG 2.0 Level AA color contrast compliance
- [x] Newsletter unsubscribe support (RFC 2369)
- [x] XSS attack prevention with comprehensive validation
- [x] CSP Report-Only headers with per-request nonce
- [x] Security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy)
- [x] Reusable focus trap hook (Tab cycling, Escape handling, focus restore)
- [x] WCAG AA prefers-reduced-motion support (global animation/transition reset)
- [x] Safe area insets for notched mobile devices
- [x] Screen reader sr-only live region for dynamic announcements
### Identity Management
- [x] Multiple sender identities (name, email, signature)
- [x] Sub-addressing support (user+tag@domain.com)
- [x] Per-identity signatures
- [x] Identity badges in email viewer and list
- [x] Tag suggestions based on context
- [x] Display name included in From header (recipients see name, not just email)
- [x] Primary identity (matching login) selected by default in composer
### Address Book & Contacts
- [x] Contact store with JMAP sync and local fallback
- [x] Contact CRUD operations (create, read, update, delete)
- [x] Contacts list view with search/filter
- [x] Contact details view/edit form
- [x] JMAP contacts sync (RFC 9553/9610 ContactCard/AddressBook)
- [x] Email autocomplete from contacts
- [x] Contacts integration in email composer (To/Cc/Bcc)
- [x] Contact groups/lists management with JMAP members map
- [x] vCard import/export (RFC 6350 parser/generator, duplicate detection)
- [x] Bulk contact operations (multi-select, delete, group add, export)
- [x] i18n support for contacts (all 8 languages)
### Vacation Responder
- [x] JMAP VacationResponse singleton management
- [x] Settings tab with date range and message configuration
- [x] Sidebar indicator when vacation auto-reply is active
- [x] i18n support (all 8 languages)
### Calendar Integration
- [x] JMAP Calendar types (RFC 8984) and client methods
- [x] Calendar capability detection (urn:ietf:params:jmap:calendars)
- [x] Calendar store with Zustand (persist middleware)
- [x] Month, week, day, and agenda views
- [x] Event modal (create/edit/delete with recurrence, reminders)
- [x] Mini-calendar sidebar with calendar visibility toggles
- [x] Calendar settings (default view, week start, time format)
- [x] Multi-day event spanning across all covered days
- [x] Column-based overlap layout for concurrent events
- [x] Locale-aware date formatting via next-intl
- [x] First day of week and time format settings wired to views
- [x] Push notification handling for calendar state changes
- [x] Calendar page capability check (redirect if unsupported)
- [x] Error handling with toast feedback on event CRUD
- [x] Timezone auto-detection on event creation
- [x] Input validation, color sanitization, focus trap
- [x] ARIA grid roles and event card accessible labels
- [x] Mobile touch targets (44px minimum)
- [x] Calendar keyboard shortcuts (m/w/d/a views, t today, n new event)
- [x] i18n support with ICU pluralization (all 8 languages)
- [x] Drag-and-drop event rescheduling (week/day time snap, month date move)
- [x] iCalendar (.ics) file import via CalendarEvent/parse with preview and bulk create
- [x] Event notifications with client-side alert evaluation and toast display
- [x] Notification sound, acknowledged alert persistence (localStorage), proactive 24h event fetch
- [x] Configurable notification settings (enable/disable, sound toggle)
- [x] Participant scheduling with iTIP invitations (organizer/attendee UI, RSVP buttons, contact autocomplete)
- [x] Inline calendar invitation banner in email viewer (auto-detect .ics attachments, RSVP, import to calendar, cancellation display)
- [x] Scheduling message support (sendSchedulingMessages flag for create/update/delete)
- [x] Click-drag to create events (pointer-based time range selection, 15-min snap, visual overlay)
- [x] Event resize by dragging bottom edge handle (15-min snap, optimistic JMAP update)
- [x] Recurring event edit/delete scope dialog (this event / this and following / all events)
- [x] Double-click quick event creation (inline title input, PT1H default)
- [x] Event duplication button in modal (clones event +1 day, opens for editing)
### Email Filters
- [x] JMAP Sieve Scripts (RFC 9661) with capability detection
- [x] Visual rule builder (conditions: From/To/Cc/Subject/Header/Size/Body, actions: Move/Copy/Forward/Mark read/Star/Label/Discard/Reject/Keep/Stop)
- [x] Raw Sieve script editor with syntax validation
- [x] Sieve generator and parser with JSON metadata round-trip
- [x] Filter store with CRUD, reorder, toggle, auto-save with rollback
- [x] Opaque script detection with reset to visual builder option
- [x] Focus trap accessibility in modals
- [x] Toast validation feedback for empty rules
- [x] Push notification handling for SieveScript state changes
- [x] i18n support (all 8 languages)
### Email Templates
- [x] Reusable email templates with local storage persistence
- [x] Category organization (General, Business, Personal, Support, Follow-up, custom)
- [x] Dynamic placeholder variables with auto-fill from composer context
- [x] Template manager modal (create, edit, duplicate, delete)
- [x] Template picker in composer toolbar with search and category filter
- [x] Custom placeholder prompt on template insertion
- [x] Settings tab for template management
- [x] Keyboard shortcut (Ctrl+Shift+T to insert template)
- [x] i18n support (all 8 languages)
### Email Display
- [x] Proper email layout without horizontal scroll or clipping
- [x] Blocked image container collapsing (no empty spaces in newsletters)
### Testing
- [x] Unit tests for validation utilities (57 tests)
- [x] Unit tests for email sanitization (27 tests)
- [x] Unit tests for color transformation (40 tests)
- [x] Unit tests for contact store (56 tests)
- [x] Unit tests for JMAP contact client (41 tests)
- [x] Unit tests for vCard parser (18 tests)
- [x] Unit tests for thread utilities (20 tests)
- [x] Unit tests for email headers (39 tests)
- [x] Component tests (contacts, UI components — 41 tests)
- [x] JMAP client method tests (identity: 20, contacts: 41)
- [x] Unit tests for Sieve generator (50 tests)
- [x] Unit tests for Sieve parser (14 tests)
- [x] Unit tests for calendar alerts (36 tests)
- [x] Unit tests for calendar notification store (8 tests)
- [x] Unit tests for calendar invitation parsing (25 tests)
- [x] Unit tests for calendar participants (26 tests)
- [x] Unit tests for template utilities (48 tests)
- [x] Unit tests for OAuth PKCE and discovery (14 tests)
- [x] XSS attack vector testing
- [x] Playwright E2E framework setup
### Deployment
- [x] Runtime environment variables (Docker-friendly configuration)
- [x] Health check endpoint
- [x] Docker support (multi-stage build, docker-compose, standalone output)
- [x] Structured server-side logger (text/JSON format, configurable level)
- [x] Pre-built Docker image on [Docker Hub](https://hub.docker.com/r/bulwarkmail/webmail) and [GHCR](https://ghcr.io/bulwarkmail/webmail) with multi-arch support (amd64/arm64)
- [x] GitHub Actions CI/CD for automated image publishing on releases
- [x] CVE remediation: remove npm from production image, upgrade Alpine packages
- [x] Server-side update check (logs newer version availability on startup)
## Planned Features
### Advanced Features
- [ ] Free/busy queries (Principal/getAvailability)
- [ ] Calendar sharing UI (JMAP Sharing RFC 9670)
- [ ] Email encryption (PGP/GPG)
### Performance Optimizations
- [ ] Email content caching
- [ ] Bundle size optimization
- [ ] Service worker for offline support
- [ ] Lazy loading for attachments
### Testing (Remaining)
- [ ] E2E tests with real JMAP server
- [ ] Accessibility testing
- [ ] Performance testing
### Deployment
- [ ] Production build optimizations
- [ ] Monitoring and logging
### Security Enhancements
- [ ] Rate limiting
## Known Issues
- [ ] Next.js workspace root warning (cosmetic)
## Contributing
Want to help implement a feature? Check out our [CONTRIBUTING.md](CONTRIBUTING.md) guide!
+1 -1
View File
@@ -1 +1 @@
1.3.0 1.4.8
+65 -34
View File
@@ -4,6 +4,7 @@ import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { getPathPrefix } from "@/lib/browser-navigation";
import { Loader2, AlertCircle } from "lucide-react"; import { Loader2, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
@@ -13,7 +14,7 @@ function OAuthCallbackInner() {
const params = useParams(); const params = useParams();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const t = useTranslations("login"); const t = useTranslations("login");
const { loginWithOAuth } = useAuthStore(); const { loginWithOAuth, loginWithServerSso } = useAuthStore();
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
@@ -32,43 +33,73 @@ function OAuthCallbackInner() {
} }
const savedState = sessionStorage.getItem("oauth_state"); const savedState = sessionStorage.getItem("oauth_state");
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
const codeVerifier = sessionStorage.getItem("oauth_code_verifier"); if (savedState) {
const serverUrl = sessionStorage.getItem("oauth_server_url"); // Classic flow — sessionStorage has the PKCE state (same-tab OAuth)
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
if (!codeVerifier || !serverUrl) { const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
setError("missing_params"); const serverUrl = sessionStorage.getItem("oauth_server_url");
return;
}
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`; if (!codeVerifier || !serverUrl) {
setError("missing_params");
return;
}
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri) const prefix = getPathPrefix(params.locale as string);
.then((success) => { const redirectUri = `${window.location.origin}${prefix}/${params.locale}/auth/callback`;
if (success) {
sessionStorage.removeItem("oauth_state"); loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
sessionStorage.removeItem("oauth_code_verifier"); .then((success) => {
sessionStorage.removeItem("oauth_server_url"); if (success) {
let redirectTo = `/${params.locale}`; sessionStorage.removeItem("oauth_state");
try { sessionStorage.removeItem("oauth_code_verifier");
const saved = sessionStorage.getItem('redirect_after_login'); sessionStorage.removeItem("oauth_server_url");
if (saved) { sessionStorage.removeItem("oauth_add_account_mode");
sessionStorage.removeItem('redirect_after_login'); let redirectTo = `${prefix}/${params.locale}`;
redirectTo = saved; try {
} const saved = sessionStorage.getItem('redirect_after_login');
} catch { /* sessionStorage may be unavailable */ } if (saved) {
router.push(redirectTo); sessionStorage.removeItem('redirect_after_login');
} else { redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
setError("token_exchange_failed");
}
})
.catch(() => {
setError("token_exchange_failed"); setError("token_exchange_failed");
} });
}) } else if (state) {
.catch(() => { // Server-side SSO flow — state was stored in encrypted httpOnly cookie
setError("token_exchange_failed"); const ssoPrefix = getPathPrefix(params.locale as string);
}); loginWithServerSso(code, state)
.then((success) => {
if (success) {
let redirectTo = `${ssoPrefix}/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
setError("token_exchange_failed");
}
})
.catch(() => {
setError("token_exchange_failed");
});
} else {
setError("invalid_state");
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps }, []); // eslint-disable-line react-hooks/exhaustive-deps
if (error) { if (error) {
@@ -86,7 +117,7 @@ function OAuthCallbackInner() {
</p> </p>
<Button <Button
variant="outline" variant="outline"
onClick={() => router.push(`/${params.locale}/login`)} onClick={() => router.push(`${getPathPrefix(params.locale as string)}/${params.locale}/login`)}
> >
{t("oauth_error.back_to_login")} {t("oauth_error.back_to_login")}
</Button> </Button>
+199 -37
View File
@@ -7,10 +7,11 @@ import { Plus } from "lucide-react";
import { import {
startOfMonth, endOfMonth, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfWeek, endOfWeek,
addMonths, subMonths, addWeeks, subWeeks, addDays, subDays, addMonths, subMonths, addWeeks, subWeeks, addDays, subDays,
format, parseISO, startOfDay, format, parseISO,
} from "date-fns"; } from "date-fns";
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { useAuthStore } from "@/stores/auth-store"; import { isCalendarViewMode } from "@/stores/calendar-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store"; import { useSettingsStore } from "@/stores/settings-store";
import { useIdentityStore } from "@/stores/identity-store"; import { useIdentityStore } from "@/stores/identity-store";
@@ -22,15 +23,22 @@ import { CalendarMonthView } from "@/components/calendar/calendar-month-view";
import { CalendarWeekView } from "@/components/calendar/calendar-week-view"; import { CalendarWeekView } from "@/components/calendar/calendar-week-view";
import { CalendarDayView } from "@/components/calendar/calendar-day-view"; import { CalendarDayView } from "@/components/calendar/calendar-day-view";
import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view"; import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view";
import { TaskListView } from "@/components/calendar/task-list-view";
import { TaskToolbar } from "@/components/calendar/task-toolbar";
import { TaskModal } from "@/components/calendar/task-modal";
import { MiniCalendar } from "@/components/calendar/mini-calendar"; import { MiniCalendar } from "@/components/calendar/mini-calendar";
import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel"; 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 { EventDetailPopover } from "@/components/calendar/event-detail-popover";
import { ICalImportModal } from "@/components/calendar/ical-import-modal"; import { ICalImportModal } from "@/components/calendar/ical-import-modal";
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal"; import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
import { RecurrenceScopeDialog, type RecurrenceEditScope } from "@/components/calendar/recurrence-scope-dialog"; import { RecurrenceScopeDialog, type RecurrenceEditScope } from "@/components/calendar/recurrence-scope-dialog";
import { NavigationRail } from "@/components/layout/navigation-rail"; import { NavigationRail } from "@/components/layout/navigation-rail";
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
import { InlineAppView } from "@/components/layout/inline-app-view";
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { ResizeHandle } from "@/components/layout/resize-handle"; import { ResizeHandle } from "@/components/layout/resize-handle";
import { useTaskStore } from "@/stores/task-store";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types"; import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
import { getUserParticipantId } from "@/lib/calendar-participants"; import { getUserParticipantId } from "@/lib/calendar-participants";
@@ -48,6 +56,7 @@ export default function CalendarPage() {
const router = useRouter(); const router = useRouter();
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore(); const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client); const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
const { quota, isPushConnected } = useEmailStore(); const { quota, isPushConnected } = useEmailStore();
@@ -58,8 +67,10 @@ export default function CalendarPage() {
setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar, setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar,
refreshAllSubscriptions, refreshAllSubscriptions,
} = useCalendarStore(); } = useCalendarStore();
const { firstDayOfWeek, timeFormat } = useSettingsStore(); const { firstDayOfWeek, timeFormat, showWeekNumbers, enableCalendarTasks, showTasksOnCalendar } = useSettingsStore();
const taskStore = useTaskStore();
const { identities } = useIdentityStore(); const { identities } = useIdentityStore();
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
const currentUserEmails = useMemo(() => const currentUserEmails = useMemo(() =>
identities.map(id => id.email).filter(Boolean), identities.map(id => id.email).filter(Boolean),
@@ -76,6 +87,9 @@ export default function CalendarPage() {
const [pendingScopeAction, setPendingScopeAction] = useState<PendingScopeAction | null>(null); const [pendingScopeAction, setPendingScopeAction] = useState<PendingScopeAction | null>(null);
const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null); const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null);
const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null); const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null);
const [pendingPreview, setPendingPreview] = useState<PendingEventPreview | null>(null);
const [showTaskModal, setShowTaskModal] = useState(false);
const [editTask, setEditTask] = useState<import("@/lib/jmap/types").CalendarTask | null>(null);
const hasFetched = useRef(false); const hasFetched = useRef(false);
// Sidebar resize state // Sidebar resize state
@@ -98,7 +112,7 @@ export default function CalendarPage() {
useEffect(() => { useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) { if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ } try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login"); redirectToLogin();
} else if (client && !supportsCalendar) { } else if (client && !supportsCalendar) {
router.push("/"); router.push("/");
} }
@@ -129,7 +143,7 @@ export default function CalendarPage() {
const dateRange = useMemo(() => { const dateRange = useMemo(() => {
const d = selectedDate; const d = selectedDate;
switch (viewMode) { switch (normalizedViewMode) {
case "month": { case "month": {
const ms = startOfMonth(d); const ms = startOfMonth(d);
const me = endOfMonth(d); const me = endOfMonth(d);
@@ -150,43 +164,58 @@ export default function CalendarPage() {
start: format(d, "yyyy-MM-dd'T'00:00:00"), start: format(d, "yyyy-MM-dd'T'00:00:00"),
end: format(d, "yyyy-MM-dd'T'23:59:59"), 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 { return {
start: format(d, "yyyy-MM-dd'T'00:00:00"), start: format(agendaStart, "yyyy-MM-dd'T'00:00:00"),
end: format(addDays(d, 30), "yyyy-MM-dd'T'23:59:59"), end: format(addDays(agendaStart, 30), "yyyy-MM-dd'T'23:59:59"),
}; };
}
case "tasks":
return null;
} }
}, [selectedDate, viewMode, firstDayOfWeek]); }, [selectedDate, normalizedViewMode, firstDayOfWeek]);
// Fetch tasks when tasks view is active or when tasks are shown on calendar grid
useEffect(() => {
if (client && enableCalendarTasks && (normalizedViewMode === "tasks" || showTasksOnCalendar)) {
taskStore.fetchTasks(client);
}
}, [client, enableCalendarTasks, normalizedViewMode, showTasksOnCalendar]);
useEffect(() => { useEffect(() => {
if (client && calendars.length > 0) { if (client && calendars.length > 0 && dateRange) {
fetchEvents(client, dateRange.start, dateRange.end); fetchEvents(client, dateRange.start, dateRange.end);
} }
}, [client, calendars.length, dateRange, fetchEvents]); }, [client, calendars.length, dateRange, fetchEvents]);
const navigatePrev = useCallback(() => { const navigatePrev = useCallback(() => {
let next: Date; let next: Date;
switch (viewMode) { switch (normalizedViewMode) {
case "month": next = subMonths(selectedDate, 1); break; case "month": next = subMonths(selectedDate, 1); break;
case "week": next = subWeeks(selectedDate, 1); break; case "week": next = subWeeks(selectedDate, 1); break;
case "day": next = subDays(selectedDate, 1); break; case "day": next = subDays(selectedDate, 1); break;
case "agenda": next = subMonths(selectedDate, 1); break; case "agenda": next = subMonths(selectedDate, 1); break;
case "tasks": return;
} }
setSelectedDate(next); setSelectedDate(next);
setMiniMonth(next); setMiniMonth(next);
}, [viewMode, selectedDate, setSelectedDate]); }, [normalizedViewMode, selectedDate, setSelectedDate]);
const navigateNext = useCallback(() => { const navigateNext = useCallback(() => {
let next: Date; let next: Date;
switch (viewMode) { switch (normalizedViewMode) {
case "month": next = addMonths(selectedDate, 1); break; case "month": next = addMonths(selectedDate, 1); break;
case "week": next = addWeeks(selectedDate, 1); break; case "week": next = addWeeks(selectedDate, 1); break;
case "day": next = addDays(selectedDate, 1); break; case "day": next = addDays(selectedDate, 1); break;
case "agenda": next = addMonths(selectedDate, 1); break; case "agenda": next = addMonths(selectedDate, 1); break;
case "tasks": return;
} }
setSelectedDate(next); setSelectedDate(next);
setMiniMonth(next); setMiniMonth(next);
}, [viewMode, selectedDate, setSelectedDate]); }, [normalizedViewMode, selectedDate, setSelectedDate]);
const goToToday = useCallback(() => { const goToToday = useCallback(() => {
setSelectedDate(new Date()); setSelectedDate(new Date());
@@ -218,10 +247,10 @@ export default function CalendarPage() {
setSelectedDate(date); setSelectedDate(date);
setMiniMonth(date); setMiniMonth(date);
// On mobile month view, tapping a date switches to day view // On mobile month view, tapping a date switches to day view
if (isMobile && viewMode === "month") { if (isMobile && normalizedViewMode === "month") {
setViewMode("day"); setViewMode("day");
} }
}, [setSelectedDate, isMobile, viewMode, setViewMode]); }, [setSelectedDate, isMobile, normalizedViewMode, setViewMode]);
const handleMiniMonthChange = useCallback((date: Date) => { const handleMiniMonthChange = useCallback((date: Date) => {
setMiniMonth(date); setMiniMonth(date);
@@ -230,10 +259,12 @@ export default function CalendarPage() {
const openCreateModal = useCallback((date?: Date, endDate?: Date) => { const openCreateModal = useCallback((date?: Date, endDate?: Date) => {
setEditEvent(null); setEditEvent(null);
setDefaultModalDate(date || selectedDate); const d = date || selectedDate;
setDefaultModalDate(d);
setDefaultModalEndDate(endDate); setDefaultModalEndDate(endDate);
setSelectedDate(d);
setShowEventModal(true); setShowEventModal(true);
}, [selectedDate]); }, [selectedDate, setSelectedDate]);
const openEditModal = useCallback((event: CalendarEvent) => { const openEditModal = useCallback((event: CalendarEvent) => {
setEditEvent(event); setEditEvent(event);
@@ -241,6 +272,34 @@ export default function CalendarPage() {
setShowEventModal(true); setShowEventModal(true);
}, []); }, []);
const openCreateTaskModal = useCallback(() => {
setEditTask(null);
setShowTaskModal(true);
}, []);
const openEditTaskModal = useCallback((task: import("@/lib/jmap/types").CalendarTask) => {
setEditTask(task);
setShowTaskModal(true);
}, []);
const handleSaveTask = useCallback(async (data: Partial<import("@/lib/jmap/types").CalendarTask>) => {
if (!client) return;
if (editTask) {
await taskStore.updateTask(client, editTask.id, data);
} else {
await taskStore.createTask(client, data);
}
setShowTaskModal(false);
setEditTask(null);
}, [client, editTask, taskStore]);
const handleDeleteTask = useCallback(async (id: string) => {
if (!client) return;
await taskStore.deleteTask(client, id);
setShowTaskModal(false);
setEditTask(null);
}, [client, taskStore]);
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null); const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeDetail = useCallback(() => { const closeDetail = useCallback(() => {
@@ -256,12 +315,13 @@ export default function CalendarPage() {
}, [closeDetail, openEditModal]); }, [closeDetail, openEditModal]);
const handleHoverEvent = useCallback((event: CalendarEvent, anchorRect: DOMRect) => { const handleHoverEvent = useCallback((event: CalendarEvent, anchorRect: DOMRect) => {
if (isMobile) return;
if (hoverTimerRef.current) { clearTimeout(hoverTimerRef.current); hoverTimerRef.current = null; } if (hoverTimerRef.current) { clearTimeout(hoverTimerRef.current); hoverTimerRef.current = null; }
// Don't show hover popover if the sidebar is already open for this event // Don't show hover popover if the sidebar is already open for this event
if (showEventModal && editEvent?.id === event.id) return; if (showEventModal && editEvent?.id === event.id) return;
setDetailEvent(event); setDetailEvent(event);
setDetailAnchorRect(anchorRect); setDetailAnchorRect(anchorRect);
}, [showEventModal, editEvent]); }, [isMobile, showEventModal, editEvent]);
const handleHoverLeave = useCallback(() => { const handleHoverLeave = useCallback(() => {
hoverTimerRef.current = setTimeout(() => { hoverTimerRef.current = setTimeout(() => {
@@ -410,9 +470,22 @@ export default function CalendarPage() {
try { try {
if (type === "edit" && updates) { if (type === "edit" && updates) {
switch (scope) { switch (scope) {
case "this": case "this": {
await updateEvent(client, event.id, updates, sendScheduling); // Synthetic IDs (from expandRecurrences) can't be updated directly.
// Patch the master event's recurrenceOverrides instead.
const master = await findMasterEvent(event);
if (master && event.recurrenceId) {
const patchUpdates: Record<string, unknown> = {};
for (const [key, value] of Object.entries(updates)) {
if (['id', 'uid', '@type', 'calendarIds', 'recurrenceRules', 'recurrenceOverrides', 'excludedRecurrenceRules'].includes(key)) continue;
patchUpdates[`recurrenceOverrides/${event.recurrenceId}/${key}`] = value;
}
await updateEvent(client, master.id, patchUpdates as Partial<CalendarEvent>, sendScheduling);
} else {
await updateEvent(client, event.id, updates, sendScheduling);
}
break; break;
}
case "this_and_future": { case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event); const result = await truncateRecurrenceAtEvent(event);
if (!result) { if (!result) {
@@ -470,9 +543,20 @@ export default function CalendarPage() {
toast.success(t("notifications.event_updated")); toast.success(t("notifications.event_updated"));
} else { } else {
switch (scope) { switch (scope) {
case "this": case "this": {
await deleteEvent(client, event.id, sendScheduling); // Synthetic IDs (from expandRecurrences) can't be destroyed directly.
// Exclude the instance via recurrenceOverrides on the master event.
const delMaster = await findMasterEvent(event);
if (delMaster && event.recurrenceId) {
await updateEvent(
client, delMaster.id,
{ [`recurrenceOverrides/${event.recurrenceId}`]: { excluded: true } } as Partial<CalendarEvent>,
);
} else {
await deleteEvent(client, event.id, sendScheduling);
}
break; break;
}
case "this_and_future": { case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event); const result = await truncateRecurrenceAtEvent(event);
if (!result) { if (!result) {
@@ -584,6 +668,7 @@ export default function CalendarPage() {
const handleKey = (e: KeyboardEvent) => { const handleKey = (e: KeyboardEvent) => {
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return; if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return;
if (target.getAttribute("contenteditable") === "true") return;
if (showEventModal || detailEvent) return; if (showEventModal || detailEvent) return;
switch (e.key) { switch (e.key) {
@@ -594,6 +679,7 @@ export default function CalendarPage() {
case "w": setViewMode("week"); break; case "w": setViewMode("week"); break;
case "d": setViewMode("day"); break; case "d": setViewMode("day"); break;
case "a": setViewMode("agenda"); break; case "a": setViewMode("agenda"); break;
case "k": if (enableCalendarTasks) setViewMode("tasks"); break;
case "n": openCreateModal(); break; case "n": openCreateModal(); break;
} }
}; };
@@ -603,6 +689,7 @@ export default function CalendarPage() {
const visibleEvents = useMemo(() => const visibleEvents = useMemo(() =>
events.filter((e) => { events.filter((e) => {
if (!e.start || !e.calendarIds) return false;
const calIds = Object.keys(e.calendarIds); const calIds = Object.keys(e.calendarIds);
return calIds.some((id) => selectedCalendarIds.includes(id)); return calIds.some((id) => selectedCalendarIds.includes(id));
}), }),
@@ -621,7 +708,7 @@ export default function CalendarPage() {
} }
const viewContent = (() => { const viewContent = (() => {
switch (viewMode) { switch (normalizedViewMode) {
case "month": case "month":
return ( return (
<CalendarMonthView <CalendarMonthView
@@ -632,8 +719,10 @@ export default function CalendarPage() {
onSelectEvent={handleSelectEvent} onSelectEvent={handleSelectEvent}
onHoverEvent={handleHoverEvent} onHoverEvent={handleHoverEvent}
onHoverLeave={handleHoverLeave} onHoverLeave={handleHoverLeave}
onCreateAtTime={openCreateModal}
firstDayOfWeek={firstDayOfWeek} firstDayOfWeek={firstDayOfWeek}
isMobile={isMobile} isMobile={isMobile}
pendingPreview={pendingPreview}
/> />
); );
case "week": case "week":
@@ -650,6 +739,9 @@ export default function CalendarPage() {
firstDayOfWeek={firstDayOfWeek} firstDayOfWeek={firstDayOfWeek}
timeFormat={timeFormat} timeFormat={timeFormat}
isMobile={isMobile} isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/> />
); );
case "day": case "day":
@@ -664,6 +756,9 @@ export default function CalendarPage() {
onCreateAtTime={openCreateModal} onCreateAtTime={openCreateModal}
timeFormat={timeFormat} timeFormat={timeFormat}
isMobile={isMobile} isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/> />
); );
case "agenda": case "agenda":
@@ -678,13 +773,40 @@ export default function CalendarPage() {
timeFormat={timeFormat} timeFormat={timeFormat}
/> />
); );
case "tasks":
return (
<div className="flex flex-col h-full">
<TaskToolbar
filter={taskStore.filter}
showCompleted={taskStore.showCompleted}
onFilterChange={taskStore.setFilter}
onShowCompletedChange={taskStore.setShowCompleted}
onCreateTask={openCreateTaskModal}
/>
<TaskListView
tasks={taskStore.tasks}
calendars={calendars}
selectedCalendarIds={selectedCalendarIds}
filter={taskStore.filter}
showCompleted={taskStore.showCompleted}
onSelectTask={openEditTaskModal}
onToggleComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
selectedTaskId={taskStore.selectedTaskId}
onQuickCreate={(title) => {
if (client) {
taskStore.createTask(client, { "@type": "Task", title, progress: "needs-action", calendarIds: { [calendars[0]?.id ?? ""]: true } });
}
}}
/>
</div>
);
} }
})(); })();
return ( return (
<div className="relative flex-1 flex flex-col overflow-hidden"> <div className="relative flex-1 flex flex-col overflow-hidden">
{viewContent} {viewContent}
{isLoadingEvents && calendars.length > 0 && ( {isLoadingEvents && calendars.length > 0 && events.length === 0 && (
<div className="absolute inset-0 bg-background/50 flex items-center justify-center pointer-events-none"> <div className="absolute inset-0 bg-background/50 flex items-center justify-center pointer-events-none">
<div className="h-5 w-5 border-2 border-primary border-t-transparent rounded-full animate-spin" /> <div className="h-5 w-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
</div> </div>
@@ -694,7 +816,7 @@ export default function CalendarPage() {
}; };
return ( 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 */} {/* Left Navigation Rail */}
{!isMobile && ( {!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}> <div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -702,13 +824,21 @@ export default function CalendarPage() {
collapsed collapsed
quota={quota} quota={quota}
isPushConnected={isPushConnected} isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }} onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/> />
</div> </div>
)} )}
{inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
)}
{/* Sidebar - full height */} {/* Sidebar - full height */}
{!isMobile && ( {!isMobile && !inlineApp && (
<> <>
<div <div
className={cn( className={cn(
@@ -724,6 +854,7 @@ export default function CalendarPage() {
onChangeMonth={handleMiniMonthChange} onChangeMonth={handleMiniMonthChange}
events={events} events={events}
firstDayOfWeek={firstDayOfWeek} firstDayOfWeek={firstDayOfWeek}
showWeekNumbers={showWeekNumbers}
/> />
<CalendarSidebarPanel <CalendarSidebarPanel
calendars={calendars} calendars={calendars}
@@ -748,10 +879,11 @@ export default function CalendarPage() {
</> </>
)} )}
<div className="flex flex-col flex-1 min-w-0"> {!inlineApp && (
<div className="flex flex-col flex-1 min-w-0 min-h-0">
<CalendarToolbar <CalendarToolbar
selectedDate={selectedDate} selectedDate={selectedDate}
viewMode={viewMode} viewMode={normalizedViewMode}
onPrev={navigatePrev} onPrev={navigatePrev}
onNext={navigateNext} onNext={navigateNext}
onToday={goToToday} onToday={goToToday}
@@ -763,10 +895,12 @@ export default function CalendarPage() {
calendars={calendars} calendars={calendars}
selectedCalendarIds={selectedCalendarIds} selectedCalendarIds={selectedCalendarIds}
onToggleVisibility={toggleCalendarVisibility} onToggleVisibility={toggleCalendarVisibility}
enableCalendarTasks={enableCalendarTasks}
/> />
<div <div
className="flex flex-1 overflow-hidden relative" className="flex flex-1 overflow-hidden relative"
data-tour="calendar-view"
onTouchStart={handleTouchStart} onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd} onTouchEnd={handleTouchEnd}
> >
@@ -776,6 +910,7 @@ export default function CalendarPage() {
{!isMobile && showEventModal && ( {!isMobile && showEventModal && (
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden"> <div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
<EventModal <EventModal
key={editEvent?.id ?? 'new'}
event={editEvent} event={editEvent}
calendars={calendars} calendars={calendars}
defaultDate={defaultModalDate} defaultDate={defaultModalDate}
@@ -784,13 +919,29 @@ export default function CalendarPage() {
onDelete={handleDeleteEvent} onDelete={handleDeleteEvent}
onDuplicate={handleDuplicateEvent} onDuplicate={handleDuplicateEvent}
onRsvp={handleRsvp} onRsvp={handleRsvp}
onClose={() => { setShowEventModal(false); setEditEvent(null); }} onClose={() => { setShowEventModal(false); setEditEvent(null); setPendingPreview(null); }}
onPreviewChange={setPendingPreview}
currentUserEmails={currentUserEmails} currentUserEmails={currentUserEmails}
isMobile={false} isMobile={false}
/> />
</div> </div>
)} )}
{/* Desktop task panel */}
{!isMobile && showTaskModal && (
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
<TaskModal
key={editTask?.id ?? 'new-task'}
task={editTask}
calendars={calendars}
onSave={handleSaveTask}
onDelete={handleDeleteTask}
onClose={() => { setShowTaskModal(false); setEditTask(null); }}
isMobile={false}
/>
</div>
)}
{/* Floating Create Event Button (mobile) */} {/* Floating Create Event Button (mobile) */}
{isMobile && ( {isMobile && (
<Button <Button
@@ -802,12 +953,21 @@ export default function CalendarPage() {
</Button> </Button>
)} )}
</div> </div>
{/* Mobile Bottom Navigation */}
{isMobile && (
<NavigationRail orientation="horizontal" />
)}
</div> </div>
)}
{/* Mobile Bottom Navigation */}
{isMobile && (
<div className="shrink-0">
<NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
</div>
)}
{detailEvent && detailAnchorRect && ( {detailEvent && detailAnchorRect && (
<EventDetailPopover <EventDetailPopover
@@ -830,6 +990,7 @@ export default function CalendarPage() {
{showEventModal && isMobile && ( {showEventModal && isMobile && (
<EventModal <EventModal
key={editEvent?.id ?? 'new'}
event={editEvent} event={editEvent}
calendars={calendars} calendars={calendars}
defaultDate={defaultModalDate} defaultDate={defaultModalDate}
@@ -859,6 +1020,7 @@ export default function CalendarPage() {
/> />
)} )}
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<RecurrenceScopeDialog <RecurrenceScopeDialog
isOpen={!!pendingScopeAction} isOpen={!!pendingScopeAction}
actionType={pendingScopeAction?.type || "edit"} actionType={pendingScopeAction?.type || "edit"}
+167 -18
View File
@@ -1,7 +1,6 @@
"use client"; "use client";
import { useState, useEffect, useCallback, useRef, useMemo } from "react"; import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { ArrowLeft, Users } from "lucide-react"; import { ArrowLeft, Users } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -13,16 +12,20 @@ import { ContactForm } from "@/components/contacts/contact-form";
import { ContactGroupForm } from "@/components/contacts/contact-group-form"; import { ContactGroupForm } from "@/components/contacts/contact-group-form";
import { ContactGroupDetail } from "@/components/contacts/contact-group-detail"; import { ContactGroupDetail } from "@/components/contacts/contact-group-detail";
import { ContactsSidebar, type ContactCategory } from "@/components/contacts/contacts-sidebar"; 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 { exportContacts } from "@/components/contacts/contact-export";
import { useContactStore, getContactDisplayName } from "@/stores/contact-store"; import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { NavigationRail } from "@/components/layout/navigation-rail"; import { NavigationRail } from "@/components/layout/navigation-rail";
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
import { InlineAppView } from "@/components/layout/inline-app-view";
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { ResizeHandle } from "@/components/layout/resize-handle"; import { ResizeHandle } from "@/components/layout/resize-handle";
import { useIsMobile } from "@/hooks/use-media-query"; import { useIsMobile } from "@/hooks/use-media-query";
import type { ContactCard } from "@/lib/jmap/types"; import type { ContactCard, AddressBook } from "@/lib/jmap/types";
type View = type View =
| "list" | "list"
@@ -35,13 +38,14 @@ type View =
| "bulk-add-to-group"; | "bulk-add-to-group";
export default function ContactsPage() { export default function ContactsPage() {
const router = useRouter();
const t = useTranslations("contacts"); const t = useTranslations("contacts");
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore(); const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client); const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
const { quota, isPushConnected } = useEmailStore(); const { quota, isPushConnected } = useEmailStore();
const { const {
contacts, contacts,
addressBooks,
selectedContactId, selectedContactId,
searchQuery, searchQuery,
supportsSync, supportsSync,
@@ -67,10 +71,13 @@ export default function ContactsPage() {
clearSelection, clearSelection,
bulkDeleteContacts, bulkDeleteContacts,
bulkAddToGroup, bulkAddToGroup,
moveContactToAddressBook,
importContacts,
} = useContactStore(); } = useContactStore();
const [view, setView] = useState<View>("list"); const [view, setView] = useState<View>("list");
const [activeCategory, setActiveCategory] = useState<ContactCategory>("all"); const [activeCategory, setActiveCategory] = useState<ContactCategory>("all");
const [showImportDialog, setShowImportDialog] = useState(false);
const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null); const [selectedGroupId, setSelectedGroupId] = useState<string | null>(null);
const hasFetched = useRef(false); const hasFetched = useRef(false);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog(); const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
@@ -78,10 +85,10 @@ export default function ContactsPage() {
// Panel resize state - sidebar (categories) // Panel resize state - sidebar (categories)
const [sidebarWidth, setSidebarWidth] = useState(() => { 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 [isSidebarResizing, setIsSidebarResizing] = useState(false);
const sidebarDragStartWidth = useRef(180); const sidebarDragStartWidth = useRef(256);
// Panel resize state - contact list // Panel resize state - contact list
const [listWidth, setListWidth] = useState(() => { const [listWidth, setListWidth] = useState(() => {
@@ -100,9 +107,9 @@ export default function ContactsPage() {
useEffect(() => { useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) { if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ } try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login"); redirectToLogin();
} }
}, [initialCheckDone, isAuthenticated, authLoading, router]); }, [initialCheckDone, isAuthenticated, authLoading]);
useEffect(() => { useEffect(() => {
if (client && supportsSync && !hasFetched.current) { if (client && supportsSync && !hasFetched.current) {
@@ -117,9 +124,34 @@ export default function ContactsPage() {
const selectedGroup = selectedGroupId ? contacts.find(c => c.id === selectedGroupId) || null : null; const selectedGroup = selectedGroupId ? contacts.find(c => c.id === selectedGroupId) || null : null;
const selectedGroupMembers = selectedGroupId ? getGroupMembers(selectedGroupId) : []; const selectedGroupMembers = selectedGroupId ? getGroupMembers(selectedGroupId) : [];
// Collect all unique keywords across contacts
const allKeywords = useMemo(() => {
const kws = new Set<string>();
for (const contact of individuals) {
if (!contact.keywords) continue;
for (const [kw, active] of Object.entries(contact.keywords)) {
if (active) kws.add(kw);
}
}
return Array.from(kws).sort((a, b) => a.localeCompare(b));
}, [individuals]);
// Contacts to display based on active category // Contacts to display based on active category
const displayedContacts = useMemo(() => { const displayedContacts = useMemo(() => {
if (activeCategory === "all") return individuals; if (activeCategory === "all") return individuals;
if (activeCategory === "uncategorized") {
return individuals.filter(c => !c.keywords || Object.keys(c.keywords).filter(k => c.keywords![k]).length === 0);
}
if ("addressBookId" in activeCategory) {
const bookId = activeCategory.addressBookId;
return individuals.filter(c => {
if (!c.addressBookIds) 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 // Show members of the selected group
return getGroupMembers(activeCategory.groupId); return getGroupMembers(activeCategory.groupId);
}, [activeCategory, individuals, getGroupMembers]); }, [activeCategory, individuals, getGroupMembers]);
@@ -127,20 +159,75 @@ export default function ContactsPage() {
// Label for the current category // Label for the current category
const categoryLabel = useMemo(() => { const categoryLabel = useMemo(() => {
if (activeCategory === "all") return t("tabs.all"); if (activeCategory === "all") return t("tabs.all");
if (activeCategory === "uncategorized") return t("no_category");
if ("addressBookId" in activeCategory) {
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); const group = contacts.find(c => c.id === activeCategory.groupId);
return group ? getContactDisplayName(group) : t("tabs.all"); return group ? getContactDisplayName(group) : t("tabs.all");
}, [activeCategory, contacts, t]); }, [activeCategory, contacts, addressBooks, t]);
const handleSelectCategory = useCallback((category: ContactCategory) => { const handleSelectCategory = useCallback((category: ContactCategory) => {
setActiveCategory(category); setActiveCategory(category);
clearSelection(); clearSelection();
if (typeof category === "object") { if (typeof category === "object" && "groupId" in category) {
setSelectedGroupId(category.groupId); setSelectedGroupId(category.groupId);
setView("group-detail");
} else { } else {
setSelectedGroupId(null); setSelectedGroupId(null);
} }
}, [clearSelection]); }, [clearSelection]);
const handleDropContacts = useCallback(async (contactIds: string[], addressBook: AddressBook) => {
if (!client) return;
try {
await moveContactToAddressBook(client, contactIds, addressBook);
const msg = contactIds.length === 1
? t("address_books.moved", { name: addressBook.name })
: t("address_books.moved_plural", { count: contactIds.length, name: addressBook.name });
toast.success(msg);
} catch (error) {
console.error('Failed to move contacts:', error);
toast.error(t("address_books.move_failed"));
}
}, [client, moveContactToAddressBook, t]);
const handleDropContactsToCategory = useCallback(async (contactIds: string[], keyword: string) => {
if (!client && supportsSync) return;
try {
for (const contactId of contactIds) {
const contact = contacts.find(c => c.id === contactId);
if (!contact) continue;
const existingKeywords = contact.keywords || {};
if (existingKeywords[keyword]) continue; // already has this keyword
const updatedKeywords = { ...existingKeywords, [keyword]: true };
if (supportsSync && client) {
await updateContact(client, contactId, { keywords: updatedKeywords });
} else {
updateLocalContact(contactId, { keywords: updatedKeywords });
}
}
const msg = contactIds.length === 1
? t("category_added", { name: keyword })
: t("category_added_plural", { count: contactIds.length, name: keyword });
toast.success(msg);
} catch (error) {
console.error('Failed to add contacts to category:', error);
toast.error(t("toast.error_update"));
}
}, [client, supportsSync, contacts, updateContact, updateLocalContact, t]);
const handleImportContacts = useCallback(async (importedContacts: ContactCard[]) => {
return importContacts(
supportsSync && client ? client : null,
importedContacts
);
}, [supportsSync, client, importContacts]);
const handleSelectContact = (id: string) => { const handleSelectContact = (id: string) => {
setSelectedContact(id); setSelectedContact(id);
clearSelection(); clearSelection();
@@ -235,6 +322,35 @@ export default function ContactsPage() {
setView("group-edit"); 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 () => { const handleDeleteGroup = async () => {
if (!selectedGroup) return; if (!selectedGroup) return;
@@ -353,13 +469,15 @@ export default function ContactsPage() {
const renderRightPanel = () => { const renderRightPanel = () => {
switch (view) { switch (view) {
case "create": case "create":
return <ContactForm onSave={handleSaveNew} onCancel={handleCancel} />; return <ContactForm addressBooks={addressBooks} allKeywords={allKeywords} onSave={handleSaveNew} onCancel={handleCancel} />;
case "edit": case "edit":
if (!selectedContact) return null; if (!selectedContact) return null;
return ( return (
<ContactForm <ContactForm
contact={selectedContact} contact={selectedContact}
addressBooks={addressBooks}
allKeywords={allKeywords}
onSave={handleSaveEdit} onSave={handleSaveEdit}
onCancel={handleCancel} onCancel={handleCancel}
/> />
@@ -377,7 +495,6 @@ export default function ContactsPage() {
isMobile={isMobile} isMobile={isMobile}
onSelectMember={(id) => { onSelectMember={(id) => {
setSelectedContact(id); setSelectedContact(id);
setActiveCategory("all");
setView("detail"); setView("detail");
}} }}
/> />
@@ -467,7 +584,7 @@ export default function ContactsPage() {
}; };
return ( 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 */} {/* Navigation Rail - desktop only */}
{!isMobile && ( {!isMobile && (
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}> <div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
@@ -475,13 +592,20 @@ export default function ContactsPage() {
collapsed collapsed
quota={quota} quota={quota}
isPushConnected={isPushConnected} isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }} onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/> />
</div> </div>
)} )}
<div className="flex flex-col flex-1 min-w-0"> <div className="flex flex-col flex-1 min-w-0">
<div className="flex flex-1 min-h-0"> {inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} />
)}
<div className={cn("flex flex-1 min-h-0", inlineApp && "hidden")}>
{showListPanel && ( {showListPanel && (
<> <>
{/* Panel 1: Categories sidebar */} {/* Panel 1: Categories sidebar */}
@@ -497,26 +621,33 @@ export default function ContactsPage() {
<ContactsSidebar <ContactsSidebar
groups={groups} groups={groups}
individuals={individuals} individuals={individuals}
addressBooks={addressBooks}
activeCategory={activeCategory} activeCategory={activeCategory}
onSelectCategory={handleSelectCategory} onSelectCategory={handleSelectCategory}
onCreateGroup={handleCreateGroup} onCreateGroup={handleCreateGroup}
onCreateContact={handleCreateNew} onCreateContact={handleCreateNew}
onImport={() => setShowImportDialog(true)}
onEditGroup={handleEditGroupFromSidebar}
onDeleteGroup={handleDeleteGroupFromSidebar}
onDropContacts={handleDropContacts}
onDropContactsToCategory={handleDropContactsToCategory}
/> />
</div> </div>
<ResizeHandle <ResizeHandle
onResizeStart={() => { sidebarDragStartWidth.current = sidebarWidth; setIsSidebarResizing(true); }} 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={() => { onResizeEnd={() => {
setIsSidebarResizing(false); setIsSidebarResizing(false);
localStorage.setItem("contacts-sidebar-width", String(sidebarWidth)); 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"); }}
/> />
</> </>
)} )}
{/* Panel 2: Contact list */} {/* Panel 2: Contact list */}
<div <div
data-tour="contacts-list"
className={cn( className={cn(
"border-r border-border bg-background flex flex-col flex-shrink-0", "border-r border-border bg-background flex flex-col flex-shrink-0",
isMobile ? "w-full" : "", isMobile ? "w-full" : "",
@@ -582,11 +713,29 @@ export default function ContactsPage() {
</div> </div>
{isMobile && ( {isMobile && (
<NavigationRail orientation="horizontal" /> <NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
)} )}
</div> </div>
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<ConfirmDialog {...confirmDialogProps} /> <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> </div>
); );
} }
+24 -6
View File
@@ -7,12 +7,15 @@ import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { useConfirmDialog } from "@/hooks/use-confirm-dialog"; import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useFileStore } from "@/stores/file-store"; import { useFileStore } from "@/stores/file-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { NavigationRail } from "@/components/layout/navigation-rail"; import { NavigationRail } from "@/components/layout/navigation-rail";
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
import { InlineAppView } from "@/components/layout/inline-app-view";
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { useIsMobile } from "@/hooks/use-media-query"; import { useIsMobile } from "@/hooks/use-media-query";
import { FileBrowser } from "@/components/files/file-browser"; import { FileBrowser } from "@/components/files/file-browser";
import { ImagePreviewModal } from "@/components/files/image-preview-modal"; import { ImagePreviewModal } from "@/components/files/image-preview-modal";
@@ -24,6 +27,7 @@ export default function FilesPage() {
const router = useRouter(); const router = useRouter();
const t = useTranslations("files"); const t = useTranslations("files");
const { isAuthenticated, logout, checkAuth, isLoading: authLoading, client } = useAuthStore(); const { isAuthenticated, logout, checkAuth, isLoading: authLoading, client } = useAuthStore();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client); const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
const { quota, isPushConnected } = useEmailStore(); const { quota, isPushConnected } = useEmailStore();
const { const {
@@ -108,9 +112,9 @@ export default function FilesPage() {
useEffect(() => { useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) { if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ } try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login"); redirectToLogin();
} }
}, [initialCheckDone, isAuthenticated, authLoading, router]); }, [initialCheckDone, isAuthenticated, authLoading]);
// Initialize JMAP files client // Initialize JMAP files client
useEffect(() => { useEffect(() => {
@@ -353,13 +357,20 @@ export default function FilesPage() {
collapsed collapsed
quota={quota} quota={quota}
isPushConnected={isPushConnected} isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }} onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/> />
</div> </div>
)} )}
<div className="flex flex-col flex-1 min-w-0"> <div className="flex flex-col flex-1 min-w-0">
<div className="flex flex-1 min-h-0"> {inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} />
)}
<div className={cn("flex flex-1 min-h-0", inlineApp && "hidden")}>
<div className="flex-1 min-w-0 flex flex-col"> <div className="flex-1 min-w-0 flex flex-col">
{folderLayout !== "sidebar" && ( {folderLayout !== "sidebar" && (
<div className={cn("p-4 border-b border-border", isMobile && "px-3 py-3")}> <div className={cn("p-4 border-b border-border", isMobile && "px-3 py-3")}>
@@ -433,7 +444,13 @@ export default function FilesPage() {
</div> </div>
{isMobile && ( {isMobile && (
<NavigationRail orientation="horizontal" /> <NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
)} )}
</div> </div>
@@ -457,6 +474,7 @@ export default function FilesPage() {
/> />
)} )}
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<ConfirmDialog {...confirmDialogProps} /> <ConfirmDialog {...confirmDialogProps} />
</div> </div>
); );
+7 -1
View File
@@ -2,6 +2,8 @@ import { notFound } from "next/navigation";
import { IntlProvider } from "@/components/providers/intl-provider"; import { IntlProvider } from "@/components/providers/intl-provider";
import { ThemeProvider } from "@/components/providers/theme-provider"; import { ThemeProvider } from "@/components/providers/theme-provider";
import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider"; import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider";
import { EmbeddedBridgeProvider } from "@/components/providers/embedded-bridge-provider";
import { TourProvider } from "@/components/tour/tour-provider";
import { locales } from "@/i18n/routing"; import { locales } from "@/i18n/routing";
export default async function LocaleLayout({ export default async function LocaleLayout({
@@ -26,7 +28,11 @@ export default async function LocaleLayout({
<IntlProvider locale={locale} messages={messages}> <IntlProvider locale={locale} messages={messages}>
<ThemeProvider> <ThemeProvider>
<CalendarAlertProvider> <CalendarAlertProvider>
{children} <EmbeddedBridgeProvider>
<TourProvider>
{children}
</TourProvider>
</EmbeddedBridgeProvider>
</CalendarAlertProvider> </CalendarAlertProvider>
</ThemeProvider> </ThemeProvider>
</IntlProvider> </IntlProvider>
+273 -19
View File
@@ -2,7 +2,7 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import { useRouter } from "@/i18n/navigation"; import { useRouter } from "@/i18n/navigation";
import { useParams } from "next/navigation"; import { useParams, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -11,12 +11,12 @@ import { useThemeStore } from "@/stores/theme-store";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import { useConfig } from "@/hooks/use-config"; import { useConfig } from "@/hooks/use-config";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Mail, AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield } from "lucide-react"; import { Mail, AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play } from "lucide-react";
import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery"; import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce"; import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
import { OAUTH_SCOPES } from "@/lib/oauth/tokens"; import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
const APP_VERSION = "1.2.4"; const APP_VERSION = "1.4.7";
const THEME_OPTIONS = [ const THEME_OPTIONS = [
{ value: "light" as const, icon: Sun, label: "Light" }, { value: "light" as const, icon: Sun, label: "Light" },
@@ -28,9 +28,11 @@ export default function LoginPage() {
const router = useRouter(); const router = useRouter();
const t = useTranslations("login"); const t = useTranslations("login");
const params = useParams(); const params = useParams();
const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore(); const searchParams = useSearchParams();
const isAddAccountMode = searchParams.get("mode") === "add-account";
const { login, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore();
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme }))); 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(); const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode } = useConfig();
const resolvedTheme = useThemeStore((s) => s.resolvedTheme); const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
const [formData, setFormData] = useState({ const [formData, setFormData] = useState({
@@ -52,6 +54,7 @@ export default function LoginPage() {
const [oauthMetadata, setOauthMetadata] = useState<OAuthMetadata | null>(null); const [oauthMetadata, setOauthMetadata] = useState<OAuthMetadata | null>(null);
const [oauthDiscoveryDone, setOauthDiscoveryDone] = useState(false); const [oauthDiscoveryDone, setOauthDiscoveryDone] = useState(false);
const [oauthLoading, setOauthLoading] = useState(false); const [oauthLoading, setOauthLoading] = useState(false);
const [demoLoading, setDemoLoading] = useState(false);
const suggestionsRef = useRef<HTMLDivElement>(null); const suggestionsRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
@@ -102,7 +105,7 @@ export default function LoginPage() {
}, [serverUrl]); }, [serverUrl]);
useEffect(() => { useEffect(() => {
if (isAuthenticated) { if (isAuthenticated && !isAddAccountMode) {
let redirectTo = '/'; let redirectTo = '/';
try { try {
const saved = sessionStorage.getItem('redirect_after_login'); const saved = sessionStorage.getItem('redirect_after_login');
@@ -113,7 +116,7 @@ export default function LoginPage() {
} catch { /* ignore */ } } catch { /* ignore */ }
router.push(redirectTo); router.push(redirectTo);
} }
}, [isAuthenticated, router]); }, [isAuthenticated, router, isAddAccountMode]);
useEffect(() => { useEffect(() => {
clearError(); clearError();
@@ -170,6 +173,63 @@ export default function LoginPage() {
}); });
}, [oauthEnabled, serverUrl, oauthIssuerUrl]); }, [oauthEnabled, serverUrl, oauthIssuerUrl]);
// Auto-SSO: when enabled with OAUTH_ONLY, skip the login page entirely
const ssoError = searchParams.get("sso_error");
const autoSsoTriggered = useRef(false);
const startServerSideSso = useCallback(async () => {
setOauthLoading(true);
try {
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
const res = await fetch('/api/auth/sso/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ redirect_uri: redirectUri, locale: params.locale }),
});
if (!res.ok) {
setOauthLoading(false);
return;
}
const { authorize_url } = await res.json();
// Navigate to the authorize URL
const isIframe = (() => { try { return window.self !== window.top; } catch { return true; } })();
if (isIframe) {
// In an iframe, try top-level navigation
try {
window.top!.location.href = authorize_url;
} catch {
// Cross-origin restriction — fall back to current frame
window.location.href = authorize_url;
}
} else {
window.location.href = authorize_url;
}
} catch {
setOauthLoading(false);
}
}, [params.locale]);
useEffect(() => {
if (!autoSsoEnabled || !oauthOnly || !oauthDiscoveryDone || !oauthMetadata) return;
if (ssoError || isAddAccountMode || isAuthenticated) return;
if (autoSsoTriggered.current) return;
// Guard against redirect loops
try {
if (sessionStorage.getItem("sso_attempted")) return;
sessionStorage.setItem("sso_attempted", "1");
// Clear the flag after 30 seconds so retries are possible
setTimeout(() => { try { sessionStorage.removeItem("sso_attempted"); } catch { /* ignore */ } }, 30000);
} catch { /* sessionStorage unavailable */ }
autoSsoTriggered.current = true;
startServerSideSso();
}, [autoSsoEnabled, oauthOnly, oauthDiscoveryDone, oauthMetadata, ssoError, isAddAccountMode, isAuthenticated, startServerSideSso]);
const handleThemeSelect = useCallback((newTheme: "light" | "dark" | "system") => { const handleThemeSelect = useCallback((newTheme: "light" | "dark" | "system") => {
setTheme(newTheme); setTheme(newTheme);
setShowThemeMenu(false); setShowThemeMenu(false);
@@ -204,7 +264,7 @@ export default function LoginPage() {
); );
} }
if (!serverUrl) { if (!serverUrl && !demoMode) {
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/30"> <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/30">
<div className="w-full max-w-md mx-auto px-4 text-center"> <div className="w-full max-w-md mx-auto px-4 text-center">
@@ -303,6 +363,9 @@ export default function LoginPage() {
sessionStorage.setItem("oauth_code_verifier", verifier); sessionStorage.setItem("oauth_code_verifier", verifier);
sessionStorage.setItem("oauth_state", state); sessionStorage.setItem("oauth_state", state);
sessionStorage.setItem("oauth_server_url", serverUrl!); sessionStorage.setItem("oauth_server_url", serverUrl!);
if (isAddAccountMode) {
sessionStorage.setItem("oauth_add_account_mode", "true");
}
const authUrl = new URL(oauthMetadata.authorization_endpoint); const authUrl = new URL(oauthMetadata.authorization_endpoint);
authUrl.searchParams.set("response_type", "code"); authUrl.searchParams.set("response_type", "code");
@@ -329,15 +392,7 @@ export default function LoginPage() {
if (success) { if (success) {
saveUsername(formData.username); saveUsername(formData.username);
let redirectTo = '/'; router.push('/');
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* ignore */ }
router.push(redirectTo);
} }
}; };
@@ -356,9 +411,167 @@ export default function LoginPage() {
} }
}; };
const handleDemoLogin = async () => {
setDemoLoading(true);
const success = await loginDemo();
if (success) {
router.push('/');
}
setDemoLoading(false);
};
const currentThemeOption = THEME_OPTIONS.find(o => o.value === theme) || THEME_OPTIONS[2]; const currentThemeOption = THEME_OPTIONS.find(o => o.value === theme) || THEME_OPTIONS[2];
const CurrentThemeIcon = currentThemeOption.icon; const CurrentThemeIcon = currentThemeOption.icon;
// Demo-only mode: show only a large demo login button
if (demoMode && !isAddAccountMode) {
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4">
{/* Theme toggle */}
<div className="absolute top-5 right-5" ref={themeMenuRef} suppressHydrationWarning>
<button
type="button"
onClick={() => setShowThemeMenu(!showThemeMenu)}
className={cn(
"flex items-center gap-2 px-3 py-2 rounded-xl border text-sm transition-all duration-200",
showThemeMenu
? "bg-secondary border-border text-foreground shadow-md"
: "bg-background/60 backdrop-blur-sm border-border/50 text-muted-foreground hover:text-foreground hover:bg-secondary/80 hover:border-border"
)}
aria-label={`Theme: ${currentThemeOption.label}`}
aria-expanded={showThemeMenu}
aria-haspopup="listbox"
>
<CurrentThemeIcon className="w-4 h-4" />
<span className="hidden sm:inline" suppressHydrationWarning>{currentThemeOption.label}</span>
</button>
{showThemeMenu && (
<div
className="absolute right-0 top-full mt-2 w-40 rounded-xl border border-border bg-background shadow-lg overflow-hidden animate-fade-in z-50"
role="listbox"
aria-label="Theme selection"
>
{THEME_OPTIONS.map((option) => {
const Icon = option.icon;
const isActive = theme === option.value;
return (
<button
key={option.value}
type="button"
role="option"
aria-selected={isActive}
onClick={() => handleThemeSelect(option.value)}
className={cn(
"w-full flex items-center gap-3 px-3.5 py-2.5 text-sm transition-colors",
isActive
? "bg-primary/10 text-foreground font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
)}
>
<Icon className="w-4 h-4" />
<span className="flex-1 text-left">{option.label}</span>
{isActive && <Check className="w-3.5 h-3.5 text-primary" />}
</button>
);
})}
</div>
)}
</div>
<div className="w-full max-w-[440px] mx-auto">
<div className="rounded-2xl border border-border/60 bg-background/80 backdrop-blur-sm shadow-xl shadow-black/5 dark:shadow-black/20 overflow-hidden">
{/* Header with logo */}
<div className="px-8 pt-12 pb-4 text-center">
<div className="inline-flex items-center justify-center w-20 h-20 mb-6">
<img
src={resolvedTheme === 'dark' ? loginLogoDarkUrl : loginLogoLightUrl}
alt={appName}
className="max-w-20 max-h-20 object-contain"
/>
</div>
<h1 className="text-3xl font-bold text-foreground tracking-tight">
{appName}
</h1>
<p className="text-base text-muted-foreground mt-2 max-w-xs mx-auto leading-relaxed">
{t("demo_tagline")}
</p>
</div>
{/* Large demo button */}
<div className="px-8 pb-10 pt-4">
{error && (
<div className={cn(
"mb-5 p-3.5 bg-red-500/10 border border-red-500/20 rounded-xl flex items-start gap-3",
shakeError && "animate-shake"
)}>
<AlertCircle className="w-4.5 h-4.5 text-red-500 flex-shrink-0 mt-0.5" />
<p className="text-sm text-red-600 dark:text-red-400 leading-relaxed">
{t(`error.${error}`) || t("error.generic")}
</p>
</div>
)}
<Button
type="button"
className="w-full h-14 font-semibold text-lg bg-primary hover:bg-primary/90 transition-all duration-200 rounded-xl shadow-lg shadow-primary/25 hover:shadow-xl hover:shadow-primary/30 hover:scale-[1.02] active:scale-[0.98]"
onClick={handleDemoLogin}
disabled={demoLoading || isLoading}
>
{demoLoading ? (
<div className="flex items-center gap-3">
<Loader2 className="w-5 h-5 animate-spin" />
{t("demo_launching")}
</div>
) : (
<div className="flex items-center gap-3">
<Play className="w-5 h-5" />
{t("demo_login_button")}
</div>
)}
</Button>
<p className="text-center text-sm text-muted-foreground mt-4 leading-relaxed">
{t("demo_no_signup")}
</p>
</div>
</div>
{/* Footer */}
<div className="mt-6 flex flex-col items-center gap-2">
{loginCompanyName && (
<p className="text-center text-xs text-muted-foreground/60 font-medium">
{loginCompanyName}
</p>
)}
{(loginImprintUrl || loginPrivacyPolicyUrl || loginWebsiteUrl) && (
<div className="flex items-center gap-3 flex-wrap justify-center">
{loginWebsiteUrl && (
<a href={loginWebsiteUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
{t("website")}
</a>
)}
{loginImprintUrl && (
<a href={loginImprintUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
{t("imprint")}
</a>
)}
{loginPrivacyPolicyUrl && (
<a href={loginPrivacyPolicyUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
{t("privacy_policy")}
</a>
)}
</div>
)}
<p className="text-center text-xs text-muted-foreground/40">
v{APP_VERSION}
</p>
</div>
</div>
</div>
);
}
return ( return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4"> <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4">
{/* Theme toggle - top right, dropdown style */} {/* Theme toggle - top right, dropdown style */}
@@ -426,10 +639,10 @@ export default function LoginPage() {
/> />
</div> </div>
<h1 className="text-2xl font-semibold text-foreground tracking-tight"> <h1 className="text-2xl font-semibold text-foreground tracking-tight">
{appName} {isAddAccountMode ? t("add_account_title") : appName}
</h1> </h1>
<p className="text-sm text-muted-foreground mt-1.5"> <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> </p>
</div> </div>
@@ -737,6 +950,47 @@ export default function LoginPage() {
)} )}
</form> </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>
)}
{/* Demo Mode Button */}
{demoMode && !isAddAccountMode && (
<div className="mt-4 pt-4 border-t border-border/40">
<Button
type="button"
variant="outline"
className="w-full h-11 font-medium text-[15px] rounded-xl border-border/60 hover:bg-muted/50"
onClick={handleDemoLogin}
disabled={demoLoading || isLoading}
>
{demoLoading ? (
<div className="flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
{t("demo_launching")}
</div>
) : (
<div className="flex items-center gap-2">
<Play className="w-4 h-4" />
{t("try_demo")}
</div>
)}
</Button>
<p className="text-center text-xs text-muted-foreground mt-2">
{t("demo_description")}
</p>
</div>
)}
</div> </div>
</div> </div>
+150 -34
View File
@@ -1,7 +1,6 @@
"use client"; "use client";
import { useEffect, useState, useRef, useMemo, useCallback } from "react"; import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Sidebar } from "@/components/layout/sidebar"; import { Sidebar } from "@/components/layout/sidebar";
import { EmailList } from "@/components/email/email-list"; import { EmailList } from "@/components/email/email-list";
@@ -13,7 +12,7 @@ import { MobileHeader, MobileViewerHeader } from "@/components/layout/mobile-hea
import { ThreadGroup, Email } from "@/lib/jmap/types"; import { ThreadGroup, Email } from "@/lib/jmap/types";
import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal"; import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useSettingsStore } from "@/stores/settings-store"; import { useSettingsStore } from "@/stores/settings-store";
import { useIdentityStore } from "@/stores/identity-store"; import { useIdentityStore } from "@/stores/identity-store";
import { useUIStore } from "@/stores/ui-store"; import { useUIStore } from "@/stores/ui-store";
@@ -35,22 +34,28 @@ import { DragDropProvider } from "@/contexts/drag-drop-context";
import { isFilterEmpty, activeFilterCount } from "@/lib/jmap/search-utils"; import { isFilterEmpty, activeFilterCount } from "@/lib/jmap/search-utils";
import { WelcomeBanner } from "@/components/ui/welcome-banner"; import { WelcomeBanner } from "@/components/ui/welcome-banner";
import { NavigationRail } from "@/components/layout/navigation-rail"; import { NavigationRail } from "@/components/layout/navigation-rail";
import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
import { InlineAppView } from "@/components/layout/inline-app-view";
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { FilePreviewModal } from "@/components/files/file-preview-modal"; import { FilePreviewModal } from "@/components/files/file-preview-modal";
import { isFilePreviewable } from "@/lib/file-preview"; 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 { Search, Filter, ChevronDown, X, Paperclip, Star, Mail, MailOpen, RotateCcw, PenSquare, PenLine, CheckSquare, Square } from "lucide-react";
import { ResizeHandle } from "@/components/layout/resize-handle"; import { ResizeHandle } from "@/components/layout/resize-handle";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useConfig } from "@/hooks/use-config";
export default function Home() { export default function Home() {
const router = useRouter();
const t = useTranslations(); const t = useTranslations();
const tCommon = useTranslations('common'); const tCommon = useTranslations('common');
const { appName } = useConfig();
const [showComposer, setShowComposer] = useState(false); const [showComposer, setShowComposer] = useState(false);
const [composerMode, setComposerMode] = useState<'compose' | 'reply' | 'replyAll' | 'forward'>('compose'); const [composerMode, setComposerMode] = useState<'compose' | 'reply' | 'replyAll' | 'forward'>('compose');
const [composerDraftText, setComposerDraftText] = useState(""); const [composerDraftText, setComposerDraftText] = useState("");
const [pendingDraft, setPendingDraft] = useState<ComposerDraftData | null>(null); const [pendingDraft, setPendingDraft] = useState<ComposerDraftData | null>(null);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog(); const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client); const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
const [showShortcutsModal, setShowShortcutsModal] = useState(false); const [showShortcutsModal, setShowShortcutsModal] = useState(false);
const [showAdvancedFields, setShowAdvancedFields] = useState(false); const [showAdvancedFields, setShowAdvancedFields] = useState(false);
@@ -224,7 +229,7 @@ export default function Home() {
// Update page title based on context // Update page title based on context
useEffect(() => { useEffect(() => {
let title = tCommon('app_title'); let title = appName;
if (showComposer) { if (showComposer) {
// Composing email // Composing email
@@ -234,11 +239,11 @@ export default function Home() {
replyAll: t('email_composer.reply_all'), replyAll: t('email_composer.reply_all'),
forward: t('email_composer.forward'), forward: t('email_composer.forward'),
}[composerMode] || t('email_composer.new_message'); }[composerMode] || t('email_composer.new_message');
title = `${modeText} - ${tCommon('app_title')}`; title = `${modeText} - ${appName}`;
} else if (selectedEmail) { } else if (selectedEmail) {
// Reading email // Reading email
const subject = selectedEmail.subject || t('email_viewer.no_subject'); const subject = selectedEmail.subject || t('email_viewer.no_subject');
title = `${subject} - ${tCommon('app_title')}`; title = `${subject} - ${appName}`;
} else if (selectedMailbox && mailboxes.length > 0) { } else if (selectedMailbox && mailboxes.length > 0) {
// Mailbox view // Mailbox view
const mailbox = mailboxes.find(mb => mb.id === selectedMailbox); const mailbox = mailboxes.find(mb => mb.id === selectedMailbox);
@@ -246,13 +251,13 @@ export default function Home() {
const mailboxName = mailbox.name; const mailboxName = mailbox.name;
const unreadCount = mailbox.unreadEmails || 0; const unreadCount = mailbox.unreadEmails || 0;
title = unreadCount > 0 title = unreadCount > 0
? `${mailboxName} (${unreadCount}) - ${tCommon('app_title')}` ? `${mailboxName} (${unreadCount}) - ${appName}`
: `${mailboxName} - ${tCommon('app_title')}`; : `${mailboxName} - ${appName}`;
} }
} }
document.title = title; document.title = title;
}, [showComposer, composerMode, selectedEmail, selectedMailbox, mailboxes, t, tCommon]); }, [showComposer, composerMode, selectedEmail, selectedMailbox, mailboxes, t, appName]);
// Check auth on mount // Check auth on mount
useEffect(() => { useEffect(() => {
@@ -278,9 +283,9 @@ export default function Home() {
useEffect(() => { useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) { if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ } try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push('/login'); redirectToLogin();
} }
}, [initialCheckDone, isAuthenticated, authLoading, router]); }, [initialCheckDone, isAuthenticated, authLoading]);
// Load mailboxes and emails when authenticated (only if not already loaded) // Load mailboxes and emails when authenticated (only if not already loaded)
useEffect(() => { useEffect(() => {
@@ -402,7 +407,10 @@ export default function Home() {
// Handle new email notifications - play sound // Handle new email notifications - play sound
useEffect(() => { useEffect(() => {
if (newEmailNotification) { if (newEmailNotification) {
playNotificationSound(); const { emailNotificationsEnabled, emailNotificationSound, notificationSoundChoice } = useSettingsStore.getState();
if (emailNotificationsEnabled && emailNotificationSound) {
playNotificationSound(notificationSoundChoice);
}
debug.log('New email received:', newEmailNotification.subject); debug.log('New email received:', newEmailNotification.subject);
clearNewEmailNotification(); clearNewEmailNotification();
} }
@@ -431,13 +439,32 @@ export default function Home() {
fromEmail?: string; fromEmail?: string;
fromName?: string; fromName?: string;
identityId?: string; identityId?: string;
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>;
}) => { }) => {
if (!client) return; if (!client) return;
try { try {
await sendEmail(client, data.to, data.subject, data.body, data.cc, data.bcc, data.identityId, data.fromEmail, data.draftId, data.fromName, data.htmlBody); const effectiveMode = pendingDraft?.mode ?? composerMode;
const originalEmailId = selectedEmail?.id;
await sendEmail(client, data.to, data.subject, data.body, data.cc, data.bcc, data.identityId, data.fromEmail, data.draftId, data.fromName, data.htmlBody, data.attachments);
setShowComposer(false); setShowComposer(false);
// Mark the original email with $answered or $forwarded keyword
if (originalEmailId && (effectiveMode === 'reply' || effectiveMode === 'replyAll')) {
try {
await client.setKeyword(originalEmailId, '$answered');
} catch (e) {
debug.error('Failed to set $answered keyword:', e);
}
} else if (originalEmailId && effectiveMode === 'forward') {
try {
await client.setKeyword(originalEmailId, '$forwarded');
} catch (e) {
debug.error('Failed to set $forwarded keyword:', e);
}
}
// Refresh the current mailbox to update the UI // Refresh the current mailbox to update the UI
await fetchEmails(client, selectedMailbox); await fetchEmails(client, selectedMailbox);
} catch (error) { } catch (error) {
@@ -462,6 +489,33 @@ export default function Home() {
if (isMobile) setActiveView('viewer'); if (isMobile) setActiveView('viewer');
}; };
const handleEditDraft = (email?: Email) => {
const draft = email || selectedEmail;
if (!draft) return;
const bodyText = draft.bodyValues
? Object.values(draft.bodyValues).map(v => v.value).join('\n')
: '';
const htmlBody = draft.htmlBody?.[0]?.partId && draft.bodyValues?.[draft.htmlBody[0].partId]
? draft.bodyValues[draft.htmlBody[0].partId].value
: undefined;
setPendingDraft({
to: draft.to?.map(a => a.email).filter(Boolean).join(', ') || '',
cc: draft.cc?.map(a => a.email).filter(Boolean).join(', ') || '',
bcc: draft.bcc?.map(a => a.email).filter(Boolean).join(', ') || '',
subject: draft.subject || '',
body: htmlBody || bodyText,
showCc: (draft.cc?.length || 0) > 0,
showBcc: (draft.bcc?.length || 0) > 0,
selectedIdentityId: null,
subAddressTag: '',
mode: 'compose',
draftId: draft.id,
});
setComposerMode('compose');
setShowComposer(true);
if (isMobile) setActiveView('viewer');
};
const handleReplyAll = () => { const handleReplyAll = () => {
setComposerMode('replyAll'); setComposerMode('replyAll');
setShowComposer(true); setShowComposer(true);
@@ -516,12 +570,46 @@ export default function Home() {
// Find archive mailbox // Find archive mailbox
const archiveMailbox = mailboxes.find(m => m.role === "archive" || m.name.toLowerCase() === "archive"); const archiveMailbox = mailboxes.find(m => m.role === "archive" || m.name.toLowerCase() === "archive");
if (archiveMailbox) { if (!archiveMailbox) return;
try {
const { archiveMode } = useSettingsStore.getState();
try {
if (archiveMode === 'single') {
await moveToMailbox(client, selectedEmail.id, archiveMailbox.id); await moveToMailbox(client, selectedEmail.id, archiveMailbox.id);
} catch (error) { } else {
console.error("Failed to archive email:", error); // Determine year/month from the email's received date
const emailDate = new Date(selectedEmail.receivedAt);
const year = emailDate.getFullYear().toString();
const month = (emailDate.getMonth() + 1).toString().padStart(2, '0');
const archiveId = archiveMailbox.originalId || archiveMailbox.id;
// Find or create year subfolder under archive
let yearMailbox = mailboxes.find(
m => m.name === year && m.parentId === archiveId
);
if (!yearMailbox) {
yearMailbox = await client.createMailbox(year, archiveId);
await fetchMailboxes(client);
}
if (archiveMode === 'year') {
await moveToMailbox(client, selectedEmail.id, yearMailbox.id);
} else {
// archiveMode === 'month' — find or create month subfolder under year
const yearId = yearMailbox.originalId || yearMailbox.id;
let monthMailbox = mailboxes.find(
m => m.name === month && m.parentId === yearId
);
if (!monthMailbox) {
monthMailbox = await client.createMailbox(month, yearId);
await fetchMailboxes(client);
}
await moveToMailbox(client, selectedEmail.id, monthMailbox.id);
}
} }
} catch (error) {
console.error("Failed to archive email:", error);
} }
}; };
@@ -699,10 +787,7 @@ export default function Home() {
} }
}; };
const handleLogout = () => { const handleLogout = logout;
logout();
router.push('/login');
};
const handleSearch = async (query: string) => { const handleSearch = async (query: string) => {
if (!client) return; if (!client) return;
@@ -745,13 +830,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; if (!client) return;
try { try {
const { mailAttachmentAction } = useSettingsStore.getState(); const { mailAttachmentAction } = useSettingsStore.getState();
if (mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) { if (!forceDownload && mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) {
setPreviewAttachment({ blobId, name, type }); setPreviewAttachment({ blobId, name, type });
return; return;
} }
@@ -792,10 +877,9 @@ export default function Home() {
const primaryIdentity = identities[0]; const primaryIdentity = identities[0];
// Append signature from the primary identity // Append signature from the primary identity
let finalBody = body; const finalBody = appendPlainTextSignature(body, primaryIdentity);
if (primaryIdentity?.textSignature) {
finalBody = body + '\n\n-- \n' + primaryIdentity.textSignature; const originalEmailId = selectedEmail.id;
}
// Send reply with just the body text // Send reply with just the body text
await sendEmail( await sendEmail(
@@ -811,6 +895,13 @@ export default function Home() {
primaryIdentity?.name || undefined primaryIdentity?.name || undefined
); );
// Mark the original email as answered
try {
await client.setKeyword(originalEmailId, '$answered');
} catch (e) {
debug.error('Failed to set $answered keyword:', e);
}
// Refresh emails to show the sent reply // Refresh emails to show the sent reply
await fetchEmails(client, selectedMailbox); await fetchEmails(client, selectedMailbox);
}; };
@@ -952,6 +1043,10 @@ export default function Home() {
</button> </button>
); );
if (!isAuthenticated) {
return null;
}
return ( return (
<DragDropProvider> <DragDropProvider>
<div className="flex flex-col h-dvh bg-background overflow-hidden"> <div className="flex flex-col h-dvh bg-background overflow-hidden">
@@ -971,12 +1066,20 @@ export default function Home() {
isPushConnected={isPushConnected} isPushConnected={isPushConnected}
onLogout={handleLogout} onLogout={handleLogout}
onShowShortcuts={() => setShowShortcutsModal(true)} onShowShortcuts={() => setShowShortcutsModal(true)}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/> />
</div> </div>
)} )}
{inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
)}
{/* Mobile/Tablet Sidebar Overlay Backdrop */} {/* Mobile/Tablet Sidebar Overlay Backdrop */}
{(isMobile || isTablet) && sidebarOpen && ( {(isMobile || isTablet) && sidebarOpen && !inlineApp && (
<div <div
className="fixed inset-0 bg-black/50 z-40 lg:hidden" className="fixed inset-0 bg-black/50 z-40 lg:hidden"
onClick={() => setSidebarOpen(false)} onClick={() => setSidebarOpen(false)}
@@ -993,7 +1096,8 @@ export default function Home() {
"max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out", "max-lg:transform max-lg:transition-transform max-lg:duration-300 max-lg:ease-in-out",
!sidebarOpen && "max-lg:-translate-x-full", !sidebarOpen && "max-lg:-translate-x-full",
// Desktop: normal flow // Desktop: normal flow
"lg:relative lg:translate-x-0" "lg:relative lg:translate-x-0",
inlineApp && "hidden"
)} )}
style={!isMobile && !isTablet ? { width: sidebarCollapsed ? 64 : sidebarWidth } : undefined} style={!isMobile && !isTablet ? { width: sidebarCollapsed ? 64 : sidebarWidth } : undefined}
> >
@@ -1019,7 +1123,7 @@ export default function Home() {
</div> </div>
{/* Sidebar resize handle (desktop only, hidden when collapsed) */} {/* Sidebar resize handle (desktop only, hidden when collapsed) */}
{!isMobile && !isTablet && !sidebarCollapsed && ( {!isMobile && !isTablet && !sidebarCollapsed && !inlineApp && (
<ResizeHandle <ResizeHandle
onResizeStart={() => { dragStartWidth.current = sidebarWidth; setIsResizing(true); }} onResizeStart={() => { dragStartWidth.current = sidebarWidth; setIsResizing(true); }}
onResize={(delta) => setSidebarWidth(dragStartWidth.current + delta)} onResize={(delta) => setSidebarWidth(dragStartWidth.current + delta)}
@@ -1029,7 +1133,7 @@ export default function Home() {
)} )}
{/* Main Content Area */} {/* Main Content Area */}
<div className="flex flex-col flex-1 min-w-0 h-full"> <div className={cn("flex flex-col flex-1 min-w-0 h-full", inlineApp && "hidden")}>
<div className="flex flex-1 min-h-0"> <div className="flex flex-1 min-h-0">
{/* Email List - full width on mobile, fixed width on tablet/desktop */} {/* Email List - full width on mobile, fixed width on tablet/desktop */}
<div <div
@@ -1093,6 +1197,7 @@ export default function Home() {
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className={cn("pl-9 h-9", searchQuery && "pr-8")} className={cn("pl-9 h-9", searchQuery && "pr-8")}
data-search-input data-search-input
data-tour="search-input"
/> />
{searchQuery && ( {searchQuery && (
<button <button
@@ -1321,6 +1426,9 @@ export default function Home() {
selectEmail(email); selectEmail(email);
await handleUndoSpam(); await handleUndoSpam();
}} }}
onEditDraft={(email) => {
handleEditDraft(email);
}}
className="flex-1 min-h-0" className="flex-1 min-h-0"
/> />
</ErrorBoundary> </ErrorBoundary>
@@ -1494,8 +1602,9 @@ export default function Home() {
onNavigateNext={handleNavigateNext} onNavigateNext={handleNavigateNext}
onNavigatePrev={handleNavigatePrev} onNavigatePrev={handleNavigatePrev}
onShowShortcuts={() => setShowShortcutsModal(true)} onShowShortcuts={() => setShowShortcutsModal(true)}
currentUserEmail={client?.["username"]} onEditDraft={handleEditDraft}
currentUserName={client?.["username"]?.split("@")[0]} currentUserEmail={client?.getUsername()}
currentUserName={client?.getUsername()?.split("@")[0]}
currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role} currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role}
mailboxes={mailboxes} mailboxes={mailboxes}
selectedMailbox={selectedMailbox} selectedMailbox={selectedMailbox}
@@ -1516,7 +1625,13 @@ export default function Home() {
{/* Bottom Navigation - mobile and tablet */} {/* Bottom Navigation - mobile and tablet */}
{(isMobile || isTablet) && activeView !== "viewer" && ( {(isMobile || isTablet) && activeView !== "viewer" && (
<NavigationRail orientation="horizontal" /> <NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
)} )}
</div> </div>
</div> </div>
@@ -1539,6 +1654,7 @@ export default function Home() {
{/* Screen reader live region for dynamic status announcements */} {/* Screen reader live region for dynamic status announcements */}
<div className="sr-only" aria-live="polite" aria-atomic="true" id="sr-status" /> <div className="sr-only" aria-live="polite" aria-atomic="true" id="sr-status" />
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
<ConfirmDialog {...confirmDialogProps} /> <ConfirmDialog {...confirmDialogProps} />
</div> </div>
</DragDropProvider> </DragDropProvider>
+54 -9
View File
@@ -22,6 +22,9 @@ import {
HardDrive, HardDrive,
Wrench, Wrench,
BookUser, BookUser,
KeyRound,
PanelLeftClose,
Bell,
type LucideIcon, type LucideIcon,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -40,15 +43,21 @@ import { KeywordSettings } from '@/components/settings/keyword-settings';
import { AccountSecuritySettings } from '@/components/settings/account-security-settings'; import { AccountSecuritySettings } from '@/components/settings/account-security-settings';
import { FilesSettingsComponent } from '@/components/settings/files-settings'; import { FilesSettingsComponent } from '@/components/settings/files-settings';
import { ContactsSettings } from '@/components/settings/contacts-settings'; import { ContactsSettings } from '@/components/settings/contacts-settings';
import { useAuthStore } from '@/stores/auth-store'; import { SmimeSettings } from '@/components/settings/smime-settings';
import { SidebarAppsSettings } from '@/components/settings/sidebar-apps-settings';
import { NotificationSettings } from '@/components/settings/notification-settings';
import { useAuthStore, redirectToLogin } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store'; import { useEmailStore } from '@/stores/email-store';
import { useIsDesktop } from '@/hooks/use-media-query'; import { useIsDesktop } from '@/hooks/use-media-query';
import { NavigationRail } from '@/components/layout/navigation-rail'; import { NavigationRail } from '@/components/layout/navigation-rail';
import { SidebarAppsModal } from '@/components/layout/sidebar-apps-modal';
import { InlineAppView } from '@/components/layout/inline-app-view';
import { useSidebarApps } from '@/hooks/use-sidebar-apps';
import { ResizeHandle } from '@/components/layout/resize-handle'; import { ResizeHandle } from '@/components/layout/resize-handle';
import { useConfig } from '@/hooks/use-config'; import { useConfig } from '@/hooks/use-config';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
type Tab = 'appearance' | 'email' | 'account' | 'security' | 'identities' | 'vacation' | 'calendar' | 'contacts' | 'filters' | 'templates' | 'folders' | 'keywords' | 'files' | 'advanced'; type Tab = 'appearance' | 'email' | 'notifications' | 'account' | 'security' | 'identities' | 'encryption' | 'vacation' | 'calendar' | 'contacts' | 'filters' | 'templates' | 'folders' | 'keywords' | 'files' | 'sidebar_apps' | 'advanced';
type TabGroup = 'general' | 'account' | 'organization' | 'apps' | 'system'; type TabGroup = 'general' | 'account' | 'organization' | 'apps' | 'system';
interface TabDef { interface TabDef {
@@ -61,9 +70,11 @@ interface TabDef {
const tabIcons: Record<Tab, LucideIcon> = { const tabIcons: Record<Tab, LucideIcon> = {
appearance: Palette, appearance: Palette,
email: Mail, email: Mail,
notifications: Bell,
account: User, account: User,
security: Shield, security: Shield,
identities: UserPen, identities: UserPen,
encryption: KeyRound,
vacation: PalmtreeIcon, vacation: PalmtreeIcon,
calendar: Calendar, calendar: Calendar,
contacts: BookUser, contacts: BookUser,
@@ -72,6 +83,7 @@ const tabIcons: Record<Tab, LucideIcon> = {
folders: FolderOpen, folders: FolderOpen,
keywords: Tags, keywords: Tags,
files: HardDrive, files: HardDrive,
sidebar_apps: PanelLeftClose,
advanced: Wrench, advanced: Wrench,
}; };
@@ -82,6 +94,7 @@ export default function SettingsPage() {
const t = useTranslations('settings'); const t = useTranslations('settings');
const tSidebar = useTranslations('sidebar'); const tSidebar = useTranslations('sidebar');
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore(); const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client); const [initialCheckDone, setInitialCheckDone] = useState(() => useAuthStore.getState().isAuthenticated && !!useAuthStore.getState().client);
const { quota, isPushConnected } = useEmailStore(); const { quota, isPushConnected } = useEmailStore();
const { stalwartFeaturesEnabled } = useConfig(); const { stalwartFeaturesEnabled } = useConfig();
@@ -112,9 +125,9 @@ export default function SettingsPage() {
useEffect(() => { useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) { if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ } try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push('/login'); redirectToLogin();
} }
}, [initialCheckDone, isAuthenticated, authLoading, router]); }, [initialCheckDone, isAuthenticated, authLoading]);
if (!isAuthenticated) { if (!isAuthenticated) {
return null; return null;
@@ -128,9 +141,11 @@ export default function SettingsPage() {
const tabs: TabDef[] = [ const tabs: TabDef[] = [
{ id: 'appearance', label: t('tabs.appearance'), icon: tabIcons.appearance, group: 'general' }, { id: 'appearance', label: t('tabs.appearance'), icon: tabIcons.appearance, group: 'general' },
{ id: 'email', label: t('tabs.email'), icon: tabIcons.email, group: 'general' }, { id: 'email', label: t('tabs.email'), icon: tabIcons.email, group: 'general' },
{ id: 'notifications', label: t('tabs.notifications'), icon: tabIcons.notifications, group: 'general' },
{ id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' }, { id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' },
...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []), ...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []),
{ id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' }, { id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' },
{ id: 'encryption', label: t('tabs.encryption'), icon: tabIcons.encryption, group: 'account' },
...(supportsVacation ? [{ id: 'vacation' as Tab, label: t('tabs.vacation'), icon: tabIcons.vacation, group: 'account' as TabGroup }] : []), ...(supportsVacation ? [{ id: 'vacation' as Tab, label: t('tabs.vacation'), icon: tabIcons.vacation, group: 'account' as TabGroup }] : []),
...(supportsSieve ? [{ id: 'filters' as Tab, label: t('tabs.filters'), icon: tabIcons.filters, group: 'organization' as TabGroup }] : []), ...(supportsSieve ? [{ id: 'filters' as Tab, label: t('tabs.filters'), icon: tabIcons.filters, group: 'organization' as TabGroup }] : []),
{ id: 'templates', label: t('tabs.templates'), icon: tabIcons.templates, group: 'organization' }, { id: 'templates', label: t('tabs.templates'), icon: tabIcons.templates, group: 'organization' },
@@ -139,6 +154,7 @@ export default function SettingsPage() {
...(supportsCalendar ? [{ id: 'calendar' as Tab, label: t('tabs.calendar'), icon: tabIcons.calendar, group: 'apps' as TabGroup }] : []), ...(supportsCalendar ? [{ id: 'calendar' as Tab, label: t('tabs.calendar'), icon: tabIcons.calendar, group: 'apps' as TabGroup }] : []),
{ id: 'contacts', label: t('tabs.contacts'), icon: tabIcons.contacts, group: 'apps' }, { id: 'contacts', label: t('tabs.contacts'), icon: tabIcons.contacts, group: 'apps' },
...(supportsFiles ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []), ...(supportsFiles ? [{ id: 'files' as Tab, label: t('tabs.files'), icon: tabIcons.files, group: 'apps' as TabGroup }] : []),
{ id: 'sidebar_apps', label: t('tabs.sidebar_apps'), icon: tabIcons.sidebar_apps, group: 'apps' },
{ id: 'advanced', label: t('tabs.advanced'), icon: tabIcons.advanced, group: 'system' }, { id: 'advanced', label: t('tabs.advanced'), icon: tabIcons.advanced, group: 'system' },
]; ];
@@ -165,9 +181,11 @@ export default function SettingsPage() {
<> <>
{activeTab === 'appearance' && <AppearanceSettings />} {activeTab === 'appearance' && <AppearanceSettings />}
{activeTab === 'email' && <EmailSettings />} {activeTab === 'email' && <EmailSettings />}
{activeTab === 'notifications' && <NotificationSettings />}
{activeTab === 'account' && <AccountSettings />} {activeTab === 'account' && <AccountSettings />}
{activeTab === 'security' && <AccountSecuritySettings />} {activeTab === 'security' && <AccountSecuritySettings />}
{activeTab === 'identities' && <IdentitySettings />} {activeTab === 'identities' && <IdentitySettings />}
{activeTab === 'encryption' && <SmimeSettings />}
{activeTab === 'vacation' && <VacationSettings />} {activeTab === 'vacation' && <VacationSettings />}
{activeTab === 'calendar' && <><CalendarSettings /><div className="mt-8"><CalendarManagementSettings /></div></>} {activeTab === 'calendar' && <><CalendarSettings /><div className="mt-8"><CalendarManagementSettings /></div></>}
{activeTab === 'contacts' && <ContactsSettings />} {activeTab === 'contacts' && <ContactsSettings />}
@@ -176,6 +194,7 @@ export default function SettingsPage() {
{activeTab === 'folders' && <FolderSettings />} {activeTab === 'folders' && <FolderSettings />}
{activeTab === 'keywords' && <KeywordSettings />} {activeTab === 'keywords' && <KeywordSettings />}
{activeTab === 'files' && <FilesSettingsComponent />} {activeTab === 'files' && <FilesSettingsComponent />}
{activeTab === 'sidebar_apps' && <SidebarAppsSettings />}
{activeTab === 'advanced' && <AdvancedSettings />} {activeTab === 'advanced' && <AdvancedSettings />}
</> </>
); );
@@ -207,7 +226,14 @@ export default function SettingsPage() {
</div> </div>
{/* Bottom Navigation */} {/* Bottom Navigation */}
<NavigationRail orientation="horizontal" /> <NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
</div> </div>
); );
} }
@@ -265,7 +291,7 @@ export default function SettingsPage() {
{/* Logout */} {/* Logout */}
<div className="border-t border-border px-5 py-3"> <div className="border-t border-border px-5 py-3">
<button <button
onClick={() => { logout(); router.push('/login'); }} onClick={logout}
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" 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" /> <LogOut className="w-4 h-4" />
@@ -275,7 +301,14 @@ export default function SettingsPage() {
</div> </div>
{/* Bottom Navigation */} {/* Bottom Navigation */}
<NavigationRail orientation="horizontal" /> <NavigationRail
orientation="horizontal"
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/>
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
</div> </div>
); );
} }
@@ -289,10 +322,19 @@ export default function SettingsPage() {
collapsed collapsed
quota={quota} quota={quota}
isPushConnected={isPushConnected} isPushConnected={isPushConnected}
onLogout={() => { logout(); router.push('/login'); }} onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
activeAppId={inlineApp?.id ?? null}
/> />
</div> </div>
{inlineApp && (
<InlineAppView apps={loadedApps} activeAppId={inlineApp!.id} onClose={closeInlineApp} className="flex-1" />
)}
{!inlineApp && (
<>
{/* Settings Sidebar */} {/* Settings Sidebar */}
<div <div
className={cn( className={cn(
@@ -315,7 +357,7 @@ export default function SettingsPage() {
</div> </div>
{/* Tabs */} {/* Tabs */}
<div className="flex-1 overflow-y-auto py-2"> <div className="flex-1 overflow-y-auto py-2" data-tour="settings-tabs">
<div className="px-2 space-y-0.5"> <div className="px-2 space-y-0.5">
{groupedTabs.map((group, groupIndex) => ( {groupedTabs.map((group, groupIndex) => (
<div key={group.group}> <div key={group.group}>
@@ -380,6 +422,9 @@ export default function SettingsPage() {
</div> </div>
</div> </div>
</div> </div>
</>
)}
<SidebarAppsModal isOpen={showAppsModal} onClose={closeAppsModal} />
</div> </div>
); );
} }
+33 -12
View File
@@ -2,30 +2,38 @@ import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
import { encryptSession, decryptSession } from '@/lib/auth/crypto'; 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';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const COOKIE_OPTIONS = { const COOKIE_OPTIONS = {
httpOnly: true, ...getCookieOptions(),
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
maxAge: SESSION_COOKIE_MAX_AGE, 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) { export async function POST(request: NextRequest) {
try { try {
if (process.env.OAUTH_ENABLED === 'true' && process.env.OAUTH_ONLY === 'true') { if (process.env.OAUTH_ENABLED === 'true' && process.env.OAUTH_ONLY === 'true') {
return NextResponse.json({ error: 'Basic authentication is disabled' }, { status: 403 }); 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) { if (!serverUrl || !username || !password) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 }); 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 token = encryptSession(serverUrl, username, password);
const cookieStore = await cookies(); const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE, token, COOKIE_OPTIONS); cookieStore.set(cookieName, token, COOKIE_OPTIONS);
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
} catch (error) { } catch (error) {
@@ -34,10 +42,12 @@ export async function POST(request: NextRequest) {
} }
} }
export async function GET() { export async function GET(request: NextRequest) {
try { try {
const slot = getSlot(request);
const cookieName = sessionCookieName(slot);
const cookieStore = await cookies(); const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value; const token = cookieStore.get(cookieName)?.value;
if (!token) { if (!token) {
return NextResponse.json({ error: 'No session' }, { status: 401 }); return NextResponse.json({ error: 'No session' }, { status: 401 });
@@ -45,7 +55,7 @@ export async function GET() {
const credentials = decryptSession(token); const credentials = decryptSession(token);
if (!credentials) { if (!credentials) {
cookieStore.delete(SESSION_COOKIE); cookieStore.delete(cookieName);
return NextResponse.json({ error: 'Invalid session' }, { status: 401 }); return NextResponse.json({ error: 'Invalid session' }, { status: 401 });
} }
@@ -58,10 +68,21 @@ export async function GET() {
} }
} }
export async function DELETE() { export async function DELETE(request: NextRequest) {
try { try {
const cookieStore = await cookies(); 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 }); return NextResponse.json({ ok: true });
} catch (error) { } catch (error) {
logger.error('Session clear error', { error: error instanceof Error ? error.message : 'Unknown error' }); logger.error('Session clear error', { error: error instanceof Error ? error.message : 'Unknown error' });
+80
View File
@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptPayload } from '@/lib/auth/crypto';
import { exchangeCodeForTokens } from '@/lib/oauth/token-exchange';
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const SSO_PENDING_COOKIE = 'sso_pending';
const SSO_PENDING_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes
export async function POST(request: NextRequest) {
const cookieStore = await cookies();
try {
const { code, state } = await request.json();
if (!code || !state) {
return NextResponse.json({ error: 'Missing code or state' }, { status: 400 });
}
// Read and decrypt the pending SSO cookie
const pendingCookie = cookieStore.get(SSO_PENDING_COOKIE)?.value;
if (!pendingCookie) {
logger.warn('SSO complete: no pending cookie found');
return NextResponse.json({ error: 'No pending SSO session. Please start the login flow again.' }, { status: 400 });
}
const pending = decryptPayload(pendingCookie);
if (!pending) {
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'Invalid SSO session' }, { status: 400 });
}
// Validate state
if (pending.state !== state) {
logger.warn('SSO complete: state mismatch');
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'State mismatch' }, { status: 400 });
}
// Validate TTL
const createdAt = pending.created_at as number;
if (!createdAt || Date.now() - createdAt > SSO_PENDING_MAX_AGE_MS) {
logger.warn('SSO complete: pending session expired');
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'SSO session expired. Please try again.' }, { status: 400 });
}
const codeVerifier = pending.code_verifier as string;
const redirectUri = pending.redirect_uri as string;
if (!codeVerifier || !redirectUri) {
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({ error: 'Invalid SSO session data' }, { status: 400 });
}
// Exchange code for tokens
const tokens = await exchangeCodeForTokens(code, codeVerifier, redirectUri);
// Store refresh token
if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(0);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
// Delete pending cookie
cookieStore.delete(SSO_PENDING_COOKIE);
return NextResponse.json({
access_token: tokens.access_token,
expires_in: tokens.expires_in,
});
} catch (error) {
// Clean up pending cookie on any error
cookieStore.delete(SSO_PENDING_COOKIE);
logger.error('SSO complete error', { error: error instanceof Error ? error.message : 'Unknown error' });
return NextResponse.json({ error: 'Token exchange failed' }, { status: 401 });
}
}
+88
View File
@@ -0,0 +1,88 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptPayload } from '@/lib/auth/crypto';
import { generateCodeVerifierServer, generateCodeChallengeServer, generateStateServer } from '@/lib/oauth/pkce-server';
import { getRequiredConfig } from '@/lib/oauth/token-exchange';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { OAUTH_SCOPES } from '@/lib/oauth/tokens';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const SSO_PENDING_COOKIE = 'sso_pending';
const SSO_PENDING_MAX_AGE = 300; // 5 minutes
export async function POST(request: NextRequest) {
try {
if (!process.env.SESSION_SECRET) {
return NextResponse.json({ error: 'SESSION_SECRET is required for SSO' }, { status: 500 });
}
const { redirect_uri, locale } = await request.json();
if (!redirect_uri || typeof redirect_uri !== 'string') {
return NextResponse.json({ error: 'Missing redirect_uri' }, { status: 400 });
}
// Validate redirect_uri origin matches the request origin to prevent open redirects
const requestOrigin = request.headers.get('origin') || request.nextUrl.origin;
try {
const redirectOrigin = new URL(redirect_uri).origin;
if (redirectOrigin !== requestOrigin) {
logger.warn('SSO start: redirect_uri origin mismatch', { redirectOrigin, requestOrigin });
return NextResponse.json({ error: 'Invalid redirect_uri' }, { status: 400 });
}
} catch {
return NextResponse.json({ error: 'Invalid redirect_uri' }, { status: 400 });
}
const { clientId, discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.authorization_endpoint) {
return NextResponse.json({ error: 'OAuth discovery failed' }, { status: 502 });
}
// Generate PKCE + state server-side
const codeVerifier = generateCodeVerifierServer();
const codeChallenge = generateCodeChallengeServer(codeVerifier);
const state = generateStateServer();
// Encrypt and store in httpOnly cookie
const pendingData = {
state,
code_verifier: codeVerifier,
redirect_uri,
created_at: Date.now(),
};
const encrypted = encryptPayload(pendingData);
const cookieStore = await cookies();
const baseCookieOpts = getCookieOptions();
cookieStore.set(SSO_PENDING_COOKIE, encrypted, {
...baseCookieOpts,
maxAge: SSO_PENDING_MAX_AGE,
});
// Build authorize URL
const authUrl = new URL(metadata.authorization_endpoint);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', clientId);
authUrl.searchParams.set('redirect_uri', redirect_uri);
authUrl.searchParams.set('scope', OAUTH_SCOPES);
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
if (locale) {
authUrl.searchParams.set('ui_locales', locale);
}
return NextResponse.json({
authorize_url: authUrl.toString(),
state,
});
} catch (error) {
logger.error('SSO start error', { error: error instanceof Error ? error.message : 'Unknown error' });
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+53 -83
View File
@@ -1,100 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery'; import { refreshTokenCookieName } from '@/lib/oauth/tokens';
import { REFRESH_TOKEN_COOKIE } from '@/lib/oauth/tokens'; import { exchangeCodeForTokens, buildOAuthParams, getMetadata, getTokenEndpoint } from '@/lib/oauth/token-exchange';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || ''; function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
const COOKIE_OPTIONS = { if (raw === null) return 0;
httpOnly: true, const slot = parseInt(raw, 10);
secure: process.env.NODE_ENV === 'production', if (isNaN(slot) || slot < 0 || slot > 4) return 0;
sameSite: 'lax' as const, return slot;
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
const issuerUrl = process.env.OAUTH_ISSUER_URL;
if (!clientId || !serverUrl) {
throw new Error(`OAuth misconfigured: ${[!clientId && 'OAUTH_CLIENT_ID', !serverUrl && 'JMAP_SERVER_URL'].filter(Boolean).join(', ')} not set`);
}
const discoveryUrl = issuerUrl?.trim() || serverUrl;
if (issuerUrl !== undefined && !issuerUrl.trim()) {
logger.warn('OAUTH_ISSUER_URL is set but empty, falling back to JMAP_SERVER_URL for discovery');
}
return { clientId, serverUrl, discoveryUrl };
}
async function getTokenEndpoint(): Promise<string> {
const { discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.token_endpoint) {
throw new Error('OAuth token endpoint not found');
}
return metadata.token_endpoint;
}
async function getMetadata(): Promise<import('@/lib/oauth/discovery').OAuthMetadata | null> {
const { discoveryUrl } = getRequiredConfig();
return discoverOAuth(discoveryUrl);
}
function buildOAuthParams(base: Record<string, string>): URLSearchParams {
const { clientId } = getRequiredConfig();
const params = new URLSearchParams({ ...base, client_id: clientId });
if (CLIENT_SECRET) {
params.set('client_secret', CLIENT_SECRET);
}
return params;
} }
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { 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) { if (!code || !code_verifier || !redirect_uri) {
return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 }); return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });
} }
const tokenEndpoint = await getTokenEndpoint(); const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
const params = buildOAuthParams({ const tokens = await exchangeCodeForTokens(code, code_verifier, redirect_uri);
grant_type: 'authorization_code',
code,
redirect_uri,
code_verifier,
});
const tokenResponse = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
logger.error('Token exchange failed', { status: tokenResponse.status, error: errorText });
return NextResponse.json({ error: 'Token exchange failed' }, { status: 401 });
}
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
return NextResponse.json({ error: 'Invalid token response' }, { status: 502 });
}
const response = NextResponse.json({ const response = NextResponse.json({
access_token: tokens.access_token, access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600, expires_in: tokens.expires_in,
}); });
if (tokens.refresh_token) { if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies(); const cookieStore = await cookies();
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS); cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
} }
return response; return response;
@@ -104,10 +43,12 @@ export async function POST(request: NextRequest) {
} }
} }
export async function PUT() { export async function PUT(request: NextRequest) {
try { try {
const slot = getSlot(request);
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies(); const cookieStore = await cookies();
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value; const refreshToken = cookieStore.get(cookieName)?.value;
if (!refreshToken) { if (!refreshToken) {
return NextResponse.json({ error: 'No refresh token' }, { status: 401 }); return NextResponse.json({ error: 'No refresh token' }, { status: 401 });
@@ -129,7 +70,7 @@ export async function PUT() {
if (!tokenResponse.ok) { if (!tokenResponse.ok) {
const errorText = await tokenResponse.text(); const errorText = await tokenResponse.text();
logger.error('Token refresh failed', { status: tokenResponse.status, error: errorText }); 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 }); return NextResponse.json({ error: 'Refresh failed' }, { status: 401 });
} }
@@ -141,7 +82,7 @@ export async function PUT() {
} }
if (tokens.refresh_token) { if (tokens.refresh_token) {
cookieStore.set(REFRESH_TOKEN_COOKIE, tokens.refresh_token, COOKIE_OPTIONS); cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
} }
return NextResponse.json({ return NextResponse.json({
@@ -154,10 +95,39 @@ export async function PUT() {
} }
} }
export async function DELETE() { export async function DELETE(request: NextRequest) {
try { 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 cookieStore = await cookies();
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value; const refreshToken = cookieStore.get(cookieName)?.value;
const metadata = await getMetadata().catch((err) => { const metadata = await getMetadata().catch((err) => {
logger.warn('Failed to discover OAuth metadata during logout', { logger.warn('Failed to discover OAuth metadata during logout', {
error: err instanceof Error ? err.message : 'Unknown error', error: err instanceof Error ? err.message : 'Unknown error',
@@ -186,7 +156,7 @@ export async function DELETE() {
} }
} }
cookieStore.delete(REFRESH_TOKEN_COOKIE); cookieStore.delete(cookieName);
} }
let end_session_url: string | undefined; 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 });
}
}
+7
View File
@@ -26,11 +26,18 @@ export async function GET() {
settingsSyncEnabled: process.env.SETTINGS_SYNC_ENABLED === 'true' && !!process.env.SESSION_SECRET, settingsSyncEnabled: process.env.SETTINGS_SYNC_ENABLED === 'true' && !!process.env.SESSION_SECRET,
stalwartFeaturesEnabled: process.env.STALWART_FEATURES !== 'false', stalwartFeaturesEnabled: process.env.STALWART_FEATURES !== 'false',
devMode: process.env.DEV_MOCK_JMAP === 'true', devMode: process.env.DEV_MOCK_JMAP === 'true',
faviconUrl: process.env.FAVICON_URL || '/branding/Bulwark_Favicon.svg',
appLogoLightUrl: process.env.APP_LOGO_LIGHT_URL || '',
appLogoDarkUrl: process.env.APP_LOGO_DARK_URL || '',
loginLogoLightUrl: process.env.LOGIN_LOGO_LIGHT_URL || '/branding/Bulwark_Logo_Color.svg', loginLogoLightUrl: process.env.LOGIN_LOGO_LIGHT_URL || '/branding/Bulwark_Logo_Color.svg',
loginLogoDarkUrl: process.env.LOGIN_LOGO_DARK_URL || '/branding/Bulwark_Logo_White.svg', loginLogoDarkUrl: process.env.LOGIN_LOGO_DARK_URL || '/branding/Bulwark_Logo_White.svg',
loginCompanyName: process.env.LOGIN_COMPANY_NAME || '', loginCompanyName: process.env.LOGIN_COMPANY_NAME || '',
loginImprintUrl: process.env.LOGIN_IMPRINT_URL || '', loginImprintUrl: process.env.LOGIN_IMPRINT_URL || '',
loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_URL || '', loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_URL || '',
loginWebsiteUrl: process.env.LOGIN_WEBSITE_URL || '', loginWebsiteUrl: process.env.LOGIN_WEBSITE_URL || '',
demoMode: process.env.DEMO_MODE === 'true',
autoSsoEnabled: process.env.AUTO_SSO_ENABLED === 'true',
embeddedMode: !!process.env.ALLOWED_FRAME_ANCESTORS && process.env.ALLOWED_FRAME_ANCESTORS !== "'none'",
parentOrigin: process.env.NEXT_PUBLIC_PARENT_ORIGIN || '',
}); });
} }
+352 -26
View File
@@ -40,32 +40,358 @@ function isValidDomain(domain: string): boolean {
// Known multi-part TLDs where the registrable domain includes one extra label. // Known multi-part TLDs where the registrable domain includes one extra label.
const MULTI_PART_TLDS = new Set([ const MULTI_PART_TLDS = new Set([
"co.uk", "org.uk", "me.uk", "ac.uk", "gov.uk", "net.uk", // .ac
"co.jp", "or.jp", "ne.jp", "ac.jp", "go.jp", "com.ac", "gov.ac", "mil.ac", "net.ac", "org.ac",
"co.kr", "or.kr", "go.kr", "ac.kr", // .ae
"co.in", "net.in", "org.in", "ac.in", "gov.in", "ac.ae", "co.ae", "gov.ae", "mil.ae", "name.ae", "net.ae", "org.ae", "pro.ae", "sch.ae",
"co.nz", "org.nz", "net.nz", "govt.nz", "ac.nz", // .af
"co.za", "org.za", "net.za", "gov.za", "ac.za", "com.af", "edu.af", "gov.af", "net.af", "org.af",
"com.au", "net.au", "org.au", "edu.au", "gov.au", // .al
"com.br", "net.br", "org.br", "edu.br", "gov.br", "com.al", "edu.al", "gov.al", "mil.al", "net.al", "org.al",
"com.cn", "net.cn", "org.cn", "gov.cn", "edu.cn", // .ao
"com.mx", "net.mx", "org.mx", "gob.mx", "edu.mx", "co.ao", "ed.ao", "gv.ao", "it.ao", "og.ao", "pb.ao",
"com.ar", "net.ar", "org.ar", "gob.ar", "edu.ar", // .ar
"com.tw", "net.tw", "org.tw", "edu.tw", "gov.tw", "com.ar", "edu.ar", "gob.ar", "gov.ar", "int.ar", "mil.ar", "net.ar", "org.ar", "tur.ar",
"com.hk", "net.hk", "org.hk", "edu.hk", "gov.hk", // .at
"com.sg", "net.sg", "org.sg", "edu.sg", "gov.sg", "ac.at", "co.at", "gv.at", "or.at",
"com.my", "net.my", "org.my", "edu.my", "gov.my", // .au
"com.ph", "net.ph", "org.ph", "edu.ph", "gov.ph", "asn.au", "com.au", "csiro.au", "edu.au", "gov.au", "id.au", "net.au", "org.au",
"com.pk", "net.pk", "org.pk", "edu.pk", "gov.pk", // .ba
"com.ng", "net.ng", "org.ng", "edu.ng", "gov.ng", "co.ba", "com.ba", "edu.ba", "gov.ba", "mil.ba", "net.ba", "org.ba", "rs.ba",
"co.il", "org.il", "net.il", "ac.il", "gov.il", "unbi.ba", "unmo.ba", "unsa.ba", "untz.ba", "unze.ba",
"co.th", "or.th", "ac.th", "go.th", "in.th", // .bb
"co.id", "or.id", "ac.id", "go.id", "web.id", "biz.bb", "co.bb", "com.bb", "edu.bb", "gov.bb", "info.bb", "net.bb", "org.bb",
"com.tr", "net.tr", "org.tr", "edu.tr", "gov.tr", "store.bb", "tv.bb",
"com.ua", "net.ua", "org.ua", "edu.ua", "gov.ua", // .bh
"com.eg", "net.eg", "org.eg", "edu.eg", "gov.eg", "biz.bh", "cc.bh", "com.bh", "edu.bh", "gov.bh", "info.bh", "net.bh", "org.bh",
"com.sa", "net.sa", "org.sa", "edu.sa", "gov.sa", // .bn
"co.ke", "or.ke", "ac.ke", "go.ke", "ne.ke", "com.bn", "edu.bn", "gov.bn", "net.bn", "org.bn",
// .bo
"com.bo", "edu.bo", "gob.bo", "gov.bo", "int.bo", "mil.bo", "net.bo", "org.bo", "tv.bo",
// .br
"adm.br", "adv.br", "agr.br", "am.br", "arq.br", "art.br", "ato.br", "b.br",
"bio.br", "blog.br", "bmd.br", "cim.br", "cng.br", "cnt.br", "com.br", "coop.br",
"ecn.br", "edu.br", "eng.br", "esp.br", "etc.br", "eti.br", "far.br", "flog.br",
"fm.br", "fnd.br", "fot.br", "fst.br", "g12.br", "ggf.br", "gov.br", "imb.br",
"ind.br", "inf.br", "jor.br", "jus.br", "lel.br", "mat.br", "med.br", "mil.br",
"mus.br", "net.br", "nom.br", "not.br", "ntr.br", "odo.br", "org.br", "ppg.br",
"pro.br", "psc.br", "psi.br", "qsl.br", "rec.br", "slg.br", "srv.br", "tmp.br",
"trd.br", "tur.br", "tv.br", "vet.br", "vlog.br", "wiki.br", "zlg.br",
// .bs
"com.bs", "edu.bs", "gov.bs", "net.bs", "org.bs",
// .bz
"com.bz", "edu.bz", "gov.bz", "net.bz", "org.bz",
// .ca
"ab.ca", "bc.ca", "mb.ca", "nb.ca", "nf.ca", "nl.ca", "ns.ca", "nt.ca",
"nu.ca", "on.ca", "pe.ca", "qc.ca", "sk.ca", "yk.ca",
// .ck
"biz.ck", "co.ck", "edu.ck", "gen.ck", "gov.ck", "info.ck", "net.ck", "org.ck",
// .cn
"ac.cn", "ah.cn", "bj.cn", "com.cn", "cq.cn", "edu.cn", "fj.cn", "gd.cn",
"gov.cn", "gs.cn", "gx.cn", "gz.cn", "ha.cn", "hb.cn", "he.cn", "hi.cn",
"hl.cn", "hn.cn", "jl.cn", "js.cn", "jx.cn", "ln.cn", "mil.cn", "net.cn",
"nm.cn", "nx.cn", "org.cn", "qh.cn", "sc.cn", "sd.cn", "sh.cn", "sn.cn",
"sx.cn", "tj.cn", "tw.cn", "xj.cn", "xz.cn", "yn.cn", "zj.cn",
// .co
"com.co", "edu.co", "gov.co", "mil.co", "net.co", "nom.co", "org.co",
// .cr
"ac.cr", "co.cr", "ed.cr", "fi.cr", "go.cr", "or.cr", "sa.cr",
// .cy
"ac.cy", "biz.cy", "com.cy", "ekloges.cy", "gov.cy", "ltd.cy", "name.cy",
"net.cy", "org.cy", "parliament.cy", "press.cy", "pro.cy", "tm.cy",
// .do
"art.do", "com.do", "edu.do", "gob.do", "gov.do", "mil.do", "net.do", "org.do",
"sld.do", "web.do",
// .dz
"art.dz", "asso.dz", "com.dz", "edu.dz", "gov.dz", "net.dz", "org.dz", "pol.dz",
// .ec
"com.ec", "edu.ec", "fin.ec", "gov.ec", "info.ec", "med.ec", "mil.ec", "net.ec",
"org.ec", "pro.ec",
// .eg
"com.eg", "edu.eg", "eun.eg", "gov.eg", "mil.eg", "name.eg", "net.eg", "org.eg", "sci.eg",
// .er
"com.er", "edu.er", "gov.er", "ind.er", "mil.er", "net.er", "org.er", "rochest.er", "w.er",
// .es
"com.es", "edu.es", "gob.es", "nom.es", "org.es",
// .et
"biz.et", "com.et", "edu.et", "gov.et", "info.et", "name.et", "net.et", "org.et",
// .fj
"ac.fj", "biz.fj", "com.fj", "info.fj", "mil.fj", "name.fj", "net.fj", "org.fj", "pro.fj",
// .fk
"ac.fk", "co.fk", "gov.fk", "net.fk", "nom.fk", "org.fk",
// .fr
"asso.fr", "com.fr", "gouv.fr", "nom.fr", "prd.fr", "presse.fr", "tm.fr",
// .gg
"co.gg", "net.gg", "org.gg",
// .gh
"com.gh", "edu.gh", "gov.gh", "mil.gh", "org.gh",
// .gn
"ac.gn", "com.gn", "gov.gn", "net.gn", "org.gn",
// .gr
"com.gr", "edu.gr", "gov.gr", "mil.gr", "net.gr", "org.gr",
// .gt
"com.gt", "edu.gt", "gob.gt", "ind.gt", "mil.gt", "net.gt", "org.gt",
// .gu
"com.gu", "edu.gu", "gov.gu", "net.gu", "org.gu",
// .hk
"com.hk", "edu.hk", "gov.hk", "idv.hk", "net.hk", "org.hk",
// .id
"ac.id", "co.id", "go.id", "mil.id", "net.id", "or.id", "sch.id", "web.id",
// .il
"ac.il", "co.il", "gov.il", "idf.il", "k12.il", "muni.il", "net.il", "org.il",
// .in
"4fd.in", "ac.in", "co.in", "edu.in", "ernet.in", "firm.in", "gen.in", "gov.in",
"ind.in", "mil.in", "net.in", "nic.in", "org.in", "res.in",
// .iq
"com.iq", "edu.iq", "gov.iq", "mil.iq", "net.iq", "org.iq",
// .ir
"ac.ir", "co.ir", "dnssec.ir", "gov.ir", "id.ir", "net.ir", "org.ir", "sch.ir",
// .it
"edu.it", "gov.it",
// .je
"co.je", "net.je", "org.je",
// .jo
"com.jo", "edu.jo", "gov.jo", "mil.jo", "name.jo", "net.jo", "org.jo", "sch.jo",
// .jp
"ac.jp", "ad.jp", "co.jp", "ed.jp", "go.jp", "gr.jp", "lg.jp", "ne.jp", "or.jp",
// .ke
"ac.ke", "co.ke", "go.ke", "info.ke", "me.ke", "mobi.ke", "ne.ke", "or.ke", "sc.ke",
// .kh
"com.kh", "edu.kh", "gov.kh", "mil.kh", "net.kh", "org.kh", "per.kh",
// .ki
"biz.ki", "com.ki", "de.ki", "edu.ki", "gov.ki", "info.ki", "mob.ki", "net.ki",
"org.ki", "tel.ki",
// .km
"asso.km", "com.km", "coop.km", "edu.km", "gouv.km", "medecin.km", "mil.km",
"nom.km", "notaires.km", "pharmaciens.km", "presse.km", "tm.km", "veterinaire.km",
// .kn
"edu.kn", "gov.kn", "net.kn", "org.kn",
// .kr
"ac.kr", "busan.kr", "chungbuk.kr", "chungnam.kr", "co.kr", "daegu.kr",
"daejeon.kr", "es.kr", "gangwon.kr", "go.kr", "gwangju.kr", "gyeongbuk.kr",
"gyeonggi.kr", "gyeongnam.kr", "hs.kr", "incheon.kr", "jeju.kr", "jeonbuk.kr",
"jeonnam.kr", "kg.kr", "mil.kr", "ms.kr", "ne.kr", "or.kr", "pe.kr", "re.kr",
"sc.kr", "seoul.kr", "ulsan.kr",
// .kw
"com.kw", "edu.kw", "gov.kw", "net.kw", "org.kw",
// .ky
"com.ky", "edu.ky", "gov.ky", "net.ky", "org.ky",
// .kz
"com.kz", "edu.kz", "gov.kz", "mil.kz", "net.kz", "org.kz",
// .lb
"com.lb", "edu.lb", "gov.lb", "net.lb", "org.lb",
// .lk
"assn.lk", "com.lk", "edu.lk", "gov.lk", "grp.lk", "hotel.lk", "int.lk", "ltd.lk",
"net.lk", "ngo.lk", "org.lk", "sch.lk", "soc.lk", "web.lk",
// .lr
"com.lr", "edu.lr", "gov.lr", "net.lr", "org.lr",
// .lv
"asn.lv", "com.lv", "conf.lv", "edu.lv", "gov.lv", "id.lv", "mil.lv", "net.lv", "org.lv",
// .ly
"com.ly", "edu.ly", "gov.ly", "id.ly", "med.ly", "net.ly", "org.ly", "plc.ly", "sch.ly",
// .ma
"ac.ma", "co.ma", "gov.ma", "net.ma", "org.ma", "press.ma",
// .mc
"asso.mc", "tm.mc",
// .me
"ac.me", "co.me", "edu.me", "gov.me", "its.me", "net.me", "org.me", "priv.me",
// .mg
"com.mg", "edu.mg", "gov.mg", "mil.mg", "nom.mg", "org.mg", "prd.mg", "tm.mg",
// .mk
"com.mk", "edu.mk", "gov.mk", "inf.mk", "name.mk", "net.mk", "org.mk", "pro.mk",
// .ml
"com.ml", "edu.ml", "gov.ml", "net.ml", "org.ml", "presse.ml",
// .mn
"edu.mn", "gov.mn", "org.mn",
// .mo
"com.mo", "edu.mo", "gov.mo", "net.mo", "org.mo",
// .mt
"com.mt", "edu.mt", "gov.mt", "net.mt", "org.mt",
// .mu
"ac.mu", "co.mu", "com.mu", "gov.mu", "net.mu", "or.mu", "org.mu",
// .mv
"aero.mv", "biz.mv", "com.mv", "coop.mv", "edu.mv", "gov.mv", "info.mv",
"int.mv", "mil.mv", "museum.mv", "name.mv", "net.mv", "org.mv", "pro.mv",
// .mw
"ac.mw", "co.mw", "com.mw", "coop.mw", "edu.mw", "gov.mw", "int.mw",
"museum.mw", "net.mw", "org.mw",
// .mx
"com.mx", "edu.mx", "gob.mx", "net.mx", "org.mx",
// .my
"com.my", "edu.my", "gov.my", "mil.my", "name.my", "net.my", "org.my", "sch.my",
// .mz
"ac.mz", "co.mz", "edu.mz", "gov.mz", "org.mz",
// .na
"co.na", "com.na",
// .nf
"arts.nf", "com.nf", "firm.nf", "info.nf", "net.nf", "other.nf", "per.nf",
"rec.nf", "store.nf", "web.nf",
// .ng
"biz.ng", "com.ng", "edu.ng", "gov.ng", "mil.ng", "mobi.ng", "name.ng",
"net.ng", "org.ng", "sch.ng",
// .ni
"ac.ni", "co.ni", "com.ni", "edu.ni", "gob.ni", "mil.ni", "net.ni", "nom.ni", "org.ni",
// .np
"com.np", "edu.np", "gov.np", "mil.np", "net.np", "org.np",
// .nr
"biz.nr", "com.nr", "edu.nr", "gov.nr", "info.nr", "net.nr", "org.nr",
// .nz
"ac.nz", "co.nz", "cri.nz", "geek.nz", "gen.nz", "govt.nz", "health.nz",
"iwi.nz", "maori.nz", "mil.nz", "net.nz", "org.nz", "parliament.nz", "school.nz",
// .om
"ac.om", "biz.om", "co.om", "com.om", "edu.om", "gov.om", "med.om", "mil.om",
"museum.om", "net.om", "org.om", "pro.om", "sch.om",
// .pa
"abo.pa", "ac.pa", "com.pa", "edu.pa", "gob.pa", "ing.pa", "med.pa", "net.pa",
"nom.pa", "org.pa", "sld.pa",
// .pe
"com.pe", "edu.pe", "gob.pe", "mil.pe", "net.pe", "nom.pe", "org.pe", "sld.pe",
// .ph
"com.ph", "edu.ph", "gov.ph", "i.ph", "mil.ph", "net.ph", "ngo.ph", "org.ph",
// .pk
"biz.pk", "com.pk", "edu.pk", "fam.pk", "gob.pk", "gok.pk", "gon.pk", "gop.pk",
"gos.pk", "gov.pk", "net.pk", "org.pk", "web.pk",
// .pl
"art.pl", "bialystok.pl", "biz.pl", "com.pl", "edu.pl", "gda.pl", "gdansk.pl",
"gorzow.pl", "gov.pl", "info.pl", "katowice.pl", "krakow.pl", "lodz.pl",
"lublin.pl", "mil.pl", "net.pl", "ngo.pl", "olsztyn.pl", "org.pl", "poznan.pl",
"pwr.pl", "radom.pl", "slupsk.pl", "szczecin.pl", "torun.pl", "warszawa.pl",
"waw.pl", "wroc.pl", "wroclaw.pl", "zgora.pl",
// .pr
"ac.pr", "biz.pr", "com.pr", "edu.pr", "est.pr", "gov.pr", "info.pr", "isla.pr",
"name.pr", "net.pr", "org.pr", "pro.pr", "prof.pr",
// .ps
"com.ps", "edu.ps", "gov.ps", "net.ps", "org.ps", "plo.ps", "sec.ps",
// .pt
"com.pt", "edu.pt", "gov.pt", "int.pt", "net.pt", "nome.pt", "org.pt", "publ.pt",
// .pw
"belau.pw", "co.pw", "ed.pw", "go.pw", "ne.pw", "or.pw",
// .py
"com.py", "edu.py", "gov.py", "mil.py", "net.py", "org.py",
// .qa
"com.qa", "edu.qa", "gov.qa", "mil.qa", "net.qa", "org.qa",
// .re
"asso.re", "com.re", "nom.re",
// .ro
"arts.ro", "com.ro", "firm.ro", "info.ro", "nom.ro", "nt.ro", "org.ro",
"rec.ro", "store.ro", "tm.ro", "www.ro",
// .rs
"ac.rs", "co.rs", "edu.rs", "gov.rs", "in.rs", "org.rs",
// .ru
"ac.ru", "adygeya.ru", "altai.ru", "amur.ru", "arkhangelsk.ru", "astrakhan.ru",
"bashkiria.ru", "belgorod.ru", "bir.ru", "bryansk.ru", "buryatia.ru", "cbg.ru",
"chel.ru", "chelyabinsk.ru", "chita.ru", "chukotka.ru", "chuvashia.ru", "com.ru",
"dagestan.ru", "e-burg.ru", "edu.ru", "gov.ru", "grozny.ru", "int.ru",
"irkutsk.ru", "ivanovo.ru", "izhevsk.ru", "jar.ru", "joshkar-ola.ru",
"kalmykia.ru", "kaluga.ru", "kamchatka.ru", "karelia.ru", "kazan.ru", "kchr.ru",
"kemerovo.ru", "khabarovsk.ru", "khakassia.ru", "khv.ru", "kirov.ru",
"koenig.ru", "komi.ru", "kostroma.ru", "kranoyarsk.ru", "kuban.ru", "kurgan.ru",
"kursk.ru", "lipetsk.ru", "magadan.ru", "mari.ru", "mari-el.ru", "marine.ru",
"mil.ru", "mordovia.ru", "mosreg.ru", "msk.ru", "murmansk.ru", "nalchik.ru",
"net.ru", "nnov.ru", "nov.ru", "novosibirsk.ru", "nsk.ru", "omsk.ru",
"orenburg.ru", "org.ru", "oryol.ru", "penza.ru", "perm.ru", "pp.ru", "pskov.ru",
"ptz.ru", "rnd.ru", "ryazan.ru", "sakhalin.ru", "samara.ru", "saratov.ru",
"simbirsk.ru", "smolensk.ru", "spb.ru", "stavropol.ru", "stv.ru", "surgut.ru",
"tambov.ru", "tatarstan.ru", "tom.ru", "tomsk.ru", "tsaritsyn.ru", "tsk.ru",
"tula.ru", "tuva.ru", "tver.ru", "tyumen.ru", "udm.ru", "udmurtia.ru",
"ulan-ude.ru", "vladikavkaz.ru", "vladimir.ru", "vladivostok.ru", "volgograd.ru",
"vologda.ru", "voronezh.ru", "vrn.ru", "vyatka.ru", "yakutia.ru", "yamal.ru",
"yekaterinburg.ru", "yuzhno-sakhalinsk.ru",
// .rw
"ac.rw", "co.rw", "com.rw", "edu.rw", "gouv.rw", "gov.rw", "int.rw", "mil.rw", "net.rw",
// .sa
"com.sa", "edu.sa", "gov.sa", "med.sa", "net.sa", "org.sa", "pub.sa", "sch.sa",
// .sb
"com.sb", "edu.sb", "gov.sb", "net.sb", "org.sb",
// .sc
"com.sc", "edu.sc", "gov.sc", "net.sc", "org.sc",
// .sd
"com.sd", "edu.sd", "gov.sd", "info.sd", "med.sd", "net.sd", "org.sd", "tv.sd",
// .se
"a.se", "ac.se", "b.se", "bd.se", "c.se", "d.se", "e.se", "f.se", "g.se",
"h.se", "i.se", "k.se", "l.se", "m.se", "n.se", "o.se", "org.se", "p.se",
"parti.se", "pp.se", "press.se", "r.se", "s.se", "t.se", "tm.se", "u.se",
"w.se", "x.se", "y.se", "z.se",
// .sg
"com.sg", "edu.sg", "gov.sg", "idn.sg", "net.sg", "org.sg", "per.sg",
// .sh
"co.sh", "com.sh", "edu.sh", "gov.sh", "net.sh", "nom.sh", "org.sh",
// .sl
"com.sl", "edu.sl", "gov.sl", "net.sl", "org.sl",
// .sn
"art.sn", "com.sn", "edu.sn", "gouv.sn", "org.sn", "perso.sn", "univ.sn",
// .st
"co.st", "com.st", "consulado.st", "edu.st", "embaixada.st", "gov.st", "mil.st",
"net.st", "org.st", "principe.st", "saotome.st", "store.st",
// .sv
"com.sv", "edu.sv", "gob.sv", "org.sv", "red.sv",
// .sy
"com.sy", "edu.sy", "gov.sy", "mil.sy", "net.sy", "news.sy", "org.sy",
// .sz
"ac.sz", "co.sz", "org.sz",
// .th
"ac.th", "co.th", "go.th", "in.th", "mi.th", "net.th", "or.th",
// .tj
"ac.tj", "biz.tj", "co.tj", "com.tj", "edu.tj", "go.tj", "gov.tj", "info.tj",
"int.tj", "mil.tj", "name.tj", "net.tj", "nic.tj", "org.tj", "test.tj", "web.tj",
// .tn
"agrinet.tn", "com.tn", "defense.tn", "edunet.tn", "ens.tn", "fin.tn", "gov.tn",
"ind.tn", "info.tn", "intl.tn", "mincom.tn", "nat.tn", "net.tn", "org.tn",
"perso.tn", "rnrt.tn", "rns.tn", "rnu.tn", "tourism.tn",
// .tr
"av.tr", "bbs.tr", "bel.tr", "biz.tr", "com.tr", "dr.tr", "edu.tr", "gen.tr",
"gov.tr", "info.tr", "k12.tr", "name.tr", "net.tr", "org.tr", "pol.tr",
"tel.tr", "tsk.tr", "tv.tr", "web.tr",
// .tt
"aero.tt", "biz.tt", "cat.tt", "co.tt", "com.tt", "coop.tt", "edu.tt", "gov.tt",
"info.tt", "int.tt", "jobs.tt", "mil.tt", "mobi.tt", "museum.tt", "name.tt",
"net.tt", "org.tt", "pro.tt", "tel.tt", "travel.tt",
// .tw
"club.tw", "com.tw", "ebiz.tw", "edu.tw", "game.tw", "gov.tw", "idv.tw",
"mil.tw", "net.tw", "org.tw",
// .tz
"ac.tz", "co.tz", "go.tz", "ne.tz", "or.tz",
// .ua
"biz.ua", "cherkassy.ua", "chernigov.ua", "chernovtsy.ua", "ck.ua", "cn.ua",
"co.ua", "com.ua", "crimea.ua", "cv.ua", "dn.ua", "dnepropetrovsk.ua",
"donetsk.ua", "dp.ua", "edu.ua", "gov.ua", "if.ua", "in.ua",
"ivano-frankivsk.ua", "kh.ua", "kharkov.ua", "kherson.ua", "khmelnitskiy.ua",
"kiev.ua", "kirovograd.ua", "km.ua", "kr.ua", "ks.ua", "kv.ua", "lg.ua",
"lugansk.ua", "lutsk.ua", "lviv.ua", "me.ua", "mk.ua", "net.ua",
"nikolaev.ua", "od.ua", "odessa.ua", "org.ua", "pl.ua", "poltava.ua", "pp.ua",
"rovno.ua", "rv.ua", "sebastopol.ua", "sumy.ua", "te.ua", "ternopil.ua",
"uzhgorod.ua", "vinnica.ua", "vn.ua", "zaporizhzhe.ua", "zhitomir.ua",
"zp.ua", "zt.ua",
// .ug
"ac.ug", "co.ug", "go.ug", "ne.ug", "or.ug", "org.ug", "sc.ug",
// .uk
"ac.uk", "bl.uk", "british-library.uk", "co.uk", "cym.uk", "gov.uk", "govt.uk",
"icnet.uk", "jet.uk", "lea.uk", "ltd.uk", "me.uk", "mil.uk", "mod.uk",
"national-library-scotland.uk", "nel.uk", "net.uk", "nhs.uk", "nic.uk",
"nls.uk", "org.uk", "orgn.uk", "parliament.uk", "plc.uk", "police.uk",
"sch.uk", "scot.uk", "soc.uk",
// .us
"4fd.us", "dni.us", "fed.us", "isa.us", "kids.us", "nsn.us",
// .uy
"com.uy", "edu.uy", "gub.uy", "mil.uy", "net.uy", "org.uy",
// .ve
"co.ve", "com.ve", "edu.ve", "gob.ve", "info.ve", "mil.ve", "net.ve", "org.ve", "web.ve",
// .vi
"co.vi", "com.vi", "k12.vi", "net.vi", "org.vi",
// .vn
"ac.vn", "biz.vn", "com.vn", "edu.vn", "gov.vn", "health.vn", "info.vn",
"int.vn", "name.vn", "net.vn", "org.vn", "pro.vn",
// .ye
"co.ye", "com.ye", "gov.ye", "ltd.ye", "me.ye", "net.ye", "org.ye", "plc.ye",
// .yu
"ac.yu", "co.yu", "edu.yu", "gov.yu", "org.yu",
// .za
"ac.za", "agric.za", "alt.za", "bourse.za", "city.za", "co.za", "cybernet.za",
"db.za", "edu.za", "gov.za", "grondar.za", "iaccess.za", "imt.za", "inca.za",
"landesign.za", "law.za", "mil.za", "net.za", "ngo.za", "nis.za", "nom.za",
"olivetti.za", "org.za", "pix.za", "school.za", "tm.za", "web.za",
// .zm
"ac.zm", "co.zm", "com.zm", "edu.zm", "gov.zm", "net.zm", "org.zm", "sch.zm",
]); ]);
function getRootDomain(domain: string): string { function getRootDomain(domain: string): string {
+26 -35
View File
@@ -1,10 +1,21 @@
import v8 from 'node:v8';
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server'; import { NextRequest } from 'next/server';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
// Health check thresholds const MEMORY_WARNING_THRESHOLD = 0.85;
const MEMORY_WARNING_THRESHOLD = 0.85; // 85% heap usage const MEMORY_CRITICAL_THRESHOLD = 0.95;
const MEMORY_CRITICAL_THRESHOLD = 0.95; // 95% heap usage
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 { interface HealthStatus {
status: 'healthy' | 'degraded' | 'unhealthy'; status: 'healthy' | 'degraded' | 'unhealthy';
@@ -14,6 +25,7 @@ interface HealthStatus {
memory?: { memory?: {
heapUsed: number; heapUsed: number;
heapTotal: number; heapTotal: number;
heapSizeLimit: number;
rss: number; rss: number;
external: number; external: number;
heapUsagePercent: number; heapUsagePercent: number;
@@ -27,14 +39,9 @@ interface HealthStatus {
/** /**
* Health check endpoint for container orchestration * Health check endpoint for container orchestration
* *
* GET /api/health - Basic health check (returns 200 OK or 503 Service Unavailable) * GET /api/health - Liveness probe for container orchestration
* GET /api/health?detailed=true - Detailed diagnostics with memory stats * GET /api/health?detailed=true - Diagnostics with advisory memory warnings
* HEAD /api/health - Lightweight health check (status code only) * HEAD /api/health - Lightweight liveness probe (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
*/ */
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams; const searchParams = request.nextUrl.searchParams;
@@ -43,38 +50,31 @@ export async function GET(request: NextRequest) {
try { try {
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
const memUsage = process.memoryUsage(); const memUsage = process.memoryUsage();
const heapUsagePercent = (memUsage.heapUsed / memUsage.heapTotal) * 100; const heapSizeLimit = v8.getHeapStatistics().heap_size_limit;
const heapUsagePercent = getHeapUsagePercent(memUsage.heapUsed, memUsage.heapTotal);
// Determine health status based on memory usage
let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy'; let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
const warnings: string[] = []; const warnings: string[] = [];
let httpStatus = 200;
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) { if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
status = 'unhealthy'; status = 'degraded';
httpStatus = 503; warnings.push(`V8 heap usage is very high: ${heapUsagePercent.toFixed(1)}% of heap limit`);
} else if (heapUsagePercent >= MEMORY_WARNING_THRESHOLD * 100) { } else if (heapUsagePercent >= MEMORY_WARNING_THRESHOLD * 100) {
status = 'degraded'; 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 = { const response: HealthStatus = {
status, status: detailed ? status : 'healthy',
timestamp, timestamp,
}; };
if (status === 'unhealthy') {
response.reason = `Memory usage critical: ${heapUsagePercent.toFixed(1)}%`;
}
// Add detailed information if requested
if (detailed) { if (detailed) {
response.uptime = process.uptime(); response.uptime = process.uptime();
response.version = process.env.npm_package_version || '0.1.0'; response.version = process.env.npm_package_version || '0.1.0';
response.memory = { response.memory = {
heapUsed: memUsage.heapUsed, heapUsed: memUsage.heapUsed,
heapTotal: memUsage.heapTotal, heapTotal: memUsage.heapTotal,
heapSizeLimit,
rss: memUsage.rss, rss: memUsage.rss,
external: memUsage.external, external: memUsage.external,
heapUsagePercent: Number(heapUsagePercent.toFixed(2)), 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, { return NextResponse.json(response, {
status: httpStatus, status: 200,
headers: { headers: {
'Cache-Control': 'no-store, no-cache, must-revalidate', 'Cache-Control': 'no-store, no-cache, must-revalidate',
'Pragma': 'no-cache', 'Pragma': 'no-cache',
@@ -116,13 +114,6 @@ export async function GET(request: NextRequest) {
*/ */
export async function HEAD() { export async function HEAD() {
try { 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 }); return new Response(null, { status: 200 });
} catch { } catch {
return new Response(null, { status: 503 }); 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 { cookies } from 'next/headers';
import { logger } from '@/lib/logger'; import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto'; 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'; import { saveUserSettings, loadUserSettings, deleteUserSettings } from '@/lib/settings-sync';
function isEnabled(): boolean { function isEnabled(): boolean {
@@ -10,19 +10,30 @@ function isEnabled(): boolean {
} }
/** /**
* Verify identity against the session cookie if available. * Verify identity against session cookies across all account slots.
* Returns true if no session cookie exists (can't verify) or if identity matches. * With multi-account, the requesting account may be on any slot (0-4).
* Returns false if session cookie exists but identity doesn't match. * Returns true if any slot matches OR if no session cookies exist at all.
*/ */
async function verifyIdentity(username: string, serverUrl: string): Promise<boolean> { async function verifyIdentity(username: string, serverUrl: string): Promise<boolean> {
const cookieStore = await cookies(); const cookieStore = await cookies();
const sessionToken = cookieStore.get(SESSION_COOKIE)?.value; let hasAnyCookie = false;
if (!sessionToken) return true; // No session cookie, can't verify (same-origin protection applies)
const session = decryptSession(sessionToken); for (let slot = 0; slot <= 4; slot++) {
if (!session) return true; // Invalid session cookie, skip verification 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) { export async function GET(request: NextRequest) {
@@ -47,7 +58,9 @@ export async function GET(request: NextRequest) {
} }
return NextResponse.json({ settings }); return NextResponse.json({ settings });
} catch (error) { } 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 }); return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
} }
} }
@@ -74,7 +87,9 @@ export async function POST(request: NextRequest) {
await saveUserSettings(username, serverUrl, settings); await saveUserSettings(username, serverUrl, settings);
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
} catch (error) { } 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 }); return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
} }
} }
+98
View File
@@ -20,6 +20,8 @@
--color-accent-foreground: #1e40af; --color-accent-foreground: #1e40af;
--color-destructive: #ef4444; --color-destructive: #ef4444;
--color-destructive-foreground: #ffffff; --color-destructive-foreground: #ffffff;
--color-popover: #ffffff;
--color-popover-foreground: #0f172a;
/* Settings variables */ /* Settings variables */
--font-size-base: 16px; --font-size-base: 16px;
@@ -50,6 +52,8 @@
--color-accent-foreground: #dbeafe; --color-accent-foreground: #dbeafe;
--color-destructive: #ef4444; --color-destructive: #ef4444;
--color-destructive-foreground: #fafafa; --color-destructive-foreground: #fafafa;
--color-popover: #1c1c1c;
--color-popover-foreground: #fafafa;
} }
@theme inline { @theme inline {
@@ -68,6 +72,8 @@
--color-accent-foreground: var(--color-accent-foreground); --color-accent-foreground: var(--color-accent-foreground);
--color-destructive: var(--color-destructive); --color-destructive: var(--color-destructive);
--color-destructive-foreground: var(--color-destructive-foreground); --color-destructive-foreground: var(--color-destructive-foreground);
--color-popover: var(--color-popover);
--color-popover-foreground: var(--color-popover-foreground);
} }
* { * {
@@ -490,3 +496,95 @@ body {
-webkit-backdrop-filter: none !important; -webkit-backdrop-filter: none !important;
} }
} }
/* TipTap Rich Text Editor */
.tiptap {
outline: none;
}
.tiptap p {
margin: 0.25rem 0;
}
.tiptap h1 {
font-size: 1.5rem;
font-weight: 700;
margin: 0.5rem 0;
}
.tiptap h2 {
font-size: 1.25rem;
font-weight: 600;
margin: 0.5rem 0;
}
.tiptap ul {
list-style-type: disc;
padding-left: 1.5rem;
margin: 0.25rem 0;
}
.tiptap ol {
list-style-type: decimal;
padding-left: 1.5rem;
margin: 0.25rem 0;
}
.tiptap li {
margin: 0.125rem 0;
}
.tiptap blockquote {
border-left: 3px solid var(--color-border);
padding-left: 1rem;
margin: 0.5rem 0;
color: var(--color-muted-foreground);
}
.tiptap pre {
background-color: var(--color-muted);
border: 1px solid var(--color-border);
border-radius: 0.375rem;
padding: 0.75rem;
font-family: monospace;
font-size: 0.875rem;
overflow-x: auto;
margin: 0.5rem 0;
}
.tiptap code {
background-color: var(--color-muted);
padding: 0.125rem 0.25rem;
border-radius: 0.25rem;
font-family: monospace;
font-size: 0.875rem;
}
.tiptap a {
color: var(--color-primary);
text-decoration: underline;
cursor: pointer;
}
.tiptap img {
max-width: 100%;
height: auto;
}
.tiptap hr {
border: none;
border-top: 1px solid var(--color-border);
margin: 1rem 0;
}
.tiptap p.is-editor-empty:first-child::before {
content: attr(data-placeholder);
float: left;
color: var(--color-muted-foreground);
pointer-events: none;
height: 0;
}
.tiptap .ProseMirror-selectednode img {
outline: none;
}
+13 -4
View File
@@ -14,10 +14,15 @@ const geistMono = Geist_Mono({
subsets: ["latin"], subsets: ["latin"],
}); });
export const metadata: Metadata = { export async function generateMetadata(): Promise<Metadata> {
title: "Bulwark Webmail", const faviconUrl = process.env.FAVICON_URL;
description: "Minimalist webmail client using JMAP protocol",
}; return {
title: process.env.APP_NAME || process.env.NEXT_PUBLIC_APP_NAME || "Webmail",
description: "Minimalist webmail client using JMAP protocol",
...(faviconUrl ? { icons: { icon: faviconUrl } } : {}),
};
}
export default async function RootLayout({ export default async function RootLayout({
children, children,
@@ -26,10 +31,14 @@ export default async function RootLayout({
}) { }) {
const locale = await getLocale(); const locale = await getLocale();
const nonce = (await headers()).get("x-nonce") ?? ""; const nonce = (await headers()).get("x-nonce") ?? "";
const parentOrigin = process.env.NEXT_PUBLIC_PARENT_ORIGIN || "";
return ( return (
<html lang={locale} suppressHydrationWarning> <html lang={locale} suppressHydrationWarning>
<head> <head>
{parentOrigin && (
<meta name="parent-origin" content={parentOrigin} />
)}
<script <script
nonce={nonce} nonce={nonce}
suppressHydrationWarning suppressHydrationWarning
+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"; "use client";
import { useMemo } from "react"; import { useMemo, useRef, useEffect, useCallback } from "react";
import { useTranslations, useFormatter } from "next-intl"; 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 { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { parseDuration, getEventColor } from "./event-card"; 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 { getParticipantCount } from "@/lib/calendar-participants";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types"; import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
@@ -27,6 +27,7 @@ interface DayGroup {
} }
export function CalendarAgendaView({ export function CalendarAgendaView({
selectedDate,
events, events,
calendars, calendars,
onSelectEvent, onSelectEvent,
@@ -43,6 +44,9 @@ export function CalendarAgendaView({
return map; return map;
}, [calendars]); }, [calendars]);
const todayRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const grouped = useMemo(() => { const grouped = useMemo(() => {
const sorted = [...events].sort((a, b) => const sorted = [...events].sort((a, b) =>
new Date(a.start).getTime() - new Date(b.start).getTime() new Date(a.start).getTime() - new Date(b.start).getTime()
@@ -69,10 +73,38 @@ export function CalendarAgendaView({
} catch { /* skip invalid dates */ } } 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()); groups.sort((a, b) => a.date.getTime() - b.date.getTime());
return groups; return groups;
}, [events]); }, [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 => { const formatDateHeader = (date: Date): string => {
if (isToday(date)) return t("events.today_header"); if (isToday(date)) return t("events.today_header");
if (isTomorrow(date)) return t("events.tomorrow_header"); if (isTomorrow(date)) return t("events.tomorrow_header");
@@ -86,19 +118,10 @@ export function CalendarAgendaView({
return format(date, "HH:mm"); 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 ( return (
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto" ref={scrollContainerRef}>
{grouped.map((group) => ( {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"> <div className="sticky top-0 bg-muted/80 backdrop-blur-sm px-4 py-2 border-b border-border">
<span className={cn( <span className={cn(
"text-sm font-medium", "text-sm font-medium",
@@ -111,10 +134,15 @@ export function CalendarAgendaView({
</span> </span>
</div> </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"> <div className="divide-y divide-border">
{group.events.map((ev) => { {group.events.map((ev) => {
const calId = Object.keys(ev.calendarIds)[0]; const calId = getPrimaryCalendarId(ev);
const calendar = calendarMap.get(calId); const calendar = calId ? calendarMap.get(calId) : undefined;
const color = getEventColor(ev, calendar); const color = getEventColor(ev, calendar);
const start = parseISO(ev.start); const start = parseISO(ev.start);
const durMin = parseDuration(ev.duration); const durMin = parseDuration(ev.duration);
@@ -176,6 +204,7 @@ export function CalendarAgendaView({
); );
})} })}
</div> </div>
)}
</div> </div>
))} ))}
</div> </div>
+107 -23
View File
@@ -2,13 +2,15 @@
import { useMemo, useEffect, useRef, useState } from "react"; import { useMemo, useEffect, useRef, useState } from "react";
import { useTranslations, useFormatter } from "next-intl"; 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 { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card"; import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input"; 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 type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions"; import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
interface CalendarDayViewProps { interface CalendarDayViewProps {
selectedDate: Date; selectedDate: Date;
@@ -20,6 +22,9 @@ interface CalendarDayViewProps {
onCreateAtTime: (date: Date, endDate?: Date) => void; onCreateAtTime: (date: Date, endDate?: Date) => void;
timeFormat?: "12h" | "24h"; timeFormat?: "12h" | "24h";
isMobile?: boolean; isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
} }
const HOUR_HEIGHT = 64; const HOUR_HEIGHT = 64;
@@ -35,6 +40,9 @@ export function CalendarDayView({
onCreateAtTime, onCreateAtTime,
timeFormat = "24h", timeFormat = "24h",
isMobile, isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarDayViewProps) { }: CalendarDayViewProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const intlFormatter = useFormatter(); const intlFormatter = useFormatter();
@@ -65,6 +73,16 @@ export function CalendarDayView({
return { timedEvents: timed, allDayEvents: allDay }; return { timedEvents: timed, allDayEvents: allDay };
}, [events, selectedDate]); }, [events, selectedDate]);
const dayTasks = useMemo(() => {
if (!tasks?.length) return [];
return tasks.filter(task => {
if (!task.due) return false;
try {
return isSameDay(parseISO(task.due), selectedDate);
} catch { return false; }
});
}, [tasks, selectedDate]);
useEffect(() => { useEffect(() => {
if (scrollRef.current) { if (scrollRef.current) {
const now = new Date(); const now = new Date();
@@ -122,25 +140,63 @@ export function CalendarDayView({
</h3> </h3>
</div> </div>
{allDayEvents.length > 0 && ( {(allDayEvents.length > 0 || dayTasks.length > 0) && (
<div className="px-4 py-2 border-b border-border"> <div className="px-4 py-2 border-b border-border">
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div> {allDayEvents.length > 0 && (
<div className="space-y-1"> <>
{allDayEvents.map((ev) => { <div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
const calId = Object.keys(ev.calendarIds)[0]; <div className="space-y-1">
return ( {allDayEvents.map((ev) => {
<EventCard const calId = getPrimaryCalendarId(ev);
key={ev.id} return (
event={ev} <EventCard
calendar={calendarMap.get(calId)} key={ev.id}
variant="chip" event={ev}
onClick={(rect) => onSelectEvent(ev, rect)} calendar={calId ? calendarMap.get(calId) : undefined}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)} variant="chip"
onMouseLeave={onHoverLeave} onClick={(rect) => onSelectEvent(ev, rect)}
/> onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
); onMouseLeave={onHoverLeave}
})} />
</div> );
})}
</div>
</>
)}
{dayTasks.length > 0 && (
<>
<div className={cn("text-[10px] text-muted-foreground mb-1", allDayEvents.length > 0 && "mt-2")}>{t("tasks.label")}</div>
<div className="space-y-0.5">
{dayTasks.map((task) => {
const isCompleted = task.progress === "completed";
const cal = calendars.find(c => task.calendarIds[c.id]);
const color = cal?.color || "#3b82f6";
return (
<div
key={task.id}
className="flex items-center gap-1.5 px-1.5 py-0.5 rounded text-xs cursor-pointer hover:bg-muted/50 transition-colors"
style={{ borderLeft: `3px solid ${color}` }}
>
<button
onClick={(e) => { e.stopPropagation(); onToggleTaskComplete?.(task); }}
className={cn(
"flex-shrink-0 w-3.5 h-3.5 rounded-full border flex items-center justify-center",
isCompleted
? "bg-green-500 border-green-500 text-white"
: "border-muted-foreground/40 hover:border-primary"
)}
>
{isCompleted && <Check className="h-2.5 w-2.5" />}
</button>
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
{task.title || t("tasks.no_title")}
</span>
</div>
);
})}
</div>
</>
)}
</div> </div>
)} )}
@@ -192,7 +248,7 @@ export function CalendarDayView({
const top = (startMin / 60) * HOUR_HEIGHT; const top = (startMin / 60) * HOUR_HEIGHT;
const baseHeight = Math.max(24, (durMin / 60) * HOUR_HEIGHT); const baseHeight = Math.max(24, (durMin / 60) * HOUR_HEIGHT);
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight; 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 leftPct = (column / totalColumns) * 100;
const widthPct = (1 / totalColumns) * 100; const widthPct = (1 / totalColumns) * 100;
@@ -205,7 +261,7 @@ export function CalendarDayView({
> >
<EventCard <EventCard
event={ev} event={ev}
calendar={calendarMap.get(calId)} calendar={calId ? calendarMap.get(calId) : undefined}
variant="block" variant="block"
onClick={(rect) => onSelectEvent(ev, rect)} onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)} onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
@@ -274,6 +330,34 @@ export function CalendarDayView({
</div> </div>
</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> </div>
</div> </div>
+60 -22
View File
@@ -8,10 +8,11 @@ import {
} from "date-fns"; } from "date-fns";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { EventCard } from "./event-card"; 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 type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import type { PendingEventPreview } from "./event-modal";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
interface CalendarMonthViewProps { interface CalendarMonthViewProps {
@@ -22,8 +23,10 @@ interface CalendarMonthViewProps {
onSelectEvent: (event: CalendarEvent, anchorRect: DOMRect) => void; onSelectEvent: (event: CalendarEvent, anchorRect: DOMRect) => void;
onHoverEvent?: (event: CalendarEvent, anchorRect: DOMRect) => void; onHoverEvent?: (event: CalendarEvent, anchorRect: DOMRect) => void;
onHoverLeave?: () => void; onHoverLeave?: () => void;
onCreateAtTime?: (date: Date) => void;
firstDayOfWeek?: number; firstDayOfWeek?: number;
isMobile?: boolean; isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
} }
export function CalendarMonthView({ export function CalendarMonthView({
@@ -34,8 +37,10 @@ export function CalendarMonthView({
onSelectEvent, onSelectEvent,
onHoverEvent, onHoverEvent,
onHoverLeave, onHoverLeave,
onCreateAtTime,
firstDayOfWeek = 1, firstDayOfWeek = 1,
isMobile, isMobile,
pendingPreview,
}: CalendarMonthViewProps) { }: CalendarMonthViewProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const intlFormatter = useFormatter(); const intlFormatter = useFormatter();
@@ -165,6 +170,7 @@ export function CalendarMonthView({
aria-selected={selected} aria-selected={selected}
aria-label={fullDateLabel} aria-label={fullDateLabel}
onClick={() => onSelectDate(day)} onClick={() => onSelectDate(day)}
onDoubleClick={() => onCreateAtTime?.(day)}
onDragOver={(e) => handleCellDragOver(e, key)} onDragOver={(e) => handleCellDragOver(e, key)}
onDragLeave={handleCellDragLeave} onDragLeave={handleCellDragLeave}
onDrop={(e) => handleCellDrop(e, day)} onDrop={(e) => handleCellDrop(e, day)}
@@ -191,35 +197,67 @@ export function CalendarMonthView({
</span> </span>
</div> </div>
{isMobile ? ( {isMobile ? (
dayEvents.length > 0 && ( <div className="flex items-center justify-center gap-0.5 flex-wrap">
<div className="flex items-center justify-center gap-0.5 flex-wrap"> {dayEvents.slice(0, 3).map((ev) => {
{dayEvents.slice(0, 3).map((ev) => { const calId = getPrimaryCalendarId(ev);
const calId = Object.keys(ev.calendarIds)[0]; const cal = calId ? calendarMap.get(calId) : undefined;
const cal = calendarMap.get(calId); const evColor = ev.color || cal?.color || "#3b82f6";
const evColor = ev.color || cal?.color || "#3b82f6"; return (
return ( <span
<span key={ev.id}
key={ev.id} className="w-1.5 h-1.5 rounded-full"
className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: evColor }}
style={{ backgroundColor: evColor }} />
/> );
); })}
})} {dayEvents.length > 3 && (
{dayEvents.length > 3 && ( <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" /> )}
)} {pendingPreview && isSameDay(pendingPreview.start, day) && (
</div> <span
) className="w-1.5 h-1.5 rounded-full border border-dashed"
style={{ borderColor: calendarMap.get(pendingPreview.calendarId)?.color || "#3b82f6" }}
/>
)}
</div>
) : null} ) : null}
</div> </div>
); );
})} })}
</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 && ( {!isMobile && segments.length > 0 && (
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}> <div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
{segments.map((segment) => { {segments.map((segment) => {
const calId = Object.keys(segment.event.calendarIds)[0]; const calId = getPrimaryCalendarId(segment.event);
return ( return (
<div <div
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`} key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
@@ -233,7 +271,7 @@ export function CalendarMonthView({
> >
<EventCard <EventCard
event={segment.event} event={segment.event}
calendar={calendarMap.get(calId)} calendar={calId ? calendarMap.get(calId) : undefined}
variant="span" variant="span"
continuesBefore={segment.continuesBefore} continuesBefore={segment.continuesBefore}
continuesAfter={segment.continuesAfter} continuesAfter={segment.continuesAfter}
+152 -97
View File
@@ -1,14 +1,16 @@
"use client"; "use client";
import { useState, useRef, useEffect } from "react"; import { useState, useRef, useEffect, useMemo } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Globe, Plus, RefreshCw, Trash2 } from "lucide-react"; import { Globe, ListTodo, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn, formatDateTime } from "@/lib/utils";
import type { Calendar } from "@/lib/jmap/types"; import type { Calendar } from "@/lib/jmap/types";
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings"; import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { useSettingsStore } from "@/stores/settings-store";
import { useTaskStore } from "@/stores/task-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import type { JMAPClient } from "@/lib/jmap/client"; import type { IJMAPClient } from '@/lib/jmap/client-interface';
interface CalendarSidebarPanelProps { interface CalendarSidebarPanelProps {
calendars: Calendar[]; calendars: Calendar[];
@@ -16,7 +18,7 @@ interface CalendarSidebarPanelProps {
onToggleVisibility: (id: string) => void; onToggleVisibility: (id: string) => void;
onColorChange?: (calendarId: string, color: string) => void; onColorChange?: (calendarId: string, color: string) => void;
onSubscribe?: () => void; onSubscribe?: () => void;
client?: JMAPClient | null; client?: IJMAPClient | null;
} }
export function CalendarSidebarPanel({ export function CalendarSidebarPanel({
@@ -33,6 +35,16 @@ export function CalendarSidebarPanel({
const icalSubscriptions = useCalendarStore((s) => s.icalSubscriptions); const icalSubscriptions = useCalendarStore((s) => s.icalSubscriptions);
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription); const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription); const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
const timeFormat = useSettingsStore((s) => s.timeFormat);
const enableCalendarTasks = useSettingsStore((s) => s.enableCalendarTasks);
const tasks = useTaskStore((s) => s.tasks);
const setViewMode = useCalendarStore((s) => s.setViewMode);
const pendingTaskCount = useMemo(() => tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled').length, [tasks]);
const overdueTaskCount = useMemo(() => {
const now = new Date();
return tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled' && t.due && new Date(t.due) < now).length;
}, [tasks]);
const [colorPickerId, setColorPickerId] = useState<string | null>(null); const [colorPickerId, setColorPickerId] = useState<string | null>(null);
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null); const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
@@ -40,6 +52,20 @@ export function CalendarSidebarPanel({
const colorPickerRef = useRef<HTMLDivElement>(null); const colorPickerRef = useRef<HTMLDivElement>(null);
const contextMenuRef = useRef<HTMLDivElement>(null); const contextMenuRef = useRef<HTMLDivElement>(null);
const personalCalendars = useMemo(() => calendars.filter(c => !c.isShared), [calendars]);
const sharedAccountGroups = useMemo(() => {
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 || cal.accountName || cal.id;
if (!groups.has(key)) {
groups.set(key, { accountName: cal.accountName || key, calendars: [] });
}
groups.get(key)!.calendars.push(cal);
}
return Array.from(groups.values());
}, [calendars]);
useEffect(() => { useEffect(() => {
if (!colorPickerId && !contextMenuCalId) return; if (!colorPickerId && !contextMenuCalId) return;
const handleClick = (e: MouseEvent) => { const handleClick = (e: MouseEvent) => {
@@ -95,108 +121,137 @@ export function CalendarSidebarPanel({
if (calendars.length === 0 && !onSubscribe) return null; if (calendars.length === 0 && !onSubscribe) return null;
return ( const renderCalendarItem = (cal: Calendar) => {
<div className="mt-4"> const isVisible = selectedCalendarIds.includes(cal.id);
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1"> const color = cal.color || "#3b82f6";
{t("my_calendars")}
</h3>
<div className="space-y-0.5">
{calendars.map((cal) => {
const isVisible = selectedCalendarIds.includes(cal.id);
const color = cal.color || "#3b82f6";
return (
<div key={cal.id} className="relative">
<button
onClick={() => onToggleVisibility(cal.id)}
onContextMenu={(e) => {
e.preventDefault();
if (isSubscriptionCalendar(cal.id) && client) {
setContextMenuCalId(contextMenuCalId === cal.id ? null : cal.id);
setColorPickerId(null);
} else if (onColorChange) {
setColorPickerId(colorPickerId === cal.id ? null : cal.id);
setContextMenuCalId(null);
}
}}
className={cn(
"flex items-center gap-2 w-full px-1.5 py-1 rounded-md text-sm transition-colors duration-150",
"hover:bg-muted"
)}
>
<span
className={cn(
"w-3 h-3 rounded-sm border-2 flex-shrink-0 transition-colors",
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
)}
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
/>
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
{cal.name}
</span>
{isSubscriptionCalendar(cal.id) && (
<>
<Globe className="w-3 h-3 text-muted-foreground flex-shrink-0" />
{refreshingSubId === getSubscriptionForCalendar(cal.id)?.id && (
<RefreshCw className="w-3 h-3 text-muted-foreground flex-shrink-0 animate-spin" />
)}
</>
)}
</button>
{/* Subscription context menu on right-click */}
{contextMenuCalId === cal.id && isSubscriptionCalendar(cal.id) && client && (() => {
const sub = getSubscriptionForCalendar(cal.id);
if (!sub) return null;
return ( return (
<div key={cal.id} className="relative"> <div
ref={contextMenuRef}
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg py-1 w-48"
>
<button <button
onClick={() => onToggleVisibility(cal.id)} onClick={() => handleRefreshSubscription(sub.id)}
onContextMenu={(e) => { className="flex items-center gap-2 w-full px-3 py-1.5 text-sm hover:bg-muted transition-colors"
e.preventDefault();
if (isSubscriptionCalendar(cal.id) && client) {
setContextMenuCalId(contextMenuCalId === cal.id ? null : cal.id);
setColorPickerId(null);
} else if (onColorChange) {
setColorPickerId(colorPickerId === cal.id ? null : cal.id);
setContextMenuCalId(null);
}
}}
className={cn(
"flex items-center gap-2 w-full px-1.5 py-1 rounded-md text-sm transition-colors duration-150",
"hover:bg-muted"
)}
> >
<span <RefreshCw className="w-3.5 h-3.5" />
className={cn( {tSub('refresh')}
"w-3 h-3 rounded-sm border-2 flex-shrink-0 transition-colors",
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
)}
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
/>
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
{cal.name}
</span>
{isSubscriptionCalendar(cal.id) && (
<>
<Globe className="w-3 h-3 text-muted-foreground flex-shrink-0" />
{refreshingSubId === getSubscriptionForCalendar(cal.id)?.id && (
<RefreshCw className="w-3 h-3 text-muted-foreground flex-shrink-0 animate-spin" />
)}
</>
)}
</button> </button>
<button
{/* Subscription context menu on right-click */} onClick={() => handleUnsubscribe(sub.id)}
{contextMenuCalId === cal.id && isSubscriptionCalendar(cal.id) && client && (() => { className="flex items-center gap-2 w-full px-3 py-1.5 text-sm text-destructive hover:bg-destructive/10 transition-colors"
const sub = getSubscriptionForCalendar(cal.id); >
if (!sub) return null; <Trash2 className="w-3.5 h-3.5" />
return ( {tSub('unsubscribe')}
<div </button>
ref={contextMenuRef} {sub.lastRefreshed && (
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg py-1 w-48" <div className="px-3 py-1.5 text-xs text-muted-foreground border-t border-border mt-1 pt-1">
> {tSub('last_refreshed', { time: formatDateTime(sub.lastRefreshed, timeFormat, { month: 'short', day: 'numeric', year: 'numeric' }) })}
<button
onClick={() => handleRefreshSubscription(sub.id)}
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm hover:bg-muted transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" />
{tSub('refresh')}
</button>
<button
onClick={() => handleUnsubscribe(sub.id)}
className="flex items-center gap-2 w-full px-3 py-1.5 text-sm text-destructive hover:bg-destructive/10 transition-colors"
>
<Trash2 className="w-3.5 h-3.5" />
{tSub('unsubscribe')}
</button>
{sub.lastRefreshed && (
<div className="px-3 py-1.5 text-xs text-muted-foreground border-t border-border mt-1 pt-1">
{tSub('last_refreshed', { time: new Date(sub.lastRefreshed).toLocaleString() })}
</div>
)}
</div>
);
})()}
{/* Color picker popover on right-click */}
{colorPickerId === cal.id && onColorChange && (
<div
ref={colorPickerRef}
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-3 w-56"
>
<p className="text-xs font-medium text-muted-foreground mb-2">{t("management.change_color")}</p>
<CalendarColorPicker
value={color}
onChange={(c) => {
onColorChange(cal.id, c);
setColorPickerId(null);
}}
allowCustom
/>
</div> </div>
)} )}
</div> </div>
); );
})} })()}
{/* Color picker popover on right-click */}
{colorPickerId === cal.id && onColorChange && (
<div
ref={colorPickerRef}
className="absolute left-6 top-full mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-3 w-56"
>
<p className="text-xs font-medium text-muted-foreground mb-2">{t("management.change_color")}</p>
<CalendarColorPicker
value={color}
onChange={(c) => {
onColorChange(cal.id, c);
setColorPickerId(null);
}}
allowCustom
/>
</div>
)}
</div> </div>
);
};
return (
<div className="mt-4">
{enableCalendarTasks && (
<button
onClick={() => setViewMode('tasks')}
className="flex items-center gap-2 w-full px-1.5 py-1.5 mb-3 rounded-md text-sm hover:bg-muted transition-colors"
>
<ListTodo className="w-4 h-4 text-muted-foreground" />
<span>{t('tasks.label')}</span>
{pendingTaskCount > 0 && (
<span className="ml-auto text-xs text-muted-foreground">{pendingTaskCount}</span>
)}
{overdueTaskCount > 0 && (
<span className="text-xs text-destructive font-medium">{overdueTaskCount} {t('tasks.filter_overdue').toLowerCase()}</span>
)}
</button>
)}
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1">
{t("my_calendars")}
</h3>
<div className="space-y-0.5">
{personalCalendars.map(renderCalendarItem)}
</div>
{sharedAccountGroups.map((group) => (
<div key={group.accountName} className="mt-4">
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1 flex items-center gap-1.5">
<Share2 className="w-3 h-3" />
{group.accountName}
</h3>
<div className="space-y-0.5">
{group.calendars.map(renderCalendarItem)}
</div>
</div>
))}
</div> </div>
); );
} }
+67 -4
View File
@@ -3,7 +3,7 @@
import { useState, useRef, useEffect } from "react"; import { useState, useRef, useEffect } from "react";
import { useTranslations, useFormatter } from "next-intl"; import { useTranslations, useFormatter } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown } from "lucide-react"; import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown, ListTodo } from "lucide-react";
import { addDays, startOfWeek } from "date-fns"; import { addDays, startOfWeek } from "date-fns";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { CalendarViewMode } from "@/stores/calendar-store"; import type { CalendarViewMode } from "@/stores/calendar-store";
@@ -25,6 +25,7 @@ interface CalendarToolbarProps {
calendars?: Calendar[]; calendars?: Calendar[];
selectedCalendarIds?: string[]; selectedCalendarIds?: string[];
onToggleVisibility?: (id: string) => void; onToggleVisibility?: (id: string) => void;
enableCalendarTasks?: boolean;
} }
export function CalendarToolbar({ export function CalendarToolbar({
@@ -42,10 +43,13 @@ export function CalendarToolbar({
calendars, calendars,
selectedCalendarIds, selectedCalendarIds,
onToggleVisibility, onToggleVisibility,
enableCalendarTasks,
}: CalendarToolbarProps) { }: CalendarToolbarProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const formatter = useFormatter(); const formatter = useFormatter();
const views: CalendarViewMode[] = ["month", "week", "day", "agenda"]; const views: CalendarViewMode[] = enableCalendarTasks
? ["month", "week", "day", "agenda", "tasks"]
: ["month", "week", "day", "agenda"];
const [showCalendarDropdown, setShowCalendarDropdown] = useState(false); const [showCalendarDropdown, setShowCalendarDropdown] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null); const dropdownRef = useRef<HTMLDivElement>(null);
@@ -86,6 +90,8 @@ export function CalendarToolbar({
return isMobile return isMobile
? formatter.dateTime(selectedDate, { month: "short", year: "numeric" }) ? formatter.dateTime(selectedDate, { month: "short", year: "numeric" })
: formatter.dateTime(selectedDate, { month: "long", year: "numeric" }); : formatter.dateTime(selectedDate, { month: "long", year: "numeric" });
case "tasks":
return t("views.tasks");
} }
}; };
@@ -136,6 +142,20 @@ export function CalendarToolbar({
{t("views.today")} {t("views.today")}
</Button> </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 && ( {isMobile && calendars && selectedCalendarIds && onToggleVisibility && (
<div className="relative" ref={dropdownRef}> <div className="relative" ref={dropdownRef}>
<Button <Button
@@ -153,7 +173,7 @@ export function CalendarToolbar({
{t("my_calendars")} {t("my_calendars")}
</h3> </h3>
<div className="space-y-0.5"> <div className="space-y-0.5">
{calendars.map((cal) => { {calendars.filter(c => !c.isShared).map((cal) => {
const isVisible = selectedCalendarIds.includes(cal.id); const isVisible = selectedCalendarIds.includes(cal.id);
const color = cal.color || "#3b82f6"; const color = cal.color || "#3b82f6";
return ( return (
@@ -179,6 +199,49 @@ export function CalendarToolbar({
); );
})} })}
</div> </div>
{(() => {
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 || c.accountName || c.id;
if (!groups.has(key)) groups.set(key, { accountName: c.accountName || key, cals: [] });
groups.get(key)!.cals.push(c);
}
return Array.from(groups.values()).map((group) => (
<div key={group.accountName} className="mt-2">
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1 px-1">
{group.accountName}
</h3>
<div className="space-y-0.5">
{group.cals.map((cal) => {
const isVisible = selectedCalendarIds.includes(cal.id);
const color = cal.color || "#3b82f6";
return (
<button
key={cal.id}
onClick={() => onToggleVisibility(cal.id)}
className={cn(
"flex items-center gap-2 w-full px-2 py-2 rounded-md text-sm transition-colors duration-150 touch-manipulation",
"hover:bg-muted"
)}
>
<span
className={cn(
"w-3.5 h-3.5 rounded-sm border-2 flex-shrink-0 transition-colors",
isVisible ? "border-transparent" : "border-muted-foreground/40 bg-transparent"
)}
style={isVisible ? { backgroundColor: color, borderColor: color } : undefined}
/>
<span className={cn("truncate", !isVisible && "text-muted-foreground")}>
{cal.name}
</span>
</button>
);
})}
</div>
</div>
));
})()}
</div> </div>
)} )}
</div> </div>
@@ -269,7 +332,7 @@ export function CalendarToolbar({
)} )}
{!isMobile && ( {!isMobile && (
<Button size="sm" onClick={onCreateEvent}> <Button size="sm" onClick={onCreateEvent} data-tour="create-event-button">
<Plus className="w-4 h-4 mr-1" /> <Plus className="w-4 h-4 mr-1" />
{t("events.create")} {t("events.create")}
</Button> </Button>
+117 -10
View File
@@ -6,11 +6,13 @@ import {
startOfWeek, addDays, format, isSameDay, isToday, parseISO, startOfWeek, addDays, format, isSameDay, isToday, parseISO,
} from "date-fns"; } from "date-fns";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card"; import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input"; 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 type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions"; import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
import type { PendingEventPreview } from "./event-modal";
interface CalendarWeekViewProps { interface CalendarWeekViewProps {
selectedDate: Date; selectedDate: Date;
@@ -24,6 +26,9 @@ interface CalendarWeekViewProps {
firstDayOfWeek?: number; firstDayOfWeek?: number;
timeFormat?: "12h" | "24h"; timeFormat?: "12h" | "24h";
isMobile?: boolean; isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
} }
const HOUR_HEIGHT = 60; const HOUR_HEIGHT = 60;
@@ -41,6 +46,9 @@ export function CalendarWeekView({
firstDayOfWeek = 1, firstDayOfWeek = 1,
timeFormat = "24h", timeFormat = "24h",
isMobile, isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarWeekViewProps) { }: CalendarWeekViewProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const intlFormatter = useFormatter(); const intlFormatter = useFormatter();
@@ -93,9 +101,36 @@ export function CalendarWeekView({
return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0); return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0);
}, [allDaySegments]); }, [allDaySegments]);
// Tasks grouped by day for the week
const tasksByDay = useMemo(() => {
if (!tasks?.length) return new Map<string, CalendarTask[]>();
const map = new Map<string, CalendarTask[]>();
for (const task of tasks) {
if (!task.due) continue;
try {
const key = format(parseISO(task.due), "yyyy-MM-dd");
const existing = map.get(key) || [];
existing.push(task);
map.set(key, existing);
} catch { /* skip */ }
}
return map;
}, [tasks]);
// Max tasks on any single day in this week
const taskRowCount = useMemo(() => {
let max = 0;
for (const day of weekDays) {
const key = format(day, "yyyy-MM-dd");
const count = tasksByDay.get(key)?.length ?? 0;
if (count > max) max = count;
}
return max;
}, [tasksByDay, weekDays]);
const hasAllDay = useMemo(() => { const hasAllDay = useMemo(() => {
return allDaySegments.length > 0; return allDaySegments.length > 0 || taskRowCount > 0;
}, [allDaySegments]); }, [allDaySegments, taskRowCount]);
useEffect(() => { useEffect(() => {
if (scrollRef.current) { if (scrollRef.current) {
@@ -148,13 +183,13 @@ export function CalendarWeekView({
<div className="flex border-b border-border"> <div className="flex border-b border-border">
<div <div
className={cn("flex-shrink-0 text-[10px] text-muted-foreground p-1 text-right", isMobile ? "w-10" : "w-14")} className={cn("flex-shrink-0 text-[10px] text-muted-foreground p-1 text-right", isMobile ? "w-10" : "w-14")}
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }} style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
> >
{t("events.all_day")} {t("events.all_day")}
</div> </div>
<div <div
className={cn("flex-1 relative grid gap-px bg-border", isMobile ? "grid-cols-3" : "grid-cols-7")} className={cn("flex-1 relative grid gap-px bg-border", isMobile ? "grid-cols-3" : "grid-cols-7")}
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }} style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
> >
{weekDays.map((day) => ( {weekDays.map((day) => (
<div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" /> <div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" />
@@ -162,7 +197,7 @@ export function CalendarWeekView({
<div className="absolute inset-0 pointer-events-none"> <div className="absolute inset-0 pointer-events-none">
{allDaySegments.map((segment) => { {allDaySegments.map((segment) => {
const calId = Object.keys(segment.event.calendarIds)[0]; const calId = getPrimaryCalendarId(segment.event);
return ( return (
<div <div
key={`${segment.event.id}-${segment.startIndex}-${segment.row}`} key={`${segment.event.id}-${segment.startIndex}-${segment.row}`}
@@ -176,7 +211,7 @@ export function CalendarWeekView({
> >
<EventCard <EventCard
event={segment.event} event={segment.event}
calendar={calendarMap.get(calId)} calendar={calId ? calendarMap.get(calId) : undefined}
variant="span" variant="span"
continuesBefore={segment.continuesBefore} continuesBefore={segment.continuesBefore}
continuesAfter={segment.continuesAfter} continuesAfter={segment.continuesAfter}
@@ -188,6 +223,49 @@ export function CalendarWeekView({
); );
})} })}
</div> </div>
{/* Task chips in all-day area */}
{taskRowCount > 0 && (
<div className="absolute inset-x-0 pointer-events-none" style={{ top: allDayRowCount * 24 + 2 }}>
{weekDays.map((day, dayIndex) => {
const key = format(day, "yyyy-MM-dd");
const dayTasks = tasksByDay.get(key) || [];
return dayTasks.map((task, taskIndex) => {
const isCompleted = task.progress === "completed";
const cal = calendars.find(c => task.calendarIds[c.id]);
const color = cal?.color || "#3b82f6";
return (
<div
key={`task-${task.id}`}
className="absolute px-0.5 pointer-events-auto"
style={{
left: `calc(${(dayIndex / colCount) * 100}% + 1px)`,
width: `calc(${(1 / colCount) * 100}% - 2px)`,
top: taskIndex * 24,
height: 20,
}}
>
<div
className="h-full rounded text-[10px] leading-[20px] font-medium px-1.5 truncate flex items-center gap-1 cursor-pointer hover:opacity-80"
style={{ backgroundColor: `${color}20`, borderLeft: `3px solid ${color}` }}
onClick={() => onToggleTaskComplete?.(task)}
>
<span className={cn(
"w-2.5 h-2.5 rounded-full border flex-shrink-0 flex items-center justify-center",
isCompleted ? "bg-green-500 border-green-500" : "border-current"
)}>
{isCompleted && <Check className="h-2 w-2 text-white" />}
</span>
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
{task.title}
</span>
</div>
</div>
);
});
})}
</div>
)}
</div> </div>
</div> </div>
)} )}
@@ -284,7 +362,7 @@ export function CalendarWeekView({
const top = (startMin / 60) * HOUR_HEIGHT; const top = (startMin / 60) * HOUR_HEIGHT;
const baseHeight = Math.max(20, (durMin / 60) * HOUR_HEIGHT); const baseHeight = Math.max(20, (durMin / 60) * HOUR_HEIGHT);
const height = resizeVisual?.eventId === ev.id ? resizeVisual.heightPx : baseHeight; 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 leftPct = (column / totalColumns) * 100;
const widthPct = (1 / totalColumns) * 100; const widthPct = (1 / totalColumns) * 100;
@@ -297,7 +375,7 @@ export function CalendarWeekView({
> >
<EventCard <EventCard
event={ev} event={ev}
calendar={calendarMap.get(calId)} calendar={calId ? calendarMap.get(calId) : undefined}
variant="block" variant="block"
onClick={(rect) => onSelectEvent(ev, rect)} onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)} onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
@@ -366,6 +444,35 @@ export function CalendarWeekView({
</div> </div>
</div> </div>
)} )}
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && (
(() => {
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
let endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
if (endMin <= startMin) endMin = 1440;
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> </div>
); );
})} })}
+8 -1
View File
@@ -7,6 +7,7 @@ import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import { format, parseISO } from "date-fns"; import { format, parseISO } from "date-fns";
import { Users } from "lucide-react"; import { Users } from "lucide-react";
import { getParticipantCount } from "@/lib/calendar-participants"; import { getParticipantCount } from "@/lib/calendar-participants";
import { useSettingsStore } from "@/stores/settings-store";
interface EventCardProps { interface EventCardProps {
event: CalendarEvent; event: CalendarEvent;
@@ -68,11 +69,14 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
const [isBeingDragged, setIsBeingDragged] = useState(false); const [isBeingDragged, setIsBeingDragged] = useState(false);
const color = getEventColor(event, calendar); const color = getEventColor(event, calendar);
const startDate = parseISO(event.start); 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 || ""; const calendarName = calendar?.name || "";
const durationMinutes = parseDuration(event.duration); const durationMinutes = parseDuration(event.duration);
const endTime = new Date(startDate.getTime() + durationMinutes * 60000); const endTime = new Date(startDate.getTime() + durationMinutes * 60000);
const timeString = `${format(startDate, "HH:mm")} ${format(endTime, "HH:mm")}`; const timeString = `${format(startDate, timeFmt)} ${format(endTime, timeFmt)}`;
const ariaLabel = `${event.title || t("events.no_title")}, ${timeString}${calendarName ? `, ${calendarName}` : ""}`; const ariaLabel = `${event.title || t("events.no_title")}, ${timeString}${calendarName ? `, ${calendarName}` : ""}`;
const handleDragStart = useCallback((e: DragEvent) => { const handleDragStart = useCallback((e: DragEvent) => {
@@ -153,6 +157,9 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
style={{ backgroundColor: `${color}24`, borderLeft: `3px solid ${color}`, color, ...style }} style={{ backgroundColor: `${color}24`, borderLeft: `3px solid ${color}`, color, ...style }}
> >
<div className="flex items-center gap-1 min-w-0"> <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> <span className="truncate font-medium">{event.title || t("events.no_title")}</span>
</div> </div>
</button> </button>
@@ -192,6 +192,10 @@ export function EventDetailPopover({
useEffect(() => { useEffect(() => {
const handleKey = (e: KeyboardEvent) => { const handleKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose(); if (e.key === "Escape") onClose();
const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select") return;
if (target?.getAttribute("contenteditable") === "true") return;
if (e.key === "e" && !noteExpanded) { if (e.key === "e" && !noteExpanded) {
e.preventDefault(); e.preventDefault();
onEdit(); onEdit();
+56 -19
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 { format, parseISO, addHours, addDays } from "date-fns";
import type { CalendarEvent, Calendar, CalendarParticipant } from "@/lib/jmap/types"; import type { CalendarEvent, Calendar, CalendarParticipant } from "@/lib/jmap/types";
import { parseDuration, getEventColor } from "./event-card"; 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 { ParticipantInput } from "./participant-input";
import { import {
isOrganizer, isOrganizer,
@@ -18,17 +18,27 @@ import {
getStatusCounts, getStatusCounts,
buildParticipantMap, buildParticipantMap,
} from "@/lib/calendar-participants"; } 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 { interface EventModalProps {
event?: CalendarEvent | null; event?: CalendarEvent | null;
calendars: Calendar[]; calendars: Calendar[];
defaultDate?: Date; defaultDate?: Date;
defaultEndDate?: 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; onDelete?: (id: string, sendSchedulingMessages?: boolean) => void;
onDuplicate?: (data: Partial<CalendarEvent>) => void; onDuplicate?: (data: Partial<CalendarEvent>) => void;
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void; onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
onClose: () => void; onClose: () => void;
onPreviewChange?: (preview: PendingEventPreview | null) => void;
currentUserEmails?: string[]; currentUserEmails?: string[];
isMobile?: boolean; isMobile?: boolean;
} }
@@ -49,10 +59,12 @@ function buildDuration(startDate: Date, endDate: Date): string {
const minutes = totalMinutes % 60; const minutes = totalMinutes % 60;
let dur = "P"; let dur = "P";
if (days > 0) dur += `${days}D`; if (days > 0) dur += `${days}D`;
dur += "T"; if (hours > 0 || minutes > 0) {
if (hours > 0) dur += `${hours}H`; dur += "T";
if (minutes > 0) dur += `${minutes}M`; if (hours > 0) dur += `${hours}H`;
if (dur === "PT") dur = "PT0M"; if (minutes > 0) dur += `${minutes}M`;
}
if (dur === "P") dur = "PT0M";
return dur; return dur;
} }
@@ -73,9 +85,9 @@ function getAlertLabel(event: CalendarEvent, t: ReturnType<typeof useTranslation
if (!first || first.trigger["@type"] !== "OffsetTrigger") return null; if (!first || first.trigger["@type"] !== "OffsetTrigger") return null;
const offset = first.trigger.offset; const offset = first.trigger.offset;
if (offset === "PT0S") return t("alerts.at_time"); if (offset === "PT0S") return t("alerts.at_time");
const minMatch = offset.match(/-?PT?(\d+)M$/); const minMatch = offset.match(/-?PT(\d+)M$/);
if (minMatch) return t("alerts.minutes_before", { count: parseInt(minMatch[1]) }); if (minMatch) return t("alerts.minutes_before", { count: parseInt(minMatch[1]) });
const hourMatch = offset.match(/-?PT?(\d+)H$/); const hourMatch = offset.match(/-?PT(\d+)H$/);
if (hourMatch) return t("alerts.hours_before", { count: parseInt(hourMatch[1]) }); if (hourMatch) return t("alerts.hours_before", { count: parseInt(hourMatch[1]) });
const dayMatch = offset.match(/-?P(\d+)D/); const dayMatch = offset.match(/-?P(\d+)D/);
if (dayMatch) return t("alerts.days_before", { count: parseInt(dayMatch[1]) }); if (dayMatch) return t("alerts.days_before", { count: parseInt(dayMatch[1]) });
@@ -104,10 +116,13 @@ export function EventModal({
onDuplicate, onDuplicate,
onRsvp, onRsvp,
onClose, onClose,
onPreviewChange,
currentUserEmails = [], currentUserEmails = [],
isMobile = false, isMobile = false,
}: EventModalProps) { }: EventModalProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const timeFormat = useSettingsStore((s) => s.timeFormat);
const timeDisplayFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
const isEdit = !!event; const isEdit = !!event;
const [mode, setMode] = useState<"view" | "edit">(isEdit ? "view" : "edit"); const [mode, setMode] = useState<"view" | "edit">(isEdit ? "view" : "edit");
@@ -181,7 +196,7 @@ export function EventModal({
const [endTime, setEndTime] = useState(formatTimeInput(getInitialEnd())); const [endTime, setEndTime] = useState(formatTimeInput(getInitialEnd()));
const [allDay, setAllDay] = useState(event?.showWithoutTime || false); const [allDay, setAllDay] = useState(event?.showWithoutTime || false);
const [calendarId, setCalendarId] = useState<string>(() => { 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); const defaultCal = calendars.find(c => c.isDefault);
return defaultCal?.id || calendars[0]?.id || ""; return defaultCal?.id || calendars[0]?.id || "";
}); });
@@ -196,9 +211,9 @@ export function EventModal({
if (first.trigger["@type"] === "OffsetTrigger") { if (first.trigger["@type"] === "OffsetTrigger") {
const offset = first.trigger.offset; const offset = first.trigger.offset;
if (offset === "PT0S") return "at_time"; if (offset === "PT0S") return "at_time";
const minMatch = offset.match(/-?PT?(\d+)M$/); const minMatch = offset.match(/-?PT(\d+)M$/);
if (minMatch) return minMatch[1] as AlertOption; if (minMatch) return minMatch[1] as AlertOption;
const hourMatch = offset.match(/-?PT?(\d+)H$/); const hourMatch = offset.match(/-?PT(\d+)H$/);
if (hourMatch) return String(parseInt(hourMatch[1]) * 60) as AlertOption; if (hourMatch) return String(parseInt(hourMatch[1]) * 60) as AlertOption;
const dayMatch = offset.match(/-?P(\d+)D/); const dayMatch = offset.match(/-?P(\d+)D/);
if (dayMatch) return String(parseInt(dayMatch[1]) * 1440) as AlertOption; if (dayMatch) return String(parseInt(dayMatch[1]) * 1440) as AlertOption;
@@ -206,6 +221,7 @@ export function EventModal({
return "none"; return "none";
}); });
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [attendees, setAttendees] = useState<{ name: string; email: string }[]>(() => { const [attendees, setAttendees] = useState<{ name: string; email: string }[]>(() => {
if (!event?.participants) return []; if (!event?.participants) return [];
@@ -215,6 +231,18 @@ export function EventModal({
}); });
const [sendInvitations, setSendInvitations] = useState(true); 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(() => { const statusCounts = useMemo(() => {
if (!event?.participants) return null; if (!event?.participants) return null;
return getStatusCounts(event); return getStatusCounts(event);
@@ -228,9 +256,9 @@ export function EventModal({
setAttendees(prev => prev.filter(a => a.email.toLowerCase() !== email.toLowerCase())); setAttendees(prev => prev.filter(a => a.email.toLowerCase() !== email.toLowerCase()));
}, []); }, []);
const handleSave = useCallback(() => { const handleSave = useCallback(async () => {
const trimmedTitle = title.trim(); const trimmedTitle = title.trim();
if (!trimmedTitle) return; if (!trimmedTitle || isSaving) return;
if (trimmedTitle.length > 500 || description.trim().length > 10000 || location.trim().length > 500) return; if (trimmedTitle.length > 500 || description.trim().length > 10000 || location.trim().length > 500) return;
const startStr = allDay const startStr = allDay
@@ -340,8 +368,13 @@ export function EventModal({
} }
const shouldSendScheduling = attendees.length > 0 && sendInvitations; const shouldSendScheduling = attendees.length > 0 && sendInvitations;
onSave(data, shouldSendScheduling); setIsSaving(true);
}, [title, description, location, startDate, startTime, endDate, endTime, allDay, calendarId, recurrence, alert, attendees, sendInvitations, currentUserEmails, existingParticipants, event, onSave]); 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']) => { const handleRsvp = useCallback((status: CalendarParticipant['participationStatus']) => {
if (!event || !userParticipantId || !onRsvp) return; if (!event || !userParticipantId || !onRsvp) return;
@@ -353,7 +386,11 @@ export function EventModal({
if (!event || !onDuplicate) return; if (!event || !onDuplicate) return;
const start = parseISO(event.start); const start = parseISO(event.start);
const newStart = addDays(start, 1); const newStart = addDays(start, 1);
const newUid = typeof crypto !== 'undefined' && crypto.randomUUID
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
const data: Partial<CalendarEvent> = { const data: Partial<CalendarEvent> = {
uid: newUid,
title: event.title, title: event.title,
description: event.description, description: event.description,
start: format(newStart, "yyyy-MM-dd'T'HH:mm:ss"), start: format(newStart, "yyyy-MM-dd'T'HH:mm:ss"),
@@ -452,7 +489,7 @@ export function EventModal({
<span className="font-medium">{format(startD, "EEE, MMM d, yyyy")}</span> <span className="font-medium">{format(startD, "EEE, MMM d, yyyy")}</span>
{!event.showWithoutTime && ( {!event.showWithoutTime && (
<span className="text-muted-foreground ml-2"> <span className="text-muted-foreground ml-2">
{format(startD, "HH:mm")} {format(endD, "HH:mm")} {format(startD, timeDisplayFmt)} {format(endD, timeDisplayFmt)}
</span> </span>
)} )}
</div> </div>
@@ -576,7 +613,7 @@ export function EventModal({
<span className="text-muted-foreground ml-1.5">{t("events.all_day")}</span> <span className="text-muted-foreground ml-1.5">{t("events.all_day")}</span>
) : ( ) : (
<div className="text-muted-foreground"> <div className="text-muted-foreground">
{format(startD, "HH:mm")} {format(endD, "HH:mm")} {format(startD, timeDisplayFmt)} {format(endD, timeDisplayFmt)}
<span className="ml-1.5 text-xs">({formatDurationDisplay(durMin)})</span> <span className="ml-1.5 text-xs">({formatDurationDisplay(durMin)})</span>
</div> </div>
)} )}
@@ -698,7 +735,7 @@ export function EventModal({
} }
return ( return (
<div ref={modalRef} role="dialog" aria-modal={isMobile || undefined} aria-label={isEdit ? t("events.edit") : t("events.create")} className={isMobile ? "fixed inset-0 z-50 flex flex-col bg-background" : "flex flex-col h-full bg-background"}> <div ref={modalRef} role="dialog" aria-modal={isMobile || undefined} aria-label={isEdit ? t("events.edit") : t("events.create")} data-tour="event-modal" className={isMobile ? "fixed inset-0 z-50 flex flex-col bg-background" : "flex flex-col h-full bg-background"}>
<div className="flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0"> <div className="flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0">
<h2 className="text-lg font-semibold"> <h2 className="text-lg font-semibold">
{isEdit ? t("events.edit") : t("events.create")} {isEdit ? t("events.edit") : t("events.create")}
@@ -942,7 +979,7 @@ export function EventModal({
<Button variant="outline" onClick={isEdit ? () => setMode("view") : onClose}> <Button variant="outline" onClick={isEdit ? () => setMode("view") : onClose}>
{t("form.cancel")} {t("form.cancel")}
</Button> </Button>
<Button onClick={handleSave} disabled={!title.trim()}> <Button onClick={handleSave} disabled={!title.trim() || isSaving}>
{t("form.save")} {t("form.save")}
</Button> </Button>
</div> </div>
+6 -3
View File
@@ -6,13 +6,14 @@ import { Button } from "@/components/ui/button";
import { X, Upload, Check, Loader2, RefreshCw, Globe } from "lucide-react"; import { X, Upload, Check, Loader2, RefreshCw, Globe } from "lucide-react";
import { format, parseISO } from "date-fns"; import { format, parseISO } from "date-fns";
import type { CalendarEvent, Calendar } from "@/lib/jmap/types"; import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
import type { JMAPClient } from "@/lib/jmap/client"; import type { IJMAPClient } from '@/lib/jmap/client-interface';
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { useSettingsStore } from "@/stores/settings-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
interface ICalImportModalProps { interface ICalImportModalProps {
calendars: Calendar[]; calendars: Calendar[];
client: JMAPClient; client: IJMAPClient;
onClose: () => void; onClose: () => void;
} }
@@ -28,6 +29,7 @@ export function ICalImportModal({ calendars, client, onClose }: ICalImportModalP
const tCommon = useTranslations("common"); const tCommon = useTranslations("common");
const tForm = useTranslations("calendar.form"); const tForm = useTranslations("calendar.form");
const importEvents = useCalendarStore((s) => s.importEvents); const importEvents = useCalendarStore((s) => s.importEvents);
const timeFormat = useSettingsStore((s) => s.timeFormat);
const [step, setStep] = useState<ImportStep>("select"); const [step, setStep] = useState<ImportStep>("select");
const [parsedEvents, setParsedEvents] = useState<Partial<CalendarEvent>[]>([]); const [parsedEvents, setParsedEvents] = useState<Partial<CalendarEvent>[]>([]);
@@ -194,9 +196,10 @@ export function ICalImportModal({ calendars, client, onClose }: ICalImportModalP
if (!event.start) return ""; if (!event.start) return "";
try { try {
const date = parseISO(event.start); const date = parseISO(event.start);
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
return event.showWithoutTime return event.showWithoutTime
? format(date, "MMM d, yyyy") ? format(date, "MMM d, yyyy")
: format(date, "MMM d, yyyy HH:mm"); : format(date, `MMM d, yyyy ${timeFmt}`);
} catch { } catch {
return event.start; return event.start;
} }
@@ -4,13 +4,13 @@ import { useState, useRef, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { X, Loader2, Globe } from "lucide-react"; import { X, Loader2, Globe } from "lucide-react";
import type { JMAPClient } from "@/lib/jmap/client"; import type { IJMAPClient } from '@/lib/jmap/client-interface';
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings"; import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
interface ICalSubscriptionModalProps { interface ICalSubscriptionModalProps {
client: JMAPClient; client: IJMAPClient;
onClose: () => void; onClose: () => void;
} }
+46 -19
View File
@@ -1,12 +1,12 @@
"use client"; "use client";
import { useState, useMemo } from "react"; import { useState, useMemo, Fragment } from "react";
import { useTranslations, useFormatter } from "next-intl"; import { useTranslations, useFormatter } from "next-intl";
import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react"; import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react";
import { import {
startOfMonth, endOfMonth, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfWeek, endOfWeek,
addMonths, subMonths, addYears, subYears, setMonth, setYear, addMonths, subMonths, addYears, subYears, setMonth, setYear,
eachDayOfInterval, getMonth, getYear, eachDayOfInterval, getMonth, getYear, getISOWeek, getWeek,
isSameDay, isSameMonth, isToday, format, isSameDay, isSameMonth, isToday, format,
} from "date-fns"; } from "date-fns";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -26,6 +26,7 @@ interface MiniCalendarProps {
onChangeMonth: (date: Date) => void; onChangeMonth: (date: Date) => void;
events?: CalendarEvent[]; events?: CalendarEvent[];
firstDayOfWeek?: number; firstDayOfWeek?: number;
showWeekNumbers?: boolean;
} }
export function MiniCalendar({ export function MiniCalendar({
@@ -35,6 +36,7 @@ export function MiniCalendar({
onChangeMonth, onChangeMonth,
events = [], events = [],
firstDayOfWeek = 1, firstDayOfWeek = 1,
showWeekNumbers = false,
}: MiniCalendarProps) { }: MiniCalendarProps) {
const t = useTranslations("calendar"); const t = useTranslations("calendar");
const intlFormatter = useFormatter(); const intlFormatter = useFormatter();
@@ -61,6 +63,17 @@ export function MiniCalendar({
? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const ? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const
: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const; : ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
// Compute week numbers for each row (one per 7-day chunk)
const weekNumbers = useMemo(() => {
if (!showWeekNumbers) return [];
const nums: number[] = [];
for (let i = 0; i < days.length; i += 7) {
// Use the first day of each row to determine the week number
nums.push(weekStart === 1 ? getISOWeek(days[i]) : getWeek(days[i], { weekStartsOn: 0 }));
}
return nums;
}, [days, showWeekNumbers, weekStart]);
const currentYear = getYear(displayMonth); const currentYear = getYear(displayMonth);
const currentMonth = getMonth(displayMonth); const currentMonth = getMonth(displayMonth);
const decadeStart = Math.floor(currentYear / 10) * 10; const decadeStart = Math.floor(currentYear / 10) * 10;
@@ -135,35 +148,49 @@ export function MiniCalendar({
</div> </div>
{pickerView === "days" && ( {pickerView === "days" && (
<div className="grid grid-cols-7 gap-0"> <div className={cn("grid gap-0", showWeekNumbers ? "grid-cols-[auto_repeat(7,1fr)]" : "grid-cols-7")}>
{showWeekNumbers && (
<div className="text-center text-[10px] font-medium text-muted-foreground py-1 w-5" />
)}
{dayHeaders.map((d) => ( {dayHeaders.map((d) => (
<div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1"> <div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1">
{t(`days.${d}`)} {t(`days.${d}`)}
</div> </div>
))} ))}
{days.map((day) => { {days.map((day, index) => {
const inMonth = isSameMonth(day, displayMonth); const inMonth = isSameMonth(day, displayMonth);
const selected = isSameDay(day, selectedDate); const selected = isSameDay(day, selectedDate);
const today = isToday(day); const today = isToday(day);
const hasEvent = eventDates.has(format(day, "yyyy-MM-dd")); const hasEvent = eventDates.has(format(day, "yyyy-MM-dd"));
const isFirstDayOfRow = index % 7 === 0;
return ( return (
<button <Fragment key={day.toISOString()}>
key={day.toISOString()} {showWeekNumbers && isFirstDayOfRow && (
onClick={() => onSelectDate(day)} <div
className={cn( key={`wk-${index}`}
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors", className="flex items-center justify-center w-5 text-[9px] text-muted-foreground/60 font-medium"
!inMonth && "text-muted-foreground/40", >
inMonth && !selected && "hover:bg-muted", {weekNumbers[index / 7]}
today && !selected && "font-bold text-primary", </div>
selected && "bg-primary text-primary-foreground"
)} )}
> <button
{format(day, "d")} key={`day-${day.toISOString()}`}
{hasEvent && !selected && ( onClick={() => onSelectDate(day)}
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" /> className={cn(
)} "relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
</button> !inMonth && "text-muted-foreground/40",
inMonth && !selected && "hover:bg-muted",
today && !selected && "font-bold text-primary",
selected && "bg-primary text-primary-foreground"
)}
>
{format(day, "d")}
{hasEvent && !selected && (
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" />
)}
</button>
</Fragment>
); );
})} })}
</div> </div>
+248
View File
@@ -0,0 +1,248 @@
"use client";
import { useMemo, useCallback, useState } from "react";
import { useTranslations } from "next-intl";
import { format, parseISO, isPast, isToday, isTomorrow } from "date-fns";
import { Check, Circle, Flag, CalendarDays, ListTodo, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import type { CalendarTask, Calendar } from "@/lib/jmap/types";
import type { TaskViewFilter } from "@/stores/task-store";
import { useSettingsStore } from "@/stores/settings-store";
interface TaskListViewProps {
tasks: CalendarTask[];
calendars: Calendar[];
selectedCalendarIds: string[];
filter: TaskViewFilter;
showCompleted: boolean;
onSelectTask: (task: CalendarTask) => void;
onToggleComplete: (task: CalendarTask) => void;
selectedTaskId?: string | null;
onQuickCreate?: (title: string) => void;
}
function getTaskPriorityIcon(priority: number) {
if (priority >= 1 && priority <= 4) return <Flag className="h-3.5 w-3.5 text-red-500" />;
if (priority === 5) return <Flag className="h-3.5 w-3.5 text-orange-500" />;
if (priority >= 6 && priority <= 9) return <Flag className="h-3.5 w-3.5 text-gray-400" />;
return null;
}
function getDueDateLabel(due: string, showWithoutTime: boolean, t: ReturnType<typeof useTranslations>, timeFormat: string): { label: string; className: string } {
const dueDate = parseISO(due);
const overdue = isPast(dueDate) && !isToday(dueDate);
if (isToday(dueDate)) {
return {
label: t("tasks.due_today"),
className: "text-blue-600 dark:text-blue-400",
};
}
if (isTomorrow(dueDate)) {
return {
label: t("tasks.due_tomorrow"),
className: "text-muted-foreground",
};
}
if (overdue) {
return {
label: t("tasks.overdue"),
className: "text-red-600 dark:text-red-400",
};
}
const formatted = showWithoutTime
? format(dueDate, "MMM d")
: format(dueDate, timeFormat === "12h" ? "MMM d, h:mm a" : "MMM d, HH:mm");
return {
label: formatted,
className: "text-muted-foreground",
};
}
export function TaskListView({
tasks,
calendars,
selectedCalendarIds,
filter,
showCompleted,
onSelectTask,
onToggleComplete,
selectedTaskId,
onQuickCreate,
}: TaskListViewProps) {
const t = useTranslations("calendar");
const timeFormat = useSettingsStore((s) => s.timeFormat);
const [quickAddTitle, setQuickAddTitle] = useState("");
const filteredTasks = useMemo(() => {
let result = tasks.filter(task => {
const calIds = Object.keys(task.calendarIds);
return calIds.some(id => selectedCalendarIds.includes(id));
});
if (!showCompleted) {
result = result.filter(task => task.progress !== "completed" && task.progress !== "cancelled");
}
switch (filter) {
case "pending":
result = result.filter(task => task.progress === "needs-action" || task.progress === "in-process");
break;
case "completed":
result = result.filter(task => task.progress === "completed");
break;
case "overdue":
result = result.filter(task => {
if (!task.due || task.progress === "completed" || task.progress === "cancelled") return false;
return isPast(parseISO(task.due)) && !isToday(parseISO(task.due));
});
break;
}
// Sort: overdue first, then by due date (no due date last), then by priority
result.sort((a, b) => {
// Completed tasks at the bottom
if (a.progress === "completed" && b.progress !== "completed") return 1;
if (a.progress !== "completed" && b.progress === "completed") return -1;
// Tasks with due dates before those without
if (a.due && !b.due) return -1;
if (!a.due && b.due) return 1;
if (a.due && b.due) {
const dateCompare = new Date(a.due).getTime() - new Date(b.due).getTime();
if (dateCompare !== 0) return dateCompare;
}
// Higher priority first (lower number = higher priority, but 0 = no priority goes last)
const aPri = a.priority || 10;
const bPri = b.priority || 10;
return aPri - bPri;
});
return result;
}, [tasks, selectedCalendarIds, filter, showCompleted]);
const handleToggle = useCallback((e: React.MouseEvent, task: CalendarTask) => {
e.stopPropagation();
onToggleComplete(task);
}, [onToggleComplete]);
if (filteredTasks.length === 0) {
return (
<div className="flex flex-col flex-1">
{onQuickCreate && (
<div className="px-4 py-2 border-b border-border">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<input
type="text"
value={quickAddTitle}
onChange={(e) => setQuickAddTitle(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && quickAddTitle.trim()) {
onQuickCreate(quickAddTitle.trim());
setQuickAddTitle("");
}
}}
placeholder={t("tasks.quick_add_placeholder")}
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
)}
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground py-12">
<ListTodo className="h-12 w-12 mb-3 opacity-30" />
<p className="text-sm">{t("tasks.no_tasks")}</p>
</div>
</div>
);
}
return (
<div className="flex-1 overflow-y-auto">
{onQuickCreate && (
<div className="px-4 py-2 border-b border-border">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<input
type="text"
value={quickAddTitle}
onChange={(e) => setQuickAddTitle(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && quickAddTitle.trim()) {
onQuickCreate(quickAddTitle.trim());
setQuickAddTitle("");
}
}}
placeholder={t("tasks.quick_add_placeholder")}
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
)}
<div className="divide-y divide-border">
{filteredTasks.map(task => {
const cal = calendars.find(c => task.calendarIds[c.id]);
const isCompleted = task.progress === "completed";
const priorityIcon = getTaskPriorityIcon(task.priority);
const dueDateInfo = task.due ? getDueDateLabel(task.due, task.showWithoutTime, t, timeFormat) : null;
return (
<div
key={task.id}
onClick={() => onSelectTask(task)}
className={cn(
"flex items-start gap-3 px-4 py-3 cursor-pointer hover:bg-muted/50 transition-colors",
selectedTaskId === task.id && "bg-muted",
)}
>
{/* Checkbox */}
<button
onClick={(e) => handleToggle(e, task)}
className={cn(
"mt-0.5 flex-shrink-0 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors",
isCompleted
? "bg-green-500 border-green-500 text-white"
: "border-muted-foreground/40 hover:border-primary"
)}
aria-label={isCompleted ? t("tasks.mark_incomplete") : t("tasks.mark_complete")}
>
{isCompleted && <Check className="h-3 w-3" />}
</button>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className={cn(
"text-sm font-medium truncate",
isCompleted && "line-through text-muted-foreground"
)}>
{task.title || t("tasks.no_title")}
</span>
{priorityIcon}
</div>
<div className="flex items-center gap-2 mt-0.5">
{dueDateInfo && (
<span className={cn("text-xs flex items-center gap-1", dueDateInfo.className)}>
<CalendarDays className="h-3 w-3" />
{dueDateInfo.label}
</span>
)}
{cal && (
<span className="text-xs text-muted-foreground flex items-center gap-1">
<span className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: cal.color || "#3b82f6" }} />
{cal.name}
</span>
)}
</div>
</div>
</div>
);
})}
</div>
</div>
);
}
+321
View File
@@ -0,0 +1,321 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X, Trash2, CalendarDays, Bell, Flag } from "lucide-react";
import { format, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import type { CalendarTask, Calendar, CalendarEventAlert } from "@/lib/jmap/types";
interface TaskModalProps {
task?: CalendarTask | null;
calendars: Calendar[];
onSave: (data: Partial<CalendarTask>) => void | Promise<void>;
onDelete?: (id: string) => void;
onClose: () => void;
isMobile?: boolean;
}
type PriorityLevel = "none" | "high" | "medium" | "low";
type AlertOption = "none" | "at_time" | "5" | "15" | "30" | "60" | "1440";
function priorityToLevel(p: number): PriorityLevel {
if (p >= 1 && p <= 4) return "high";
if (p === 5) return "medium";
if (p >= 6 && p <= 9) return "low";
return "none";
}
function levelToPriority(l: PriorityLevel): number {
switch (l) {
case "high": return 1;
case "medium": return 5;
case "low": return 9;
default: return 0;
}
}
export function TaskModal({
task,
calendars,
onSave,
onDelete,
onClose,
isMobile,
}: TaskModalProps) {
const t = useTranslations("calendar");
const isEdit = !!task;
const titleRef = useRef<HTMLInputElement>(null);
const writableCalendars = calendars.filter(c => !c.isShared || c.myRights?.mayWriteAll || c.myRights?.mayWriteOwn);
const defaultCalendarId = writableCalendars[0]?.id ?? calendars[0]?.id ?? "";
const [title, setTitle] = useState(task?.title ?? "");
const [description, setDescription] = useState(task?.description ?? "");
const [dueDate, setDueDate] = useState(task?.due ? format(parseISO(task.due), "yyyy-MM-dd") : "");
const [dueTime, setDueTime] = useState(task?.due && !task.showWithoutTime ? format(parseISO(task.due), "HH:mm") : "");
const [showTime, setShowTime] = useState(task?.due ? !task.showWithoutTime : false);
const [priority, setPriority] = useState<PriorityLevel>(priorityToLevel(task?.priority ?? 0));
const [progress, setProgress] = useState<CalendarTask["progress"]>(task?.progress ?? "needs-action");
const [calendarId, setCalendarId] = useState(() => {
if (task) {
const ids = Object.keys(task.calendarIds);
return ids[0] ?? defaultCalendarId;
}
return defaultCalendarId;
});
const [alertOption, setAlertOption] = useState<AlertOption>(() => {
if (!task?.alerts) return "none";
const first = Object.values(task.alerts)[0];
if (!first || first.trigger["@type"] !== "OffsetTrigger") return "none";
const offset = first.trigger.offset;
if (offset === "PT0S") return "at_time";
const m = offset.match(/-?PT?(\d+)M$/);
if (m) return m[1] as AlertOption;
const h = offset.match(/-?PT?(\d+)H$/);
if (h) return String(parseInt(h[1]) * 60) as AlertOption;
const d = offset.match(/-?P(\d+)D/);
if (d) return String(parseInt(d[1]) * 1440) as AlertOption;
return "none";
});
const [saving, setSaving] = useState(false);
useEffect(() => {
titleRef.current?.focus();
}, []);
const handleSave = useCallback(async () => {
if (!title.trim()) return;
setSaving(true);
try {
let due: string | null = null;
let showWithoutTime = true;
if (dueDate) {
if (showTime && dueTime) {
due = `${dueDate}T${dueTime}:00`;
showWithoutTime = false;
} else {
due = `${dueDate}T00:00:00`;
showWithoutTime = true;
}
}
let alerts: Record<string, CalendarEventAlert> | null = null;
if (alertOption !== "none") {
const offset = alertOption === "at_time" ? "PT0S" : `-PT${alertOption}M`;
alerts = {
"default-alert": {
"@type": "Alert",
trigger: { "@type": "OffsetTrigger", offset, relativeTo: "start" },
action: "display",
acknowledged: null,
relatedTo: null,
},
};
}
const data: Partial<CalendarTask> = {
"@type": "Task",
title: title.trim(),
description: description.trim() || "",
due,
showWithoutTime,
priority: levelToPriority(priority),
progress,
calendarIds: { [calendarId]: true },
alerts,
};
if (isEdit && task) {
data.id = task.id;
}
await onSave(data);
onClose();
} finally {
setSaving(false);
}
}, [title, description, dueDate, dueTime, showTime, priority, progress, calendarId, alertOption, isEdit, task, onSave, onClose]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
}
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
handleSave();
}
}, [onClose, handleSave]);
return (
<div className="flex flex-col h-full bg-background" onKeyDown={handleKeyDown}>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
<h2 className="text-sm font-semibold">
{isEdit ? t("tasks.edit") : t("tasks.create")}
</h2>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={onClose}>
<X className="h-4 w-4" />
</Button>
</div>
{/* Body */}
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{/* Title */}
<Input
ref={titleRef}
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t("tasks.title_placeholder")}
className="text-base font-medium"
/>
{/* Description */}
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder={t("tasks.description_placeholder")}
rows={3}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring resize-none"
/>
{/* Due Date */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<CalendarDays className="h-3.5 w-3.5" />
{t("tasks.due_date")}
</label>
<div className="flex items-center gap-2">
<input
type="date"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm"
/>
{dueDate && (
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={showTime}
onChange={(e) => setShowTime(e.target.checked)}
className="rounded"
/>
{t("tasks.include_time")}
</label>
)}
{showTime && (
<input
type="time"
value={dueTime}
onChange={(e) => setDueTime(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm"
/>
)}
</div>
</div>
{/* Priority */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<Flag className="h-3.5 w-3.5" />
{t("tasks.priority")}
</label>
<select
value={priority}
onChange={(e) => setPriority(e.target.value as PriorityLevel)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="none">{t("tasks.priority_none")}</option>
<option value="high">{t("tasks.priority_high")}</option>
<option value="medium">{t("tasks.priority_medium")}</option>
<option value="low">{t("tasks.priority_low")}</option>
</select>
</div>
{/* Progress */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
{t("tasks.progress")}
</label>
<select
value={progress}
onChange={(e) => setProgress(e.target.value as CalendarTask["progress"])}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="needs-action">{t("tasks.progress_needs_action")}</option>
<option value="in-process">{t("tasks.progress_in_process")}</option>
<option value="completed">{t("tasks.progress_completed")}</option>
<option value="cancelled">{t("tasks.progress_cancelled")}</option>
</select>
</div>
{/* Calendar */}
{writableCalendars.length > 1 && (
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
{t("tasks.calendar")}
</label>
<select
value={calendarId}
onChange={(e) => setCalendarId(e.target.value)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
{writableCalendars.map((cal) => (
<option key={cal.id} value={cal.id}>{cal.name}</option>
))}
</select>
</div>
)}
{/* Alert */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
<Bell className="h-3.5 w-3.5" />
{t("tasks.alert")}
</label>
<select
value={alertOption}
onChange={(e) => setAlertOption(e.target.value as AlertOption)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm w-full"
>
<option value="none">{t("tasks.alert_none")}</option>
<option value="at_time">{t("tasks.alert_at_time")}</option>
<option value="5">{t("tasks.alert_5min")}</option>
<option value="15">{t("tasks.alert_15min")}</option>
<option value="30">{t("tasks.alert_30min")}</option>
<option value="60">{t("tasks.alert_1hr")}</option>
<option value="1440">{t("tasks.alert_1day")}</option>
</select>
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between px-4 py-3 border-t border-border">
<div>
{isEdit && onDelete && task && (
<Button
variant="ghost"
size="sm"
className="text-destructive hover:text-destructive"
onClick={() => onDelete(task.id)}
>
<Trash2 className="h-4 w-4 mr-1" />
{t("tasks.delete")}
</Button>
)}
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={onClose}>
{t("tasks.cancel")}
</Button>
<Button size="sm" onClick={handleSave} disabled={!title.trim() || saving}>
{t("tasks.save")}
</Button>
</div>
</div>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
"use client";
import { useTranslations } from "next-intl";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { TaskViewFilter } from "@/stores/task-store";
interface TaskToolbarProps {
filter: TaskViewFilter;
showCompleted: boolean;
onFilterChange: (filter: TaskViewFilter) => void;
onShowCompletedChange: (show: boolean) => void;
onCreateTask: () => void;
}
const FILTERS: TaskViewFilter[] = ["all", "pending", "completed", "overdue"];
export function TaskToolbar({
filter,
showCompleted,
onFilterChange,
onShowCompletedChange,
onCreateTask,
}: TaskToolbarProps) {
const t = useTranslations("calendar");
return (
<div className="flex items-center gap-2 px-4 py-2 border-b border-border flex-wrap">
<div className="flex border border-border rounded-md overflow-hidden">
{FILTERS.map((f) => (
<button
key={f}
onClick={() => onFilterChange(f)}
className={cn(
"px-3 py-1.5 text-xs font-medium transition-colors",
f === filter
? "bg-primary text-primary-foreground"
: "hover:bg-muted text-muted-foreground"
)}
>
{t(`tasks.filter_${f}`)}
</button>
))}
</div>
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer select-none ml-2">
<input
type="checkbox"
checked={showCompleted}
onChange={(e) => onShowCompletedChange(e.target.checked)}
className="rounded border-border"
/>
{t("tasks.show_completed")}
</label>
<div className="flex-1" />
<Button size="sm" onClick={onCreateTask}>
<Plus className="w-4 h-4 mr-1" />
{t("tasks.create")}
</Button>
</div>
);
}
@@ -30,6 +30,7 @@ describe('ContactListItem', () => {
density: 'regular' as const, density: 'regular' as const,
onClick: vi.fn(), onClick: vi.fn(),
onCheckboxClick: vi.fn(), onCheckboxClick: vi.fn(),
selectedContactIds: new Set<string>(),
}; };
it('renders contact name and email', () => { it('renders contact name and email', () => {
+160 -26
View File
@@ -1,12 +1,16 @@
"use client"; "use client";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Copy, Send, Globe, Cake, Tag, KeyRound, Link, Users, Briefcase, Heart, Languages, MessageCircle, User, Calendar, UserCircle } from "lucide-react"; import { Mail, Phone, Building, MapPin, StickyNote, Pencil, Trash2, BookUser, Copy, Send, Globe, Cake, Tag, KeyRound, Link, Users, Briefcase, Heart, Languages, MessageCircle, User, Calendar, UserCircle, ShieldCheck, ShieldAlert, Download } from "lucide-react";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils"; 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 { getContactDisplayName, getContactPrimaryEmail } from "@/stores/contact-store";
import { useSmimeStore } from "@/stores/smime-store";
import { parseCertificatePemOrDer, extractCertificateInfo } from "@/lib/smime/certificate-utils";
import type { CertificateInfo } from "@/lib/smime/types";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
interface ContactDetailProps { interface ContactDetailProps {
@@ -22,12 +26,23 @@ function formatPhoneFeatures(features?: Record<string, boolean>): string {
return Object.keys(features).filter(k => features[k]).join(", "); 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 PartialDate objects: { year?, month?, day?, calendarScale? }
// Handle RFC 9553 Timestamp objects: { "@type": "Timestamp", utc: "..." }
if (typeof dateInput === 'object' && dateInput !== null) { if (typeof dateInput === 'object' && dateInput !== null) {
const year = dateInput.year as number | undefined; if (dateInput['@type'] === 'Timestamp' && typeof dateInput.utc === 'string') {
const month = dateInput.month as number | undefined; try {
const day = dateInput.day as number | undefined; 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 monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const parts: string[] = []; const parts: string[] = [];
if (month && monthNames[month - 1]) parts.push(monthNames[month - 1]); if (month && monthNames[month - 1]) parts.push(monthNames[month - 1]);
@@ -56,6 +71,50 @@ function formatDate(dateInput: string | Record<string, unknown>): string {
export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }: ContactDetailProps) { export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }: ContactDetailProps) {
const t = useTranslations("contacts"); const t = useTranslations("contacts");
const smimeStore = useSmimeStore();
const [parsedCerts, setParsedCerts] = useState<Map<number, CertificateInfo>>(new Map());
const cryptoKeys = contact?.cryptoKeys ? Object.values(contact.cryptoKeys) : [];
useEffect(() => {
if (!contact) return;
let cancelled = false;
const parseCerts = async () => {
const results = new Map<number, CertificateInfo>();
for (let i = 0; i < cryptoKeys.length; i++) {
const key = cryptoKeys[i];
if (typeof key.uri !== 'string') continue;
try {
let derBytes: ArrayBuffer | string | null = null;
if (key.uri.startsWith('data:')) {
// data URI — extract base64 content
const commaIdx = key.uri.indexOf(',');
if (commaIdx === -1) continue;
const b64 = key.uri.substring(commaIdx + 1);
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let j = 0; j < binary.length; j++) bytes[j] = binary.charCodeAt(j);
derBytes = bytes.buffer;
} else if (key.uri.startsWith('-----BEGIN')) {
// PEM-encoded certificate inline
derBytes = key.uri;
}
if (!derBytes) continue;
const cert = parseCertificatePemOrDer(derBytes);
const der = typeof derBytes === 'string' ? cert.toSchema(true).toBER(false) : derBytes;
const info = await extractCertificateInfo(cert, der);
if (!cancelled) results.set(i, info);
} catch { /* skip unparseable keys */ }
}
if (!cancelled) setParsedCerts(results);
};
if (cryptoKeys.length > 0) {
parseCerts();
} else {
setParsedCerts(new Map());
}
return () => { cancelled = true; };
}, [contact?.id]); // eslint-disable-line react-hooks/exhaustive-deps
if (!contact) { if (!contact) {
return ( return (
@@ -79,7 +138,31 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
const onlineServices = contact.onlineServices ? Object.values(contact.onlineServices) : []; const onlineServices = contact.onlineServices ? Object.values(contact.onlineServices) : [];
const anniversaries = contact.anniversaries ? Object.values(contact.anniversaries) : []; const anniversaries = contact.anniversaries ? Object.values(contact.anniversaries) : [];
const keywords = contact.keywords ? Object.keys(contact.keywords).filter(k => contact.keywords![k]) : []; const keywords = contact.keywords ? Object.keys(contact.keywords).filter(k => contact.keywords![k]) : [];
const cryptoKeys = contact.cryptoKeys ? Object.values(contact.cryptoKeys) : [];
const handleImportContactCert = async (keyIndex: number) => {
const key = cryptoKeys[keyIndex];
if (!key?.uri || typeof key.uri !== 'string') return;
try {
let derBytes: ArrayBuffer | string;
if (key.uri.startsWith('data:')) {
const commaIdx = key.uri.indexOf(',');
if (commaIdx === -1) return;
const b64 = key.uri.substring(commaIdx + 1);
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let j = 0; j < binary.length; j++) bytes[j] = binary.charCodeAt(j);
derBytes = bytes.buffer;
} else if (key.uri.startsWith('-----BEGIN')) {
derBytes = key.uri;
} else {
return;
}
await smimeStore.importPublicCert(derBytes, 'contact', contact.id);
toast.success(t("detail.cert_imported"));
} catch (err) {
toast.error(err instanceof Error ? err.message : t("detail.cert_import_failed"));
}
};
const relatedTo = contact.relatedTo ? Object.entries(contact.relatedTo) : []; const relatedTo = contact.relatedTo ? Object.entries(contact.relatedTo) : [];
const preferredLanguages = contact.preferredLanguages ? Object.values(contact.preferredLanguages) : []; const preferredLanguages = contact.preferredLanguages ? Object.values(contact.preferredLanguages) : [];
const personalInfo = contact.personalInfo ? Object.values(contact.personalInfo) : []; const personalInfo = contact.personalInfo ? Object.values(contact.personalInfo) : [];
@@ -210,9 +293,11 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
{addresses.map((a, i) => ( {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 key={i} className="text-sm space-y-0.5 rounded-md border border-border/60 bg-muted/30 p-3">
<div> <div>
{a.fullAddress {a.full || a.fullAddress
? a.fullAddress ? (a.full || a.fullAddress)
: [a.street, a.locality, a.region, a.postcode, a.country].filter(Boolean).join(", ")} : 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} />} {a.contexts && <ContextBadge contexts={a.contexts} />}
</div> </div>
{a.timeZone && ( {a.timeZone && (
@@ -279,13 +364,16 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
</Section> </Section>
)} )}
{contact.gender && (contact.gender.sex || contact.gender.identity) && ( {contact.speakToAs && (contact.speakToAs.grammaticalGender || contact.speakToAs.pronouns) && (
<Section icon={UserCircle} title={t("detail.gender")} category="personal"> <Section icon={UserCircle} title={t("detail.gender")} category="personal">
<div className="text-sm"> <div className="text-sm">
{contact.gender.sex && <span>{t(`detail.gender_${contact.gender.sex.toUpperCase()}`, { defaultValue: contact.gender.sex })}</span>} {contact.speakToAs.grammaticalGender && <span>{t(`detail.gender_${contact.speakToAs.grammaticalGender}`, { defaultValue: contact.speakToAs.grammaticalGender })}</span>}
{contact.gender.identity && ( {contact.speakToAs.pronouns && (() => {
<span className="text-muted-foreground">{contact.gender.sex ? " — " : ""}{contact.gender.identity}</span> const firstPronoun = Object.values(contact.speakToAs!.pronouns!)[0]?.pronouns;
)} return firstPronoun ? (
<span className="text-muted-foreground">{contact.speakToAs!.grammaticalGender ? " — " : ""}{firstPronoun}</span>
) : null;
})()}
</div> </div>
</Section> </Section>
)} )}
@@ -331,17 +419,63 @@ export function ContactDetail({ contact, onEdit, onDelete, isMobile, className }
{cryptoKeys.length > 0 && ( {cryptoKeys.length > 0 && (
<Section icon={KeyRound} title={t("detail.crypto_keys")} category="digital"> <Section icon={KeyRound} title={t("detail.crypto_keys")} category="digital">
{cryptoKeys.map((key, i) => ( {cryptoKeys.map((key, i) => {
<div key={i} className="text-sm break-all"> const certInfo = parsedCerts.get(i);
{typeof key.uri === 'string' && key.uri.startsWith("http") ? ( const isExpired = certInfo ? new Date(certInfo.notAfter) < new Date() : false;
<a href={key.uri} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline"> const alreadyImported = certInfo?.emailAddresses?.[0]
{key.uri} ? !!smimeStore.getPublicCertForEmail(certInfo.emailAddresses[0])
</a> : false;
) : (
<span className="text-muted-foreground">{typeof key.uri === 'string' ? `${key.uri.substring(0, 80)}${key.uri.length > 80 ? "…" : ""}` : String(key.uri ?? '')}</span> return (
)} <div key={i} className="p-3 rounded-lg border border-border space-y-1">
</div> {certInfo ? (
))} <>
<div className="flex items-center gap-2">
{isExpired ? (
<ShieldAlert className="w-4 h-4 text-destructive flex-shrink-0" />
) : (
<ShieldCheck className="w-4 h-4 text-primary flex-shrink-0" />
)}
<span className="text-sm font-medium truncate">{certInfo.subject}</span>
</div>
<div className="text-xs text-muted-foreground space-y-0.5 pl-6">
<p>{t("detail.cert_issuer")}: {certInfo.issuer}</p>
<p>
{t("detail.cert_expires")}: {new Date(certInfo.notAfter).toLocaleDateString()}
{isExpired && <span className="text-destructive ml-1">({t("detail.cert_expired")})</span>}
</p>
<p>{t("detail.cert_fingerprint")}: {certInfo.fingerprint.substring(0, 20)}...</p>
{certInfo.algorithm && <p>{t("detail.cert_algorithm")}: {certInfo.algorithm}</p>}
</div>
{!alreadyImported && (
<Button
variant="ghost"
size="sm"
className="ml-4 mt-1"
onClick={() => handleImportContactCert(i)}
>
<Download className="w-3 h-3 mr-1" />
{t("detail.import_to_smime")}
</Button>
)}
{alreadyImported && (
<p className="text-xs text-green-600 pl-6 mt-1">{t("detail.cert_already_imported")}</p>
)}
</>
) : (
<div className="text-sm break-all">
{typeof key.uri === 'string' && key.uri.startsWith("http") ? (
<a href={key.uri} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
{key.uri}
</a>
) : (
<span className="text-muted-foreground">{typeof key.uri === 'string' ? `${key.uri.substring(0, 80)}${key.uri.length > 80 ? "…" : ""}` : String(key.uri ?? '')}</span>
)}
</div>
)}
</div>
);
})}
</Section> </Section>
)} )}
+276 -37
View File
@@ -1,12 +1,12 @@
"use client"; "use client";
import { useState } from "react"; import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle } from "lucide-react"; import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle, Book } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo } from "@/lib/jmap/types"; import type { ContactCard, ContactOnlineService, ContactAnniversary, ContactPersonalInfo, AddressBook, AnniversaryDate, PartialDate, ContactAddress } from "@/lib/jmap/types";
interface EmailEntry { interface EmailEntry {
address: string; address: string;
@@ -47,6 +47,8 @@ interface AddressEntry {
interface ContactFormProps { interface ContactFormProps {
contact?: ContactCard | null; contact?: ContactCard | null;
addressBooks?: AddressBook[];
allKeywords?: string[];
onSave: (data: Partial<ContactCard>) => Promise<void>; onSave: (data: Partial<ContactCard>) => Promise<void>;
onCancel: () => void; onCancel: () => void;
} }
@@ -122,12 +124,73 @@ function Select({ value, onChange, children, className }: {
); );
} }
export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) { export function ContactForm({ contact, addressBooks, allKeywords, onSave, onCancel }: ContactFormProps) {
const t = useTranslations("contacts.form"); const t = useTranslations("contacts.form");
const isEditing = !!contact; const isEditing = !!contact;
const findComponent = (kind: string) => contact?.name?.components?.find(c => c.kind === kind)?.value || ""; 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 [prefix, setPrefix] = useState(findComponent("prefix"));
const [givenName, setGivenName] = useState(findComponent("given")); const [givenName, setGivenName] = useState(findComponent("given"));
const [additionalName, setAdditionalName] = useState(findComponent("additional")); const [additionalName, setAdditionalName] = useState(findComponent("additional"));
@@ -183,14 +246,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
const [addresses, setAddresses] = useState<AddressEntry[]>(() => { const [addresses, setAddresses] = useState<AddressEntry[]>(() => {
if (contact?.addresses) { if (contact?.addresses) {
return Object.values(contact.addresses).map(a => ({ return Object.values(contact.addresses).map(a => addressToFlat(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 []; return [];
}); });
@@ -209,7 +265,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
const [anniversaries, setAnniversaries] = useState<AnniversaryEntry[]>(() => { const [anniversaries, setAnniversaries] = useState<AnniversaryEntry[]>(() => {
if (contact?.anniversaries) { if (contact?.anniversaries) {
return Object.values(contact.anniversaries).map(a => ({ return Object.values(contact.anniversaries).map(a => ({
date: a.date, date: anniversaryDateToString(a.date),
kind: a.kind, kind: a.kind,
})); }));
} }
@@ -235,12 +291,31 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
contact?.notes ? Object.values(contact.notes)[0]?.note || "" : "" contact?.notes ? Object.values(contact.notes)[0]?.note || "" : ""
); );
const [genderSex, setGenderSex] = useState(contact?.gender?.sex || ""); const [genderSex, setGenderSex] = useState(contact?.speakToAs?.grammaticalGender || "");
const [genderIdentity, setGenderIdentity] = useState(contact?.gender?.identity || ""); const [genderIdentity, setGenderIdentity] = useState(
contact?.speakToAs?.pronouns ? Object.values(contact.speakToAs.pronouns)[0]?.pronouns || "" : ""
);
const [calendarUri, setCalendarUri] = useState(contact?.calendarUri || ""); const [calendarUri, setCalendarUri] = useState(contact?.calendarUri || "");
const [schedulingUri, setSchedulingUri] = useState(contact?.schedulingUri || ""); const [schedulingUri, setSchedulingUri] = useState(contact?.schedulingUri || "");
const [freeBusyUri, setFreeBusyUri] = useState(contact?.freeBusyUri || ""); const [freeBusyUri, setFreeBusyUri] = useState(contact?.freeBusyUri || "");
// Address book selection
const currentBookId = useMemo(() => {
if (contact?.addressBookIds) {
const ids = Object.keys(contact.addressBookIds).filter(k => contact.addressBookIds[k]);
if (ids.length > 0) {
// For shared contacts, the addressBookIds uses the original (non-namespaced) id
// but we need the namespaced id to match addressBooks entries
if (contact.isShared && contact.accountId) {
return `${contact.accountId}:${ids[0]}`;
}
return ids[0];
}
}
return "";
}, [contact]);
const [selectedBookId, setSelectedBookId] = useState(currentBookId);
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [emailErrors, setEmailErrors] = useState<Record<number, string>>({}); const [emailErrors, setEmailErrors] = useState<Record<number, string>>({});
@@ -316,12 +391,13 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
const addressesMap: Record<string, ContactCard["addresses"] extends Record<string, infer V> ? V : never> = {}; 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) => { addresses.filter(a => a.street.trim() || a.locality.trim() || a.country.trim()).forEach((a, i) => {
const obj: Record<string, unknown> = {}; const components: Array<{ kind: string; value: string }> = [];
if (a.street.trim()) obj.street = a.street.trim(); if (a.street.trim()) components.push({ kind: "name", value: a.street.trim() });
if (a.locality.trim()) obj.locality = a.locality.trim(); if (a.locality.trim()) components.push({ kind: "locality", value: a.locality.trim() });
if (a.region.trim()) obj.region = a.region.trim(); if (a.region.trim()) components.push({ kind: "region", value: a.region.trim() });
if (a.postcode.trim()) obj.postcode = a.postcode.trim(); if (a.postcode.trim()) components.push({ kind: "postcode", value: a.postcode.trim() });
if (a.country.trim()) obj.country = a.country.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 }; if (a.context) obj.contexts = { [a.context]: true };
// @ts-expect-error - dynamic build // @ts-expect-error - dynamic build
addressesMap[`a${i}`] = obj; addressesMap[`a${i}`] = obj;
@@ -337,7 +413,7 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
const anniversariesMap: Record<string, ContactAnniversary> = {}; const anniversariesMap: Record<string, ContactAnniversary> = {};
anniversaries.filter(a => a.date.trim()).forEach((a, i) => { 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> = {}; const personalInfoMap: Record<string, ContactPersonalInfo> = {};
@@ -371,12 +447,16 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
notes: note.trim() notes: note.trim()
? { n0: { note: note.trim() } } ? { n0: { note: note.trim() } }
: undefined, : undefined,
gender: (genderSex.trim() || genderIdentity.trim()) speakToAs: (genderSex.trim() || genderIdentity.trim())
? { sex: genderSex.trim() || undefined, identity: genderIdentity.trim() || undefined } ? {
grammaticalGender: genderSex.trim() || undefined,
pronouns: genderIdentity.trim() ? { p0: { pronouns: genderIdentity.trim() } } : undefined,
}
: undefined, : undefined,
calendarUri: calendarUri.trim() || undefined, calendarUri: calendarUri.trim() || undefined,
schedulingUri: schedulingUri.trim() || undefined, schedulingUri: schedulingUri.trim() || undefined,
freeBusyUri: freeBusyUri.trim() || undefined, freeBusyUri: freeBusyUri.trim() || undefined,
...(selectedBookId ? { addressBookIds: { [selectedBookId]: true } } : {}),
}; };
setIsSaving(true); setIsSaving(true);
@@ -410,6 +490,26 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
{/* Address Book Selector */}
{addressBooks && addressBooks.length > 1 && (
<div className="md:col-span-2 xl:col-span-3">
<FormSection icon={Book} title={t("section_address_book") || "Directory"} category="contact">
<select
value={selectedBookId}
onChange={(e) => setSelectedBookId(e.target.value)}
className="w-full px-3 py-2 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
>
<option value="">{t("select_address_book") || "Select a directory..."}</option>
{addressBooks.map((book) => (
<option key={book.id} value={book.id}>
{book.accountName ? `${book.name} (${book.accountName})` : book.name}
</option>
))}
</select>
</FormSection>
</div>
)}
{/* Name & Identity — full width */} {/* Name & Identity — full width */}
<div className="md:col-span-2 xl:col-span-3"> <div className="md:col-span-2 xl:col-span-3">
<FormSection icon={User} title={t("section_identity")} category="contact"> <FormSection icon={User} title={t("section_identity")} category="contact">
@@ -720,14 +820,14 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
{/* Categories */} {/* Categories */}
<FormSection icon={Tag} title={t("categories")} collapsible defaultOpen category="digital"> <FormSection icon={Tag} title={t("categories")} collapsible defaultOpen category="digital">
<div> <CategoryComboBox
<Input keywordsStr={keywordsStr}
value={keywordsStr} onChange={setKeywordsStr}
onChange={(e) => setKeywordsStr(e.target.value)} allKeywords={allKeywords || []}
placeholder={t("categories_placeholder")} placeholder={t("categories_placeholder")}
/> hint={t("categories_hint")}
<p className="text-xs text-muted-foreground mt-1.5">{t("categories_hint")}</p> addLabel={t("category_add")}
</div> />
</FormSection> </FormSection>
{/* Gender */} {/* Gender */}
@@ -737,11 +837,11 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
<label className="text-xs text-muted-foreground mb-1 block">{t("gender_sex")}</label> <label className="text-xs text-muted-foreground mb-1 block">{t("gender_sex")}</label>
<Select value={genderSex} onChange={(e) => setGenderSex(e.target.value)} className="w-full"> <Select value={genderSex} onChange={(e) => setGenderSex(e.target.value)} className="w-full">
<option value=""></option> <option value=""></option>
<option value="M">{t("gender_male")}</option> <option value="masculine">{t("gender_male")}</option>
<option value="F">{t("gender_female")}</option> <option value="feminine">{t("gender_female")}</option>
<option value="O">{t("gender_other")}</option> <option value="other">{t("gender_other")}</option>
<option value="N">{t("gender_none")}</option> <option value="none">{t("gender_none")}</option>
<option value="U">{t("gender_unknown")}</option> <option value="unknown">{t("gender_unknown")}</option>
</Select> </Select>
</div> </div>
<div> <div>
@@ -796,3 +896,142 @@ export function ContactForm({ contact, onSave, onCancel }: ContactFormProps) {
</form> </form>
); );
} }
function CategoryComboBox({
keywordsStr,
onChange,
allKeywords,
placeholder,
hint,
addLabel,
}: {
keywordsStr: string;
onChange: (value: string) => void;
allKeywords: string[];
placeholder: string;
hint: string;
addLabel: string;
}) {
const [isOpen, setIsOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const wrapperRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Parse current keywords from comma-separated string
const currentKeywords = useMemo(() => {
return keywordsStr.split(",").map(k => k.trim()).filter(Boolean);
}, [keywordsStr]);
// Suggestions: existing keywords not already selected
const suggestions = useMemo(() => {
const lower = inputValue.toLowerCase();
return allKeywords.filter(kw =>
!currentKeywords.includes(kw) &&
(!lower || kw.toLowerCase().includes(lower))
);
}, [allKeywords, currentKeywords, inputValue]);
// Can add a new keyword if typed text is non-empty and not already in the list
const canAddNew = inputValue.trim() &&
!currentKeywords.includes(inputValue.trim()) &&
!allKeywords.some(kw => kw.toLowerCase() === inputValue.trim().toLowerCase());
const addKeyword = useCallback((keyword: string) => {
const trimmed = keyword.trim();
if (!trimmed || currentKeywords.includes(trimmed)) return;
const next = [...currentKeywords, trimmed].join(", ");
onChange(next);
setInputValue("");
}, [currentKeywords, onChange]);
const removeKeyword = useCallback((keyword: string) => {
const next = currentKeywords.filter(k => k !== keyword).join(", ");
onChange(next);
}, [currentKeywords, onChange]);
// Close dropdown on outside click
useEffect(() => {
if (!isOpen) return;
const handler = (e: MouseEvent) => {
if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [isOpen]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
if (inputValue.trim()) {
addKeyword(inputValue);
}
} else if (e.key === "Escape") {
setIsOpen(false);
}
};
return (
<div ref={wrapperRef} className="relative">
{/* Keyword badges */}
{currentKeywords.length > 0 && (
<div className="flex flex-wrap gap-1.5 mb-2">
{currentKeywords.map(kw => (
<span
key={kw}
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary border border-primary/20"
>
{kw}
<button
type="button"
onClick={() => removeKeyword(kw)}
className="hover:text-destructive transition-colors"
>
<X className="w-3 h-3" />
</button>
</span>
))}
</div>
)}
{/* Input with dropdown */}
<Input
ref={inputRef}
value={inputValue}
onChange={(e) => { setInputValue(e.target.value); setIsOpen(true); }}
onFocus={() => setIsOpen(true)}
onKeyDown={handleKeyDown}
placeholder={currentKeywords.length === 0 ? placeholder : ""}
/>
<p className="text-xs text-muted-foreground mt-1.5">{hint}</p>
{/* Dropdown */}
{isOpen && (suggestions.length > 0 || canAddNew) && (
<div className="absolute left-0 right-0 top-[calc(100%-1.5rem)] mt-1 rounded-md border border-border bg-popover text-popover-foreground shadow-md z-50 max-h-48 overflow-y-auto py-1">
{suggestions.map(kw => (
<button
key={kw}
type="button"
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
onClick={() => { addKeyword(kw); inputRef.current?.focus(); }}
>
<Tag className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
{kw}
</button>
))}
{canAddNew && (
<button
type="button"
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left text-primary"
onClick={() => { addKeyword(inputValue); inputRef.current?.focus(); }}
>
<Plus className="w-3.5 h-3.5 flex-shrink-0" />
{addLabel}: &quot;{inputValue.trim()}&quot;
</button>
)}
</div>
)}
</div>
);
}
+30 -1
View File
@@ -1,5 +1,6 @@
"use client"; "use client";
import { useCallback, type DragEvent } from "react";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { ContactCard } from "@/lib/jmap/types"; import type { ContactCard } from "@/lib/jmap/types";
@@ -13,19 +14,47 @@ interface ContactListItemProps {
isChecked: boolean; isChecked: boolean;
hasSelection: boolean; hasSelection: boolean;
density: Density; density: Density;
selectedContactIds: Set<string>;
onClick: (e: React.MouseEvent) => void; onClick: (e: React.MouseEvent) => void;
onCheckboxClick: (e: React.MouseEvent) => void; onCheckboxClick: (e: React.MouseEvent) => void;
} }
export function ContactListItem({ contact, isSelected, isChecked, hasSelection, density, onClick, onCheckboxClick }: ContactListItemProps) { export function ContactListItem({ contact, isSelected, isChecked, hasSelection, density, selectedContactIds, onClick, onCheckboxClick }: ContactListItemProps) {
const name = getContactDisplayName(contact); const name = getContactDisplayName(contact);
const email = getContactPrimaryEmail(contact); const email = getContactPrimaryEmail(contact);
const org = contact.organizations const org = contact.organizations
? Object.values(contact.organizations)[0]?.name ? Object.values(contact.organizations)[0]?.name
: undefined; : undefined;
const handleDragStart = useCallback((e: DragEvent<HTMLDivElement>) => {
// Drag all selected contacts if this one is selected, otherwise just this one
const ids = selectedContactIds.has(contact.id)
? Array.from(selectedContactIds)
: [contact.id];
e.dataTransfer.effectAllowed = "copyMove";
e.dataTransfer.setData("application/x-contact-ids", JSON.stringify(ids));
e.dataTransfer.setData("text/plain", name || email || contact.id);
// Custom drag preview
const preview = document.createElement("div");
preview.style.cssText = `
position: fixed; top: -9999px; left: 0;
padding: 8px 16px; background-color: var(--color-primary, #3b82f6);
color: var(--color-primary-foreground, #ffffff); border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15); font-size: 14px; font-weight: 500;
z-index: 9999; white-space: nowrap; pointer-events: none;
`;
preview.textContent = ids.length === 1 ? (name || "1 contact") : `${ids.length} contacts`;
document.body.appendChild(preview);
e.dataTransfer.setDragImage(preview, 0, 0);
requestAnimationFrame(() => preview.remove());
}, [contact.id, name, email, selectedContactIds]);
return ( return (
<div <div
draggable
onDragStart={handleDragStart}
onClick={onClick} onClick={onClick}
className={cn( className={cn(
"w-full flex items-center cursor-pointer select-none transition-all duration-200 border-b border-border", "w-full flex items-center cursor-pointer select-none transition-all duration-200 border-b border-border",
+1
View File
@@ -193,6 +193,7 @@ export function ContactList({
isChecked={selectedContactIds.has(contact.id)} isChecked={selectedContactIds.has(contact.id)}
hasSelection={hasSelection} hasSelection={hasSelection}
density={density} density={density}
selectedContactIds={selectedContactIds}
onClick={(e) => { onClick={(e) => {
if (e.ctrlKey || e.metaKey) { if (e.ctrlKey || e.metaKey) {
e.preventDefault(); e.preventDefault();
+466 -37
View File
@@ -1,35 +1,95 @@
"use client"; "use client";
import { useMemo } from "react"; import { useMemo, useState, useCallback, useEffect, useRef, type DragEvent } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { BookUser, Users, Plus, UserPlus } 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 { 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 { cn } from "@/lib/utils";
import type { ContactCard } from "@/lib/jmap/types"; import type { ContactCard, AddressBook } from "@/lib/jmap/types";
import { getContactDisplayName } from "@/stores/contact-store"; import { getContactDisplayName } from "@/stores/contact-store";
export type ContactCategory = "all" | { groupId: string }; export type ContactCategory = "all" | { groupId: string } | { addressBookId: string } | { keyword: string } | "uncategorized";
interface ContactsSidebarProps { interface ContactsSidebarProps {
groups: ContactCard[]; groups: ContactCard[];
individuals: ContactCard[]; individuals: ContactCard[];
addressBooks: AddressBook[];
activeCategory: ContactCategory; activeCategory: ContactCategory;
onSelectCategory: (category: ContactCategory) => void; onSelectCategory: (category: ContactCategory) => void;
onCreateGroup: () => void; onCreateGroup: () => void;
onCreateContact: () => void; onCreateContact: () => void;
onImport?: () => void;
onEditGroup?: (groupId: string) => void;
onDeleteGroup?: (groupId: string) => void;
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
onDropContactsToCategory?: (contactIds: string[], keyword: string) => void;
className?: string; 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({ export function ContactsSidebar({
groups, groups,
individuals, individuals,
addressBooks,
activeCategory, activeCategory,
onSelectCategory, onSelectCategory,
onCreateGroup, onCreateGroup,
onCreateContact, onCreateContact,
onImport,
onEditGroup,
onDeleteGroup,
onDropContacts,
onDropContactsToCategory,
className, className,
}: ContactsSidebarProps) { }: ContactsSidebarProps) {
const t = useTranslations("contacts"); 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(() => { const sortedGroups = useMemo(() => {
return [...groups].sort((a, b) => return [...groups].sort((a, b) =>
@@ -39,17 +99,131 @@ export function ContactsSidebar({
const isAllActive = activeCategory === "all"; const isAllActive = activeCategory === "all";
// Group address books: personal vs shared accounts
const personalBooks = useMemo(() =>
addressBooks.filter(b => !b.isShared),
[addressBooks]);
const sharedBookGroups = useMemo(() => {
const map = new Map<string, { accountId: string; accountName: string; books: AddressBook[] }>();
for (const book of addressBooks) {
if (!book.isShared || !book.accountId) continue;
const existing = map.get(book.accountId);
if (existing) {
existing.books.push(book);
} else {
map.set(book.accountId, {
accountId: book.accountId,
accountName: book.accountName || book.accountId,
books: [book],
});
}
}
return Array.from(map.values());
}, [addressBooks]);
// Count contacts per address book
const contactCountByBook = useMemo(() => {
const counts: Record<string, number> = {};
for (const contact of individuals) {
if (!contact.addressBookIds) continue;
for (const bookId of Object.keys(contact.addressBookIds)) {
if (!contact.addressBookIds[bookId]) continue;
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]);
// Count of contacts without any keywords
const uncategorizedCount = useMemo(() => {
return individuals.filter(c => !c.keywords || Object.keys(c.keywords).filter(k => c.keywords![k]).length === 0).length;
}, [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 ( return (
<div className={cn("flex flex-col h-full bg-secondary", className)}> <div className={cn("flex flex-col h-full bg-secondary", className)}>
{/* Header */} {/* Header */}
<div className="px-3 border-b border-border flex items-center justify-between" style={{ paddingBlock: 'var(--density-header-py)' }}> <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> <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"> <div className="relative flex-shrink-0">
<UserPlus className="w-4 h-4" /> <Button
</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> </div>
{/* Categories */} {/* Navigation */}
<div className="flex-1 overflow-y-auto py-1"> <div className="flex-1 overflow-y-auto py-1">
{/* All contacts */} {/* All contacts */}
<button <button
@@ -69,30 +243,63 @@ export function ContactsSidebar({
</span> </span>
</button> </button>
{/* Groups section */} {/* My Address Books */}
{(sortedGroups.length > 0) && ( {personalBooks.length > 0 && (
<div className="mt-2"> <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>
</button>
{!collapsed.addressBooks && personalBooks.map((book) => (
<AddressBookItem
key={book.id}
book={book}
isActive={typeof activeCategory === "object" && "addressBookId" in activeCategory && activeCategory.addressBookId === book.id}
contactCount={contactCountByBook[book.id] || 0}
onSelect={() => onSelectCategory({ addressBookId: book.id })}
onDropContacts={onDropContacts}
/>
))}
</div>
)}
{/* Groups section */}
{sortedGroups.length > 0 && (
<div className="mt-2">
<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"> <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("tabs.groups")} {t("tabs.groups")}
</span> </span>
<Button size="icon" variant="ghost" onClick={onCreateGroup} className="h-5 w-5"> </button>
<Plus className="w-3 h-3" />
</Button>
</div>
{sortedGroups.map((group) => { {!collapsed.groups && sortedGroups.map((group) => {
const isActive = typeof activeCategory === "object" && activeCategory.groupId === group.id; const isActive = typeof activeCategory === "object" && "groupId" in activeCategory && activeCategory.groupId === group.id;
const memberCount = group.members const memberCount = memberCountByGroup[group.id] || 0;
? Object.values(group.members).filter(Boolean).length
: 0;
return ( return (
<button <button
key={group.id} key={group.id}
onClick={() => onSelectCategory({ groupId: group.id })} onClick={() => onSelectCategory({ groupId: group.id })}
onContextMenu={(e) => openGroupContextMenu(e, group)}
className={cn( 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 isActive
? "bg-accent text-accent-foreground font-medium" ? "bg-accent text-accent-foreground font-medium"
: "text-foreground/80 hover:bg-muted" : "text-foreground/80 hover:bg-muted"
@@ -110,25 +317,247 @@ export function ContactsSidebar({
</div> </div>
)} )}
{sortedGroups.length === 0 && ( {/* Categories section (from contact keywords) */}
<div className="mt-2 px-3"> <div className="mt-2">
<div className="flex items-center justify-between py-1"> <button
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider"> onClick={() => toggleSection("categories")}
{t("tabs.groups")} className="flex items-center gap-1 px-3 py-1 w-full text-left group"
</span> >
</div> {collapsed.categories ? (
<Button <ChevronRight className="w-3 h-3 text-muted-foreground" />
size="sm" ) : (
variant="ghost" <ChevronDown className="w-3 h-3 text-muted-foreground" />
onClick={onCreateGroup} )}
className="w-full justify-start text-xs text-muted-foreground h-7" <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{t("detail.categories")}
</span>
</button>
{!collapsed.categories && (
<>
{/* No Category item */}
<button
onClick={() => onSelectCategory("uncategorized")}
className={cn(
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
activeCategory === "uncategorized"
? "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 opacity-50" />
<span className="truncate italic">{t("no_category")}</span>
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
{uncategorizedCount}
</span>
</button>
{allKeywords.map(([keyword, count]) => {
const isActive = typeof activeCategory === "object" && "keyword" in activeCategory && activeCategory.keyword === keyword;
return (
<CategoryItem
key={keyword}
keyword={keyword}
count={count}
isActive={isActive}
onSelect={() => onSelectCategory({ keyword })}
onDropContacts={onDropContactsToCategory}
/>
);
})}
</>
)}
</div>
{/* Shared accounts with address books */}
{sharedBookGroups.map((group) => (
<div key={group.accountId} className="mt-2">
<button
onClick={() => toggleSection(`shared-${group.accountId}`)}
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
> >
<Plus className="w-3 h-3 mr-1.5" /> {collapsed[`shared-${group.accountId}`] ? (
{t("groups.create")} <ChevronRight className="w-3 h-3 text-muted-foreground" />
</Button> ) : (
<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>
</button>
{!collapsed[`shared-${group.accountId}`] && group.books.map((book) => (
<AddressBookItem
key={book.id}
book={book}
isActive={typeof activeCategory === "object" && "addressBookId" in activeCategory && activeCategory.addressBookId === book.id}
contactCount={contactCountByBook[book.id] || 0}
onSelect={() => onSelectCategory({ addressBookId: book.id })}
onDropContacts={onDropContacts}
/>
))}
</div> </div>
)} ))}
</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> </div>
); );
} }
function CategoryItem({
keyword,
count,
isActive,
onSelect,
onDropContacts,
}: {
keyword: string;
count: number;
isActive: boolean;
onSelect: () => void;
onDropContacts?: (contactIds: string[], keyword: string) => void;
}) {
const [isDragOver, setIsDragOver] = useState(false);
const handleDragOver = useCallback((e: DragEvent<HTMLButtonElement>) => {
if (!e.dataTransfer.types.includes("application/x-contact-ids")) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback(() => {
setIsDragOver(false);
}, []);
const handleDrop = useCallback((e: DragEvent<HTMLButtonElement>) => {
e.preventDefault();
setIsDragOver(false);
const data = e.dataTransfer.getData("application/x-contact-ids");
if (!data || !onDropContacts) return;
try {
const contactIds = JSON.parse(data) as string[];
if (contactIds.length > 0) {
onDropContacts(contactIds, keyword);
}
} catch {
// ignore invalid data
}
}, [keyword, onDropContacts]);
return (
<button
onClick={onSelect}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
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",
isDragOver && "bg-primary/20 ring-2 ring-primary/50"
)}
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>
);
}
function AddressBookItem({
book,
isActive,
contactCount,
onSelect,
onDropContacts,
}: {
book: AddressBook;
isActive: boolean;
contactCount: number;
onSelect: () => void;
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
}) {
const [isDragOver, setIsDragOver] = useState(false);
const handleDragOver = useCallback((e: DragEvent<HTMLButtonElement>) => {
if (!e.dataTransfer.types.includes("application/x-contact-ids")) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback(() => {
setIsDragOver(false);
}, []);
const handleDrop = useCallback((e: DragEvent<HTMLButtonElement>) => {
e.preventDefault();
setIsDragOver(false);
const data = e.dataTransfer.getData("application/x-contact-ids");
if (!data || !onDropContacts) return;
try {
const contactIds = JSON.parse(data) as string[];
if (contactIds.length > 0) {
onDropContacts(contactIds, book);
}
} catch {
// ignore invalid data
}
}, [book, onDropContacts]);
return (
<button
onClick={onSelect}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
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",
isDragOver && "bg-primary/20 ring-2 ring-primary/50"
)}
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
>
<Book className="w-4 h-4 flex-shrink-0" />
<span className="truncate">{book.name}</span>
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
{contactCount}
</span>
</button>
);
}
@@ -360,6 +360,7 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
const client = useAuthStore((s) => s.client); const client = useAuthStore((s) => s.client);
const currentUserEmail = useAuthStore((s) => s.primaryIdentity?.email); const currentUserEmail = useAuthStore((s) => s.primaryIdentity?.email);
const calendarInvitationParsingEnabled = useSettingsStore((s) => s.calendarInvitationParsingEnabled); const calendarInvitationParsingEnabled = useSettingsStore((s) => s.calendarInvitationParsingEnabled);
const timeFormat = useSettingsStore((s) => s.timeFormat);
const { calendars, supportsCalendar, importEvents, rsvpEvent, updateEvent, events: storeEvents, setSelectedDate } = useCalendarStore(); const { calendars, supportsCalendar, importEvents, rsvpEvent, updateEvent, events: storeEvents, setSelectedDate } = useCalendarStore();
const [state, setState] = useState<BannerState>('loading'); const [state, setState] = useState<BannerState>('loading');
@@ -544,6 +545,7 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
dtStart: parsedEvent.start || undefined, dtStart: parsedEvent.start || undefined,
dtEnd: summary?.end || undefined, dtEnd: summary?.end || undefined,
timeZone: parsedEvent.timeZone || undefined, timeZone: parsedEvent.timeZone || undefined,
isAllDay: parsedEvent.showWithoutTime || false,
sequence: parsedEvent.sequence, sequence: parsedEvent.sequence,
status: imipStatus, status: imipStatus,
}); });
@@ -659,16 +661,26 @@ export function CalendarInvitationBanner({ email }: CalendarInvitationBannerProp
} }
}; };
const isAllDayEvent = parsedEvent?.showWithoutTime ?? false;
const formatDateTime = (dateStr: string | null) => { const formatDateTime = (dateStr: string | null) => {
if (!dateStr) return ''; if (!dateStr) return '';
const date = new Date(dateStr); const date = new Date(dateStr);
if (isNaN(date.getTime())) return dateStr; if (isNaN(date.getTime())) return dateStr;
if (isAllDayEvent) {
return format.dateTime(date, {
weekday: 'short',
month: 'short',
day: 'numeric',
});
}
return format.dateTime(date, { return format.dateTime(date, {
weekday: 'short', weekday: 'short',
month: 'short', month: 'short',
day: 'numeric', day: 'numeric',
hour: 'numeric', hour: 'numeric',
minute: '2-digit', minute: '2-digit',
hour12: timeFormat === '12h',
}); });
}; };
+338 -106
View File
@@ -5,13 +5,20 @@ import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus } from "lucide-react"; import { X, Paperclip, Send, Save, Check, Loader2, AlertCircle, FileText, BookmarkPlus, ShieldCheck, Lock } from "lucide-react";
import { cn, formatFileSize } from "@/lib/utils"; import { cn, formatFileSize, formatDateTime } from "@/lib/utils";
import { debug } from "@/lib/debug"; import { debug } from "@/lib/debug";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import { sanitizeEmailHtml } from "@/lib/email-sanitization"; import { sanitizeEmailHtml } from "@/lib/email-sanitization";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { useIdentityStore } from "@/stores/identity-store"; import { useIdentityStore } from "@/stores/identity-store";
import { useSmimeStore } from "@/stores/smime-store";
import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { buildMimeMessage, wrapCmsAsSmimeMessage } from "@/lib/smime/mime-builder";
import type { MimeAttachment } from "@/lib/smime/mime-builder";
import { smimeSign } from "@/lib/smime/smime-sign";
import { smimeEncrypt } from "@/lib/smime/smime-encrypt";
import { useContactStore } from "@/stores/contact-store"; import { useContactStore } from "@/stores/contact-store";
import { useTemplateStore } from "@/stores/template-store"; import { useTemplateStore } from "@/stores/template-store";
import { SubAddressHelper } from "@/components/identity/sub-address-helper"; import { SubAddressHelper } from "@/components/identity/sub-address-helper";
@@ -20,6 +27,15 @@ import { substitutePlaceholders } from "@/lib/template-utils";
import { TemplatePicker } from "@/components/templates/template-picker"; import { TemplatePicker } from "@/components/templates/template-picker";
import { TemplateForm } from "@/components/templates/template-form"; import { TemplateForm } from "@/components/templates/template-form";
import type { EmailTemplate } from "@/lib/template-types"; import type { EmailTemplate } from "@/lib/template-types";
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
import { RichTextEditor } from "@/components/email/rich-text-editor";
/** Strip HTML tags and decode entities to get a plain-text version */
function htmlToPlainText(html: string): string {
const tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || '';
}
export interface ComposerDraftData { export interface ComposerDraftData {
to: string; to: string;
@@ -48,6 +64,7 @@ interface EmailComposerProps {
fromEmail?: string; fromEmail?: string;
fromName?: string; fromName?: string;
identityId?: string; identityId?: string;
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>;
}) => void | Promise<void>; }) => void | Promise<void>;
onClose?: () => void; onClose?: () => void;
onDiscardDraft?: (draftId: string) => void; onDiscardDraft?: (draftId: string) => void;
@@ -80,6 +97,7 @@ export function EmailComposer({
}: EmailComposerProps) { }: EmailComposerProps) {
const t = useTranslations('email_composer'); const t = useTranslations('email_composer');
const tCommon = useTranslations('common'); const tCommon = useTranslations('common');
const timeFormat = useSettingsStore((state) => state.timeFormat);
// Initialize with reply/forward data if provided // Initialize with reply/forward data if provided
const getInitialTo = () => { const getInitialTo = () => {
@@ -115,23 +133,28 @@ export function EmailComposer({
}; };
const getInitialBody = () => { const getInitialBody = () => {
const prefix = initialDraftText || ""; const prefix = initialDraftText ? `<p>${initialDraftText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</p>` : "";
if (!replyTo?.body && !replyTo?.htmlBody) return prefix; if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
const date = replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : ""; const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
const from = replyTo.from?.[0]; const from = replyTo.from?.[0];
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown'); const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
// When HTML body is available, don't include quoted text in the textarea // Build quoted content as HTML
// The HTML original will be shown separately below the textarea
if (replyTo.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) { if (replyTo.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
return prefix; const quoteHeader = mode === 'forward'
? `---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>`
: `On ${date}, ${fromStr} wrote:<br>`;
return `${prefix}<br><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote>`;
} }
if (mode === 'forward') { if (replyTo.body) {
return `${prefix}\n\n---------- Forwarded message ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ""}\n\n${replyTo.body}`; const escapedOriginal = replyTo.body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
} else if (mode === 'reply' || mode === 'replyAll') { if (mode === 'forward') {
return `${prefix}\n\nOn ${date}, ${fromStr} wrote:\n> ${(replyTo.body || '').split('\n').join('\n> ')}`; return `${prefix}<br><br>---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>${escapedOriginal}`;
} else if (mode === 'reply' || mode === 'replyAll') {
return `${prefix}<br><br>On ${date}, ${fromStr} wrote:<br><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${escapedOriginal}</blockquote>`;
}
} }
return prefix; return prefix;
}; };
@@ -147,18 +170,6 @@ export function EmailComposer({
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle'); const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null); const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const lastSavedDataRef = useRef<string>(""); const lastSavedDataRef = useRef<string>("");
const textareaRef = useRef<HTMLTextAreaElement>(null);
const autoResizeTextarea = useCallback(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
}, []);
useEffect(() => {
autoResizeTextarea();
}, [body, autoResizeTextarea]);
const [attachments, setAttachments] = useState<Array<{ file: File; blobId?: string; uploading?: boolean; error?: boolean; abortController?: AbortController }>>([]); const [attachments, setAttachments] = useState<Array<{ file: File; blobId?: string; uploading?: boolean; error?: boolean; abortController?: AbortController }>>([]);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({}); const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({});
@@ -169,6 +180,11 @@ export function EmailComposer({
const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false); const [showSaveAsTemplate, setShowSaveAsTemplate] = useState(false);
const [showCloseDialog, setShowCloseDialog] = useState(false); const [showCloseDialog, setShowCloseDialog] = useState(false);
const [showAllAttachments, setShowAllAttachments] = useState(false); const [showAllAttachments, setShowAllAttachments] = useState(false);
const [smimeSign_, setSmimeSign] = useState(false);
const [smimeEncrypt_, setSmimeEncrypt] = useState(false);
const [smimePassphrasePrompt, setSmimePassphrasePrompt] = useState<{ keyId: string; resolve: (passphrase: string) => void; reject: () => void } | null>(null);
const [smimePassphraseInput, setSmimePassphraseInput] = useState('');
const [smimePassphraseError, setSmimePassphraseError] = useState('');
const saveTemplateModalRef = useFocusTrap({ const saveTemplateModalRef = useFocusTrap({
isActive: showSaveAsTemplate, isActive: showSaveAsTemplate,
@@ -185,8 +201,43 @@ export function EmailComposer({
const { client } = useAuthStore(); const { client } = useAuthStore();
const identities = useIdentityStore((s) => s.identities); const identities = useIdentityStore((s) => s.identities);
const primaryIdentity = identities[0] ?? null; 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 getAutocomplete = useContactStore((s) => s.getAutocomplete);
const addTemplate = useTemplateStore((s) => s.addTemplate); const addTemplate = useTemplateStore((s) => s.addTemplate);
const sendRawEmail = useEmailStore((s) => s.sendRawEmail);
const smimeStore = useSmimeStore();
// Determine S/MIME availability for the selected identity
const currentSmimeIdentityId = selectedIdentityId || primaryIdentity?.id;
const smimeKeyRecord = currentSmimeIdentityId ? smimeStore.getKeyRecordForIdentity(currentSmimeIdentityId) : undefined;
const canSmimeSign = !!smimeKeyRecord;
const canSmimeEncrypt = (() => {
if (!smimeKeyRecord) return false;
const toAddrs = to.split(',').map(e => e.trim()).filter(Boolean);
const ccAddrs = cc.split(',').map(e => e.trim()).filter(Boolean);
const bccAddrs = bcc.split(',').map(e => e.trim()).filter(Boolean);
const allRecipients = [...toAddrs, ...ccAddrs, ...bccAddrs];
if (allRecipients.length === 0) return false;
const { missing } = smimeStore.getRecipientCerts(allRecipients);
return missing.length === 0;
})();
// Initialize S/MIME defaults from store when identity changes
useEffect(() => {
if (currentSmimeIdentityId) {
setSmimeSign(!!smimeStore.defaultSignIdentity[currentSmimeIdentityId] && canSmimeSign);
}
setSmimeEncrypt(smimeStore.defaultEncrypt && canSmimeEncrypt);
// Only run when identity changes, not on every recipient edit
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentSmimeIdentityId]);
// Keep a ref to current state for the unmount save // Keep a ref to current state for the unmount save
const stateRef = useRef({ to, cc, bcc, subject, body, showCc, showBcc, selectedIdentityId, subAddressTag, draftId }); const stateRef = useRef({ to, cc, bcc, subject, body, showCc, showBcc, selectedIdentityId, subAddressTag, draftId });
@@ -317,9 +368,12 @@ export function EmailComposer({
? substitutePlaceholders(template.body, filledValues) ? substitutePlaceholders(template.body, filledValues)
: template.body; : template.body;
// Convert template plain text body to HTML for the rich text editor
const htmlBody = `<p>${filledBody.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}</p>`;
if (mode === 'compose') { if (mode === 'compose') {
setSubject(filledSubject); setSubject(filledSubject);
setBody(filledBody); setBody(htmlBody);
if (template.defaultRecipients?.to?.length) { if (template.defaultRecipients?.to?.length) {
setTo(template.defaultRecipients.to.join(', ') + ', '); setTo(template.defaultRecipients.to.join(', ') + ', ');
} }
@@ -332,7 +386,7 @@ export function EmailComposer({
setShowBcc(true); setShowBcc(true);
} }
} else { } else {
setBody((prev) => filledBody + prev); setBody((prev) => htmlBody + prev);
} }
if (template.identityId) { if (template.identityId) {
@@ -344,8 +398,10 @@ export function EmailComposer({
useEffect(() => { useEffect(() => {
const handleTemplateKey = (e: KeyboardEvent) => { const handleTemplateKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName?.toLowerCase(); const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return; if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
if (target?.getAttribute('contenteditable') === 'true') return;
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) { if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault(); e.preventDefault();
setShowTemplatePicker(true); setShowTemplatePicker(true);
@@ -395,6 +451,18 @@ export function EmailComposer({
} }
}, [client, t]); }, [client, t]);
const handleImageUpload = useCallback(async (file: File): Promise<string | null> => {
if (!client) return null;
try {
const { blobId } = await client.uploadBlob(file);
return await client.fetchBlobAsObjectUrl(blobId, file.name, file.type);
} catch (error) {
debug.error(`Failed to upload inline image ${file.name}:`, error);
toast.error(t('upload_failed', { filename: file.name }));
return null;
}
}, [client, t]);
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => { const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) return; if (!event.target.files) return;
await addFiles(Array.from(event.target.files)); await addFiles(Array.from(event.target.files));
@@ -461,7 +529,7 @@ export function EmailComposer({
const ccAddresses = cc.split(",").map(e => e.trim()).filter(Boolean); const ccAddresses = cc.split(",").map(e => e.trim()).filter(Boolean);
const bccAddresses = bcc.split(",").map(e => e.trim()).filter(Boolean); const bccAddresses = bcc.split(",").map(e => e.trim()).filter(Boolean);
if (!toAddresses.length && !subject && !body) { if (!toAddresses.length && !subject && !htmlToPlainText(body).trim()) {
return null; return null;
} }
@@ -486,10 +554,6 @@ export function EmailComposer({
setSaveStatus('saving'); setSaveStatus('saving');
// Get the selected identity or primary identity // 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 // Generate sub-addressed email if tag is set
const fromEmail = currentIdentity?.email const fromEmail = currentIdentity?.email
? subAddressTag ? subAddressTag
@@ -501,7 +565,7 @@ export function EmailComposer({
const savedDraftId = await client.createDraft( const savedDraftId = await client.createDraft(
toAddresses, toAddresses,
subject || t('no_subject'), subject || t('no_subject'),
body, htmlToPlainText(body),
ccAddresses, ccAddresses,
bccAddresses, bccAddresses,
currentIdentity?.id, currentIdentity?.id,
@@ -565,7 +629,8 @@ export function EmailComposer({
}, []); }, []);
const toAddresses = to.split(",").map(e => e.trim()).filter(Boolean); const toAddresses = to.split(",").map(e => e.trim()).filter(Boolean);
const hasContent = body || attachments.some(att => att.blobId && !att.uploading); const bodyPlainText = htmlToPlainText(body).trim();
const hasContent = bodyPlainText || attachments.some(att => att.blobId && !att.uploading);
const canSend = toAddresses.length > 0 && !!subject && hasContent; const canSend = toAddresses.length > 0 && !!subject && hasContent;
const getSendTooltip = (): string | undefined => { const getSendTooltip = (): string | undefined => {
@@ -608,52 +673,149 @@ export function EmailComposer({
} }
} }
const currentIdentity = selectedIdentityId
? identities.find(id => id.id === selectedIdentityId)
: primaryIdentity;
const fromEmail = currentIdentity?.email const fromEmail = currentIdentity?.email
? subAddressTag ? subAddressTag
? generateSubAddress(currentIdentity.email, subAddressTag) ? generateSubAddress(currentIdentity.email, subAddressTag)
: currentIdentity.email : currentIdentity.email
: undefined; : undefined;
// Append signature from the selected identity // Body is already HTML from the rich text editor.
let finalBody = body; // Build HTML signature block
if (currentIdentity?.textSignature) { const buildSignatureHtml = (): string => {
finalBody = body + '\n\n-- \n' + currentIdentity.textSignature; if (currentIdentity?.htmlSignature) {
} return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
}
if (currentIdentity?.textSignature) {
return `<br><br>-- <br>${currentIdentity.textSignature.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}`;
}
return '';
};
// Build HTML body when replying/forwarding with original HTML content const signatureHtml = buildSignatureHtml();
let finalHtmlBody: string | undefined;
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
const escapedBody = body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
const signatureHtml = currentIdentity?.textSignature
? `<br><br>-- <br>${currentIdentity.textSignature.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')}`
: '';
const date = replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : '';
const fromAddr = replyTo.from?.[0];
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
const quoteHeader = mode === 'forward'
? `---------- ${t('prefix.forward')} ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>`
: `On ${date}, ${fromStr} wrote:<br>`;
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}<br><div><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote></div>`; // Build final HTML body: editor content + signature
} const finalHtmlBody = `<div>${body}</div>${signatureHtml}`;
// Generate plain text version from the HTML body for multipart/alternative
const finalBody = appendPlainTextSignature(htmlToPlainText(body), currentIdentity);
try { try {
await onSend?.({ // S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
to: toAddresses, if ((smimeSign_ || smimeEncrypt_) && client && currentIdentity?.id) {
cc: ccAddresses, // 1. Resolve S/MIME key
bcc: bccAddresses, if (smimeSign_ && !smimeKeyRecord) {
subject, throw new Error('No S/MIME key bound to this identity');
body: finalBody, }
htmlBody: finalHtmlBody,
draftId: finalDraftId || undefined, // 2. Ensure key is unlocked for signing
fromEmail, if (smimeSign_ && smimeKeyRecord && !smimeStore.isKeyUnlocked(smimeKeyRecord.id)) {
fromName: currentIdentity?.name || undefined, const passphrase = await new Promise<string>((resolve, reject) => {
identityId: currentIdentity?.id, setSmimePassphrasePrompt({ keyId: smimeKeyRecord.id, resolve, reject });
}); });
try {
await smimeStore.unlockKey(smimeKeyRecord.id, passphrase);
} finally {
setSmimePassphrasePrompt(null);
setSmimePassphraseInput('');
setSmimePassphraseError('');
}
}
// 3. Resolve attachments as ArrayBuffers
const mimeAttachments: MimeAttachment[] = [];
for (const att of attachments) {
if (att.error || att.uploading) continue;
let content: ArrayBuffer;
if (att.file.size > 0) {
content = await att.file.arrayBuffer();
} else if (att.blobId && client) {
content = await client.fetchBlobArrayBuffer(att.blobId, att.file.name, att.file.type);
} else {
continue;
}
mimeAttachments.push({
filename: att.file.name,
contentType: att.file.type || 'application/octet-stream',
content,
});
}
// 4. Build canonical MIME
const mimeBytes = buildMimeMessage({
from: { name: currentIdentity.name || undefined, email: fromEmail || currentIdentity.email },
to: toAddresses.map(e => ({ email: e })),
cc: ccAddresses.length > 0 ? ccAddresses.map(e => ({ email: e })) : undefined,
bcc: bccAddresses.length > 0 ? bccAddresses.map(e => ({ email: e })) : undefined,
subject,
textBody: finalBody,
htmlBody: finalHtmlBody,
attachments: mimeAttachments.length > 0 ? mimeAttachments : undefined,
});
let payload: Blob = new Blob([mimeBytes.buffer as ArrayBuffer], { type: 'message/rfc822' });
const smimeHeaders = {
from: { name: currentIdentity.name || undefined, email: fromEmail || currentIdentity.email },
to: toAddresses.map(e => ({ email: e })),
cc: ccAddresses.length > 0 ? ccAddresses.map(e => ({ email: e })) : undefined,
subject,
};
// 5. Sign if enabled
if (smimeSign_ && smimeKeyRecord) {
const privateKey = smimeStore.getUnlockedKey(smimeKeyRecord.id);
if (!privateKey) throw new Error('S/MIME key is not unlocked');
const cmsBlob = await smimeSign(
mimeBytes,
privateKey,
smimeKeyRecord.certificate,
smimeKeyRecord.certificateChain || [],
);
const cmsBytes = new Uint8Array(await cmsBlob.arrayBuffer());
payload = wrapCmsAsSmimeMessage(cmsBytes, { ...smimeHeaders, smimeType: 'signed-data' });
}
// 6. Encrypt if enabled
if (smimeEncrypt_ && smimeKeyRecord) {
const allRecipients = [...toAddresses, ...ccAddresses, ...bccAddresses];
const { found, missing } = smimeStore.getRecipientCerts(allRecipients);
if (missing.length > 0) {
throw new Error(`Missing certificates for: ${missing.join(', ')}`);
}
const recipientCertsDer = found.map(c => c.certificate instanceof ArrayBuffer ? c.certificate : new Uint8Array(c.certificate as ArrayBuffer).buffer);
const payloadBytes = new Uint8Array(await payload.arrayBuffer());
const cmsBlob = await smimeEncrypt(
payloadBytes,
recipientCertsDer,
smimeKeyRecord.certificate,
);
const cmsBytes = new Uint8Array(await cmsBlob.arrayBuffer());
payload = wrapCmsAsSmimeMessage(cmsBytes, { ...smimeHeaders, smimeType: 'enveloped-data' });
}
// 7. Send via raw email path
await sendRawEmail(client, payload, currentIdentity.id);
} else {
// Standard JMAP send path
// Collect uploaded attachment blobIds for the send request
const uploadedAttachments = attachments
.filter(att => att.blobId && !att.uploading && !att.error)
.map(att => ({ blobId: att.blobId!, name: att.file.name, type: att.file.type || 'application/octet-stream', size: att.file.size }));
await onSend?.({
to: toAddresses,
cc: ccAddresses,
bcc: bccAddresses,
subject,
body: finalBody,
htmlBody: finalHtmlBody,
draftId: finalDraftId || undefined,
fromEmail,
fromName: currentIdentity?.name || undefined,
identityId: currentIdentity?.id,
attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
});
}
setTo(""); setTo("");
setCc(""); setCc("");
@@ -712,6 +874,7 @@ export function EmailComposer({
return ( return (
<div <div
className={cn("flex flex-col h-full bg-background relative", className)} className={cn("flex flex-col h-full bg-background relative", className)}
data-tour="composer"
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
onDragOver={handleDragOver} onDragOver={handleDragOver}
@@ -780,11 +943,16 @@ export function EmailComposer({
onChange={(e) => setSelectedIdentityId(e.target.value)} onChange={(e) => setSelectedIdentityId(e.target.value)}
className="flex-1 bg-transparent text-sm text-foreground outline-none cursor-pointer hover:text-muted-foreground transition-colors min-w-0 truncate" className="flex-1 bg-transparent text-sm text-foreground outline-none cursor-pointer hover:text-muted-foreground transition-colors min-w-0 truncate"
> >
{identities.map((identity) => ( {identities.map((identity) => {
<option key={identity.id} value={identity.id}> const displayEmail = subAddressTag
{identity.name ? `${identity.name} <${identity.email}>` : identity.email} ? generateSubAddress(identity.email, subAddressTag)
</option> : identity.email;
))} return (
<option key={identity.id} value={identity.id}>
{identity.name ? `${identity.name} <${displayEmail}>` : displayEmail}
</option>
);
})}
</select> </select>
) : ( ) : (
<span className="text-sm text-foreground flex-1 truncate"> <span className="text-sm text-foreground flex-1 truncate">
@@ -932,39 +1100,23 @@ export function EmailComposer({
</div> </div>
</div> </div>
{/* Body */} {/* Body - Rich Text Editor */}
<div className="px-4 py-3"> <RichTextEditor
<textarea content={body}
ref={textareaRef} onChange={(html) => {
className={cn( setBody(html);
"w-full resize-none outline-none text-sm bg-transparent text-foreground placeholder:text-muted-foreground rounded min-h-[100px] overflow-hidden", if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
validationErrors.body && "ring-2 ring-red-500 dark:ring-red-400" }}
)} onImageUpload={handleImageUpload}
placeholder={t('body_placeholder')} placeholder={t('body_placeholder')}
value={body} hasError={validationErrors.body}
onChange={(e) => { />
setBody(e.target.value);
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
}}
aria-invalid={validationErrors.body || undefined}
/>
</div>
{/* Quoted original HTML */} {composerSignatureHtml && (
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && ( <div
<div className="border-t border-border"> className="px-4 pb-3 text-sm leading-6 text-foreground break-words [&_a]:text-primary [&_a]:underline-offset-2 [&_a:hover]:underline"
<div className="px-4 py-2 text-xs text-muted-foreground"> dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
{mode === 'forward' />
? `---------- ${t('prefix.forward')} ----------`
: `${replyTo.receivedAt ? new Date(replyTo.receivedAt).toLocaleString() : ''}, ${replyTo.from?.[0]?.name || replyTo.from?.[0]?.email || tCommon('unknown')}:`
}
</div>
<div
className="email-reply-quote px-4 pb-3 border-l-2 border-muted-foreground/30 ml-4 max-w-none rounded"
style={{ backgroundColor: '#ffffff', color: '#1a1a1a', fontSize: '14px' }}
dangerouslySetInnerHTML={{ __html: sanitizeEmailHtml(replyTo.htmlBody) }}
/>
</div>
)} )}
</div> </div>
@@ -1059,6 +1211,32 @@ export function EmailComposer({
> >
<BookmarkPlus className="w-4 h-4" /> <BookmarkPlus className="w-4 h-4" />
</Button> </Button>
{/* S/MIME toggles */}
{canSmimeSign && (
<>
<div className="w-px h-5 bg-border mx-1" />
<Button
variant="ghost"
size="icon"
onClick={() => setSmimeSign(v => !v)}
className={cn("h-9 w-9", smimeSign_ && "bg-primary/10 text-primary")}
title={smimeSign_ ? t('smime_sign_on') : t('smime_sign_off')}
>
<ShieldCheck className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => setSmimeEncrypt(v => !v)}
disabled={!canSmimeEncrypt}
className={cn("h-9 w-9", smimeEncrypt_ && "bg-primary/10 text-primary")}
title={smimeEncrypt_ ? t('smime_encrypt_on') : canSmimeEncrypt ? t('smime_encrypt_off') : t('smime_encrypt_unavailable')}
>
<Lock className="w-4 h-4" />
</Button>
</>
)}
</div> </div>
{/* Right side - Discard + Send (desktop) */} {/* Right side - Discard + Send (desktop) */}
@@ -1117,6 +1295,60 @@ export function EmailComposer({
</div> </div>
)} )}
{/* S/MIME passphrase prompt */}
{smimePassphrasePrompt && (
<div
className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150"
>
<div
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-sm animate-in zoom-in-95 duration-200"
>
<div className="p-6">
<h2 className="text-lg font-semibold text-foreground">{t('smime_unlock_title')}</h2>
<p className="mt-2 text-sm text-muted-foreground">{t('smime_unlock_message')}</p>
<input
type="password"
autoFocus
value={smimePassphraseInput}
onChange={(e) => {
setSmimePassphraseInput(e.target.value);
setSmimePassphraseError('');
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && smimePassphraseInput) {
smimePassphrasePrompt.resolve(smimePassphraseInput);
}
}}
placeholder={t('smime_passphrase_placeholder')}
className="mt-3 w-full px-3 py-2 border border-border rounded-md text-sm bg-background text-foreground outline-none focus:ring-2 focus:ring-primary"
/>
{smimePassphraseError && (
<p className="mt-1 text-xs text-red-500">{smimePassphraseError}</p>
)}
</div>
<div className="flex items-center justify-end gap-3 px-6 pb-6">
<Button variant="outline" onClick={() => {
smimePassphrasePrompt.reject();
setSmimePassphrasePrompt(null);
setSmimePassphraseInput('');
setSmimePassphraseError('');
}}>
{t('cancel')}
</Button>
<Button
disabled={!smimePassphraseInput}
onClick={() => smimePassphrasePrompt.resolve(smimePassphraseInput)}
>
{t('smime_unlock_button')}
</Button>
</div>
</div>
</div>
)}
{showCloseDialog && ( {showCloseDialog && (
<div <div
className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150" className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150"
+16
View File
@@ -28,6 +28,7 @@ import {
Folder, Folder,
ShieldAlert, ShieldAlert,
ShieldCheck, ShieldCheck,
EditIcon,
} from "lucide-react"; } from "lucide-react";
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils"; import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store"; import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
@@ -60,6 +61,7 @@ interface EmailContextMenuProps {
onMoveToMailbox?: (mailboxId: string) => void; onMoveToMailbox?: (mailboxId: string) => void;
onMarkAsSpam?: () => void; onMarkAsSpam?: () => void;
onUndoSpam?: () => void; onUndoSpam?: () => void;
onEditDraft?: () => void;
// Batch actions // Batch actions
onBatchMarkAsRead?: (read: boolean) => void; onBatchMarkAsRead?: (read: boolean) => void;
onBatchDelete?: () => void; onBatchDelete?: () => void;
@@ -126,12 +128,14 @@ export function EmailContextMenu({
onBatchMoveToMailbox, onBatchMoveToMailbox,
onBatchMarkAsSpam, onBatchMarkAsSpam,
onBatchUndoSpam, onBatchUndoSpam,
onEditDraft,
}: EmailContextMenuProps) { }: EmailContextMenuProps) {
const t = useTranslations("context_menu"); const t = useTranslations("context_menu");
const tColor = useTranslations("email_viewer.color_tag"); const tColor = useTranslations("email_viewer.color_tag");
const emailKeywords = useSettingsStore((state) => state.emailKeywords); const emailKeywords = useSettingsStore((state) => state.emailKeywords);
const isUnread = !email.keywords?.$seen; const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged; const isStarred = email.keywords?.$flagged;
const isDraft = email.keywords?.['$draft'] === true;
const currentColor = getCurrentColor(email.keywords); const currentColor = getCurrentColor(email.keywords);
const showBatchActions = isMultiSelect && selectedCount > 1; const showBatchActions = isMultiSelect && selectedCount > 1;
const isInJunkFolder = currentMailboxRole === 'junk'; const isInJunkFolder = currentMailboxRole === 'junk';
@@ -188,6 +192,18 @@ export function EmailContextMenu({
</ContextMenuHeader> </ContextMenuHeader>
)} )}
{/* Edit Draft - only for single draft emails */}
{!showBatchActions && isDraft && onEditDraft && (
<>
<ContextMenuItem
icon={EditIcon}
label={t("edit_draft")}
onClick={() => handleAction(onEditDraft)}
/>
<ContextMenuSeparator />
</>
)}
{/* Single email actions - Reply, Reply All, Forward */} {/* Single email actions - Reply, Reply All, Forward */}
{!showBatchActions && ( {!showBatchActions && (
<> <>
+138
View File
@@ -0,0 +1,138 @@
"use client";
import { Email } from "@/lib/jmap/types";
import { useSettingsStore } from "@/stores/settings-store";
import type { HoverAction } from "@/stores/settings-store";
import { cn } from "@/lib/utils";
import { Trash2, Star, Mail, MailOpen, Archive, Tag, ShieldAlert } from "lucide-react";
import { useTranslations } from "next-intl";
interface EmailHoverActionsProps {
email: Email;
onToggleStar?: () => void;
onMarkAsRead?: (read: boolean) => void;
onDelete?: () => void;
onArchive?: () => void;
onSetColorTag?: (color: string | null) => void;
onMarkAsSpam?: () => void;
}
const ACTION_CONFIG: Record<HoverAction, {
icon: typeof Trash2;
titleKey: string;
className?: string;
}> = {
delete: {
icon: Trash2,
titleKey: "delete",
className: "hover:text-red-600 dark:hover:text-red-400",
},
star: {
icon: Star,
titleKey: "star",
className: "hover:text-amber-500 dark:hover:text-amber-400",
},
markRead: {
icon: Mail,
titleKey: "mark_read",
className: "hover:text-blue-600 dark:hover:text-blue-400",
},
archive: {
icon: Archive,
titleKey: "archive",
className: "hover:text-green-600 dark:hover:text-green-400",
},
tag: {
icon: Tag,
titleKey: "tag",
className: "hover:text-purple-600 dark:hover:text-purple-400",
},
spam: {
icon: ShieldAlert,
titleKey: "spam",
className: "hover:text-orange-600 dark:hover:text-orange-400",
},
};
export function EmailHoverActions({
email,
onToggleStar,
onMarkAsRead,
onDelete,
onArchive,
onSetColorTag,
onMarkAsSpam,
}: EmailHoverActionsProps) {
const hoverActions = useSettingsStore((state) => state.hoverActions);
const t = useTranslations("settings.email_behavior.hover_actions");
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
if (hoverActions.length === 0) return null;
const handleAction = (e: React.MouseEvent, action: HoverAction) => {
e.stopPropagation();
e.preventDefault();
switch (action) {
case "delete":
onDelete?.();
break;
case "star":
onToggleStar?.();
break;
case "markRead":
onMarkAsRead?.(!isUnread);
break;
case "archive":
onArchive?.();
break;
case "tag":
onSetColorTag?.(null);
break;
case "spam":
onMarkAsSpam?.();
break;
}
};
return (
<div
className="absolute right-0 top-0 bottom-0 z-10 hidden group-hover:flex items-center"
>
<div className="w-8 h-full bg-gradient-to-r from-transparent to-muted" />
<div className="flex items-center gap-0.5 h-full bg-muted pr-3 pl-0.5">
{hoverActions.map((actionId) => {
const config = ACTION_CONFIG[actionId];
if (!config) return null;
const Icon = config.icon;
const DisplayIcon = actionId === "markRead"
? (isUnread ? MailOpen : Mail)
: actionId === "star" && isStarred
? Star
: Icon;
return (
<button
key={actionId}
onClick={(e) => handleAction(e, actionId)}
title={t(config.titleKey)}
className={cn(
"p-1.5 rounded-md transition-colors duration-100 text-muted-foreground hover:bg-black/5 dark:hover:bg-white/10",
config.className,
)}
>
<DisplayIcon
className={cn(
"w-4 h-4",
actionId === "star" && isStarred && "fill-amber-400 text-amber-400",
)}
/>
</button>
);
})}
</div>
</div>
);
}
+35 -3
View File
@@ -6,7 +6,7 @@ import { formatDate } from "@/lib/utils";
import { Email } from "@/lib/jmap/types"; import { Email } from "@/lib/jmap/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Paperclip, Star, Circle, CheckSquare, Square, Tag } from "lucide-react"; import { Paperclip, Star, Circle, CheckSquare, Square, Tag, Reply, Forward } from "lucide-react";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store"; import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
@@ -14,6 +14,7 @@ import { useEmailDrag } from "@/hooks/use-email-drag";
import { useLongPress } from "@/hooks/use-long-press"; import { useLongPress } from "@/hooks/use-long-press";
import { useUIStore } from "@/stores/ui-store"; import { useUIStore } from "@/stores/ui-store";
import { EmailIdentityBadge } from "./email-identity-badge"; import { EmailIdentityBadge } from "./email-identity-badge";
import { EmailHoverActions } from "./email-hover-actions";
import { getEmailColorTag } from "@/lib/thread-utils"; import { getEmailColorTag } from "@/lib/thread-utils";
interface EmailListItemProps { interface EmailListItemProps {
@@ -21,9 +22,15 @@ interface EmailListItemProps {
selected?: boolean; selected?: boolean;
onClick?: () => void; onClick?: () => void;
onContextMenu?: (e: React.MouseEvent, email: Email) => void; onContextMenu?: (e: React.MouseEvent, email: Email) => void;
onToggleStar?: () => void;
onMarkAsRead?: (read: boolean) => void;
onDelete?: () => void;
onArchive?: () => void;
onSetColorTag?: (color: string | null) => void;
onMarkAsSpam?: () => void;
} }
export function EmailListItem({ email, selected, onClick, onContextMenu }: EmailListItemProps) { export function EmailListItem({ email, selected, onClick, onContextMenu, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }: EmailListItemProps) {
const t = useTranslations('email_viewer'); const t = useTranslations('email_viewer');
const { selectedEmailIds, toggleEmailSelection, selectRangeEmails, selectedMailbox, clearSelection } = useEmailStore(); const { selectedEmailIds, toggleEmailSelection, selectRangeEmails, selectedMailbox, clearSelection } = useEmailStore();
const showPreview = useSettingsStore((state) => state.showPreview); const showPreview = useSettingsStore((state) => state.showPreview);
@@ -34,6 +41,8 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
const isUnread = !email.keywords?.$seen; const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged; const isStarred = email.keywords?.$flagged;
const isImportant = email.keywords?.["$important"]; const isImportant = email.keywords?.["$important"];
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0]; const sender = email.from?.[0];
// Resolve color tag using keyword definitions from settings // Resolve color tag using keyword definitions from settings
@@ -74,7 +83,7 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
{...dragHandlers} {...dragHandlers}
{...longPressHandlers} {...longPressHandlers}
className={cn( className={cn(
"relative group cursor-pointer select-none transition-all duration-200 border-b border-border", "relative group cursor-pointer select-none transition-shadow duration-200 border-b border-border overflow-hidden",
// Apply color tag as background, with selected and unread states // Apply color tag as background, with selected and unread states
colorTag ? colorTag : ( colorTag ? colorTag : (
selected selected
@@ -168,6 +177,18 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
</span> </span>
)} )}
<EmailIdentityBadge email={email} identities={identities} compact={true} /> <EmailIdentityBadge email={email} identities={identities} compact={true} />
{isAnswered && !isForwarded && (
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
)}
{isForwarded && !isAnswered && (
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
)}
{isAnswered && isForwarded && (
<>
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
</>
)}
{email.hasAttachment && ( {email.hasAttachment && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" /> <Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)} )}
@@ -217,6 +238,17 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
)} )}
</div> </div>
</div> </div>
{/* Hover Quick Actions */}
<EmailHoverActions
email={email}
onToggleStar={onToggleStar}
onMarkAsRead={onMarkAsRead}
onDelete={onDelete}
onArchive={onArchive}
onSetColorTag={onSetColorTag}
onMarkAsSpam={onMarkAsSpam}
/>
</div> </div>
); );
} }
+10 -1
View File
@@ -37,6 +37,7 @@ interface EmailListProps {
onMoveToMailbox?: (emailId: string, mailboxId: string) => void; onMoveToMailbox?: (emailId: string, mailboxId: string) => void;
onMarkAsSpam?: (email: Email) => void; onMarkAsSpam?: (email: Email) => void;
onUndoSpam?: (email: Email) => void; onUndoSpam?: (email: Email) => void;
onEditDraft?: (email: Email) => void;
} }
export function EmailList({ export function EmailList({
@@ -57,6 +58,7 @@ export function EmailList({
onMarkAsSpam, onMarkAsSpam,
onUndoSpam, onUndoSpam,
onMoveToMailbox, onMoveToMailbox,
onEditDraft,
}: EmailListProps) { }: EmailListProps) {
const t = useTranslations('email_list'); const t = useTranslations('email_list');
const { client } = useAuthStore(); const { client } = useAuthStore();
@@ -356,7 +358,7 @@ export function EmailList({
)} )}
{/* Email List */} {/* Email List */}
<div ref={parentRef} className="flex-1 overflow-y-auto bg-background relative"> <div ref={parentRef} className="flex-1 overflow-y-auto bg-background relative" data-tour="email-list">
{/* Loading overlay */} {/* Loading overlay */}
{isLoading && emails.length > 0 && ( {isLoading && emails.length > 0 && (
<div className="absolute inset-0 bg-background/50 z-10 flex items-center justify-center animate-in fade-in duration-150"> <div className="absolute inset-0 bg-background/50 z-10 flex items-center justify-center animate-in fade-in duration-150">
@@ -420,6 +422,12 @@ export function EmailList({
onEmailSelect={(email) => onEmailSelect?.(email)} onEmailSelect={(email) => onEmailSelect?.(email)}
onContextMenu={openContextMenu} onContextMenu={openContextMenu}
onOpenConversation={onOpenConversation} onOpenConversation={onOpenConversation}
onToggleStar={onToggleStar ? (email) => onToggleStar(email) : undefined}
onMarkAsRead={onMarkAsRead ? (email, read) => onMarkAsRead(email, read) : undefined}
onDelete={onDelete ? (email) => onDelete(email) : undefined}
onArchive={onArchive ? (email) => onArchive(email) : undefined}
onSetColorTag={onSetColorTag}
onMarkAsSpam={onMarkAsSpam ? (email) => onMarkAsSpam(email) : undefined}
/> />
</div> </div>
); );
@@ -467,6 +475,7 @@ export function EmailList({
onMoveToMailbox={(mailboxId) => onMoveToMailbox?.(contextMenu.data!.id, mailboxId)} onMoveToMailbox={(mailboxId) => onMoveToMailbox?.(contextMenu.data!.id, mailboxId)}
onMarkAsSpam={() => onMarkAsSpam?.(contextMenu.data!)} onMarkAsSpam={() => onMarkAsSpam?.(contextMenu.data!)}
onUndoSpam={() => onUndoSpam?.(contextMenu.data!)} onUndoSpam={() => onUndoSpam?.(contextMenu.data!)}
onEditDraft={() => onEditDraft?.(contextMenu.data!)}
onBatchMarkAsRead={(read) => client && batchMarkAsRead(client, read)} onBatchMarkAsRead={(read) => client && batchMarkAsRead(client, read)}
onBatchDelete={() => client && batchDelete(client)} onBatchDelete={() => client && batchDelete(client)}
onBatchMoveToMailbox={(mailboxId) => client && batchMoveToMailbox(client, mailboxId)} onBatchMoveToMailbox={(mailboxId) => client && batchMoveToMailbox(client, mailboxId)}
File diff suppressed because it is too large Load Diff
+135
View File
@@ -0,0 +1,135 @@
"use client";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Node, mergeAttributes } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
function ResizableImageView({ node, updateAttributes, selected }: NodeViewProps) {
const imgRef = useRef<HTMLImageElement>(null);
const [resizing, setResizing] = useState(false);
const startState = useRef<{ x: number; y: number; width: number; height: number; handle: string }>({
x: 0, y: 0, width: 0, height: 0, handle: "",
});
const onMouseDown = useCallback((e: React.MouseEvent, handle: string) => {
e.preventDefault();
e.stopPropagation();
const img = imgRef.current;
if (!img) return;
startState.current = {
x: e.clientX,
y: e.clientY,
width: img.offsetWidth,
height: img.offsetHeight,
handle,
};
setResizing(true);
}, []);
useEffect(() => {
if (!resizing) return;
const onMouseMove = (e: MouseEvent) => {
const { x, width, handle } = startState.current;
const dx = e.clientX - x;
let newWidth: number;
if (handle === "right" || handle === "bottom-right" || handle === "top-right") {
newWidth = Math.max(50, width + dx);
} else {
newWidth = Math.max(50, width - dx);
}
updateAttributes({ width: Math.round(newWidth) });
};
const onMouseUp = () => {
setResizing(false);
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
return () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
};
}, [resizing, updateAttributes]);
const width = node.attrs.width;
const style: React.CSSProperties = {
...(width ? { width: `${width}px` } : {}),
maxWidth: "100%",
};
return (
<NodeViewWrapper as="span" className="inline-block relative" draggable data-drag-handle>
<span
className={`relative inline-block group ${selected ? "ring-2 ring-primary rounded" : ""}`}
style={style}
>
<img
ref={imgRef}
src={node.attrs.src}
alt={node.attrs.alt || ""}
title={node.attrs.title || undefined}
style={{ width: "100%", height: "auto", display: "block" }}
draggable={false}
/>
{selected && (
<>
{/* Resize handle: right */}
<span
onMouseDown={(e) => onMouseDown(e, "right")}
className="absolute top-1/2 -right-1.5 -translate-y-1/2 w-3 h-8 bg-primary rounded cursor-ew-resize"
/>
{/* Resize handle: left */}
<span
onMouseDown={(e) => onMouseDown(e, "left")}
className="absolute top-1/2 -left-1.5 -translate-y-1/2 w-3 h-8 bg-primary rounded cursor-ew-resize"
/>
{/* Resize handle: bottom-right corner */}
<span
onMouseDown={(e) => onMouseDown(e, "bottom-right")}
className="absolute -bottom-1.5 -right-1.5 w-3 h-3 bg-primary rounded cursor-nwse-resize"
/>
</>
)}
</span>
</NodeViewWrapper>
);
}
export const ResizableImage = Node.create({
name: "image",
group: "inline",
inline: true,
draggable: true,
selectable: true,
addAttributes() {
return {
src: { default: null },
alt: { default: null },
title: { default: null },
width: { default: null },
};
},
parseHTML() {
return [{ tag: "img[src]" }];
},
renderHTML({ HTMLAttributes }) {
const attrs: Record<string, string> = { ...HTMLAttributes };
if (attrs.width) {
attrs.style = `width: ${attrs.width}px; max-width: 100%;`;
delete attrs.width;
}
return ["img", mergeAttributes(attrs)];
},
addNodeView() {
return ReactNodeViewRenderer(ResizableImageView);
},
});
+337
View File
@@ -0,0 +1,337 @@
"use client";
import React, { useEffect, useCallback } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import Link from "@tiptap/extension-link";
import TextAlign from "@tiptap/extension-text-align";
import { TextStyle } from "@tiptap/extension-text-style";
import Color from "@tiptap/extension-color";
import { ResizableImage } from "@/components/email/resizable-image";
import Placeholder from "@tiptap/extension-placeholder";
import { cn } from "@/lib/utils";
import {
Bold,
Italic,
Underline as UnderlineIcon,
Strikethrough,
List,
ListOrdered,
AlignLeft,
AlignCenter,
AlignRight,
Link as LinkIcon,
Undo,
Redo,
Quote,
Code,
RemoveFormatting,
Heading1,
Heading2,
} from "lucide-react";
interface RichTextEditorProps {
content: string;
onChange: (html: string) => void;
onImageUpload?: (file: File) => Promise<string | null>;
placeholder?: string;
className?: string;
hasError?: boolean;
}
function ToolbarButton({
active,
onClick,
children,
title,
disabled,
}: {
active?: boolean;
onClick: () => void;
children: React.ReactNode;
title: string;
disabled?: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
title={title}
className={cn(
"p-1.5 rounded hover:bg-accent transition-colors",
active && "bg-accent text-accent-foreground",
disabled && "opacity-40 cursor-not-allowed"
)}
>
{children}
</button>
);
}
function ToolbarSeparator() {
return <div className="w-px h-5 bg-border mx-0.5" />;
}
export function RichTextEditor({
content,
onChange,
onImageUpload,
placeholder,
className,
hasError,
}: RichTextEditorProps) {
const onImageUploadRef = React.useRef(onImageUpload);
onImageUploadRef.current = onImageUpload;
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: { levels: [1, 2] },
}),
Underline,
Link.configure({
openOnClick: false,
HTMLAttributes: { rel: "noopener noreferrer nofollow" },
}),
TextAlign.configure({
types: ["heading", "paragraph"],
}),
TextStyle,
Color,
ResizableImage,
Placeholder.configure({
placeholder,
}),
],
content,
editorProps: {
attributes: {
class: "tiptap min-h-[100px] px-4 py-3 text-sm text-foreground",
},
handleDrop: (view, event) => {
const upload = onImageUploadRef.current;
if (!upload || !event.dataTransfer?.files?.length) return false;
const imageFiles = Array.from(event.dataTransfer.files).filter(f =>
f.type.startsWith("image/")
);
if (imageFiles.length === 0) return false;
event.preventDefault();
for (const file of imageFiles) {
upload(file).then((url) => {
if (url) {
const { state } = view;
const pos = view.posAtCoords({ left: event.clientX, top: event.clientY });
const node = state.schema.nodes.image.create({ src: url, alt: file.name });
const tr = state.tr.insert(pos?.pos ?? state.selection.anchor, node);
view.dispatch(tr);
}
});
}
return true;
},
handlePaste: (view, event) => {
const upload = onImageUploadRef.current;
if (!upload || !event.clipboardData?.files?.length) return false;
const imageFiles = Array.from(event.clipboardData.files).filter(f =>
f.type.startsWith("image/")
);
if (imageFiles.length === 0) return false;
event.preventDefault();
for (const file of imageFiles) {
upload(file).then((url) => {
if (url) {
const { state } = view;
const node = state.schema.nodes.image.create({ src: url, alt: file.name });
const tr = state.tr.replaceSelectionWith(node);
view.dispatch(tr);
}
});
}
return true;
},
},
onUpdate: ({ editor }) => {
onChange(editor.getHTML());
},
immediatelyRender: false,
});
// Sync external content changes (e.g. template application)
useEffect(() => {
if (editor && content !== editor.getHTML()) {
editor.commands.setContent(content, { emitUpdate: false });
}
}, [content, editor]);
const addLink = useCallback(() => {
if (!editor) return;
const previousUrl = editor.getAttributes("link").href;
const url = window.prompt("URL", previousUrl);
if (url === null) return;
if (url === "") {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
return;
}
editor
.chain()
.focus()
.extendMarkRange("link")
.setLink({ href: url })
.run();
}, [editor]);
if (!editor) {
return (
<div className={cn("min-h-[100px]", className)} />
);
}
return (
<div className={cn("flex flex-col", hasError && "ring-2 ring-red-500 dark:ring-red-400 rounded", className)}>
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-0.5 px-3 py-1.5 border-b border-border/50 bg-muted/30">
<ToolbarButton
active={editor.isActive("bold")}
onClick={() => editor.chain().focus().toggleBold().run()}
title="Bold"
>
<Bold className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("italic")}
onClick={() => editor.chain().focus().toggleItalic().run()}
title="Italic"
>
<Italic className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("underline")}
onClick={() => editor.chain().focus().toggleUnderline().run()}
title="Underline"
>
<UnderlineIcon className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("strike")}
onClick={() => editor.chain().focus().toggleStrike().run()}
title="Strikethrough"
>
<Strikethrough className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("heading", { level: 1 })}
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
title="Heading 1"
>
<Heading1 className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("heading", { level: 2 })}
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
title="Heading 2"
>
<Heading2 className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("bulletList")}
onClick={() => editor.chain().focus().toggleBulletList().run()}
title="Bullet List"
>
<List className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("orderedList")}
onClick={() => editor.chain().focus().toggleOrderedList().run()}
title="Ordered List"
>
<ListOrdered className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("blockquote")}
onClick={() => editor.chain().focus().toggleBlockquote().run()}
title="Quote"
>
<Quote className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive("codeBlock")}
onClick={() => editor.chain().focus().toggleCodeBlock().run()}
title="Code Block"
>
<Code className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive({ textAlign: "left" })}
onClick={() => editor.chain().focus().setTextAlign("left").run()}
title="Align Left"
>
<AlignLeft className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive({ textAlign: "center" })}
onClick={() => editor.chain().focus().setTextAlign("center").run()}
title="Align Center"
>
<AlignCenter className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
active={editor.isActive({ textAlign: "right" })}
onClick={() => editor.chain().focus().setTextAlign("right").run()}
title="Align Right"
>
<AlignRight className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
active={editor.isActive("link")}
onClick={addLink}
title="Link"
>
<LinkIcon className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
onClick={() => editor.chain().focus().clearNodes().unsetAllMarks().run()}
title="Clear Formatting"
>
<RemoveFormatting className="w-4 h-4" />
</ToolbarButton>
<ToolbarSeparator />
<ToolbarButton
onClick={() => editor.chain().focus().undo().run()}
disabled={!editor.can().undo()}
title="Undo"
>
<Undo className="w-4 h-4" />
</ToolbarButton>
<ToolbarButton
onClick={() => editor.chain().focus().redo().run()}
disabled={!editor.can().redo()}
title="Redo"
>
<Redo className="w-4 h-4" />
</ToolbarButton>
</div>
{/* Editor */}
<EditorContent editor={editor} />
</div>
);
}
+116
View File
@@ -0,0 +1,116 @@
"use client";
import React from "react";
import { ShieldCheck, ShieldAlert, ShieldX, Lock, LockOpen, AlertTriangle, Info } from "lucide-react";
import { cn } from "@/lib/utils";
import { useTranslations } from "next-intl";
import type { SmimeStatus } from "@/lib/smime/types";
interface SmimeStatusBannerProps {
status: SmimeStatus;
onUnlockKey?: () => void;
className?: string;
}
export function SmimeStatusBanner({ status, onUnlockKey, className }: SmimeStatusBannerProps) {
const t = useTranslations('smime');
const items: Array<{
icon: React.ReactNode;
text: string;
variant: 'success' | 'warning' | 'error' | 'info';
}> = [];
// Encryption status
if (status.isEncrypted) {
if (status.decryptionError) {
if (status.decryptionError === 'locked') {
items.push({
icon: <Lock className="w-4 h-4" />,
text: t('unlock_key_desc'),
variant: 'warning',
});
} else {
items.push({
icon: <ShieldX className="w-4 h-4" />,
text: t('status_encrypted_failed'),
variant: 'error',
});
}
} else {
items.push({
icon: <LockOpen className="w-4 h-4" />,
text: t('status_encrypted_ok'),
variant: 'success',
});
}
}
// Signature status
if (status.isSigned) {
if (status.signatureValid === true) {
if (status.signerEmailMatch === false) {
items.push({
icon: <AlertTriangle className="w-4 h-4" />,
text: t('status_signed_mismatch'),
variant: 'warning',
});
} else {
items.push({
icon: <ShieldCheck className="w-4 h-4" />,
text: t('status_signed_valid'),
variant: 'success',
});
}
} else if (status.signatureValid === false) {
items.push({
icon: <ShieldAlert className="w-4 h-4" />,
text: status.signatureError || t('status_signed_invalid'),
variant: 'error',
});
}
}
// Unsupported S/MIME
if (status.unsupportedReason) {
items.push({
icon: <Info className="w-4 h-4" />,
text: t('status_unsupported'),
variant: 'info',
});
}
if (items.length === 0) return null;
const variantStyles = {
success: 'bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800',
warning: 'bg-yellow-50 dark:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800',
error: 'bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800',
info: 'bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800',
};
return (
<div className={cn("flex flex-col gap-1.5 py-1", className)}>
{items.map((item, i) => (
<div
key={i}
className={cn(
"flex items-center gap-2 px-3 py-1.5 rounded-md text-sm border",
variantStyles[item.variant],
)}
>
{item.icon}
<span className="flex-1">{item.text}</span>
{item.variant === 'warning' && status.decryptionError === 'locked' && onUnlockKey && (
<button
onClick={onUnlockKey}
className="text-xs font-medium underline hover:no-underline"
>
{t('unlock_key')}
</button>
)}
</div>
))}
</div>
);
}
+20 -6
View File
@@ -4,6 +4,7 @@ import { useState, useEffect, useMemo } from "react";
import DOMPurify from "dompurify"; import DOMPurify from "dompurify";
import { Email, ThreadGroup } from "@/lib/jmap/types"; import { Email, ThreadGroup } from "@/lib/jmap/types";
import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization"; import { EMAIL_SANITIZE_CONFIG, collapseBlockedImageContainers } from "@/lib/email-sanitization";
import { hasMeaningfulHtmlBody } from "@/lib/signature-utils";
import { transformInlineStyles, transformColorForDarkMode, transformBgColorForDarkMode } from "@/lib/color-transform"; import { transformInlineStyles, transformColorForDarkMode, transformBgColorForDarkMode } from "@/lib/color-transform";
import { useThemeStore } from "@/stores/theme-store"; import { useThemeStore } from "@/stores/theme-store";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
@@ -225,6 +226,7 @@ function EmailCard({
const resolvedTheme = useThemeStore((state) => state.resolvedTheme); const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
const density = useSettingsStore((state) => state.density); const density = useSettingsStore((state) => state.density);
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction); const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
const emailAlwaysLightMode = useSettingsStore((state) => state.emailAlwaysLightMode);
const sender = email.from?.[0]; const sender = email.from?.[0];
const isUnread = !email.keywords?.$seen; const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged; const isStarred = email.keywords?.$flagged;
@@ -315,7 +317,14 @@ function EmailCard({
if (email.htmlBody?.[0]?.partId && email.bodyValues[email.htmlBody[0].partId]) { if (email.htmlBody?.[0]?.partId && email.bodyValues[email.htmlBody[0].partId]) {
htmlContent = email.bodyValues[email.htmlBody[0].partId].value; htmlContent = email.bodyValues[email.htmlBody[0].partId].value;
useHtmlVersion = !!htmlContent; // Prefer textBody when HTML is auto-generated minimal wrapper (no rich formatting).
// 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) {
useHtmlVersion = hasMeaningfulHtmlBody(htmlContent);
} else {
useHtmlVersion = !!htmlContent;
}
} }
if (useHtmlVersion && htmlContent) { if (useHtmlVersion && htmlContent) {
@@ -363,7 +372,7 @@ function EmailCard({
node.setAttribute('rel', 'noopener noreferrer'); node.setAttribute('rel', 'noopener noreferrer');
} }
if (resolvedTheme === 'dark') { if (resolvedTheme === 'dark' && !emailAlwaysLightMode) {
if (htmlNode.style) { if (htmlNode.style) {
const originalStyles = htmlNode.style.cssText; const originalStyles = htmlNode.style.cssText;
const transformedStyles = transformInlineStyles(originalStyles, 'dark'); const transformedStyles = transformInlineStyles(originalStyles, 'dark');
@@ -403,7 +412,6 @@ function EmailCard({
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;') .replace(/>/g, '&gt;')
.replace(/\n/g, '<br>')
.replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">$1</a>'); .replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline">$1</a>');
return { html: htmlEscaped, isHtml: false }; return { html: htmlEscaped, isHtml: false };
} }
@@ -411,11 +419,15 @@ function EmailCard({
// Fallback to preview // Fallback to preview
if (email.preview) { if (email.preview) {
return { html: email.preview.replace(/\n/g, '<br>'), isHtml: false }; const previewHtml = email.preview
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
return { html: previewHtml, isHtml: false };
} }
return { html: "", isHtml: false }; return { html: "", isHtml: false };
}, [email, allowExternal, resolvedTheme, cidBlobUrls]); }, [email, allowExternal, resolvedTheme, emailAlwaysLightMode, cidBlobUrls]);
return ( return (
<div className={cn( <div className={cn(
@@ -513,12 +525,14 @@ function EmailCard({
<div style={{ padding: 'var(--density-card-p)' }}> <div style={{ padding: 'var(--density-card-p)' }}>
<div <div
className={cn( className={cn(
"prose prose-sm max-w-none dark:prose-invert", "prose prose-sm max-w-none",
!emailAlwaysLightMode && "dark:prose-invert",
"prose-p:my-2 prose-headings:my-3", "prose-p:my-2 prose-headings:my-3",
"prose-a:text-primary prose-a:no-underline hover:prose-a:underline", "prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
"[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2", "[&_table]:border-collapse [&_td]:p-2 [&_th]:p-2",
"[&_img]:max-w-full [&_img]:h-auto" "[&_img]:max-w-full [&_img]:h-auto"
)} )}
style={!emailContent.isHtml ? { whiteSpace: 'pre-wrap', fontFamily: 'ui-monospace, "SF Mono", Consolas, monospace', fontSize: '13px' } : undefined}
dangerouslySetInnerHTML={{ __html: emailContent.html }} dangerouslySetInnerHTML={{ __html: emailContent.html }}
/> />
</div> </div>
+15 -1
View File
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
import { Email } from "@/lib/jmap/types"; import { Email } from "@/lib/jmap/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Paperclip, Star, Circle, CheckSquare, Square } from "lucide-react"; import { Paperclip, Star, Circle, CheckSquare, Square, Reply, Forward } from "lucide-react";
import { useEmailDrag } from "@/hooks/use-email-drag"; import { useEmailDrag } from "@/hooks/use-email-drag";
import { useLongPress } from "@/hooks/use-long-press"; import { useLongPress } from "@/hooks/use-long-press";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
@@ -29,6 +29,8 @@ export function ThreadEmailItem({
}: ThreadEmailItemProps) { }: ThreadEmailItemProps) {
const isUnread = !email.keywords?.$seen; const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged; const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0]; const sender = email.from?.[0];
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore(); const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
const density = useSettingsStore((state) => state.density); const density = useSettingsStore((state) => state.density);
@@ -151,6 +153,18 @@ export function ThreadEmailItem({
{isStarred && ( {isStarred && (
<Star className="w-3 h-3 fill-amber-400 text-amber-400" /> <Star className="w-3 h-3 fill-amber-400 text-amber-400" />
)} )}
{isAnswered && !isForwarded && (
<Reply className="w-3 h-3 text-muted-foreground" />
)}
{isForwarded && !isAnswered && (
<Forward className="w-3 h-3 text-muted-foreground" />
)}
{isAnswered && isForwarded && (
<>
<Reply className="w-3 h-3 text-muted-foreground" />
<Forward className="w-3 h-3 text-muted-foreground" />
</>
)}
{email.hasAttachment && ( {email.hasAttachment && (
<Paperclip className="w-3 h-3 text-muted-foreground" /> <Paperclip className="w-3 h-3 text-muted-foreground" />
)} )}
+78 -5
View File
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
import { Email, ThreadGroup } from "@/lib/jmap/types"; import { Email, ThreadGroup } from "@/lib/jmap/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Avatar } from "@/components/ui/avatar"; import { Avatar } from "@/components/ui/avatar";
import { Paperclip, Star, Circle, ChevronRight, ChevronDown, Loader2, MessageSquare, CheckSquare, Square } from "lucide-react"; import { Paperclip, Star, Circle, ChevronRight, ChevronDown, Loader2, MessageSquare, CheckSquare, Square, Reply, Forward } from "lucide-react";
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store"; import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
import { useUIStore } from "@/stores/ui-store"; import { useUIStore } from "@/stores/ui-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
@@ -13,6 +13,7 @@ import { getThreadColorTag, getEmailColorTag } from "@/lib/thread-utils";
import { useEmailDrag } from "@/hooks/use-email-drag"; import { useEmailDrag } from "@/hooks/use-email-drag";
import { useLongPress } from "@/hooks/use-long-press"; import { useLongPress } from "@/hooks/use-long-press";
import { ThreadEmailItem } from "./thread-email-item"; import { ThreadEmailItem } from "./thread-email-item";
import { EmailHoverActions } from "./email-hover-actions";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
interface ThreadListItemProps { interface ThreadListItemProps {
@@ -25,6 +26,12 @@ interface ThreadListItemProps {
onEmailSelect: (email: Email) => void; onEmailSelect: (email: Email) => void;
onContextMenu?: (e: React.MouseEvent, email: Email) => void; onContextMenu?: (e: React.MouseEvent, email: Email) => void;
onOpenConversation?: (thread: ThreadGroup) => void; onOpenConversation?: (thread: ThreadGroup) => void;
onToggleStar?: (email: Email) => void;
onMarkAsRead?: (email: Email, read: boolean) => void;
onDelete?: (email: Email) => void;
onArchive?: (email: Email) => void;
onSetColorTag?: (emailId: string, color: string | null) => void;
onMarkAsSpam?: (email: Email) => void;
} }
interface SingleEmailItemProps { interface SingleEmailItemProps {
@@ -34,12 +41,20 @@ interface SingleEmailItemProps {
onContextMenu?: (e: React.MouseEvent, email: Email) => void; onContextMenu?: (e: React.MouseEvent, email: Email) => void;
showPreview: boolean; showPreview: boolean;
colorTag: string | null; colorTag: string | null;
onToggleStar?: () => void;
onMarkAsRead?: (read: boolean) => void;
onDelete?: () => void;
onArchive?: () => void;
onSetColorTag?: (color: string | null) => void;
onMarkAsSpam?: () => void;
} }
const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>( const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag }, ref) { function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }, ref) {
const isUnread = !email.keywords?.$seen; const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged; const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0]; const sender = email.from?.[0];
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore(); const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
const emailKeywords = useSettingsStore((state) => state.emailKeywords); const emailKeywords = useSettingsStore((state) => state.emailKeywords);
@@ -100,7 +115,7 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
{...dragHandlers} {...dragHandlers}
{...longPressHandlers} {...longPressHandlers}
className={cn( className={cn(
"relative group cursor-pointer select-none transition-all duration-200 border-b border-border", "relative group cursor-pointer select-none transition-shadow duration-200 border-b border-border overflow-hidden",
resolvedColorTag ? resolvedColorTag : ( resolvedColorTag ? resolvedColorTag : (
selected selected
? "bg-accent" ? "bg-accent"
@@ -169,6 +184,18 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
{isStarred && ( {isStarred && (
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" /> <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
)} )}
{isAnswered && !isForwarded && (
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
)}
{isForwarded && !isAnswered && (
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
)}
{isAnswered && isForwarded && (
<>
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
</>
)}
{email.hasAttachment && ( {email.hasAttachment && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" /> <Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)} )}
@@ -216,6 +243,17 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
)} )}
</div> </div>
</div> </div>
{/* Hover Quick Actions */}
<EmailHoverActions
email={email}
onToggleStar={onToggleStar}
onMarkAsRead={onMarkAsRead}
onDelete={onDelete}
onArchive={onArchive}
onSetColorTag={onSetColorTag}
onMarkAsSpam={onMarkAsSpam}
/>
</div> </div>
); );
} }
@@ -232,12 +270,18 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
onEmailSelect, onEmailSelect,
onContextMenu, onContextMenu,
onOpenConversation, onOpenConversation,
onToggleStar,
onMarkAsRead,
onDelete,
onArchive,
onSetColorTag,
onMarkAsSpam,
}, ref) { }, ref) {
const t = useTranslations('threads'); const t = useTranslations('threads');
const showPreview = useSettingsStore((state) => state.showPreview); const showPreview = useSettingsStore((state) => state.showPreview);
const density = useSettingsStore((state) => state.density); const density = useSettingsStore((state) => state.density);
const isMobile = useUIStore((state) => state.isMobile); const isMobile = useUIStore((state) => state.isMobile);
const { latestEmail, participantNames, hasUnread, hasStarred, hasAttachment, emailCount } = thread; const { latestEmail, participantNames, hasUnread, hasStarred, hasAttachment, hasAnswered, hasForwarded, emailCount } = thread;
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore(); const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
@@ -278,6 +322,12 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
onContextMenu={onContextMenu} onContextMenu={onContextMenu}
showPreview={showPreview} showPreview={showPreview}
colorTag={colorTag} colorTag={colorTag}
onToggleStar={onToggleStar ? () => onToggleStar(latestEmail) : undefined}
onMarkAsRead={onMarkAsRead ? (read) => onMarkAsRead(latestEmail, read) : undefined}
onDelete={onDelete ? () => onDelete(latestEmail) : undefined}
onArchive={onArchive ? () => onArchive(latestEmail) : undefined}
onSetColorTag={onSetColorTag ? (color) => onSetColorTag(latestEmail.id, color) : undefined}
onMarkAsSpam={onMarkAsSpam ? () => onMarkAsSpam(latestEmail) : undefined}
/> />
); );
} }
@@ -339,7 +389,7 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
{...dragHandlers} {...dragHandlers}
{...threadLongPressHandlers} {...threadLongPressHandlers}
className={cn( className={cn(
"relative group cursor-pointer select-none transition-all duration-200", "relative group cursor-pointer select-none transition-shadow duration-200 overflow-hidden",
colorTag ? colorTag : ( colorTag ? colorTag : (
isSelected isSelected
? "bg-accent" ? "bg-accent"
@@ -446,6 +496,18 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
{hasStarred && ( {hasStarred && (
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" /> <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
)} )}
{hasAnswered && !hasForwarded && (
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
)}
{hasForwarded && !hasAnswered && (
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
)}
{hasAnswered && hasForwarded && (
<>
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
</>
)}
{hasAttachment && ( {hasAttachment && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" /> <Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)} )}
@@ -493,6 +555,17 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
)} )}
</div> </div>
</div> </div>
{/* Hover Quick Actions for thread header */}
<EmailHoverActions
email={latestEmail}
onToggleStar={onToggleStar ? () => onToggleStar(latestEmail) : undefined}
onMarkAsRead={onMarkAsRead ? (read) => onMarkAsRead(latestEmail, read) : undefined}
onDelete={onDelete ? () => onDelete(latestEmail) : undefined}
onArchive={onArchive ? () => onArchive(latestEmail) : undefined}
onSetColorTag={onSetColorTag ? (color) => onSetColorTag(latestEmail.id, color) : undefined}
onMarkAsSpam={onMarkAsSpam ? () => onMarkAsSpam(latestEmail) : undefined}
/>
</div> </div>
{isExpanded && !isMobile && ( {isExpanded && !isMobile && (
+31 -8
View File
@@ -21,6 +21,7 @@ import { loadFilesSettings } from "@/components/files/files-settings-dialog";
import type { FolderLayout } from "@/components/files/files-settings-dialog"; import type { FolderLayout } from "@/components/files/files-settings-dialog";
import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar"; import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar";
import { ResizeHandle } from "@/components/layout/resize-handle"; import { ResizeHandle } from "@/components/layout/resize-handle";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
import type { FileResource } from "@/stores/file-store"; import type { FileResource } from "@/stores/file-store";
type SortKey = "name" | "size" | "modified"; type SortKey = "name" | "size" | "modified";
@@ -624,16 +625,20 @@ export function FileBrowser({
e.stopPropagation(); e.stopPropagation();
setIsDraggingOver(false); setIsDraggingOver(false);
const files = Array.from(e.dataTransfer.files); setIsUploading(true);
if (files.length > 0) { try {
setIsUploading(true); const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
try { if (files.length > 0) {
await onUploadFiles(files); if (hasDirectories) {
} finally { await onUploadFolder(files);
setIsUploading(false); } else {
await onUploadFiles(files);
}
} }
} finally {
setIsUploading(false);
} }
}, [onUploadFiles]); }, [onUploadFiles, onUploadFolder]);
const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []); const files = Array.from(e.target.files || []);
@@ -945,6 +950,16 @@ export function FileBrowser({
> >
<Upload className="w-4 h-4" /> <Upload className="w-4 h-4" />
</Button> </Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => folderInputRef.current?.click()}
title={t("upload_folder")}
disabled={isUploading}
>
<FolderUp className="w-4 h-4" />
</Button>
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
@@ -1195,6 +1210,14 @@ export function FileBrowser({
setIsUploading(false); setIsUploading(false);
} }
}} }}
onUploadFolder={async (files: File[]) => {
setIsUploading(true);
try {
await onUploadFolder(files);
} finally {
setIsUploading(false);
}
}}
onCreateFolder={() => setShowNewFolder(true)} onCreateFolder={() => setShowNewFolder(true)}
onCreateTextFile={() => setShowNewTextFile(true)} onCreateTextFile={() => setShowNewTextFile(true)}
/> />
+11 -5
View File
@@ -2,16 +2,18 @@
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Upload, FolderPlus, FilePlus } from "lucide-react"; import { Upload, FolderPlus, FilePlus, FolderUp } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
interface FileUploadAreaProps { interface FileUploadAreaProps {
onUpload: (files: File[]) => Promise<void>; onUpload: (files: File[]) => Promise<void>;
onUploadFolder?: (files: File[]) => Promise<void>;
onCreateFolder: () => void; onCreateFolder: () => void;
onCreateTextFile?: () => void; onCreateTextFile?: () => void;
} }
export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) { export function FileUploadArea({ onUpload, onUploadFolder, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
const t = useTranslations("files"); const t = useTranslations("files");
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
@@ -32,11 +34,15 @@ export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: F
e.stopPropagation(); e.stopPropagation();
setIsDragging(false); setIsDragging(false);
const files = Array.from(e.dataTransfer.files); const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
if (files.length > 0) { if (files.length > 0) {
await onUpload(files); if (hasDirectories && onUploadFolder) {
await onUploadFolder(files);
} else {
await onUpload(files);
}
} }
}, [onUpload]); }, [onUpload, onUploadFolder]);
return ( return (
<div className="flex items-center justify-center h-full p-8"> <div className="flex items-center justify-center h-full p-8">
+5 -1
View File
@@ -42,7 +42,11 @@ export function ImagePreviewModal({ name, onClose, onDownload, getImageUrl }: Im
}, [name, getImageUrl]); }, [name, getImageUrl]);
const handleKeyDown = useCallback((e: KeyboardEvent) => { const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "Escape") onClose(); if (e.key === "Escape") { onClose(); return; }
const target = e.target as HTMLElement;
const tag = target?.tagName?.toLowerCase();
if (tag === "input" || tag === "textarea" || tag === "select") return;
if (target?.getAttribute("contenteditable") === "true") return;
if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 5)); if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 5));
if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25)); if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25));
if (e.key === "r") setRotation((r) => r + 90); if (e.key === "r") setRotation((r) => r + 90);
+74 -14
View File
@@ -2,7 +2,7 @@
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from 'react';
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { X, Mail, Pencil, Trash2, Plus, AlertTriangle } from 'lucide-react'; import { X, Mail, Pencil, Trash2, Plus, AlertTriangle, Star } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog'; import { ConfirmDialog } from '@/components/ui/confirm-dialog';
@@ -19,6 +19,12 @@ import { toast } from '@/stores/toast-store';
import { useFocusTrap } from '@/hooks/use-focus-trap'; import { useFocusTrap } from '@/hooks/use-focus-trap';
import { useConfirmDialog } from '@/hooks/use-confirm-dialog'; import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
function emailMatchesUsername(email: string, username: string): boolean {
if (email === username) return true;
if (!username.includes('@') && email.split('@')[0] === username) return true;
return false;
}
interface IdentityFormData { interface IdentityFormData {
name: string; name: string;
email: string; email: string;
@@ -38,7 +44,9 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
const tNotif = useTranslations('notifications'); const tNotif = useTranslations('notifications');
const client = useAuthStore((state) => state.client); const client = useAuthStore((state) => state.client);
const { identities, addIdentity, updateIdentityLocal, removeIdentity } = useIdentityStore(); const identities = useIdentityStore((state) => state.identities);
const preferredPrimaryId = useIdentityStore((state) => state.preferredPrimaryId);
const setPreferredPrimary = useIdentityStore((state) => state.setPreferredPrimary);
const syncIdentities = useSyncIdentities(); const syncIdentities = useSyncIdentities();
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
@@ -46,6 +54,40 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
const [deletingId, setDeletingId] = useState<string | null>(null); const [deletingId, setDeletingId] = useState<string | null>(null);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog(); const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
// Re-fetch all identities from server and update stores
const refreshIdentities = useCallback(async () => {
if (!client) return;
try {
const serverIdentities = await client.getIdentities();
const username = useAuthStore.getState().username;
const preferredPrimaryId = useIdentityStore.getState().preferredPrimaryId;
const sorted = [...serverIdentities].sort((a, b) => {
const aMatch = emailMatchesUsername(a.email, username || '');
const bMatch = emailMatchesUsername(b.email, username || '');
if (aMatch && !bMatch) return -1;
if (!aMatch && bMatch) return 1;
if (aMatch && bMatch) {
if (!a.mayDelete && b.mayDelete) return -1;
if (a.mayDelete && !b.mayDelete) return 1;
}
return 0;
});
// Move preferred primary to front if set
if (preferredPrimaryId) {
const idx = sorted.findIndex((id) => id.id === preferredPrimaryId);
if (idx > 0) {
const [preferred] = sorted.splice(idx, 1);
sorted.unshift(preferred);
}
}
useIdentityStore.getState().setIdentities(sorted);
syncIdentities();
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to refresh identities';
toast.error(message);
}
}, [client, syncIdentities]);
// Focus trap with Escape handling // Focus trap with Escape handling
const modalRef = useFocusTrap({ const modalRef = useFocusTrap({
isActive: isOpen, isActive: isOpen,
@@ -60,9 +102,10 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
restoreFocus: true, restoreFocus: true,
}); });
// Close on click outside // Close on click outside (but not when ConfirmDialog is open)
useEffect(() => { useEffect(() => {
const handleClickOutside = (e: MouseEvent) => { const handleClickOutside = (e: MouseEvent) => {
if (confirmDialogProps.isOpen) return;
if (modalRef.current && !modalRef.current.contains(e.target as Node)) { if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
onClose(); onClose();
} }
@@ -72,13 +115,13 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
document.addEventListener('mousedown', handleClickOutside); document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside);
} }
}, [isOpen, onClose, modalRef]); }, [isOpen, onClose, modalRef, confirmDialogProps.isOpen]);
const handleCreate = useCallback(async (data: IdentityFormData) => { const handleCreate = useCallback(async (data: IdentityFormData) => {
if (!client) return; if (!client) return;
try { try {
const newIdentity = await client.createIdentity( await client.createIdentity(
data.name, data.name,
data.email, data.email,
data.replyTo, data.replyTo,
@@ -87,8 +130,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
data.htmlSignature data.htmlSignature
); );
addIdentity(newIdentity); await refreshIdentities();
syncIdentities();
setIsCreating(false); setIsCreating(false);
toast.success(tNotif('identity_created')); toast.success(tNotif('identity_created'));
} catch (error) { } catch (error) {
@@ -96,7 +138,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
toast.error(tNotif('identity_create_failed', { error: message })); toast.error(tNotif('identity_create_failed', { error: message }));
throw error; throw error;
} }
}, [client, addIdentity, t, tNotif]); }, [client, refreshIdentities, t, tNotif]);
const handleUpdate = useCallback(async (identity: Identity, data: IdentityFormData) => { const handleUpdate = useCallback(async (identity: Identity, data: IdentityFormData) => {
if (!client) return; if (!client) return;
@@ -110,8 +152,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
htmlSignature: data.htmlSignature, htmlSignature: data.htmlSignature,
}); });
updateIdentityLocal(identity.id, data); await refreshIdentities();
syncIdentities();
setEditingId(null); setEditingId(null);
toast.success(tNotif('identity_updated')); toast.success(tNotif('identity_updated'));
} catch (error) { } catch (error) {
@@ -119,7 +160,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
toast.error(tNotif('identity_update_failed', { error: message })); toast.error(tNotif('identity_update_failed', { error: message }));
throw error; throw error;
} }
}, [client, updateIdentityLocal, t, tNotif]); }, [client, refreshIdentities, t, tNotif]);
const handleDelete = useCallback(async (identity: Identity) => { const handleDelete = useCallback(async (identity: Identity) => {
if (!client) return; if (!client) return;
@@ -140,8 +181,7 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
try { try {
await client.deleteIdentity(identity.id); await client.deleteIdentity(identity.id);
removeIdentity(identity.id); await refreshIdentities();
syncIdentities();
toast.success(tNotif('identity_deleted')); toast.success(tNotif('identity_deleted'));
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : t('validation_errors.unknown_error'); const message = error instanceof Error ? error.message : t('validation_errors.unknown_error');
@@ -149,7 +189,16 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
} finally { } finally {
setDeletingId(null); setDeletingId(null);
} }
}, [client, removeIdentity, t, tNotif, confirmDialog]); }, [client, refreshIdentities, t, tNotif, confirmDialog]);
const handleSetPrimary = useCallback((identity: Identity) => {
setPreferredPrimary(identity.id);
// Re-sort: move the preferred identity to the front
const reordered = [identity, ...identities.filter((id) => id.id !== identity.id)];
useIdentityStore.getState().setIdentities(reordered);
syncIdentities();
toast.success(tNotif('identity_set_primary'));
}, [identities, setPreferredPrimary, syncIdentities, tNotif]);
if (!isOpen) return null; if (!isOpen) return null;
@@ -264,6 +313,17 @@ export function IdentityManagerModal({ isOpen, onClose }: IdentityManagerModalPr
{/* Actions */} {/* Actions */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{identities[0]?.id !== identity.id && identities.length > 1 && (
<Button
variant="ghost"
size="sm"
onClick={() => handleSetPrimary(identity)}
disabled={!!editingId || isCreating}
title={t('set_as_primary')}
>
<Star className="w-4 h-4" />
</Button>
)}
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
+1 -1
View File
@@ -135,7 +135,7 @@ export function SubAddressHelper({
<div <div
ref={popoverRef} ref={popoverRef}
className={cn( 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', 'bg-background border border-border rounded-lg shadow-lg',
'w-80 p-4 animate-in fade-in zoom-in-95 duration-150' 'w-80 p-4 animate-in fade-in zoom-in-95 duration-150'
)} )}
+10
View File
@@ -5,6 +5,7 @@ import { X, Keyboard } from "lucide-react";
import { KEYBOARD_SHORTCUTS } from "@/hooks/use-keyboard-shortcuts"; import { KEYBOARD_SHORTCUTS } from "@/hooks/use-keyboard-shortcuts";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useFocusTrap } from "@/hooks/use-focus-trap"; import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTour } from "@/components/tour/tour-provider";
interface KeyboardShortcutsModalProps { interface KeyboardShortcutsModalProps {
isOpen: boolean; isOpen: boolean;
@@ -13,6 +14,7 @@ interface KeyboardShortcutsModalProps {
export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsModalProps) { export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsModalProps) {
const t = useTranslations(); const t = useTranslations();
const { startTour } = useTour();
const modalRef = useFocusTrap({ const modalRef = useFocusTrap({
isActive: isOpen, isActive: isOpen,
@@ -144,6 +146,14 @@ export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsMod
<p className="text-sm text-muted-foreground text-center"> <p className="text-sm text-muted-foreground text-center">
{t("shortcuts.tip")} {t("shortcuts.tip")}
</p> </p>
<p className="text-sm text-center mt-2">
<button
onClick={() => { onClose(); startTour(); }}
className="text-primary hover:text-primary/80 underline underline-offset-2 transition-colors"
>
{t("tour.take_a_tour")}
</button>
</p>
</div> </div>
</div> </div>
</div> </div>
+269
View File
@@ -0,0 +1,269 @@
"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();
};
const handleLogoutAll = () => {
setOpen(false);
logoutAll();
};
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
)}
</>
);
}
+149
View File
@@ -0,0 +1,149 @@
'use client';
import { useState, useMemo, useRef, useEffect, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { icons as lucideIcons, type LucideIcon } from 'lucide-react';
import { Search, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Input } from '@/components/ui/input';
// Curated list of commonly useful icons, organized by category
const POPULAR_ICONS = [
// Communication
'Globe', 'Rss', 'Radio', 'Podcast', 'MessageCircle', 'MessageSquare', 'MessagesSquare',
'Phone', 'Video', 'Webcam', 'Headphones', 'Mic',
// Productivity
'FileText', 'FileSpreadsheet', 'Notebook', 'BookOpen', 'ClipboardList',
'ListTodo', 'CheckSquare', 'SquareKanban', 'Kanban', 'Trello',
'PenLine', 'Pencil', 'Edit', 'NotebookPen',
// Dev / Tech
'Code', 'Terminal', 'Braces', 'Bug', 'Database', 'Server', 'Cpu',
'HardDrive', 'Monitor', 'Laptop', 'Smartphone', 'Tablet',
'Wifi', 'Cloud', 'CloudDownload', 'CloudUpload',
// Social / People
'Users', 'UserPlus', 'UserCircle', 'Contact', 'PersonStanding',
'Heart', 'ThumbsUp', 'Star', 'Award', 'Trophy', 'Crown',
// Media
'Image', 'Camera', 'Film', 'Music', 'Play', 'Tv', 'Youtube', 'Clapperboard',
'Palette', 'Paintbrush', 'Brush',
// Navigation / Location
'Map', 'MapPin', 'Navigation', 'Compass', 'Home', 'Building', 'Building2',
'Landmark', 'Store', 'Warehouse',
// Finance
'DollarSign', 'Euro', 'CreditCard', 'Wallet', 'Receipt', 'PiggyBank',
'TrendingUp', 'BarChart', 'BarChart3', 'LineChart', 'PieChart',
// Security
'Shield', 'ShieldCheck', 'Lock', 'Unlock', 'Key', 'Fingerprint', 'Eye',
// Science / Health
'Beaker', 'Atom', 'Dna', 'Microscope', 'Stethoscope', 'HeartPulse', 'Pill',
'Syringe', 'Thermometer',
// Nature
'Sun', 'Moon', 'CloudSun', 'Snowflake', 'Zap', 'Flame',
'TreePine', 'Flower', 'Leaf', 'Mountain', 'Waves',
// Tools
'Wrench', 'Hammer', 'Scissors', 'Ruler', 'Magnet',
'Package', 'Gift', 'Box', 'Archive',
// Transport
'Car', 'Bike', 'Bus', 'Train', 'Plane', 'Ship', 'Rocket',
// Food
'Coffee', 'Wine', 'Beer', 'Pizza', 'Apple', 'Cake', 'CookingPot',
// Misc
'Gamepad2', 'Dice5', 'Puzzle', 'Sparkles', 'Wand2', 'Bot', 'BrainCircuit',
'Lightbulb', 'Bookmark', 'Flag', 'Bell', 'Clock', 'Timer',
'Link', 'ExternalLink', 'QrCode', 'Scan', 'LayoutGrid', 'Layers',
'Aperture', 'CircleDot', 'Target', 'Crosshair',
];
interface IconPickerProps {
value: string;
onChange: (iconName: string) => void;
className?: string;
}
export function IconPicker({ value, onChange, className }: IconPickerProps) {
const t = useTranslations('sidebar_apps');
const [search, setSearch] = useState('');
const [showAll, setShowAll] = useState(false);
const gridRef = useRef<HTMLDivElement>(null);
// Get all available icon names
const allIconNames = useMemo(() => {
return Object.keys(lucideIcons).filter(
k => /^[A-Z]/.test(k) && k !== 'createLucideIcon' && k !== 'Icon'
).sort();
}, []);
const filteredIcons = useMemo(() => {
const source = showAll ? allIconNames : POPULAR_ICONS.filter(name => name in lucideIcons);
if (!search.trim()) return source;
const q = search.toLowerCase();
return source.filter(name => name.toLowerCase().includes(q));
}, [search, showAll, allIconNames]);
const renderIcon = useCallback((name: string) => {
const IconComponent = lucideIcons[name as keyof typeof lucideIcons] as LucideIcon | undefined;
if (!IconComponent) return null;
return <IconComponent className="w-5 h-5" />;
}, []);
return (
<div className={cn('space-y-2', className)}>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('search_icons')}
className="pl-8 h-8 text-xs"
/>
{search && (
<button
onClick={() => setSearch('')}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="w-3 h-3" />
</button>
)}
</div>
<button
onClick={() => setShowAll(!showAll)}
className={cn(
'text-xs px-2 py-1 rounded-md border transition-colors whitespace-nowrap',
showAll
? 'bg-primary/10 text-primary border-primary/30'
: 'bg-muted text-muted-foreground border-border hover:text-foreground'
)}
>
{showAll ? t('show_popular') : t('show_all')}
</button>
</div>
<div
ref={gridRef}
className="grid grid-cols-8 gap-1 max-h-[200px] overflow-y-auto p-1 border rounded-md bg-muted/30"
>
{filteredIcons.map(name => (
<button
key={name}
type="button"
onClick={() => onChange(name)}
title={name}
className={cn(
'flex items-center justify-center w-8 h-8 rounded-md transition-colors',
value === name
? 'bg-primary text-primary-foreground'
: 'hover:bg-muted text-muted-foreground hover:text-foreground'
)}
>
{renderIcon(name)}
</button>
))}
{filteredIcons.length === 0 && (
<p className="col-span-8 py-4 text-center text-xs text-muted-foreground">
{t('no_icons_found')}
</p>
)}
</div>
</div>
);
}
+49
View File
@@ -0,0 +1,49 @@
'use client';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { InlineAppState } from '@/hooks/use-sidebar-apps';
interface InlineAppViewProps {
apps: InlineAppState[];
activeAppId: string;
onClose: () => void;
className?: string;
}
export function InlineAppView({ apps, activeAppId, onClose, className }: InlineAppViewProps) {
const activeApp = apps.find((a) => a.id === activeAppId);
return (
<div className={cn('flex flex-col h-full bg-background', className)}>
{/* Header bar */}
<div className="flex items-center justify-between px-4 py-2 border-b border-border bg-secondary/50 flex-shrink-0">
<h3 className="text-sm font-medium truncate">{activeApp?.name}</h3>
<button
onClick={onClose}
className="p-1 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
aria-label="Close"
>
<X className="w-4 h-4" />
</button>
</div>
{/* Iframes - active one visible, rest hidden but alive */}
<div className="flex-1 relative">
{apps.map((app) => (
<iframe
key={app.id}
src={app.url}
title={app.name}
className={cn(
'absolute inset-0 w-full h-full border-0',
app.id !== activeAppId && 'hidden'
)}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
referrerPolicy="no-referrer"
loading="lazy"
/>
))}
</div>
</div>
);
}
+167 -14
View File
@@ -2,12 +2,15 @@
import { useState, useRef, useEffect, useCallback } from "react"; import { useState, useRef, useEffect, useCallback } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Mail, Calendar, BookUser, HardDrive, Settings, LogOut, Keyboard } from "lucide-react"; 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 { usePathname, Link } from "@/i18n/navigation";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useCalendarStore } from "@/stores/calendar-store"; import { useCalendarStore } from "@/stores/calendar-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useWebDAVStore } from "@/stores/webdav-store"; import { useWebDAVStore } from "@/stores/webdav-store";
import { useSettingsStore } from "@/stores/settings-store";
import { cn, formatFileSize } from "@/lib/utils"; import { cn, formatFileSize } from "@/lib/utils";
interface NavItem { interface NavItem {
@@ -27,6 +30,10 @@ interface NavigationRailProps {
isPushConnected?: boolean; isPushConnected?: boolean;
onLogout?: () => void; onLogout?: () => void;
onShowShortcuts?: () => void; onShowShortcuts?: () => void;
onManageApps?: () => void;
onInlineApp?: (appId: string, url: string, name: string) => void;
onCloseInlineApp?: () => void;
activeAppId?: string | null;
} }
function StorageQuotaCircle({ quota, usagePercent }: { quota: { used: number; total: number }; usagePercent: number }) { function StorageQuotaCircle({ quota, usagePercent }: { quota: { used: number; total: number }; usagePercent: number }) {
@@ -138,12 +145,17 @@ export function NavigationRail({
isPushConnected, isPushConnected,
onLogout, onLogout,
onShowShortcuts, onShowShortcuts,
onManageApps,
onInlineApp,
onCloseInlineApp,
activeAppId,
}: NavigationRailProps) { }: NavigationRailProps) {
const t = useTranslations("sidebar"); const t = useTranslations("sidebar");
const pathname = usePathname(); const pathname = usePathname();
const { supportsCalendar } = useCalendarStore(); const { supportsCalendar } = useCalendarStore();
const { mailboxes } = useEmailStore(); const { mailboxes } = useEmailStore();
const { supportsWebDAV } = useWebDAVStore(); const { supportsWebDAV } = useWebDAVStore();
const sidebarApps = useSettingsStore((s) => s.sidebarApps);
const inboxUnread = mailboxes.find(m => m.role === "inbox")?.unreadEmails || 0; const inboxUnread = mailboxes.find(m => m.role === "inbox")?.unreadEmails || 0;
const navItems: NavItem[] = [ const navItems: NavItem[] = [
@@ -151,12 +163,14 @@ export function NavigationRail({
{ id: "calendar", icon: Calendar, labelKey: "calendar", href: "/calendar", hidden: !supportsCalendar }, { id: "calendar", icon: Calendar, labelKey: "calendar", href: "/calendar", hidden: !supportsCalendar },
{ id: "contacts", icon: BookUser, labelKey: "contacts", href: "/contacts" }, { id: "contacts", icon: BookUser, labelKey: "contacts", href: "/contacts" },
{ id: "files", icon: HardDrive, labelKey: "files", href: "/files", hidden: supportsWebDAV === false }, { id: "files", icon: HardDrive, labelKey: "files", href: "/files", hidden: supportsWebDAV === false },
{ id: "settings", icon: Settings, labelKey: "settings", href: "/settings" },
]; ];
const isSettingsActive = !activeAppId && pathname.startsWith("/settings");
const visibleItems = navItems.filter((item) => !item.hidden); const visibleItems = navItems.filter((item) => !item.hidden);
const getIsActive = (href: string) => { const getIsActive = (href: string) => {
if (activeAppId) return false;
if (href === "/") { if (href === "/") {
return pathname === "/" || pathname === ""; return pathname === "/" || pathname === "";
} }
@@ -177,6 +191,7 @@ export function NavigationRail({
<Link <Link
key={item.id} key={item.id}
href={item.href} href={item.href}
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
className={cn( className={cn(
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]", "flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
"transition-colors duration-150", "transition-colors duration-150",
@@ -201,6 +216,63 @@ export function NavigationRail({
</Link> </Link>
); );
})} })}
{/* 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 (
<button
key={app.id}
onClick={() => {
if (isActive) {
onCloseInlineApp?.();
} else if (app.openMode === 'tab') {
window.open(app.url, '_blank', 'noopener,noreferrer');
} else {
onInlineApp?.(app.id, app.url, app.name);
}
}}
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",
isActive
? "text-primary"
: "text-muted-foreground hover:text-foreground"
)}
>
<div className="relative">
{AppIcon ? <AppIcon className="w-5 h-5" /> : null}
{isActive && (
<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 truncate max-w-[64px]">{app.name}</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> </nav>
); );
} }
@@ -230,6 +302,8 @@ export function NavigationRail({
<Link <Link
key={item.id} key={item.id}
href={item.href} href={item.href}
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
data-tour={`nav-${item.id}`}
className={cn( className={cn(
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150", "relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
collapsed collapsed
@@ -257,17 +331,96 @@ export function NavigationRail({
</Link> </Link>
); );
})} })}
{/* Custom sidebar apps */}
{sidebarApps.length > 0 && (
<div
className={cn(
"border-t",
collapsed ? "w-8 mx-auto my-1 pt-1" : "mx-2 my-0.5 pt-0.5"
)}
style={{ borderColor: 'rgba(128, 128, 128, 0.3)' }}
/>
)}
{sidebarApps.map((app) => {
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
const isActive = activeAppId === app.id;
return (
<button
key={app.id}
onClick={() => {
if (isActive) {
onCloseInlineApp?.();
} else if (app.openMode === 'tab') {
window.open(app.url, '_blank', 'noopener,noreferrer');
} else {
onInlineApp?.(app.id, app.url, app.name);
}
}}
className={cn(
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
collapsed
? "justify-center w-10 h-10"
: "px-2.5 text-sm",
"max-lg:min-h-[44px]",
isActive
? "bg-primary/10 text-primary font-medium"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
)}
title={collapsed ? app.name : undefined}
style={collapsed ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
>
{AppIcon ? <AppIcon className={cn("w-[18px] h-[18px] flex-shrink-0", isActive && "text-primary")} /> : null}
{!collapsed && <span className="truncate">{app.name}</span>}
</button>
);
})}
{/* Manage apps button */}
{onManageApps && (
<button
onClick={onManageApps}
className={cn(
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
collapsed
? "justify-center w-10 h-10"
: "px-2.5 text-sm",
"max-lg:min-h-[44px]",
"text-muted-foreground hover:bg-muted hover:text-foreground"
)}
title={collapsed ? t("add_app") : undefined}
style={collapsed ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
>
<Plus className="w-[18px] h-[18px] flex-shrink-0" />
{!collapsed && <span className="truncate">{t("add_app")}</span>}
</button>
)}
</nav> </nav>
{/* Footer: Storage Quota + Sign Out + Push Status */} {/* Footer: Settings + Help + Storage Quota + Sign Out + Push Status */}
<div className="mt-auto flex flex-col items-center gap-2 pb-3 px-1 border-t border-border pt-2"> <div className="mt-auto flex flex-col items-center gap-2 pb-3 px-1">
{quota && quota.total > 0 && ( <Link
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} /> href="/settings"
)} onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
data-tour="nav-settings"
className={cn(
"flex items-center justify-center w-10 h-10 rounded-md transition-colors",
isSettingsActive
? "bg-primary/10 text-primary"
: "text-muted-foreground hover:text-foreground hover:bg-muted"
)}
title={t("settings")}
aria-current={isSettingsActive ? "page" : undefined}
>
<Settings className="w-[18px] h-[18px]" />
</Link>
<div className="w-8 border-t" style={{ borderColor: 'rgba(128, 128, 128, 0.3)' }} />
{onShowShortcuts && ( {onShowShortcuts && (
<button <button
onClick={onShowShortcuts} onClick={onShowShortcuts}
data-tour="nav-shortcuts"
className="flex items-center justify-center w-10 h-10 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors" 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("keyboard_shortcuts")} title={t("keyboard_shortcuts")}
> >
@@ -275,6 +428,12 @@ export function NavigationRail({
</button> </button>
)} )}
{quota && quota.total > 0 && (
<div data-tour="storage-quota">
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} />
</div>
)}
{isPushConnected != null && ( {isPushConnected != null && (
<span <span
className="relative group" className="relative group"
@@ -290,13 +449,7 @@ export function NavigationRail({
)} )}
{onLogout && ( {onLogout && (
<button <AccountSwitcher variant="rail" />
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>
)} )}
</div> </div>
</div> </div>
+357
View File
@@ -0,0 +1,357 @@
'use client';
import { useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { X, Plus, Pencil, Trash2, GripVertical, ExternalLink, PanelRight } from 'lucide-react';
import { icons as lucideIcons, type LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { IconPicker } from './icon-picker';
import { useSettingsStore, type SidebarApp } from '@/stores/settings-store';
import { useFocusTrap } from '@/hooks/use-focus-trap';
import { useConfirmDialog } from '@/hooks/use-confirm-dialog';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
interface SidebarAppFormData {
name: string;
url: string;
icon: string;
openMode: 'tab' | 'inline';
showOnMobile: boolean;
}
function SidebarAppForm({
app,
onSave,
onCancel,
}: {
app?: SidebarApp;
onSave: (data: SidebarAppFormData) => void;
onCancel: () => void;
}) {
const t = useTranslations('sidebar_apps');
const isEditing = !!app;
const [formData, setFormData] = useState<SidebarAppFormData>({
name: app?.name || '',
url: app?.url || '',
icon: app?.icon || 'Globe',
openMode: app?.openMode || 'tab',
showOnMobile: app?.showOnMobile ?? false,
});
const [errors, setErrors] = useState<Record<string, string>>({});
const validate = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) {
newErrors.name = t('name_required');
}
if (!formData.url.trim()) {
newErrors.url = t('url_required');
} else {
try {
const parsed = new URL(formData.url);
if (!['http:', 'https:'].includes(parsed.protocol)) {
newErrors.url = t('url_invalid');
}
} catch {
newErrors.url = t('url_invalid');
}
}
if (!formData.icon) {
newErrors.icon = t('icon_required');
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!validate()) return;
onSave(formData);
};
const SelectedIcon = formData.icon
? (lucideIcons[formData.icon as keyof typeof lucideIcons] as LucideIcon | undefined)
: null;
return (
<form onSubmit={handleSubmit} className="space-y-4">
{/* Name */}
<div>
<label htmlFor="app-name" className="block text-sm font-medium mb-1">
{t('name_label')} <span className="text-destructive">*</span>
</label>
<Input
id="app-name"
type="text"
maxLength={50}
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder={t('name_placeholder')}
className={errors.name ? 'border-destructive' : ''}
/>
{errors.name && (
<p className="text-sm text-destructive mt-1">{errors.name}</p>
)}
</div>
{/* URL */}
<div>
<label htmlFor="app-url" className="block text-sm font-medium mb-1">
{t('url_label')} <span className="text-destructive">*</span>
</label>
<Input
id="app-url"
type="url"
maxLength={2048}
value={formData.url}
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
placeholder="https://example.com"
className={errors.url ? 'border-destructive' : ''}
/>
{errors.url && (
<p className="text-sm text-destructive mt-1">{errors.url}</p>
)}
</div>
{/* Open Mode */}
<div>
<label className="block text-sm font-medium mb-2">{t('open_mode_label')}</label>
<div className="flex gap-2">
<button
type="button"
onClick={() => setFormData({ ...formData, openMode: 'tab' })}
className={cn(
'flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors flex-1',
formData.openMode === 'tab'
? 'bg-primary/10 border-primary/30 text-primary'
: 'border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground'
)}
>
<ExternalLink className="w-4 h-4" />
{t('open_new_tab')}
</button>
<button
type="button"
onClick={() => setFormData({ ...formData, openMode: 'inline' })}
className={cn(
'flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors flex-1',
formData.openMode === 'inline'
? 'bg-primary/10 border-primary/30 text-primary'
: 'border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground'
)}
>
<PanelRight className="w-4 h-4" />
{t('open_inline')}
</button>
</div>
</div>
{/* Icon Picker */}
<div>
<label className="block text-sm font-medium mb-2">
{t('icon_label')} <span className="text-destructive">*</span>
{SelectedIcon && (
<span className="inline-flex items-center gap-1.5 ml-2 text-muted-foreground font-normal">
<SelectedIcon className="w-4 h-4" /> {formData.icon}
</span>
)}
</label>
<IconPicker
value={formData.icon}
onChange={(icon) => setFormData({ ...formData, icon })}
/>
{errors.icon && (
<p className="text-sm text-destructive mt-1">{errors.icon}</p>
)}
</div>
{/* Actions */}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onCancel}>
{t('cancel')}
</Button>
<Button type="submit">
{isEditing ? t('update') : t('add')}
</Button>
</div>
</form>
);
}
interface SidebarAppsModalProps {
isOpen: boolean;
onClose: () => void;
}
export function SidebarAppsModal({ isOpen, onClose }: SidebarAppsModalProps) {
const t = useTranslations('sidebar_apps');
const { sidebarApps, addSidebarApp, updateSidebarApp, removeSidebarApp } = useSettingsStore();
const [editingId, setEditingId] = useState<string | null>(null);
const [isCreating, setIsCreating] = useState(false);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
const modalRef = useFocusTrap({
isActive: isOpen,
onEscape: () => {
if (isCreating || editingId) {
setIsCreating(false);
setEditingId(null);
} else {
onClose();
}
},
restoreFocus: true,
});
const handleCreate = useCallback((data: SidebarAppFormData) => {
const id = `app-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
addSidebarApp({ id, ...data });
setIsCreating(false);
}, [addSidebarApp]);
const handleUpdate = useCallback((id: string, data: SidebarAppFormData) => {
updateSidebarApp(id, data);
setEditingId(null);
}, [updateSidebarApp]);
const handleDelete = useCallback(async (app: SidebarApp) => {
const confirmed = await confirmDialog({
title: t('delete_confirm_title'),
message: t('delete_confirm', { name: app.name }),
confirmText: t('delete'),
variant: 'destructive',
});
if (!confirmed) return;
removeSidebarApp(app.id);
}, [removeSidebarApp, confirmDialog, t]);
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-50 p-4 animate-in fade-in duration-150">
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby="sidebar-apps-modal-title"
className={cn(
'bg-background border border-border rounded-lg shadow-xl',
'w-full max-w-2xl max-h-[90vh] overflow-hidden',
'animate-in zoom-in-95 duration-200'
)}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
<h2 id="sidebar-apps-modal-title" className="text-lg font-semibold text-foreground">
{t('modal_title')}
</h2>
<button
onClick={onClose}
className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground hover:text-foreground"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 overflow-y-auto max-h-[calc(90vh-80px)]">
{/* Create form */}
{isCreating && (
<div className="mb-6 p-4 border border-border rounded-lg bg-muted/30">
<h3 className="text-sm font-semibold mb-4">{t('add_new')}</h3>
<SidebarAppForm
onSave={handleCreate}
onCancel={() => setIsCreating(false)}
/>
</div>
)}
{/* Add button */}
{!isCreating && !editingId && (
<Button
onClick={() => setIsCreating(true)}
className="mb-6 w-full sm:w-auto"
>
<Plus className="w-4 h-4 mr-2" />
{t('add_new')}
</Button>
)}
{/* Apps list */}
<div className="space-y-3">
{sidebarApps.map((app) => {
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
if (editingId === app.id) {
return (
<div key={app.id} className="p-4 border border-border rounded-lg bg-muted/30">
<h3 className="text-sm font-semibold mb-4">{t('edit_app')}</h3>
<SidebarAppForm
app={app}
onSave={(data) => handleUpdate(app.id, data)}
onCancel={() => setEditingId(null)}
/>
</div>
);
}
return (
<div
key={app.id}
className="flex items-center gap-3 p-3 border border-border rounded-lg"
>
<div className="flex items-center justify-center w-9 h-9 rounded-md bg-muted">
{AppIcon ? <AppIcon className="w-5 h-5 text-muted-foreground" /> : null}
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{app.name}</p>
<p className="text-xs text-muted-foreground truncate">{app.url}</p>
</div>
<span className={cn(
'text-[10px] px-1.5 py-0.5 rounded-full font-medium',
app.openMode === 'inline'
? 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-400'
: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400'
)}>
{app.openMode === 'inline' ? t('inline_badge') : t('tab_badge')}
</span>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => setEditingId(app.id)}
disabled={!!editingId || isCreating}
>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(app)}
disabled={!!editingId || isCreating}
>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
</div>
</div>
);
})}
{sidebarApps.length === 0 && !isCreating && (
<div className="text-center py-12 text-muted-foreground">
<Plus className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p className="text-sm">{t('no_apps')}</p>
<p className="text-xs mt-1">{t('no_apps_hint')}</p>
</div>
)}
</div>
</div>
</div>
<ConfirmDialog {...confirmDialogProps} />
</div>
);
}
+95 -16
View File
@@ -24,6 +24,10 @@ import {
Settings, Settings,
X, X,
Tag, Tag,
RotateCcw,
FlaskConical,
PlayCircle,
Loader2,
} from "lucide-react"; } from "lucide-react";
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils"; import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
import { Mailbox } from "@/lib/jmap/types"; import { Mailbox } from "@/lib/jmap/types";
@@ -37,6 +41,10 @@ import { useSettingsStore, KEYWORD_PALETTE, KeywordDefinition } from "@/stores/s
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import { debug } from "@/lib/debug"; import { debug } from "@/lib/debug";
import { useConfig } from "@/hooks/use-config";
import { useThemeStore } from "@/stores/theme-store";
import { AccountSwitcher } from "./account-switcher";
import { useTour } from "@/components/tour/tour-provider";
interface SidebarProps { interface SidebarProps {
mailboxes: Mailbox[]; mailboxes: Mailbox[];
@@ -325,6 +333,68 @@ function TagItem({
); );
} }
function DemoBanner() {
const t = useTranslations('sidebar');
const { isDemoMode, loginDemo } = useAuthStore();
const { startTour, resetTourCompletion } = useTour();
const router = useRouter();
const [isResetting, setIsResetting] = useState(false);
if (!isDemoMode) return null;
const handleReset = async () => {
setIsResetting(true);
// Navigate to home first so the mail page re-fetches data
router.push('/');
await loginDemo();
setIsResetting(false);
};
const handleStartTour = () => {
resetTourCompletion();
router.push('/');
setTimeout(() => startTour(), 100);
};
return (
<div
data-tour="demo-banner"
className={cn(
"flex flex-col gap-1.5 w-full px-3 py-2 text-xs",
"bg-primary/10 dark:bg-primary/10 text-primary",
)}
>
<div className="flex items-center gap-2">
<FlaskConical className="w-3.5 h-3.5 flex-shrink-0" />
<span className="truncate font-medium">{t("demo_banner")}</span>
</div>
<div className="flex items-center gap-1.5">
<button
onClick={handleStartTour}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 hover:bg-primary/20 transition-colors"
title={t("demo_tour")}
>
<PlayCircle className="w-3 h-3" />
{t("demo_tour")}
</button>
<button
onClick={handleReset}
disabled={isResetting}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 hover:bg-primary/20 transition-colors disabled:opacity-50"
title={t("demo_reset")}
>
{isResetting ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<RotateCcw className="w-3 h-3" />
)}
{t("demo_reset")}
</button>
</div>
</div>
);
}
function VacationBanner() { function VacationBanner() {
const t = useTranslations('sidebar'); const t = useTranslations('sidebar');
const router = useRouter(); const router = useRouter();
@@ -361,6 +431,8 @@ export function Sidebar({
}: SidebarProps) { }: SidebarProps) {
const { sidebarCollapsed: isCollapsed, toggleSidebarCollapsed } = useUIStore(); const { sidebarCollapsed: isCollapsed, toggleSidebarCollapsed } = useUIStore();
const { primaryIdentity } = useAuthStore(); const { primaryIdentity } = useAuthStore();
const { appLogoLightUrl, appLogoDarkUrl } = useConfig();
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set()); const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [tagsExpanded, setTagsExpanded] = useState(() => { const [tagsExpanded, setTagsExpanded] = useState(() => {
try { try {
@@ -449,44 +521,51 @@ export function Sidebar({
)} )}
> >
{/* Header */} {/* Header */}
<div className={cn("flex items-center border-b border-border", isCollapsed ? "justify-center px-2 py-3" : "gap-2 px-4 py-3")}> <div className={cn("flex items-center border-b border-border", isCollapsed ? "justify-center px-2 py-2" : "gap-1 px-2 py-2")}>
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={onSidebarClose} onClick={onSidebarClose}
className="lg:hidden h-11 w-11 flex-shrink-0" className="lg:hidden h-9 w-9 flex-shrink-0"
aria-label={t("close")} aria-label={t("close")}
> >
<X className="w-5 h-5" /> <X className="w-5 h-5" />
</Button> </Button>
{(() => {
const logoUrl = resolvedTheme === 'dark' ? (appLogoDarkUrl || appLogoLightUrl) : (appLogoLightUrl || appLogoDarkUrl);
return logoUrl ? (
<img
src={logoUrl}
alt=""
className={cn("object-contain flex-shrink-0", isCollapsed ? "w-6 h-6" : "w-6 h-6")}
/>
) : null;
})()}
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={toggleSidebarCollapsed} onClick={toggleSidebarCollapsed}
className="hidden lg:flex flex-shrink-0" className="hidden lg:flex h-8 w-8 flex-shrink-0"
title={isCollapsed ? t("expand_tooltip") : t("collapse_tooltip")} title={isCollapsed ? t("expand_tooltip") : t("collapse_tooltip")}
> >
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />} {isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
</Button> </Button>
{!isCollapsed && primaryIdentity && ( {!isCollapsed && (
<div className="min-w-0"> <AccountSwitcher variant="expanded" className="flex-1" />
<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>
)} )}
</div> </div>
{/* Demo Banner */}
{!isCollapsed && <DemoBanner />}
{/* Vacation Banner */} {/* Vacation Banner */}
{!isCollapsed && <VacationBanner />} {!isCollapsed && <VacationBanner />}
{/* Mailbox List */} {/* Mailbox List */}
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto" data-tour="sidebar">
<div className="py-1"> <div className="py-1">
{mailboxes.length === 0 ? ( {mailboxes.length === 0 ? (
<div className="px-4 py-2 text-sm text-muted-foreground"> <div className="px-4 py-2 text-sm text-muted-foreground">
@@ -573,7 +652,7 @@ export function Sidebar({
</div> </div>
{((tagsExpanded && !isCollapsed) || isCollapsed) && ( {((tagsExpanded && !isCollapsed) || isCollapsed) && (
<div className="relative"> <div className="relative" data-tour="keyword-tags">
{emailKeywords.map((kw) => { {emailKeywords.map((kw) => {
const isSelected = selectedKeyword === kw.id; const isSelected = selectedKeyword === kw.id;
return ( return (
@@ -597,11 +676,11 @@ export function Sidebar({
{/* Compose Button */} {/* Compose Button */}
<div className={cn("border-t border-border", isCollapsed ? "flex justify-center py-3" : "px-3 py-3")}> <div className={cn("border-t border-border", isCollapsed ? "flex justify-center py-3" : "px-3 py-3")}>
{isCollapsed ? ( {isCollapsed ? (
<Button onClick={onCompose} variant="ghost" size="icon" title={t("compose_hint")}> <Button onClick={onCompose} variant="ghost" size="icon" title={t("compose_hint")} data-tour="compose-button">
<PenSquare className="w-5 h-5" /> <PenSquare className="w-5 h-5" />
</Button> </Button>
) : ( ) : (
<Button onClick={onCompose} className="w-full" title={t("compose_hint")}> <Button onClick={onCompose} className="w-full" title={t("compose_hint")} data-tour="compose-button">
<PenSquare className="w-4 h-4 mr-2" /> <PenSquare className="w-4 h-4 mr-2" />
{t("compose")} {t("compose")}
</Button> </Button>
@@ -0,0 +1,35 @@
"use client";
import { useEffect } from "react";
import { isEmbedded, listenFromParent } from "@/lib/iframe-bridge";
import { getPathPrefix, getLocaleFromPath } from "@/lib/browser-navigation";
import { useAuthStore } from "@/stores/auth-store";
import { useConfig } from "@/hooks/use-config";
export function EmbeddedBridgeProvider({ children }: { children: React.ReactNode }) {
const { parentOrigin, embeddedMode } = useConfig();
const logout = useAuthStore((s) => s.logout);
useEffect(() => {
if (!embeddedMode || !isEmbedded()) return;
const unsubscribe = listenFromParent((msg) => {
switch (msg.type) {
case "sso:trigger-login": {
// Navigate to login page to start SSO flow
const prefix = getPathPrefix();
const locale = getLocaleFromPath();
window.location.href = `${prefix}/${locale}/login`;
break;
}
case "sso:trigger-logout":
logout();
break;
}
}, parentOrigin || undefined);
return unsubscribe;
}, [embeddedMode, parentOrigin, logout]);
return <>{children}</>;
}
+35 -2
View File
@@ -3,21 +3,44 @@
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store'; import { useEmailStore } from '@/stores/email-store';
import { useAccountStore } from '@/stores/account-store';
import { SettingsSection, SettingItem } from './settings-section'; import { SettingsSection, SettingItem } from './settings-section';
import { formatFileSize } from '@/lib/utils'; import { formatFileSize } from '@/lib/utils';
export function AccountSettings() { export function AccountSettings() {
const t = useTranslations('settings.account'); const t = useTranslations('settings.account');
const { username, serverUrl } = useAuthStore(); const { username, serverUrl, isDemoMode, primaryIdentity, authMode, activeAccountId } = useAuthStore();
const { quota } = useEmailStore(); const { quota } = useEmailStore();
const account = useAccountStore((s) => activeAccountId ? s.getAccountById(activeAccountId) : undefined);
const quotaPercentage = quota ? Math.round((quota.used / quota.total) * 100) : 0; const quotaPercentage = quota ? Math.round((quota.used / quota.total) * 100) : 0;
const displayName = primaryIdentity?.name || account?.displayName || (isDemoMode ? 'Demo User' : undefined);
const email = primaryIdentity?.email || account?.email || username;
return ( return (
<SettingsSection title={t('title')} description={t('description')}> <SettingsSection title={t('title')} description={t('description')}>
{/* Display Name */}
<SettingItem label={t('name_label')}>
<span className="text-sm text-foreground">{displayName || t('../../common.unknown')}</span>
</SettingItem>
{/* Email Address */} {/* Email Address */}
<SettingItem label={t('email.label')}> <SettingItem label={t('email.label')}>
<span className="text-sm text-foreground">{username || t('../../common.unknown')}</span> <span className="text-sm text-foreground">{email || t('../../common.unknown')}</span>
</SettingItem>
{/* Username / Login (show when it differs from email) */}
{username && username !== email && (
<SettingItem label={t('username_label')}>
<span className="text-sm text-foreground">{username}</span>
</SettingItem>
)}
{/* Authentication Method */}
<SettingItem label={t('auth_method_label')}>
<span className="text-sm text-foreground">
{authMode === 'oauth' ? t('auth_method_oauth') : t('auth_method_basic')}
</span>
</SettingItem> </SettingItem>
{/* Server */} {/* Server */}
@@ -49,6 +72,16 @@ export function AccountSettings() {
</div> </div>
</SettingItem> </SettingItem>
)} )}
{/* Demo mode indicator */}
{isDemoMode && (
<SettingItem label={t('account_type_label')}>
<span className="inline-flex items-center gap-1.5 text-sm font-medium text-amber-600 dark:text-amber-400">
<span className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" />
{t('demo_account')}
</span>
</SettingItem>
)}
</SettingsSection> </SettingsSection>
); );
} }
@@ -6,6 +6,9 @@ import { useSettingsStore, type ToolbarPosition, type Density } from '@/stores/s
import { LanguageSwitcher } from '@/components/ui/language-switcher'; import { LanguageSwitcher } from '@/components/ui/language-switcher';
import { SettingsSection, SettingItem, RadioGroup, ToggleSwitch } from './settings-section'; import { SettingsSection, SettingItem, RadioGroup, ToggleSwitch } from './settings-section';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useTour } from '@/components/tour/tour-provider';
import { Button } from '@/components/ui/button';
import { PlayCircle } from 'lucide-react';
const DENSITY_PREVIEW: Record<Density, { py: string; gap: string; showAvatar: boolean; showPreview: boolean }> = { const DENSITY_PREVIEW: Record<Density, { py: string; gap: string; showAvatar: boolean; showPreview: boolean }> = {
'extra-compact': { py: 'py-0.5', gap: 'gap-1.5', showAvatar: false, showPreview: false }, 'extra-compact': { py: 'py-0.5', gap: 'gap-1.5', showAvatar: false, showPreview: false },
@@ -61,8 +64,10 @@ function DensityPreview({ density }: { density: Density }) {
export function AppearanceSettings() { export function AppearanceSettings() {
const t = useTranslations('settings.appearance'); const t = useTranslations('settings.appearance');
const tTour = useTranslations('tour');
const { theme, setTheme } = useThemeStore(); const { theme, setTheme } = useThemeStore();
const { fontSize, density, animationsEnabled, toolbarPosition, showToolbarLabels, updateSetting } = useSettingsStore(); const { fontSize, density, animationsEnabled, toolbarPosition, showToolbarLabels, updateSetting } = useSettingsStore();
const { startTour, resetTourCompletion } = useTour();
return ( return (
<SettingsSection title={t('title')} description={t('description')}> <SettingsSection title={t('title')} description={t('description')}>
@@ -141,6 +146,19 @@ export function AppearanceSettings() {
onChange={(checked) => updateSetting('animationsEnabled', checked)} onChange={(checked) => updateSetting('animationsEnabled', checked)}
/> />
</SettingItem> </SettingItem>
{/* Restart Tour */}
<SettingItem label={tTour('restart_title')} description={tTour('restart_desc')}>
<Button
variant="outline"
size="sm"
onClick={() => { resetTourCompletion(); startTour(); }}
className="text-xs h-7"
>
<PlayCircle className="w-3.5 h-3.5 mr-1" />
{tTour('restart_button')}
</Button>
</SettingItem>
</SettingsSection> </SettingsSection>
); );
} }
@@ -7,9 +7,10 @@ import { useAuthStore } from '@/stores/auth-store';
import { toast } from '@/stores/toast-store'; import { toast } from '@/stores/toast-store';
import { SettingsSection } from './settings-section'; import { SettingsSection } from './settings-section';
import { Plus, Pencil, Trash2, Check, X, Calendar as CalendarIcon, Copy, Link, Upload, Globe, RefreshCw, Eraser } from 'lucide-react'; import { Plus, Pencil, Trash2, Check, X, Calendar as CalendarIcon, Copy, Link, Upload, Globe, RefreshCw, Eraser } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn, formatDateTime } from '@/lib/utils';
import { ICalImportModal } from '@/components/calendar/ical-import-modal'; import { ICalImportModal } from '@/components/calendar/ical-import-modal';
import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal'; import { ICalSubscriptionModal } from '@/components/calendar/ical-subscription-modal';
import { useSettingsStore } from '@/stores/settings-store';
const CALENDAR_COLORS = [ const CALENDAR_COLORS = [
"#3b82f6", // blue "#3b82f6", // blue
@@ -152,6 +153,9 @@ export function CalendarManagementSettings() {
const { client, serverUrl, username } = useAuthStore(); const { client, serverUrl, username } = useAuthStore();
const { calendars, updateCalendar, createCalendar, removeCalendar, clearCalendarEvents, fetchCalendars, icalSubscriptions, removeICalSubscription, refreshICalSubscription, isSubscriptionCalendar } = useCalendarStore(); 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 [isCreating, setIsCreating] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null); const [deletingId, setDeletingId] = useState<string | null>(null);
@@ -164,6 +168,7 @@ export function CalendarManagementSettings() {
const [refreshingSubId, setRefreshingSubId] = useState<string | null>(null); const [refreshingSubId, setRefreshingSubId] = useState<string | null>(null);
const tImport = useTranslations('calendar.import'); const tImport = useTranslations('calendar.import');
const tSub = useTranslations('calendar.subscription'); const tSub = useTranslations('calendar.subscription');
const timeFormat = useSettingsStore((s) => s.timeFormat);
const colorPickerRef = useRef<HTMLDivElement>(null); const colorPickerRef = useRef<HTMLDivElement>(null);
// Load calendars if not yet loaded // Load calendars if not yet loaded
@@ -173,6 +178,60 @@ export function CalendarManagementSettings() {
} }
}, [client, calendars.length, fetchCalendars]); }, [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) => { const handleRefreshSubscription = async (subId: string) => {
if (!client) return; if (!client) return;
setRefreshingSubId(subId); setRefreshingSubId(subId);
@@ -293,8 +352,10 @@ export function CalendarManagementSettings() {
const buildCalDavUrl = (calendarId: string) => { const buildCalDavUrl = (calendarId: string) => {
if (!serverUrl || !username) return null; if (!serverUrl || !username) return null;
const base = serverUrl.replace(/\/$/, ''); const calendar = calendars.find((entry) => entry.id === calendarId);
return `${base}/dav/calendars/user/${encodeURIComponent(username)}/${encodeURIComponent(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) => { const handleCopyUrl = async (url: string) => {
@@ -563,7 +624,7 @@ export function CalendarManagementSettings() {
</span> </span>
{sub.lastRefreshed && ( {sub.lastRefreshed && (
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{tSub('last_refreshed', { time: new Date(sub.lastRefreshed).toLocaleString() })} {tSub('last_refreshed', { time: formatDateTime(sub.lastRefreshed, timeFormat, { month: 'short', day: 'numeric', year: 'numeric' }) })}
</span> </span>
)} )}
</div> </div>
+28 -16
View File
@@ -14,9 +14,10 @@ export function CalendarSettings() {
const { const {
timeFormat, timeFormat,
firstDayOfWeek, firstDayOfWeek,
calendarNotificationsEnabled, showTimeInMonthView,
calendarNotificationSound, showWeekNumbers,
calendarInvitationParsingEnabled, enableCalendarTasks,
showTasksOnCalendar,
updateSetting, updateSetting,
} = useSettingsStore(); } = useSettingsStore();
@@ -58,36 +59,47 @@ export function CalendarSettings() {
</SettingItem> </SettingItem>
<SettingItem <SettingItem
label={t('notifications_enabled')} label={t('show_time_in_month_view')}
description={t('notifications_enabled_desc')} description={t('show_time_in_month_view_desc')}
> >
<ToggleSwitch <ToggleSwitch
checked={calendarNotificationsEnabled} checked={showTimeInMonthView}
onChange={(checked) => updateSetting('calendarNotificationsEnabled', checked)} onChange={(checked) => updateSetting('showTimeInMonthView', checked)}
/> />
</SettingItem> </SettingItem>
<SettingItem <SettingItem
label={t('notification_sound')} label={t('show_week_numbers')}
description={t('notification_sound_desc')} description={t('show_week_numbers_desc')}
> >
<ToggleSwitch <ToggleSwitch
checked={calendarNotificationSound} checked={showWeekNumbers}
onChange={(checked) => updateSetting('calendarNotificationSound', checked)} onChange={(checked) => updateSetting('showWeekNumbers', checked)}
disabled={!calendarNotificationsEnabled}
/> />
</SettingItem> </SettingItem>
<SettingItem <SettingItem
label={t('invitation_parsing')} label={t('enable_tasks')}
description={t('invitation_parsing_desc')} description={t('enable_tasks_desc')}
> >
<ToggleSwitch <ToggleSwitch
checked={calendarInvitationParsingEnabled} checked={enableCalendarTasks}
onChange={(checked) => updateSetting('calendarInvitationParsingEnabled', checked)} onChange={(checked) => updateSetting('enableCalendarTasks', checked)}
/> />
</SettingItem> </SettingItem>
{enableCalendarTasks && (
<SettingItem
label={t('show_tasks_on_calendar')}
description={t('show_tasks_on_calendar_desc')}
>
<ToggleSwitch
checked={showTasksOnCalendar}
onChange={(checked) => updateSetting('showTasksOnCalendar', checked)}
/>
</SettingItem>
)}
</SettingsSection> </SettingsSection>
); );
} }
+196 -2
View File
@@ -1,15 +1,36 @@
"use client"; "use client";
import { useState } from 'react'; import { useState, useCallback } from 'react';
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { useConfig } from '@/hooks/use-config';
import { useSettingsStore } from '@/stores/settings-store'; import { useSettingsStore } from '@/stores/settings-store';
import type { ArchiveMode, HoverAction } from '@/stores/settings-store';
import { ALL_HOVER_ACTIONS } from '@/stores/settings-store';
import { useAuthStore } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
import { cn } from '@/lib/utils';
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section'; import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
import { TrustedSendersModal } from '@/components/trusted-senders-modal'; import { TrustedSendersModal } from '@/components/trusted-senders-modal';
import { ChevronRight, AlertTriangle } from 'lucide-react'; import { ChevronRight, AlertTriangle, FolderSync, Loader2, Mail } from 'lucide-react';
export function EmailSettings() { export function EmailSettings() {
const t = useTranslations('settings.email_behavior'); const t = useTranslations('settings.email_behavior');
const { appName } = useConfig();
const [showTrustedModal, setShowTrustedModal] = useState(false); const [showTrustedModal, setShowTrustedModal] = useState(false);
const [isReorganizing, setIsReorganizing] = useState(false);
const [reorganizeResult, setReorganizeResult] = useState<string | null>(null);
const [defaultMailStatus, setDefaultMailStatus] = useState<'idle' | 'success' | 'error'>('idle');
const handleSetDefaultMailProgram = useCallback(() => {
try {
if (typeof navigator !== 'undefined' && navigator.registerProtocolHandler) {
navigator.registerProtocolHandler('mailto', `${window.location.origin}/compose?mailto=%s`);
setDefaultMailStatus('success');
}
} catch {
setDefaultMailStatus('error');
}
}, []);
const { const {
markAsReadDelay, markAsReadDelay,
@@ -19,6 +40,10 @@ export function EmailSettings() {
emailsPerPage, emailsPerPage,
externalContentPolicy, externalContentPolicy,
mailAttachmentAction, mailAttachmentAction,
attachmentPosition,
emailAlwaysLightMode,
archiveMode,
hoverActions,
trustedSenders, trustedSenders,
updateSetting, updateSetting,
} = useSettingsStore(); } = useSettingsStore();
@@ -31,6 +56,69 @@ export function EmailSettings() {
return t('trusted_senders.count_other', { count }); return t('trusted_senders.count_other', { count });
}; };
const handleReorganizeArchive = async () => {
const { client } = useAuthStore.getState();
const { mailboxes, fetchMailboxes } = useEmailStore.getState();
if (!client) return;
const archiveMailbox = mailboxes.find(m => m.role === 'archive' || m.name.toLowerCase() === 'archive');
if (!archiveMailbox) return;
setIsReorganizing(true);
setReorganizeResult(null);
try {
const archiveId = archiveMailbox.originalId || archiveMailbox.id;
// Fetch all emails in the root archive mailbox
const emails = await client.getEmailsInMailbox(archiveId);
let movedCount = 0;
for (const email of emails) {
const emailDate = new Date(email.receivedAt);
const year = emailDate.getFullYear().toString();
const month = (emailDate.getMonth() + 1).toString().padStart(2, '0');
// Re-read mailboxes from store each iteration in case new ones were created
let currentMailboxes = useEmailStore.getState().mailboxes;
// Find or create year subfolder
let yearMailbox = currentMailboxes.find(
m => m.name === year && m.parentId === archiveId
);
if (!yearMailbox) {
yearMailbox = await client.createMailbox(year, archiveId);
await fetchMailboxes(client);
currentMailboxes = useEmailStore.getState().mailboxes;
}
if (archiveMode === 'year') {
await client.moveEmail(email.id, yearMailbox.id);
movedCount++;
} else {
// month mode
const yearId = yearMailbox.originalId || yearMailbox.id;
let monthMailbox = currentMailboxes.find(
m => m.name === month && m.parentId === yearId
);
if (!monthMailbox) {
monthMailbox = await client.createMailbox(month, yearId);
await fetchMailboxes(client);
}
await client.moveEmail(email.id, monthMailbox.id);
movedCount++;
}
}
setReorganizeResult(t('archive_mode.reorganize_success', { count: movedCount }));
} catch (error) {
console.error('Failed to reorganize archive:', error);
setReorganizeResult(t('archive_mode.reorganize_error'));
} finally {
setIsReorganizing(false);
}
};
return ( return (
<SettingsSection title={t('title')} description={t('description')}> <SettingsSection title={t('title')} description={t('description')}>
{/* Mark as Read */} {/* Mark as Read */}
@@ -67,6 +155,40 @@ export function EmailSettings() {
</div> </div>
</SettingItem> </SettingItem>
{/* Archive Mode */}
<SettingItem label={t('archive_mode.label')} description={t('archive_mode.description')}>
<div className="flex flex-col gap-2">
<Select
value={archiveMode}
onChange={(value) => updateSetting('archiveMode', value as ArchiveMode)}
options={[
{ value: 'single', label: t('archive_mode.single') },
{ value: 'year', label: t('archive_mode.year') },
{ value: 'month', label: t('archive_mode.month') },
]}
/>
{archiveMode !== 'single' && (
<div className="flex flex-col gap-2">
<button
onClick={handleReorganizeArchive}
disabled={isReorganizing}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-accent rounded-md transition-colors text-sm disabled:opacity-50"
>
{isReorganizing ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<FolderSync className="w-4 h-4" />
)}
<span>{t('archive_mode.reorganize')}</span>
</button>
{reorganizeResult && (
<p className="text-xs text-muted-foreground">{reorganizeResult}</p>
)}
</div>
)}
</div>
</SettingItem>
{/* Permanently Delete Junk */} {/* Permanently Delete Junk */}
<SettingItem label={t('permanently_delete_junk.label')} description={t('permanently_delete_junk.description')}> <SettingItem label={t('permanently_delete_junk.label')} description={t('permanently_delete_junk.description')}>
<ToggleSwitch <ToggleSwitch
@@ -80,6 +202,39 @@ export function EmailSettings() {
<ToggleSwitch checked={showPreview} onChange={(checked) => updateSetting('showPreview', checked)} /> <ToggleSwitch checked={showPreview} onChange={(checked) => updateSetting('showPreview', checked)} />
</SettingItem> </SettingItem>
{/* Quick Hover Actions */}
<div className="py-3 border-b border-border space-y-3">
<div>
<label className="text-sm font-medium text-foreground">{t('hover_actions.label')}</label>
<p className="text-xs text-muted-foreground mt-1">{t('hover_actions.description')}</p>
</div>
<div className="flex flex-wrap gap-2">
{ALL_HOVER_ACTIONS.map((action) => {
const isEnabled = hoverActions.includes(action.id);
return (
<button
key={action.id}
type="button"
onClick={() => {
const newActions = isEnabled
? hoverActions.filter((a: HoverAction) => a !== action.id)
: [...hoverActions, action.id];
updateSetting('hoverActions', newActions);
}}
className={cn(
'px-3 py-1.5 text-xs rounded-md transition-colors duration-150',
isEnabled
? 'bg-primary text-primary-foreground font-medium'
: 'bg-muted hover:bg-accent text-foreground'
)}
>
{t(`hover_actions.${action.labelKey}`)}
</button>
);
})}
</div>
</div>
<SettingItem label={t('attachment_click_action.label')} description={t('attachment_click_action.description')}> <SettingItem label={t('attachment_click_action.label')} description={t('attachment_click_action.description')}>
<Select <Select
value={mailAttachmentAction} value={mailAttachmentAction}
@@ -91,12 +246,24 @@ export function EmailSettings() {
/> />
</SettingItem> </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 */} {/* Emails Per Page */}
<SettingItem label={t('emails_per_page.label')} description={t('emails_per_page.description')}> <SettingItem label={t('emails_per_page.label')} description={t('emails_per_page.description')}>
<Select <Select
value={emailsPerPage.toString()} value={emailsPerPage.toString()}
onChange={(value) => updateSetting('emailsPerPage', parseInt(value))} onChange={(value) => updateSetting('emailsPerPage', parseInt(value))}
options={[ options={[
{ value: '10', label: t('emails_per_page.10') },
{ value: '25', label: t('emails_per_page.25') }, { value: '25', label: t('emails_per_page.25') },
{ value: '50', label: t('emails_per_page.50') }, { value: '50', label: t('emails_per_page.50') },
{ value: '100', label: t('emails_per_page.100') }, { value: '100', label: t('emails_per_page.100') },
@@ -104,6 +271,14 @@ export function EmailSettings() {
/> />
</SettingItem> </SettingItem>
{/* Always Light Mode for Emails */}
<SettingItem label={t('always_light_mode.label')} description={t('always_light_mode.description')}>
<ToggleSwitch
checked={emailAlwaysLightMode}
onChange={(checked) => updateSetting('emailAlwaysLightMode', checked)}
/>
</SettingItem>
{/* External Content */} {/* External Content */}
<SettingItem label={t('external_content.label')} description={t('external_content.description')}> <SettingItem label={t('external_content.label')} description={t('external_content.description')}>
<Select <Select
@@ -119,6 +294,25 @@ export function EmailSettings() {
/> />
</SettingItem> </SettingItem>
{/* Default Mail Program */}
<SettingItem label={t('default_mail_program.label')} description={t('default_mail_program.description', { appName: appName || 'Bulwark' })}>
<div className="flex flex-col items-end gap-1">
<button
onClick={handleSetDefaultMailProgram}
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-accent rounded-md transition-colors"
>
<Mail className="w-4 h-4" />
<span className="text-sm text-foreground">{t('default_mail_program.button')}</span>
</button>
{defaultMailStatus === 'success' && (
<p className="text-xs text-green-600 dark:text-green-400">{t('default_mail_program.success')}</p>
)}
{defaultMailStatus === 'error' && (
<p className="text-xs text-destructive">{t('default_mail_program.error')}</p>
)}
</div>
</SettingItem>
{/* Trusted Senders */} {/* Trusted Senders */}
<SettingItem label={t('trusted_senders.label')} description={t('trusted_senders.description')}> <SettingItem label={t('trusted_senders.label')} description={t('trusted_senders.description')}>
<button <button
+118 -31
View File
@@ -9,6 +9,7 @@ import { SieveEditorModal } from "@/components/filters/sieve-editor-modal";
import { useFilterStore } from "@/stores/filter-store"; import { useFilterStore } from "@/stores/filter-store";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store"; import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { toast } from "@/stores/toast-store"; import { toast } from "@/stores/toast-store";
import type { FilterRule } from "@/lib/jmap/sieve-types"; import type { FilterRule } from "@/lib/jmap/sieve-types";
import { import {
@@ -25,31 +26,98 @@ import {
function RuleSummary({ rule }: { rule: FilterRule }) { function RuleSummary({ rule }: { rule: FilterRule }) {
const t = useTranslations("settings.filters"); const t = useTranslations("settings.filters");
const conditionSummary = rule.conditions const conditions = rule.conditions.slice(0, 2).map((c) => {
.slice(0, 2) const field = t(`condition_fields.${c.field}`);
.map((c) => { const comparator = t(`comparators.${c.comparator}`);
const field = t(`condition_fields.${c.field}`); return `${field} ${comparator} "${c.value}"`;
const comparator = t(`comparators.${c.comparator}`); });
return `${field} ${comparator} "${c.value}"`;
}) const joiner = rule.matchType === "all" ? t("and") : t("or");
.join(rule.matchType === "all" ? ` ${t("and")} ` : ` ${t("or")} `);
const extra = rule.conditions.length > 2 const extra = rule.conditions.length > 2
? ` (+${rule.conditions.length - 2})` ? ` (+${rule.conditions.length - 2})`
: ""; : "";
const actionSummary = rule.actions const actions = rule.actions.slice(0, 2).map((a) => {
.slice(0, 2) const action = t(`action_types.${a.type}`);
.map((a) => { return a.value ? `${action} "${a.value}"` : action;
const action = t(`action_types.${a.type}`); });
return a.value ? `${action} "${a.value}"` : action;
})
.join(", ");
return ( return (
<span className="text-xs text-muted-foreground truncate"> <div className="text-xs text-muted-foreground break-words">
{conditionSummary}{extra} {actionSummary} <span className="inline">
</span> {conditions.map((cond, i) => (
<span key={i}>
{i > 0 && <span className="italic opacity-70"> {joiner} </span>}
{cond}
</span>
))}
{extra}
</span>
<span className="mx-1 opacity-50"></span>
<span className="inline">
{actions.map((act, i) => (
<span key={i}>
{i > 0 && ", "}
{act}
</span>
))}
</span>
</div>
);
}
function VisualRuleSummary({ rule }: { rule: FilterRule }) {
const t = useTranslations("settings.filters");
const joiner = rule.matchType === "all" ? t("and") : t("or");
const matchLabel = rule.matchType === "all" ? t("match_all_conditions") : t("match_any_condition");
return (
<div className="mt-1.5 space-y-1 text-xs">
<div className="flex items-baseline gap-1.5 flex-wrap">
<span className="text-[10px] font-semibold uppercase tracking-wider text-blue-500 dark:text-blue-400">
{t("if")}
</span>
{rule.conditions.map((c, i) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return (
<span key={i} className="contents">
{i > 0 && (
<span className="text-[10px] text-muted-foreground/70 italic">{joiner}</span>
)}
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
<span className="font-medium text-blue-600 dark:text-blue-400">{field}</span>
<span className="text-muted-foreground">{comparator}</span>
<span className="text-foreground">{c.value}</span>
</span>
</span>
);
})}
<span className="text-[10px] text-muted-foreground/60 italic">({matchLabel})</span>
</div>
<div className="flex items-baseline gap-1.5 flex-wrap">
<span className="text-[10px] font-semibold uppercase tracking-wider text-emerald-500 dark:text-emerald-400">
{t("then")}
</span>
{rule.actions.map((a, i) => {
const action = t(`action_types.${a.type}`);
return (
<span key={i} className="contents">
{i > 0 && (
<span className="text-muted-foreground/50"></span>
)}
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
<span className="font-medium text-emerald-600 dark:text-emerald-400">{action}</span>
{a.value && <span className="text-muted-foreground">{a.value}</span>}
</span>
</span>
);
})}
</div>
</div>
); );
} }
@@ -58,6 +126,8 @@ export function FilterSettings() {
const tNotifications = useTranslations("notifications"); const tNotifications = useTranslations("notifications");
const { client } = useAuthStore(); const { client } = useAuthStore();
const mailboxes = useEmailStore((s) => s.mailboxes); const mailboxes = useEmailStore((s) => s.mailboxes);
const expandedFilterView = useSettingsStore((s) => s.expandedFilterView);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const { const {
rules, rules,
@@ -337,23 +407,25 @@ export function FilterSettings() {
onDragOver={(e) => handleDragOver(e, index)} onDragOver={(e) => handleDragOver(e, index)}
onDrop={(e) => handleDrop(e, index)} onDrop={(e) => handleDrop(e, index)}
onDragEnd={handleDragEnd} onDragEnd={handleDragEnd}
className={`flex items-center gap-3 p-3 rounded-md border transition-colors ${ className={`flex items-start gap-3 p-3 rounded-md border transition-colors ${
dragOverIndex === index dragOverIndex === index
? "border-primary bg-primary/5" ? "border-primary bg-primary/5"
: "border-border hover:bg-muted/50" : "border-border hover:bg-muted/50"
} ${!rule.enabled ? "opacity-60" : ""}`} } ${!rule.enabled ? "opacity-60" : ""}`}
> >
<div <div
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground" className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground pt-0.5"
aria-label={t("drag_to_reorder")} aria-label={t("drag_to_reorder")}
> >
<GripVertical className="w-4 h-4" /> <GripVertical className="w-4 h-4" />
</div> </div>
<ToggleSwitch <div className="pt-0.5">
checked={rule.enabled} <ToggleSwitch
onChange={() => handleToggle(rule.id)} checked={rule.enabled}
/> onChange={() => handleToggle(rule.id)}
/>
</div>
<div <div
className="flex-1 min-w-0 cursor-pointer" className="flex-1 min-w-0 cursor-pointer"
@@ -374,7 +446,11 @@ export function FilterSettings() {
<p className="text-sm font-medium text-foreground truncate"> <p className="text-sm font-medium text-foreground truncate">
{rule.name} {rule.name}
</p> </p>
<RuleSummary rule={rule} /> {expandedFilterView ? (
<VisualRuleSummary rule={rule} />
) : (
<RuleSummary rule={rule} />
)}
</div> </div>
{deleteConfirmId === rule.id ? ( {deleteConfirmId === rule.id ? (
@@ -435,12 +511,23 @@ export function FilterSettings() {
</Button> </Button>
</div> </div>
{isSaving && ( <div className="flex items-center gap-3">
<div className="flex items-center gap-2 text-sm text-muted-foreground"> {isSaving && (
<Loader2 className="w-4 h-4 animate-spin" /> <div className="flex items-center gap-2 text-sm text-muted-foreground">
{t("saving")} <Loader2 className="w-4 h-4 animate-spin" />
</div> {t("saving")}
)} </div>
)}
{!isOpaque && rules.length > 0 && (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{t("expanded_view")}</span>
<ToggleSwitch
checked={expandedFilterView}
onChange={(v) => updateSetting("expandedFilterView", v)}
/>
</div>
)}
</div>
</div> </div>
{showRuleModal && ( {showRuleModal && (
+28 -15
View File
@@ -490,21 +490,34 @@ export function FolderSettings() {
{/* Standard Folder Roles — advanced section */} {/* Standard Folder Roles — advanced section */}
<SettingsSection title={t('standard_roles')} description={t('standard_roles_description')}> <SettingsSection title={t('standard_roles')} description={t('standard_roles_description')}>
{STANDARD_ROLES.map((role) => ( {STANDARD_ROLES.map((role) => {
<SettingItem key={role} label={t(`role_${role}`)}> // Disambiguate duplicate folder names by appending parent path
<Select const nameCounts = new Map<string, number>();
value={getRoleMailboxId(role)} ownMailboxes.forEach(mb => nameCounts.set(mb.name, (nameCounts.get(mb.name) || 0) + 1));
onChange={(value) => handleRoleChange(role, value)} const getParentPath = (mb: { parentId?: string; name: string }) => {
options={[ if (!mb.parentId) return '';
{ value: '', label: t('role_none') }, const parent = ownMailboxes.find(p => p.id === mb.parentId);
...ownMailboxes.map(mb => ({ return parent ? `${parent.name}/` : '';
value: mb.id, };
label: mb.name,
})), return (
]} <SettingItem key={role} label={t(`role_${role}`)}>
/> <Select
</SettingItem> 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> </SettingsSection>
</div> </div>
); );
+46 -13
View File
@@ -3,8 +3,10 @@
import { useState } from "react"; import { useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useSettingsStore, KEYWORD_PALETTE, DEFAULT_KEYWORDS, type KeywordDefinition } from "@/stores/settings-store"; import { useSettingsStore, KEYWORD_PALETTE, DEFAULT_KEYWORDS, type KeywordDefinition } from "@/stores/settings-store";
import { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { SettingsSection } from "./settings-section"; import { SettingsSection } from "./settings-section";
import { Plus, Pencil, Trash2, GripVertical, Check, X, RotateCcw } from "lucide-react"; import { Plus, Pencil, Trash2, GripVertical, Check, X, RotateCcw, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
const PALETTE_KEYS = Object.keys(KEYWORD_PALETTE); const PALETTE_KEYS = Object.keys(KEYWORD_PALETTE);
@@ -91,16 +93,14 @@ function KeywordEditForm({
const [color, setColor] = useState(initial?.color || "blue"); const [color, setColor] = useState(initial?.color || "blue");
const isEditing = !!initial; const isEditing = !!initial;
const normalizedId = isEditing const normalizedId = label
? initial.id .trim()
: label .toLowerCase()
.trim() .replace(/[^a-z0-9_-]/g, "-")
.toLowerCase() .replace(/-+/g, "-")
.replace(/[^a-z0-9_-]/g, "-") .replace(/^-|-$/g, "");
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
const isDuplicate = !isEditing && normalizedId.length > 0 && existingIds.includes(normalizedId); const isDuplicate = normalizedId.length > 0 && existingIds.includes(normalizedId);
const isValid = normalizedId.length > 0 && label.trim().length > 0 && !isDuplicate; const isValid = normalizedId.length > 0 && label.trim().length > 0 && !isDuplicate;
const handleSave = () => { const handleSave = () => {
@@ -159,10 +159,13 @@ function KeywordEditForm({
export function KeywordSettings() { export function KeywordSettings() {
const t = useTranslations("settings.keywords"); const t = useTranslations("settings.keywords");
const { emailKeywords, addKeyword, updateKeyword, removeKeyword, reorderKeywords } = const { emailKeywords, addKeyword, updateKeyword, renameKeyword, removeKeyword, reorderKeywords } =
useSettingsStore(); useSettingsStore();
const { client } = useAuthStore();
const { fetchTagCounts } = useEmailStore();
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
const [isAdding, setIsAdding] = useState(false); const [isAdding, setIsAdding] = useState(false);
const [isMigrating, setIsMigrating] = useState(false);
const existingIds = emailKeywords.map((k) => k.id); const existingIds = emailKeywords.map((k) => k.id);
@@ -171,8 +174,32 @@ export function KeywordSettings() {
setIsAdding(false); setIsAdding(false);
}; };
const handleEdit = (keyword: KeywordDefinition) => { const handleEdit = async (keyword: KeywordDefinition) => {
updateKeyword(keyword.id, { label: keyword.label, color: keyword.color }); const oldId = editingId;
if (!oldId) return;
const idChanged = oldId !== keyword.id;
if (idChanged && client) {
setIsMigrating(true);
try {
const oldJmapKeyword = `$label:${oldId}`;
const newJmapKeyword = `$label:${keyword.id}`;
await client.migrateKeyword(oldJmapKeyword, newJmapKeyword);
renameKeyword(oldId, keyword);
fetchTagCounts(client);
} catch (error) {
console.error("Failed to migrate keyword:", error);
const toastModule = await import('sonner');
toastModule.toast.error(t("migration_error"));
setIsMigrating(false);
return;
}
setIsMigrating(false);
} else {
updateKeyword(oldId, { label: keyword.label, color: keyword.color });
}
setEditingId(null); setEditingId(null);
}; };
@@ -187,6 +214,12 @@ export function KeywordSettings() {
return ( return (
<SettingsSection title={t("title")} description={t("description")}> <SettingsSection title={t("title")} description={t("description")}>
<div className="space-y-2"> <div className="space-y-2">
{isMigrating && (
<div className="flex items-center gap-2 p-2 text-xs text-muted-foreground bg-accent/50 rounded-md">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
{t("migrating")}
</div>
)}
{emailKeywords.map((keyword) => {emailKeywords.map((keyword) =>
editingId === keyword.id ? ( editingId === keyword.id ? (
<KeywordEditForm <KeywordEditForm
@@ -0,0 +1,115 @@
"use client";
import { useTranslations } from 'next-intl';
import { useSettingsStore } from '@/stores/settings-store';
import { SettingsSection, SettingItem, ToggleSwitch, Select } from './settings-section';
import { playNotificationSound, NOTIFICATION_SOUNDS } from '@/lib/notification-sound';
import type { NotificationSoundChoice } from '@/lib/notification-sound';
import { Button } from '@/components/ui/button';
import { Volume2 } from 'lucide-react';
export function NotificationSettings() {
const t = useTranslations('settings.notifications');
const {
emailNotificationsEnabled,
emailNotificationSound,
notificationSoundChoice,
calendarNotificationsEnabled,
calendarNotificationSound,
calendarInvitationParsingEnabled,
updateSetting,
} = useSettingsStore();
const soundOptions = NOTIFICATION_SOUNDS.map((s) => ({
value: s.id,
label: t(`sounds.${s.id}`),
}));
return (
<div className="space-y-8">
<SettingsSection title={t('sound_selection.title')} description={t('sound_selection.description')}>
<SettingItem
label={t('sound_selection.choose')}
description={t('sound_selection.choose_desc')}
>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => playNotificationSound(notificationSoundChoice)}
title={t('test_sound')}
>
<Volume2 className="w-4 h-4" />
</Button>
<Select
value={notificationSoundChoice}
onChange={(value) => {
const choice = value as NotificationSoundChoice;
updateSetting('notificationSoundChoice', choice);
playNotificationSound(choice);
}}
options={soundOptions}
/>
</div>
</SettingItem>
</SettingsSection>
<SettingsSection title={t('email.title')} description={t('email.description')}>
<SettingItem
label={t('email.enabled')}
description={t('email.enabled_desc')}
>
<ToggleSwitch
checked={emailNotificationsEnabled}
onChange={(checked) => updateSetting('emailNotificationsEnabled', checked)}
/>
</SettingItem>
<SettingItem
label={t('email.sound')}
description={t('email.sound_desc')}
>
<ToggleSwitch
checked={emailNotificationSound}
onChange={(checked) => updateSetting('emailNotificationSound', checked)}
disabled={!emailNotificationsEnabled}
/>
</SettingItem>
</SettingsSection>
<SettingsSection title={t('calendar.title')} description={t('calendar.description')}>
<SettingItem
label={t('calendar.enabled')}
description={t('calendar.enabled_desc')}
>
<ToggleSwitch
checked={calendarNotificationsEnabled}
onChange={(checked) => updateSetting('calendarNotificationsEnabled', checked)}
/>
</SettingItem>
<SettingItem
label={t('calendar.sound')}
description={t('calendar.sound_desc')}
>
<ToggleSwitch
checked={calendarNotificationSound}
onChange={(checked) => updateSetting('calendarNotificationSound', checked)}
disabled={!calendarNotificationsEnabled}
/>
</SettingItem>
<SettingItem
label={t('calendar.invitation_parsing')}
description={t('calendar.invitation_parsing_desc')}
>
<ToggleSwitch
checked={calendarInvitationParsingEnabled}
onChange={(checked) => updateSetting('calendarInvitationParsingEnabled', checked)}
/>
</SettingItem>
</SettingsSection>
</div>
);
}
@@ -0,0 +1,301 @@
"use client";
import { useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Plus, Pencil, Trash2, ExternalLink, PanelRight, GripVertical } from "lucide-react";
import { icons as lucideIcons, type LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SettingsSection, SettingItem, ToggleSwitch } from "./settings-section";
import { IconPicker } from "@/components/layout/icon-picker";
import { useSettingsStore, type SidebarApp } from "@/stores/settings-store";
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { cn } from "@/lib/utils";
interface SidebarAppFormData {
name: string;
url: string;
icon: string;
openMode: "tab" | "inline";
showOnMobile: boolean;
}
function AppForm({
app,
onSave,
onCancel,
}: {
app?: SidebarApp;
onSave: (data: SidebarAppFormData) => void;
onCancel: () => void;
}) {
const t = useTranslations("sidebar_apps");
const isEditing = !!app;
const [formData, setFormData] = useState<SidebarAppFormData>({
name: app?.name || "",
url: app?.url || "",
icon: app?.icon || "Globe",
openMode: app?.openMode || "tab",
showOnMobile: app?.showOnMobile ?? false,
});
const [errors, setErrors] = useState<Record<string, string>>({});
const validate = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) {
newErrors.name = t("name_required");
}
if (!formData.url.trim()) {
newErrors.url = t("url_required");
} else {
try {
const parsed = new URL(formData.url);
if (!["http:", "https:"].includes(parsed.protocol)) {
newErrors.url = t("url_invalid");
}
} catch {
newErrors.url = t("url_invalid");
}
}
if (!formData.icon) {
newErrors.icon = t("icon_required");
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!validate()) return;
onSave(formData);
};
const SelectedIcon = formData.icon
? (lucideIcons[formData.icon as keyof typeof lucideIcons] as LucideIcon | undefined)
: null;
return (
<form onSubmit={handleSubmit} className="space-y-4 p-4 border border-border rounded-lg bg-secondary/30">
<div>
<label className="text-sm font-medium">{t("name_label")}</label>
<Input
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder={t("name_placeholder")}
className="mt-1"
/>
{errors.name && <p className="text-xs text-destructive mt-1">{errors.name}</p>}
</div>
<div>
<label className="text-sm font-medium">{t("url_label")}</label>
<Input
value={formData.url}
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
placeholder="https://example.com"
className="mt-1"
/>
{errors.url && <p className="text-xs text-destructive mt-1">{errors.url}</p>}
</div>
<div>
<label className="text-sm font-medium block mb-1">{t("icon_label")}</label>
<div className="flex items-center gap-2 mb-2">
{SelectedIcon && (
<div className="w-8 h-8 rounded-md bg-muted flex items-center justify-center">
<SelectedIcon className="w-4 h-4" />
</div>
)}
<span className="text-sm text-muted-foreground">{formData.icon}</span>
</div>
<IconPicker value={formData.icon} onChange={(icon) => setFormData({ ...formData, icon })} />
{errors.icon && <p className="text-xs text-destructive mt-1">{errors.icon}</p>}
</div>
<div>
<label className="text-sm font-medium block mb-2">{t("open_mode_label")}</label>
<div className="flex gap-2">
<button
type="button"
onClick={() => setFormData({ ...formData, openMode: "tab" })}
className={cn(
"flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-colors",
formData.openMode === "tab"
? "border-primary bg-primary/10 text-primary"
: "border-border hover:bg-muted"
)}
>
<ExternalLink className="w-4 h-4" />
{t("open_new_tab")}
</button>
<button
type="button"
onClick={() => setFormData({ ...formData, openMode: "inline" })}
className={cn(
"flex items-center gap-2 px-3 py-2 rounded-md text-sm border transition-colors",
formData.openMode === "inline"
? "border-primary bg-primary/10 text-primary"
: "border-border hover:bg-muted"
)}
>
<PanelRight className="w-4 h-4" />
{t("open_inline")}
</button>
</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")}
</Button>
<Button type="submit" size="sm">
{isEditing ? t("update") : t("add")}
</Button>
</div>
</form>
);
}
export function SidebarAppsSettings() {
const t = useTranslations("settings.sidebar_apps");
const tApps = useTranslations("sidebar_apps");
const { sidebarApps, keepAppsLoaded, addSidebarApp, updateSidebarApp, removeSidebarApp, updateSetting } = useSettingsStore();
const [editingApp, setEditingApp] = useState<string | null>(null);
const [showAddForm, setShowAddForm] = useState(false);
const { dialogProps: confirmDialogProps, confirm: confirmDialog } = useConfirmDialog();
const handleAdd = useCallback((data: SidebarAppFormData) => {
const id = `app-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
addSidebarApp({ id, ...data });
setShowAddForm(false);
}, [addSidebarApp]);
const handleUpdate = useCallback((id: string, data: SidebarAppFormData) => {
updateSidebarApp(id, data);
setEditingApp(null);
}, [updateSidebarApp]);
const handleDelete = useCallback(async (app: SidebarApp) => {
const confirmed = await confirmDialog({
title: tApps("delete_confirm_title"),
message: tApps("delete_confirm", { name: app.name }),
confirmText: tApps("delete"),
variant: 'destructive',
});
if (!confirmed) return;
removeSidebarApp(app.id);
}, [confirmDialog, tApps, removeSidebarApp]);
return (
<>
<SettingsSection title={t("title")} description={t("description")}>
<SettingItem label={t("keep_loaded")} description={t("keep_loaded_description")}>
<ToggleSwitch
checked={keepAppsLoaded}
onChange={(v) => updateSetting("keepAppsLoaded", v)}
/>
</SettingItem>
</SettingsSection>
<SettingsSection title={t("manage_title")} description={t("manage_description")}>
<div className="space-y-3">
{sidebarApps.length === 0 && !showAddForm && (
<p className="text-sm text-muted-foreground py-4 text-center">{tApps("no_apps_hint")}</p>
)}
{sidebarApps.map((app) => {
if (editingApp === app.id) {
return (
<AppForm
key={app.id}
app={app}
onSave={(data) => handleUpdate(app.id, data)}
onCancel={() => setEditingApp(null)}
/>
);
}
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
return (
<div
key={app.id}
className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-muted/50 transition-colors"
>
<GripVertical className="w-4 h-4 text-muted-foreground/50 flex-shrink-0" />
<div className="w-8 h-8 rounded-md bg-muted flex items-center justify-center flex-shrink-0">
{AppIcon ? <AppIcon className="w-4 h-4" /> : null}
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">{app.name}</div>
<div className="text-xs text-muted-foreground truncate">{app.url}</div>
</div>
<span className={cn(
"text-[10px] px-1.5 py-0.5 rounded-full flex-shrink-0",
app.openMode === "inline"
? "bg-blue-500/10 text-blue-600 dark:text-blue-400"
: "bg-muted text-muted-foreground"
)}>
{app.openMode === "inline" ? tApps("inline_badge") : tApps("tab_badge")}
</span>
<button
onClick={() => setEditingApp(app.id)}
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
>
<Pencil className="w-3.5 h-3.5" />
</button>
<button
onClick={() => handleDelete(app)}
className="p-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
);
})}
{showAddForm && (
<AppForm
onSave={handleAdd}
onCancel={() => setShowAddForm(false)}
/>
)}
{!showAddForm && !editingApp && (
<Button
variant="outline"
size="sm"
onClick={() => setShowAddForm(true)}
className="w-full"
>
<Plus className="w-4 h-4 mr-2" />
{tApps("add_new")}
</Button>
)}
</div>
</SettingsSection>
<ConfirmDialog {...confirmDialogProps} />
</>
);
}
@@ -0,0 +1,117 @@
"use client";
import { useId } from "react";
import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { ShieldCheck, X } from "lucide-react";
import type { SmimeKeyRecord, SmimePublicCert } from "@/lib/smime/types";
interface SmimeCertificateModalProps {
isOpen: boolean;
onClose: () => void;
record: SmimeKeyRecord | SmimePublicCert | null;
type: "private" | "public";
}
export function SmimeCertificateModal({
isOpen,
onClose,
record,
type,
}: SmimeCertificateModalProps) {
const t = useTranslations("smime");
const id = useId();
const dialogRef = useFocusTrap({
isActive: isOpen,
onEscape: onClose,
restoreFocus: true,
});
if (!isOpen || !record) return null;
const isExpired = new Date(record.notAfter) < new Date();
const isNotYetValid = new Date(record.notBefore) > new Date();
const rows: { label: string; value: string }[] = [
{ label: t("cert_subject"), value: record.subject ?? "" },
{ label: t("cert_issuer"), value: record.issuer ?? "" },
{ label: t("cert_email"), value: record.email },
{
label: t("cert_validity"),
value: `${new Date(record.notBefore).toLocaleDateString()}${new Date(record.notAfter).toLocaleDateString()}`,
},
{ label: t("cert_fingerprint"), value: record.fingerprint },
];
if ("serialNumber" in record) {
rows.splice(2, 0, { label: t("cert_serial"), value: record.serialNumber });
}
if ("algorithm" in record) {
rows.push({ label: t("cert_algorithm"), value: record.algorithm });
}
if ("capabilities" in record) {
const caps: string[] = [];
if (record.capabilities.canSign) caps.push(t("cap_sign"));
if (record.capabilities.canEncrypt) caps.push(t("cap_encrypt"));
rows.push({ label: t("cert_capabilities"), value: caps.join(", ") || t("cap_none") });
}
if ("source" in record) {
rows.push({ label: t("cert_source"), value: record.source });
}
return (
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={`${id}-title`}
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-lg animate-in zoom-in-95 duration-200"
>
<div className="flex items-center justify-between p-6 pb-4 border-b border-border">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center">
<ShieldCheck className="w-5 h-5 text-primary" />
</div>
<h2 id={`${id}-title`} className="text-lg font-semibold text-foreground">
{t("certificate_details")}
</h2>
</div>
<Button variant="ghost" size="icon" onClick={onClose}>
<X className="w-4 h-4" />
</Button>
</div>
<div className="p-6 space-y-3 max-h-[60vh] overflow-y-auto">
{(isExpired || isNotYetValid) && (
<div className="px-3 py-2 rounded-md bg-destructive/10 text-destructive text-sm">
{isExpired ? t("cert_expired") : t("cert_not_yet_valid")}
</div>
)}
{rows.map(({ label, value }) => (
<div key={label}>
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{label}
</dt>
<dd className="text-sm text-foreground mt-0.5 break-all font-mono">
{value}
</dd>
</div>
))}
</div>
<div className="flex justify-end px-6 pb-6">
<Button variant="ghost" onClick={onClose}>
{t("close")}
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,169 @@
"use client";
import { useState, useId } from "react";
import { useFocusTrap } from "@/hooks/use-focus-trap";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { KeyRound, Eye, EyeOff } from "lucide-react";
interface SmimePassphraseDialogProps {
isOpen: boolean;
onClose: () => void;
onSubmit: (passphrase: string) => void | Promise<void>;
title: string;
description?: string;
submitText?: string;
error?: string | null;
/** Show a second passphrase field for import/export confirmation. */
showConfirm?: boolean;
}
export function SmimePassphraseDialog({
isOpen,
onClose,
onSubmit,
title,
description,
submitText,
error,
showConfirm = false,
}: SmimePassphraseDialogProps) {
const t = useTranslations("smime");
const id = useId();
const [passphrase, setPassphrase] = useState("");
const [confirm, setConfirm] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const dialogRef = useFocusTrap({
isActive: isOpen,
onEscape: onClose,
restoreFocus: true,
});
if (!isOpen) return null;
const mismatch = showConfirm && passphrase !== confirm && confirm.length > 0;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!passphrase || (showConfirm && passphrase !== confirm)) return;
setIsSubmitting(true);
try {
await onSubmit(passphrase);
} finally {
setIsSubmitting(false);
}
};
const handleClose = () => {
setPassphrase("");
setConfirm("");
setShowPassword(false);
onClose();
};
return (
<div className="fixed inset-0 bg-black/50 backdrop-blur-[1px] flex items-center justify-center z-[60] p-4 animate-in fade-in duration-150">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={`${id}-title`}
aria-describedby={description ? `${id}-desc` : undefined}
className="bg-background border border-border rounded-lg shadow-xl w-full max-w-md animate-in zoom-in-95 duration-200"
>
<form onSubmit={handleSubmit}>
<div className="p-6">
<div className="flex items-start gap-4">
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
<KeyRound className="w-5 h-5 text-primary" />
</div>
<div className="flex-1 min-w-0">
<h2
id={`${id}-title`}
className="text-lg font-semibold text-foreground"
>
{title}
</h2>
{description && (
<p
id={`${id}-desc`}
className="text-sm text-muted-foreground mt-1"
>
{description}
</p>
)}
</div>
</div>
<div className="mt-4 space-y-3">
<div className="relative">
<Input
type={showPassword ? "text" : "password"}
value={passphrase}
onChange={(e) => setPassphrase(e.target.value)}
placeholder={t("passphrase_placeholder")}
autoFocus
className="pr-10"
autoComplete="off"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground"
aria-label={showPassword ? t("hide_passphrase") : t("show_passphrase")}
>
{showPassword ? (
<EyeOff className="w-4 h-4" />
) : (
<Eye className="w-4 h-4" />
)}
</button>
</div>
{showConfirm && (
<div>
<Input
type={showPassword ? "text" : "password"}
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
placeholder={t("confirm_passphrase_placeholder")}
autoComplete="off"
/>
{mismatch && (
<p className="text-xs text-destructive mt-1">
{t("passphrase_mismatch")}
</p>
)}
</div>
)}
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</div>
</div>
<div className="flex justify-end gap-2 px-6 pb-6">
<Button
type="button"
variant="ghost"
onClick={handleClose}
disabled={isSubmitting}
>
{t("cancel")}
</Button>
<Button
type="submit"
disabled={!passphrase || isSubmitting || (showConfirm && passphrase !== confirm)}
>
{isSubmitting ? t("processing") : (submitText ?? t("unlock"))}
</Button>
</div>
</form>
</div>
</div>
);
}
+559
View File
@@ -0,0 +1,559 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import {
Upload,
Trash2,
Eye,
Lock,
Unlock,
Download,
ShieldCheck,
ShieldAlert,
Users,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { SettingsSection, SettingItem, ToggleSwitch } from "@/components/settings/settings-section";
import { SmimePassphraseDialog } from "@/components/settings/smime-passphrase-dialog";
import { SmimeCertificateModal } from "@/components/settings/smime-certificate-modal";
import { useSmimeStore } from "@/stores/smime-store";
import { useIdentityStore } from "@/stores/identity-store";
import { exportPkcs12, downloadPkcs12 } from "@/lib/smime/pkcs12-export";
import type { SmimeKeyRecord, SmimePublicCert } from "@/lib/smime/types";
export function SmimeSettings() {
const t = useTranslations("smime");
const {
keyRecords,
publicCerts,
identityKeyBindings,
defaultSignIdentity,
defaultEncrypt,
rememberUnlockedKeys,
autoImportSignerCerts,
isLoading,
error,
load,
importPKCS12,
removeKeyRecord,
removePublicCert,
bindIdentityToKey,
unlockKey,
lockKey,
setSignDefault,
setEncryptDefault,
setRememberUnlockedKeys,
setAutoImportSignerCerts,
isKeyUnlocked,
setError,
} = useSmimeStore();
const { identities } = useIdentityStore();
// Local UI state
const [importDialogOpen, setImportDialogOpen] = useState(false);
const [unlockDialogOpen, setUnlockDialogOpen] = useState(false);
const [unlockTargetId, setUnlockTargetId] = useState<string | null>(null);
const [certModalRecord, setCertModalRecord] = useState<SmimeKeyRecord | SmimePublicCert | null>(null);
const [certModalType, setCertModalType] = useState<"private" | "public">("private");
const [importError, setImportError] = useState<string | null>(null);
const [unlockError, setUnlockError] = useState<string | null>(null);
const [pendingFile, setPendingFile] = useState<ArrayBuffer | null>(null);
const [pendingP12Pass, setPendingP12Pass] = useState("");
const fileInputRef = useRef<HTMLInputElement>(null);
const pubCertInputRef = useRef<HTMLInputElement>(null);
// State for the two-step PKCS#12 flow
const [importStep, setImportStep] = useState<"p12" | "storage">("p12");
// Export flow state
const [exportDialogOpen, setExportDialogOpen] = useState(false);
const [exportTargetRecord, setExportTargetRecord] = useState<SmimeKeyRecord | null>(null);
const [exportStep, setExportStep] = useState<"storage" | "export">("storage");
const [exportStoragePass, setExportStoragePass] = useState("");
const [exportError, setExportError] = useState<string | null>(null);
useEffect(() => {
load();
}, [load]);
// ── PKCS#12 import flow ────────────────────────────────────────
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
setPendingFile(reader.result as ArrayBuffer);
setImportStep("p12");
setImportError(null);
setImportDialogOpen(true);
};
reader.readAsArrayBuffer(file);
// Reset so same file can be re-selected
e.target.value = "";
};
const handleImportSubmit = async (passphrase: string) => {
if (importStep === "p12") {
setPendingP12Pass(passphrase);
setImportStep("storage");
setImportError(null);
return;
}
// Storage passphrase step
if (!pendingFile) return;
try {
await importPKCS12(pendingFile, pendingP12Pass, passphrase);
setImportDialogOpen(false);
setPendingFile(null);
setPendingP12Pass("");
setImportError(null);
} catch (err) {
setImportError(err instanceof Error ? err.message : "Import failed");
}
};
// ── Public cert import ─────────────────────────────────────────
const handlePublicCertFile = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
try {
const store = useSmimeStore.getState();
await store.importPublicCert(reader.result as ArrayBuffer, "manual");
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to import certificate");
}
};
reader.readAsArrayBuffer(file);
e.target.value = "";
};
// ── Unlock ─────────────────────────────────────────────────────
const handleUnlockRequest = (id: string) => {
setUnlockTargetId(id);
setUnlockError(null);
setUnlockDialogOpen(true);
};
const handleUnlockSubmit = async (passphrase: string) => {
if (!unlockTargetId) return;
try {
await unlockKey(unlockTargetId, passphrase);
setUnlockDialogOpen(false);
setUnlockTargetId(null);
setUnlockError(null);
} catch (err) {
setUnlockError(err instanceof Error ? err.message : "Unlock failed");
}
};
// ── Export flow ────────────────────────────────────────────────
const handleExportRequest = (record: SmimeKeyRecord) => {
setExportTargetRecord(record);
setExportStep("storage");
setExportStoragePass("");
setExportError(null);
setExportDialogOpen(true);
};
const handleExportSubmit = async (passphrase: string) => {
if (!exportTargetRecord) return;
if (exportStep === "storage") {
// Verify storage passphrase by attempting to decrypt
try {
const { decryptPrivateKeyBytes } = await import("@/lib/smime/pkcs12-import");
await decryptPrivateKeyBytes(exportTargetRecord, passphrase);
setExportStoragePass(passphrase);
setExportStep("export");
setExportError(null);
} catch {
setExportError(t("incorrect_passphrase"));
}
return;
}
// Export passphrase step
try {
const p12Bytes = await exportPkcs12(exportTargetRecord, exportStoragePass, passphrase);
const filename = `${exportTargetRecord.email.replace(/[^a-zA-Z0-9.-]/g, '_')}.p12`;
downloadPkcs12(p12Bytes, filename);
setExportDialogOpen(false);
setExportTargetRecord(null);
setExportStoragePass("");
setExportError(null);
} catch (err) {
setExportError(err instanceof Error ? err.message : "Export failed");
}
};
// ── Helpers ────────────────────────────────────────────────────
const isExpired = (dateStr: string) => new Date(dateStr) < new Date();
const formatDate = (dateStr: string) => {
try {
return new Date(dateStr).toLocaleDateString();
} catch {
return dateStr;
}
};
const getBoundIdentityNames = (keyId: string): string[] => {
return Object.entries(identityKeyBindings)
.filter(([, kId]) => kId === keyId)
.map(([identityId]) => {
const identity = identities.find((i) => i.id === identityId);
return identity?.email ?? identityId;
});
};
return (
<div className="space-y-8">
{error && (
<div className="px-4 py-3 rounded-md bg-destructive/10 text-destructive text-sm">
{error}
</div>
)}
{/* ── Your Certificates ──────────────────────────────────── */}
<SettingsSection
title={t("your_certificates")}
description={t("your_certificates_desc")}
>
<div className="space-y-2">
{keyRecords.map((record) => {
const expired = isExpired(record.notAfter);
const unlocked = isKeyUnlocked(record.id);
const boundIdentities = getBoundIdentityNames(record.id);
return (
<div
key={record.id}
className="flex items-center justify-between p-3 rounded-lg border border-border"
>
<div className="flex items-center gap-3 min-w-0 flex-1">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${expired ? "bg-destructive/10" : "bg-primary/10"}`}>
{expired ? (
<ShieldAlert className="w-4 h-4 text-destructive" />
) : (
<ShieldCheck className="w-4 h-4 text-primary" />
)}
</div>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{record.email || record.subject}
</p>
<p className="text-xs text-muted-foreground">
{record.issuer} · {t("expires")} {formatDate(record.notAfter)}
{expired && <span className="text-destructive ml-1">({t("expired")})</span>}
</p>
{boundIdentities.length > 0 && (
<p className="text-xs text-muted-foreground">
{t("bound_to")}: {boundIdentities.join(", ")}
</p>
)}
</div>
</div>
<div className="flex items-center gap-1">
{unlocked ? (
<Button
variant="ghost"
size="icon"
onClick={() => lockKey(record.id)}
title={t("lock")}
>
<Unlock className="w-4 h-4 text-green-600" />
</Button>
) : (
<Button
variant="ghost"
size="icon"
onClick={() => handleUnlockRequest(record.id)}
title={t("unlock")}
>
<Lock className="w-4 h-4" />
</Button>
)}
<Button
variant="ghost"
size="icon"
onClick={() => {
setCertModalRecord(record);
setCertModalType("private");
}}
title={t("details")}
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => handleExportRequest(record)}
title={t("export")}
>
<Download className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => removeKeyRecord(record.id)}
title={t("delete")}
>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
</div>
</div>
);
})}
{keyRecords.length === 0 && !isLoading && (
<p className="text-sm text-muted-foreground py-4 text-center">
{t("no_certificates")}
</p>
)}
</div>
<input
ref={fileInputRef}
type="file"
accept=".p12,.pfx"
className="hidden"
onChange={handleFileSelect}
/>
<Button
variant="outline"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading}
className="mt-2"
>
<Upload className="w-4 h-4 mr-2" />
{t("import_pkcs12")}
</Button>
</SettingsSection>
{/* ── Recipient Certificates ─────────────────────────────── */}
<SettingsSection
title={t("recipient_certificates")}
description={t("recipient_certificates_desc")}
>
<div className="space-y-2">
{publicCerts.map((cert) => {
const expired = isExpired(cert.notAfter);
return (
<div
key={cert.id}
className="flex items-center justify-between p-3 rounded-lg border border-border"
>
<div className="flex items-center gap-3 min-w-0 flex-1">
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
<Users className="w-4 h-4 text-muted-foreground" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{cert.email || cert.subject}
</p>
<p className="text-xs text-muted-foreground">
{cert.issuer} · {cert.source}
{expired && <span className="text-destructive ml-1">({t("expired")})</span>}
</p>
</div>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => {
setCertModalRecord(cert);
setCertModalType("public");
}}
title={t("details")}
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => removePublicCert(cert.id)}
title={t("delete")}
>
<Trash2 className="w-4 h-4 text-destructive" />
</Button>
</div>
</div>
);
})}
{publicCerts.length === 0 && !isLoading && (
<p className="text-sm text-muted-foreground py-4 text-center">
{t("no_recipient_certs")}
</p>
)}
</div>
<input
ref={pubCertInputRef}
type="file"
accept=".pem,.cer,.crt,.der"
className="hidden"
onChange={handlePublicCertFile}
/>
<Button
variant="outline"
onClick={() => pubCertInputRef.current?.click()}
disabled={isLoading}
className="mt-2"
>
<Upload className="w-4 h-4 mr-2" />
{t("import_public_cert")}
</Button>
</SettingsSection>
{/* ── Identity Bindings ──────────────────────────────────── */}
{identities.length > 0 && keyRecords.length > 0 && (
<SettingsSection
title={t("identity_bindings")}
description={t("identity_bindings_desc")}
>
{identities.map((identity) => {
const boundKeyId = identityKeyBindings[identity.id];
return (
<SettingItem key={identity.id} label={identity.email}>
<select
value={boundKeyId ?? ""}
onChange={(e) =>
bindIdentityToKey(identity.id, e.target.value || null)
}
className="text-sm bg-background border border-border rounded-md px-2 py-1"
>
<option value="">{t("no_key_bound")}</option>
{keyRecords.map((kr) => (
<option key={kr.id} value={kr.id}>
{kr.email} ({kr.algorithm})
</option>
))}
</select>
</SettingItem>
);
})}
</SettingsSection>
)}
{/* ── Defaults ───────────────────────────────────────────── */}
<SettingsSection
title={t("defaults_title")}
description={t("defaults_desc")}
>
<SettingItem
label={t("encrypt_by_default")}
description={t("encrypt_by_default_desc")}
>
<ToggleSwitch
checked={defaultEncrypt}
onChange={setEncryptDefault}
/>
</SettingItem>
<SettingItem
label={t("remember_unlocked")}
description={t("remember_unlocked_desc")}
>
<ToggleSwitch
checked={rememberUnlockedKeys}
onChange={setRememberUnlockedKeys}
/>
</SettingItem>
<SettingItem
label={t("auto_import_signer_certs")}
description={t("auto_import_signer_certs_desc")}
>
<ToggleSwitch
checked={autoImportSignerCerts}
onChange={setAutoImportSignerCerts}
/>
</SettingItem>
{identities.map((identity) => {
const bound = identityKeyBindings[identity.id];
if (!bound) return null;
return (
<SettingItem
key={identity.id}
label={`${t("sign_default_for")} ${identity.email}`}
>
<ToggleSwitch
checked={defaultSignIdentity[identity.id] ?? false}
onChange={(v) => setSignDefault(identity.id, v)}
/>
</SettingItem>
);
})}
</SettingsSection>
{/* ── Dialogs ────────────────────────────────────────────── */}
<SmimePassphraseDialog
isOpen={importDialogOpen}
onClose={() => {
setImportDialogOpen(false);
setPendingFile(null);
setPendingP12Pass("");
setImportError(null);
setImportStep("p12");
}}
onSubmit={handleImportSubmit}
title={importStep === "p12" ? t("enter_p12_passphrase") : t("enter_storage_passphrase")}
description={importStep === "p12" ? t("p12_passphrase_desc") : t("storage_passphrase_desc")}
submitText={importStep === "p12" ? t("next") : t("import")}
error={importError}
showConfirm={importStep === "storage"}
/>
<SmimePassphraseDialog
isOpen={unlockDialogOpen}
onClose={() => {
setUnlockDialogOpen(false);
setUnlockTargetId(null);
setUnlockError(null);
}}
onSubmit={handleUnlockSubmit}
title={t("unlock_key")}
description={t("unlock_key_desc")}
error={unlockError}
/>
<SmimeCertificateModal
isOpen={!!certModalRecord}
onClose={() => setCertModalRecord(null)}
record={certModalRecord}
type={certModalType}
/>
<SmimePassphraseDialog
isOpen={exportDialogOpen}
onClose={() => {
setExportDialogOpen(false);
setExportTargetRecord(null);
setExportStoragePass("");
setExportError(null);
setExportStep("storage");
}}
onSubmit={handleExportSubmit}
title={exportStep === "storage" ? t("enter_storage_passphrase") : t("enter_export_passphrase")}
description={exportStep === "storage" ? t("export_storage_desc") : t("export_passphrase_desc")}
submitText={exportStep === "storage" ? t("next") : t("export")}
error={exportError}
showConfirm={exportStep === "export"}
/>
</div>
);
}
+413
View File
@@ -0,0 +1,413 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { createPortal } from "react-dom";
import { useTranslations } from "next-intl";
import { useTour } from "./tour-provider";
import { cn } from "@/lib/utils";
import { useFocusTrap } from "@/hooks/use-focus-trap";
interface Rect {
top: number;
left: number;
width: number;
height: number;
}
const PADDING = 8;
const TOOLTIP_GAP = 12;
const TOOLTIP_MAX_W = 360;
function getTargetRect(selector: string): Rect | null {
const el = document.querySelector(selector);
if (!el) return null;
const r = el.getBoundingClientRect();
// Element might exist but be hidden (zero dimensions)
if (r.width === 0 && r.height === 0) return null;
return { top: r.top, left: r.left, width: r.width, height: r.height };
}
function computeTooltipPosition(
target: Rect,
placement: "top" | "bottom" | "left" | "right",
tooltipSize: { width: number; height: number }
): { top: number; left: number; actualPlacement: string } {
const vw = window.innerWidth;
const vh = window.innerHeight;
const tw = Math.max(tooltipSize.width, 200); // minimum fallback width
const th = Math.max(tooltipSize.height, 100); // minimum fallback height
const positions = {
bottom: {
top: target.top + target.height + PADDING + TOOLTIP_GAP,
left: target.left + target.width / 2 - tw / 2,
},
top: {
top: target.top - PADDING - TOOLTIP_GAP - th,
left: target.left + target.width / 2 - tw / 2,
},
right: {
top: target.top + target.height / 2 - th / 2,
left: target.left + target.width + PADDING + TOOLTIP_GAP,
},
left: {
top: target.top + target.height / 2 - th / 2,
left: target.left - PADDING - TOOLTIP_GAP - tw,
},
};
const fits = (p: { top: number; left: number }) =>
p.top >= 8 && p.left >= 8 && p.top + th <= vh - 8 && p.left + tw <= vw - 8;
// Try preferred placement first, then fallback order
const order: Array<"top" | "bottom" | "left" | "right"> = [placement, "bottom", "right", "left", "top"];
for (const dir of order) {
const pos = positions[dir];
if (fits(pos)) return { ...pos, actualPlacement: dir };
}
// If nothing fits perfectly, use preferred but clamped
const pos = positions[placement];
return {
top: Math.max(8, Math.min(pos.top, vh - th - 8)),
left: Math.max(8, Math.min(pos.left, vw - tw - 8)),
actualPlacement: placement,
};
}
export function TourOverlay() {
const t = useTranslations();
const { currentStep, totalSteps, steps, nextStep, prevStep, stopTour } = useTour();
const step = steps[currentStep];
const [targetRect, setTargetRect] = useState<Rect | null>(null);
const [tooltipPos, setTooltipPos] = useState<{ top: number; left: number } | null>(null);
const [visible, setVisible] = useState(false);
const [mounted, setMounted] = useState(false);
const tooltipRef = useRef<HTMLDivElement>(null);
const pendingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Use refs for callbacks to avoid stale closures in timers/intervals
const updatePositionRef = useRef<() => void>(() => {});
const nextStepRef = useRef<() => void>(() => {});
nextStepRef.current = nextStep;
const focusTrapRef = useFocusTrap({
isActive: visible,
onEscape: stopTour,
restoreFocus: true,
});
// Set mounted for portal
useEffect(() => { setMounted(true); }, []);
const updatePosition = useCallback(() => {
if (!step) return;
const rect = getTargetRect(step.target);
if (rect) {
setTargetRect(rect);
if (tooltipRef.current) {
const { width, height } = tooltipRef.current.getBoundingClientRect();
const pos = computeTooltipPosition(rect, step.placement, { width, height });
setTooltipPos({ top: pos.top, left: pos.left });
}
}
// If rect is null, keep previous targetRect (element temporarily hidden during scroll/resize)
// Only the step-change effect should null out targetRect
}, [step]);
// Keep ref in sync
updatePositionRef.current = updatePosition;
// Wait for target element to appear, then show
useEffect(() => {
if (!step) return;
console.log(`[Tour] Step ${currentStep + 1}/${totalSteps}: "${step.id}" — target: ${step.target}, placement: ${step.placement}, interactive: ${!!step.interactive}`);
setVisible(false);
// Keep old targetRect and tooltipPos so the cutout/tooltip animate to the new position
// instead of disappearing and reappearing
// Clear any pending timer from a previous step
if (pendingTimerRef.current) {
clearTimeout(pendingTimerRef.current);
pendingTimerRef.current = null;
}
// Run beforeAction if defined (e.g. click an email to open the viewer)
if (step.beforeAction) {
step.beforeAction();
}
let attempts = 0;
const maxAttempts = 50; // 5 seconds
let cancelled = false;
const tryFind = () => {
if (cancelled) return true;
const el = document.querySelector(step.target);
if (el) {
const rect = el.getBoundingClientRect();
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": element FOUND (${rect.width}x${rect.height} at ${Math.round(rect.left)},${Math.round(rect.top)})`);
el.scrollIntoView({ behavior: "smooth", block: "nearest" });
// Delay after scroll for layout to settle
pendingTimerRef.current = setTimeout(() => {
if (cancelled) return;
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": showing tooltip`);
updatePositionRef.current();
setVisible(true);
// Second position update after tooltip renders with final dimensions
requestAnimationFrame(() => {
if (!cancelled) updatePositionRef.current();
});
}, 200);
return true;
}
if (attempts % 10 === 0) {
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": element NOT found (attempt ${attempts + 1}/${maxAttempts})`);
}
return false;
};
if (tryFind()) return () => { cancelled = true; };
// Poll for element appearance (for page navigation)
const interval = setInterval(() => {
attempts++;
if (tryFind() || attempts >= maxAttempts) {
clearInterval(interval);
if (attempts >= maxAttempts && !cancelled) {
// Skip this step if element never appears
console.warn(`[Tour] Step ${currentStep + 1} "${step.id}": SKIPPED — element never appeared after ${maxAttempts} attempts`);
nextStepRef.current();
}
}
}, 100);
return () => {
cancelled = true;
clearInterval(interval);
if (pendingTimerRef.current) {
clearTimeout(pendingTimerRef.current);
pendingTimerRef.current = null;
}
};
}, [step, currentStep]); // eslint-disable-line react-hooks/exhaustive-deps
// Recalculate on resize/scroll (debounced)
useEffect(() => {
if (!visible) return;
let rafId: number | null = null;
const handler = () => {
if (rafId) cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
updatePosition();
});
};
window.addEventListener("resize", handler);
window.addEventListener("scroll", handler, true);
return () => {
window.removeEventListener("resize", handler);
window.removeEventListener("scroll", handler, true);
if (rafId) cancelAnimationFrame(rafId);
};
}, [visible, updatePosition]);
// Keyboard navigation
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "ArrowRight" || e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
nextStep();
} else if (e.key === "ArrowLeft") {
e.preventDefault();
e.stopPropagation();
prevStep();
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
stopTour();
}
};
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, [nextStep, prevStep, stopTour]);
// Re-position after tooltip content renders with new dimensions
useEffect(() => {
if (!visible || !tooltipRef.current) return;
// Use rAF to wait for the browser to lay out the tooltip content
const id = requestAnimationFrame(() => {
updatePosition();
});
return () => cancelAnimationFrame(id);
}, [visible, updatePosition, currentStep]);
if (!mounted || !step) return null;
const cutout = targetRect
? {
x: targetRect.left - PADDING,
y: targetRect.top - PADDING,
w: targetRect.width + PADDING * 2,
h: targetRect.height + PADDING * 2,
}
: null;
const isLast = currentStep >= totalSteps - 1;
const isFirst = currentStep === 0;
const isInteractive = step.interactive;
const reducedMotion =
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const transitionStyle = reducedMotion ? "none" : "all 300ms ease";
return createPortal(
<>
{/* SVG overlay with cutout */}
<svg
className="fixed inset-0 z-[9998]"
width="100%"
height="100%"
style={{ pointerEvents: isInteractive ? "none" : "auto" }}
onClick={stopTour}
>
<defs>
<mask id="tour-mask">
<rect fill="white" width="100%" height="100%" />
{cutout && (
<rect
fill="black"
x={cutout.x}
y={cutout.y}
width={cutout.w}
height={cutout.h}
rx="8"
style={{ transition: transitionStyle }}
/>
)}
</mask>
</defs>
<rect
fill="black"
opacity="0.5"
mask="url(#tour-mask)"
width="100%"
height="100%"
/>
</svg>
{/* Click-through cutout zone for interactive steps */}
{isInteractive && cutout && (
<div
className="fixed z-[9998]"
style={{
top: cutout.y,
left: cutout.x,
width: cutout.w,
height: cutout.h,
pointerEvents: "none",
transition: transitionStyle,
}}
/>
)}
{/* Non-interactive overlay click blocker around cutout */}
{!isInteractive && cutout && (
<div
className="fixed z-[9998]"
style={{
top: cutout.y,
left: cutout.x,
width: cutout.w,
height: cutout.h,
pointerEvents: "none",
}}
/>
)}
{/* Tooltip */}
<div
ref={(node) => {
(tooltipRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
(focusTrapRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
}}
role="dialog"
aria-modal="true"
aria-label={t(step.titleKey)}
className={cn(
"fixed z-[9999] transition-all",
visible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-2"
)}
style={{
top: tooltipPos?.top ?? -9999,
left: tooltipPos?.left ?? -9999,
maxWidth: TOOLTIP_MAX_W,
transition: reducedMotion ? "none" : "opacity 200ms ease, transform 200ms ease, top 300ms ease, left 300ms ease",
pointerEvents: "auto",
}}
onClick={(e) => e.stopPropagation()}
>
<div className="bg-background border border-border rounded-xl shadow-2xl p-4">
{/* Step counter */}
<p className="text-xs text-muted-foreground mb-1" aria-live="polite">
{t("tour.step_counter", { current: currentStep + 1, total: totalSteps })}
</p>
{/* Title */}
<h3 className="font-semibold text-sm text-foreground">{t(step.titleKey)}</h3>
{/* Description */}
<p className="text-sm text-muted-foreground mt-1">{t(step.descriptionKey)}</p>
{/* Navigation buttons */}
<div className="flex items-center justify-between mt-3">
<button
onClick={stopTour}
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1 rounded hover:bg-muted"
>
{t("tour.skip")}
</button>
<div className="flex gap-2">
<button
onClick={prevStep}
disabled={isFirst}
className={cn(
"text-xs px-3 py-1.5 rounded-md border border-border transition-colors",
isFirst
? "opacity-40 cursor-not-allowed"
: "hover:bg-muted"
)}
>
{t("tour.back")}
</button>
<button
onClick={nextStep}
className="text-xs px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
>
{isLast ? t("tour.finish") : t("tour.next")}
</button>
</div>
</div>
{/* Progress dots */}
<div className="flex justify-center gap-1 mt-2">
{steps.map((_, i) => (
<span
key={i}
className={cn(
"w-1.5 h-1.5 rounded-full transition-colors",
i === currentStep ? "bg-primary" : "bg-muted-foreground/30"
)}
/>
))}
</div>
</div>
</div>
</>,
document.body
);
}
+148
View File
@@ -0,0 +1,148 @@
"use client";
import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react";
import { useRouter } from "@/i18n/navigation";
import { useAuthStore } from "@/stores/auth-store";
import { useCalendarStore } from "@/stores/calendar-store";
import { useWebDAVStore } from "@/stores/webdav-store";
import { getTourSteps, type TourStep } from "./tour-steps";
import { TourOverlay } from "./tour-overlay";
const TOUR_COMPLETED_KEY = "tour_completed";
const TOUR_CURRENT_STEP_KEY = "tour_current_step";
interface TourContextValue {
isActive: boolean;
currentStep: number;
totalSteps: number;
steps: TourStep[];
startTour: () => void;
stopTour: () => void;
nextStep: () => void;
prevStep: () => void;
hasCompletedTour: boolean;
resetTourCompletion: () => void;
}
const TourContext = createContext<TourContextValue | null>(null);
export function useTour() {
const ctx = useContext(TourContext);
if (!ctx) throw new Error("useTour must be used within TourProvider");
return ctx;
}
export function TourProvider({ children }: { children: ReactNode }) {
const router = useRouter();
const { isDemoMode } = useAuthStore();
const { supportsCalendar } = useCalendarStore();
const { supportsWebDAV } = useWebDAVStore();
const [isActive, setIsActive] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
const [hasCompletedTour, setHasCompletedTour] = useState(false);
const steps = getTourSteps({ isDemoMode, supportsCalendar, supportsWebDAV: supportsWebDAV !== false });
useEffect(() => {
try {
setHasCompletedTour(localStorage.getItem(TOUR_COMPLETED_KEY) === "true");
} catch { /* */ }
}, []);
const startTour = useCallback(() => {
let resumeStep = 0;
try {
const stored = localStorage.getItem(TOUR_CURRENT_STEP_KEY);
if (stored) {
const parsed = parseInt(stored, 10);
if (!isNaN(parsed) && parsed >= 0) resumeStep = parsed;
}
} catch { /* */ }
// If the resume step is beyond the current steps, start from 0
if (resumeStep >= steps.length) resumeStep = 0;
setCurrentStep(resumeStep);
setIsActive(true);
}, [steps.length]);
const stopTour = useCallback(() => {
setIsActive(false);
try {
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
} catch { /* */ }
}, []);
const completeTour = useCallback(() => {
setIsActive(false);
setHasCompletedTour(true);
try {
localStorage.setItem(TOUR_COMPLETED_KEY, "true");
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
} catch { /* */ }
}, []);
const nextStep = useCallback(() => {
if (currentStep >= steps.length - 1) {
completeTour();
return;
}
const next = currentStep + 1;
const nextStepDef = steps[next];
setCurrentStep(next);
try {
localStorage.setItem(TOUR_CURRENT_STEP_KEY, String(next));
} catch { /* */ }
// Navigate if the next step requires a different page
if (nextStepDef?.page) {
router.push(nextStepDef.page);
}
}, [currentStep, steps, completeTour, router]);
const prevStep = useCallback(() => {
if (currentStep <= 0) return;
const prev = currentStep - 1;
const prevStepDef = steps[prev];
setCurrentStep(prev);
try {
localStorage.setItem(TOUR_CURRENT_STEP_KEY, String(prev));
} catch { /* */ }
if (prevStepDef?.page) {
router.push(prevStepDef.page);
} else if (steps[currentStep]?.page) {
// Going back from a page-specific step to a non-page step => go to mail
router.push("/");
}
}, [currentStep, steps, router]);
const resetTourCompletion = useCallback(() => {
setHasCompletedTour(false);
try {
localStorage.removeItem(TOUR_COMPLETED_KEY);
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
} catch { /* */ }
}, []);
const value: TourContextValue = {
isActive,
currentStep,
totalSteps: steps.length,
steps,
startTour,
stopTour,
nextStep,
prevStep,
hasCompletedTour,
resetTourCompletion,
};
return (
<TourContext.Provider value={value}>
{children}
{isActive && <TourOverlay />}
</TourContext.Provider>
);
}
+221
View File
@@ -0,0 +1,221 @@
export interface TourStep {
id: string;
target: string;
titleKey: string;
descriptionKey: string;
placement: "top" | "bottom" | "left" | "right";
interactive?: boolean;
spotlight?: "rect" | "circle";
page?: string;
demoOnly?: boolean;
beforeAction?: () => void;
}
export const BASE_TOUR_STEPS: TourStep[] = [
{
id: "sidebar",
target: '[data-tour="sidebar"]',
titleKey: "tour.sidebar_title",
descriptionKey: "tour.sidebar_desc",
placement: "right",
},
{
id: "compose",
target: '[data-tour="compose-button"]',
titleKey: "tour.compose_title",
descriptionKey: "tour.compose_desc",
placement: "right",
interactive: true,
},
{
id: "search",
target: '[data-tour="search-input"]',
titleKey: "tour.search_title",
descriptionKey: "tour.search_desc",
placement: "bottom",
interactive: true,
},
{
id: "email-list",
target: '[data-tour="email-list"]',
titleKey: "tour.email_list_title",
descriptionKey: "tour.email_list_desc",
placement: "right",
},
{
id: "email-viewer",
target: '[data-tour="email-viewer"]',
titleKey: "tour.email_viewer_title",
descriptionKey: "tour.email_viewer_desc",
placement: "left",
beforeAction: () => {
// Click the "Welcome to Bulwark Mail!" email (or the first email) to open the viewer
const emailList = document.querySelector('[data-tour="email-list"]');
if (!emailList) return;
// Try to find the welcome email by subject text
const items = emailList.querySelectorAll('.cursor-pointer');
let target: HTMLElement | null = null;
for (const item of items) {
if (item.textContent?.includes("Welcome to Bulwark Mail")) {
target = item as HTMLElement;
break;
}
}
// Fallback to first email if welcome email not found
if (!target) target = emailList.querySelector('.cursor-pointer') as HTMLElement | null;
if (target) target.click();
},
},
{
id: "keywords",
target: '[data-tour="keyword-tags"]',
titleKey: "tour.keywords_title",
descriptionKey: "tour.keywords_desc",
placement: "right",
},
{
id: "nav-calendar",
target: '[data-tour="nav-calendar"]',
titleKey: "tour.calendar_title",
descriptionKey: "tour.calendar_desc",
placement: "right",
},
{
id: "nav-contacts",
target: '[data-tour="nav-contacts"]',
titleKey: "tour.contacts_title",
descriptionKey: "tour.contacts_desc",
placement: "right",
},
{
id: "nav-settings",
target: '[data-tour="nav-settings"]',
titleKey: "tour.settings_title",
descriptionKey: "tour.settings_desc",
placement: "right",
},
{
id: "shortcuts",
target: '[data-tour="nav-shortcuts"]',
titleKey: "tour.shortcuts_title",
descriptionKey: "tour.shortcuts_desc",
placement: "right",
interactive: true,
},
];
export const DEMO_TOUR_STEPS: TourStep[] = [
{
id: "compose-open",
target: '[data-tour="composer"]',
titleKey: "tour.compose_open_title",
descriptionKey: "tour.compose_open_desc",
placement: "left",
demoOnly: true,
beforeAction: () => {
// Click the compose button to open the composer
const btn = document.querySelector('[data-tour="compose-button"]') as HTMLElement | null;
if (btn) btn.click();
},
},
{
id: "calendar-view",
target: '[data-tour="calendar-view"]',
titleKey: "tour.calendar_view_title",
descriptionKey: "tour.calendar_view_desc",
placement: "bottom",
page: "/calendar",
demoOnly: true,
},
{
id: "create-event",
target: '[data-tour="create-event-button"]',
titleKey: "tour.create_event_title",
descriptionKey: "tour.create_event_desc",
placement: "bottom",
page: "/calendar",
interactive: true,
demoOnly: true,
},
{
id: "event-modal",
target: '[data-tour="event-modal"]',
titleKey: "tour.event_modal_title",
descriptionKey: "tour.event_modal_desc",
placement: "left",
page: "/calendar",
interactive: true,
demoOnly: true,
beforeAction: () => {
// Click the create event button to open the modal
const btn = document.querySelector('[data-tour="create-event-button"]') as HTMLElement | null;
if (btn) btn.click();
},
},
{
id: "contacts-list",
target: '[data-tour="contacts-list"]',
titleKey: "tour.contacts_list_title",
descriptionKey: "tour.contacts_list_desc",
placement: "right",
page: "/contacts",
demoOnly: true,
},
{
id: "settings-tabs",
target: '[data-tour="settings-tabs"]',
titleKey: "tour.settings_tabs_title",
descriptionKey: "tour.settings_tabs_desc",
placement: "right",
page: "/settings",
demoOnly: true,
},
{
id: "nav-files",
target: '[data-tour="nav-files"]',
titleKey: "tour.files_title",
descriptionKey: "tour.files_desc",
placement: "right",
demoOnly: true,
},
{
id: "demo-banner",
target: '[data-tour="demo-banner"]',
titleKey: "tour.demo_banner_title",
descriptionKey: "tour.demo_banner_desc",
placement: "bottom",
page: "/",
demoOnly: true,
},
{
id: "quota",
target: '[data-tour="storage-quota"]',
titleKey: "tour.quota_title",
descriptionKey: "tour.quota_desc",
placement: "right",
demoOnly: true,
},
];
export function getTourSteps(options: {
isDemoMode: boolean;
supportsCalendar: boolean;
supportsWebDAV: boolean;
}): TourStep[] {
let steps = [...BASE_TOUR_STEPS];
if (!options.supportsCalendar) {
steps = steps.filter((s) => s.id !== "nav-calendar");
}
if (options.isDemoMode) {
const demoSteps = DEMO_TOUR_STEPS.filter((s) => {
if (s.id === "nav-files" && !options.supportsWebDAV) return false;
if ((s.id === "calendar-view" || s.id === "create-event" || s.id === "event-modal") && !options.supportsCalendar) return false;
return true;
});
steps = [...steps, ...demoSteps];
}
return steps;
}
+12 -1
View File
@@ -2,15 +2,17 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { X, Lightbulb, Settings } from "lucide-react"; import { X, Lightbulb, Settings, PlayCircle } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { useRouter } from "@/i18n/navigation"; import { useRouter } from "@/i18n/navigation";
import { useTour } from "@/components/tour/tour-provider";
const ONBOARDING_KEY = "onboarding_completed"; const ONBOARDING_KEY = "onboarding_completed";
export function WelcomeBanner() { export function WelcomeBanner() {
const t = useTranslations("welcome"); const t = useTranslations("welcome");
const router = useRouter(); const router = useRouter();
const { startTour } = useTour();
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [dismissed, setDismissed] = useState(false); const [dismissed, setDismissed] = useState(false);
@@ -78,6 +80,15 @@ export function WelcomeBanner() {
</button> </button>
</div> </div>
<div className="mt-2.5 flex justify-end gap-2"> <div className="mt-2.5 flex justify-end gap-2">
<Button
variant="outline"
size="sm"
onClick={() => { dismiss(); startTour(); }}
className="text-xs h-7"
>
<PlayCircle className="w-3.5 h-3.5 mr-1" />
{t("start_tour")}
</Button>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
+3
View File
@@ -3,6 +3,9 @@ services:
image: ghcr.io/bulwarkmail/webmail:latest image: ghcr.io/bulwarkmail/webmail:latest
ports: ports:
- "3000:3000" - "3000:3000"
environment:
- HOSTNAME=0.0.0.0 # Use "::" for IPv6
- PORT=3000
env_file: env_file:
- .env.local - .env.local
healthcheck: healthcheck:
+9 -5
View File
@@ -28,15 +28,18 @@ export default [
}, },
plugins: { plugins: {
"@typescript-eslint": tseslint, "@typescript-eslint": tseslint,
"react": reactPlugin, react: reactPlugin,
"react-hooks": reactHooksPlugin, "react-hooks": reactHooksPlugin,
}, },
rules: { rules: {
...tseslint.configs.recommended.rules, ...tseslint.configs.recommended.rules,
"@typescript-eslint/no-unused-vars": ["warn", { "@typescript-eslint/no-unused-vars": [
argsIgnorePattern: "^_", "warn",
varsIgnorePattern: "^_" {
}], argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
},
],
"@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-empty-object-type": "off", "@typescript-eslint/no-empty-object-type": "off",
"react-hooks/rules-of-hooks": "error", "react-hooks/rules-of-hooks": "error",
@@ -70,6 +73,7 @@ export default [
"*.config.js", "*.config.js",
"*.config.mjs", "*.config.mjs",
"e2e/**", "e2e/**",
"local-data/**/*.mjs",
], ],
}, },
]; ];
+36 -4
View File
@@ -5,9 +5,10 @@ import { useTranslations, useLocale } from 'next-intl';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { useCalendarStore } from '@/stores/calendar-store'; import { useCalendarStore } from '@/stores/calendar-store';
import { useSettingsStore } from '@/stores/settings-store'; import { useSettingsStore } from '@/stores/settings-store';
import { useTaskStore } from '@/stores/task-store';
import { useCalendarNotificationStore } from '@/stores/calendar-notification-store'; import { useCalendarNotificationStore } from '@/stores/calendar-notification-store';
import { useToastStore } from '@/stores/toast-store'; import { useToastStore } from '@/stores/toast-store';
import { getPendingAlerts, buildAlertKey } from '@/lib/calendar-alerts'; import { getPendingAlerts, getPendingTaskAlerts, buildAlertKey } from '@/lib/calendar-alerts';
import { playNotificationSound } from '@/lib/notification-sound'; import { playNotificationSound } from '@/lib/notification-sound';
import type { CalendarEvent } from '@/lib/jmap/types'; import type { CalendarEvent } from '@/lib/jmap/types';
@@ -18,7 +19,8 @@ const PROACTIVE_THROTTLE_MS = CHECK_INTERVAL_MS * 5;
export function useCalendarAlerts() { export function useCalendarAlerts() {
const { isAuthenticated, client } = useAuthStore(); const { isAuthenticated, client } = useAuthStore();
const { events, calendars, supportsCalendar } = useCalendarStore(); const { events, calendars, supportsCalendar } = useCalendarStore();
const { calendarNotificationsEnabled, calendarNotificationSound } = useSettingsStore(); const { calendarNotificationsEnabled, calendarNotificationSound, enableCalendarTasks, notificationSoundChoice } = useSettingsStore();
const { tasks: storeTasks } = useTaskStore();
const { acknowledgedAlerts, acknowledgeAlert, cleanupStaleAlerts } = useCalendarNotificationStore(); const { acknowledgedAlerts, acknowledgeAlert, cleanupStaleAlerts } = useCalendarNotificationStore();
const addToast = useToastStore((s) => s.addToast); const addToast = useToastStore((s) => s.addToast);
const t = useTranslations('calendar.notifications'); const t = useTranslations('calendar.notifications');
@@ -45,7 +47,7 @@ export function useCalendarAlerts() {
acknowledgeAlert(key, alert.fireTimeMs); acknowledgeAlert(key, alert.fireTimeMs);
if (calendarNotificationSound) { if (calendarNotificationSound) {
playNotificationSound(); playNotificationSound(notificationSoundChoice);
} }
const diffMs = new Date(alert.event.utcStart || alert.event.start).getTime() - now; const diffMs = new Date(alert.event.utcStart || alert.event.start).getTime() - now;
@@ -69,11 +71,41 @@ export function useCalendarAlerts() {
}, },
}); });
} }
// Task alerts
if (enableCalendarTasks && storeTasks.length > 0) {
const pendingTaskAlerts = getPendingTaskAlerts(storeTasks, calendars, acknowledgedKeys, now);
for (const taskAlert of pendingTaskAlerts) {
const key = buildAlertKey(taskAlert.taskId, taskAlert.alertId, taskAlert.fireTimeMs);
if (shownKeysRef.current.has(key)) continue;
shownKeysRef.current.add(key);
acknowledgeAlert(key, taskAlert.fireTimeMs);
if (calendarNotificationSound) {
playNotificationSound(notificationSoundChoice);
}
const taskMsg = taskAlert.calendarName
? `${t('task_due')} · ${taskAlert.calendarName}`
: t('task_due');
addToast({
type: 'info',
title: taskAlert.task.title || t('alert_title'),
message: taskMsg,
duration: 15000,
onClick: () => {
window.location.href = `/${locale}/calendar`;
},
});
}
}
} catch { } catch {
// Silently ignore alert evaluation errors // Silently ignore alert evaluation errors
} }
}, [ }, [
calendarNotificationsEnabled, calendarNotificationSound, calendarNotificationsEnabled, calendarNotificationSound, notificationSoundChoice,
isAuthenticated, events, calendars, acknowledgedAlerts, isAuthenticated, events, calendars, acknowledgedAlerts,
acknowledgeAlert, addToast, t, locale, acknowledgeAlert, addToast, t, locale,
]); ]);
+28
View File
@@ -13,12 +13,19 @@ interface ConfigData {
settingsSyncEnabled: boolean; settingsSyncEnabled: boolean;
stalwartFeaturesEnabled: boolean; stalwartFeaturesEnabled: boolean;
devMode: boolean; devMode: boolean;
faviconUrl: string;
appLogoLightUrl: string;
appLogoDarkUrl: string;
loginLogoLightUrl: string; loginLogoLightUrl: string;
loginLogoDarkUrl: string; loginLogoDarkUrl: string;
loginCompanyName: string; loginCompanyName: string;
loginImprintUrl: string; loginImprintUrl: string;
loginPrivacyPolicyUrl: string; loginPrivacyPolicyUrl: string;
loginWebsiteUrl: string; loginWebsiteUrl: string;
demoMode: boolean;
autoSsoEnabled: boolean;
embeddedMode: boolean;
parentOrigin: string;
} }
interface AppConfig extends ConfigData { interface AppConfig extends ConfigData {
@@ -79,12 +86,19 @@ export function useConfig(): AppConfig {
settingsSyncEnabled: configCache?.settingsSyncEnabled || false, settingsSyncEnabled: configCache?.settingsSyncEnabled || false,
stalwartFeaturesEnabled: configCache?.stalwartFeaturesEnabled ?? true, stalwartFeaturesEnabled: configCache?.stalwartFeaturesEnabled ?? true,
devMode: configCache?.devMode || false, devMode: configCache?.devMode || false,
faviconUrl: configCache?.faviconUrl || '/branding/Bulwark_Favicon.svg',
appLogoLightUrl: configCache?.appLogoLightUrl || '',
appLogoDarkUrl: configCache?.appLogoDarkUrl || '',
loginLogoLightUrl: configCache?.loginLogoLightUrl || '/branding/Bulwark_Logo_Color.svg', loginLogoLightUrl: configCache?.loginLogoLightUrl || '/branding/Bulwark_Logo_Color.svg',
loginLogoDarkUrl: configCache?.loginLogoDarkUrl || '/branding/Bulwark_Logo_White.svg', loginLogoDarkUrl: configCache?.loginLogoDarkUrl || '/branding/Bulwark_Logo_White.svg',
loginCompanyName: configCache?.loginCompanyName || '', loginCompanyName: configCache?.loginCompanyName || '',
loginImprintUrl: configCache?.loginImprintUrl || '', loginImprintUrl: configCache?.loginImprintUrl || '',
loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '', loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '',
loginWebsiteUrl: configCache?.loginWebsiteUrl || '', loginWebsiteUrl: configCache?.loginWebsiteUrl || '',
demoMode: configCache?.demoMode || false,
autoSsoEnabled: configCache?.autoSsoEnabled || false,
embeddedMode: configCache?.embeddedMode || false,
parentOrigin: configCache?.parentOrigin || '',
isLoading: !configCache, isLoading: !configCache,
error: null, error: null,
}); });
@@ -103,12 +117,19 @@ export function useConfig(): AppConfig {
settingsSyncEnabled: configCache.settingsSyncEnabled, settingsSyncEnabled: configCache.settingsSyncEnabled,
stalwartFeaturesEnabled: configCache.stalwartFeaturesEnabled, stalwartFeaturesEnabled: configCache.stalwartFeaturesEnabled,
devMode: configCache.devMode, devMode: configCache.devMode,
faviconUrl: configCache.faviconUrl,
appLogoLightUrl: configCache.appLogoLightUrl,
appLogoDarkUrl: configCache.appLogoDarkUrl,
loginLogoLightUrl: configCache.loginLogoLightUrl, loginLogoLightUrl: configCache.loginLogoLightUrl,
loginLogoDarkUrl: configCache.loginLogoDarkUrl, loginLogoDarkUrl: configCache.loginLogoDarkUrl,
loginCompanyName: configCache.loginCompanyName, loginCompanyName: configCache.loginCompanyName,
loginImprintUrl: configCache.loginImprintUrl, loginImprintUrl: configCache.loginImprintUrl,
loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl, loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl,
loginWebsiteUrl: configCache.loginWebsiteUrl, loginWebsiteUrl: configCache.loginWebsiteUrl,
demoMode: configCache.demoMode,
autoSsoEnabled: configCache.autoSsoEnabled,
embeddedMode: configCache.embeddedMode,
parentOrigin: configCache.parentOrigin,
isLoading: false, isLoading: false,
error: null, error: null,
}); });
@@ -128,12 +149,19 @@ export function useConfig(): AppConfig {
settingsSyncEnabled: data.settingsSyncEnabled, settingsSyncEnabled: data.settingsSyncEnabled,
stalwartFeaturesEnabled: data.stalwartFeaturesEnabled, stalwartFeaturesEnabled: data.stalwartFeaturesEnabled,
devMode: data.devMode, devMode: data.devMode,
faviconUrl: data.faviconUrl,
appLogoLightUrl: data.appLogoLightUrl,
appLogoDarkUrl: data.appLogoDarkUrl,
loginLogoLightUrl: data.loginLogoLightUrl, loginLogoLightUrl: data.loginLogoLightUrl,
loginLogoDarkUrl: data.loginLogoDarkUrl, loginLogoDarkUrl: data.loginLogoDarkUrl,
loginCompanyName: data.loginCompanyName, loginCompanyName: data.loginCompanyName,
loginImprintUrl: data.loginImprintUrl, loginImprintUrl: data.loginImprintUrl,
loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl, loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl,
loginWebsiteUrl: data.loginWebsiteUrl, loginWebsiteUrl: data.loginWebsiteUrl,
demoMode: data.demoMode,
autoSsoEnabled: data.autoSsoEnabled,
embeddedMode: data.embeddedMode,
parentOrigin: data.parentOrigin,
isLoading: false, isLoading: false,
error: null, error: null,
}); });
+49
View File
@@ -0,0 +1,49 @@
import { useState, useCallback } from 'react';
import { useSettingsStore } from '@/stores/settings-store';
export interface InlineAppState {
id: string;
url: string;
name: string;
}
export function useSidebarApps() {
const [showAppsModal, setShowAppsModal] = useState(false);
const [inlineApp, setInlineApp] = useState<InlineAppState | null>(null);
const [loadedApps, setLoadedApps] = useState<InlineAppState[]>([]);
const keepAppsLoaded = useSettingsStore((s) => s.keepAppsLoaded);
const handleManageApps = useCallback(() => {
setShowAppsModal(true);
}, []);
const handleInlineApp = useCallback((appId: string, url: string, name: string) => {
const app = { id: appId, url, name };
setInlineApp(app);
setLoadedApps((prev) => {
if (prev.some((a) => a.id === appId)) return prev;
return [...prev, app];
});
}, []);
const closeInlineApp = useCallback(() => {
if (!keepAppsLoaded) {
setLoadedApps((prev) => prev.filter((a) => a.id !== inlineApp?.id));
}
setInlineApp(null);
}, [keepAppsLoaded, inlineApp]);
const closeAppsModal = useCallback(() => {
setShowAppsModal(false);
}, []);
return {
showAppsModal,
inlineApp,
loadedApps: keepAppsLoaded ? loadedApps : (inlineApp ? [inlineApp] : []),
handleManageApps,
handleInlineApp,
closeInlineApp,
closeAppsModal,
};
}
+4 -3
View File
@@ -239,9 +239,10 @@ export function useTimeGridInteractions({
clearTimeout(clickTimerRef.current); clearTimeout(clickTimerRef.current);
clickTimerRef.current = null; clickTimerRef.current = null;
} }
const key = format(day, "yyyy-MM-dd"); const d = new Date(day);
setQuickCreate({ dayKey: key, day, hour, top: hour * hourHeight }); d.setHours(hour, 0, 0, 0);
}, [hourHeight]); onCreateRange(d);
}, [onCreateRange]);
const handleQuickCreateSubmit = useCallback(async (title: string) => { const handleQuickCreateSubmit = useCallback(async (title: string) => {
if (!quickCreate) return; if (!quickCreate) return;

Some files were not shown because too many files have changed in this diff Show More