Compare commits

..
36 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
95 changed files with 5957 additions and 823 deletions
+4 -1
View File
@@ -64,7 +64,10 @@ JMAP_SERVER_URL=https://your-jmap-server.com
# SETTINGS_SYNC_ENABLED=true
# 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
# =============================================================================
@@ -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 }}
+5 -6
View File
@@ -2,7 +2,9 @@ name: Publish Docker Image
on:
push:
branches: [main]
branches:
- main
- dev
paths:
- "Dockerfile"
- ".dockerignore"
@@ -17,7 +19,6 @@ on:
- "package.json"
- "package-lock.json"
- ".github/workflows/docker-publish.yml"
tags: ["v*.*.*"]
workflow_dispatch:
env:
@@ -114,10 +115,8 @@ jobs:
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
type=raw,value={{branch}}
type=sha,prefix={{branch}}-
- name: Create manifest list and push
working-directory: /tmp/digests
+38
View File
@@ -1,5 +1,43 @@
# 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
+4 -3
View File
@@ -11,9 +11,10 @@
A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.art/).<br/>
Built with Next.js and the JMAP protocol.
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.4.3-green.svg)](CHANGELOG.md)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fbulwarkmail%2Fwebmail-blue)](https://ghcr.io/bulwarkmail/webmail)
[![License: AGPL v3](https://img.shields.io/badge/license-AGPL%20v3-blue.svg?logo=gnu&logoColor=white)](LICENSE)
[![Discord](https://img.shields.io/discord/1482128142939455674?color=7289da&label=discord&logo=discord&logoColor=white)](https://discord.gg/tYCujymGrT)
[![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>
+1 -1
View File
@@ -1 +1 @@
1.4.6
1.4.8
+65 -35
View File
@@ -4,6 +4,7 @@ import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useAuthStore } from "@/stores/auth-store";
import { getPathPrefix } from "@/lib/browser-navigation";
import { Loader2, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useParams } from "next/navigation";
@@ -13,7 +14,7 @@ function OAuthCallbackInner() {
const params = useParams();
const searchParams = useSearchParams();
const t = useTranslations("login");
const { loginWithOAuth } = useAuthStore();
const { loginWithOAuth, loginWithServerSso } = useAuthStore();
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -32,44 +33,73 @@ function OAuthCallbackInner() {
}
const savedState = sessionStorage.getItem("oauth_state");
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
const serverUrl = sessionStorage.getItem("oauth_server_url");
if (savedState) {
// Classic flow — sessionStorage has the PKCE state (same-tab OAuth)
if (!state || state !== savedState) {
setError("invalid_state");
return;
}
if (!codeVerifier || !serverUrl) {
setError("missing_params");
return;
}
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
const serverUrl = sessionStorage.getItem("oauth_server_url");
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
if (!codeVerifier || !serverUrl) {
setError("missing_params");
return;
}
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
.then((success) => {
if (success) {
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("oauth_code_verifier");
sessionStorage.removeItem("oauth_server_url");
sessionStorage.removeItem("oauth_add_account_mode");
let redirectTo = `/${params.locale}`;
try {
const saved = sessionStorage.getItem('redirect_after_login');
if (saved) {
sessionStorage.removeItem('redirect_after_login');
redirectTo = saved;
}
} catch { /* sessionStorage may be unavailable */ }
router.push(redirectTo);
} else {
const prefix = getPathPrefix(params.locale as string);
const redirectUri = `${window.location.origin}${prefix}/${params.locale}/auth/callback`;
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
.then((success) => {
if (success) {
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("oauth_code_verifier");
sessionStorage.removeItem("oauth_server_url");
sessionStorage.removeItem("oauth_add_account_mode");
let redirectTo = `${prefix}/${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");
}
})
.catch(() => {
setError("token_exchange_failed");
});
});
} else if (state) {
// Server-side SSO flow — state was stored in encrypted httpOnly cookie
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
if (error) {
@@ -87,7 +117,7 @@ function OAuthCallbackInner() {
</p>
<Button
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")}
</Button>
+128 -8
View File
@@ -11,7 +11,7 @@ import {
} from "date-fns";
import { useCalendarStore } from "@/stores/calendar-store";
import { isCalendarViewMode } from "@/stores/calendar-store";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { useIdentityStore } from "@/stores/identity-store";
@@ -23,6 +23,9 @@ import { CalendarMonthView } from "@/components/calendar/calendar-month-view";
import { CalendarWeekView } from "@/components/calendar/calendar-week-view";
import { CalendarDayView } from "@/components/calendar/calendar-day-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 { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel";
import { EventModal, type PendingEventPreview } from "@/components/calendar/event-modal";
@@ -35,6 +38,7 @@ 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 { useTaskStore } from "@/stores/task-store";
import { cn } from "@/lib/utils";
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
import { getUserParticipantId } from "@/lib/calendar-participants";
@@ -63,7 +67,8 @@ export default function CalendarPage() {
setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar,
refreshAllSubscriptions,
} = useCalendarStore();
const { firstDayOfWeek, timeFormat } = useSettingsStore();
const { firstDayOfWeek, timeFormat, showWeekNumbers, enableCalendarTasks, showTasksOnCalendar } = useSettingsStore();
const taskStore = useTaskStore();
const { identities } = useIdentityStore();
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
@@ -83,6 +88,8 @@ export default function CalendarPage() {
const [detailEvent, setDetailEvent] = useState<CalendarEvent | 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);
// Sidebar resize state
@@ -105,7 +112,7 @@ export default function CalendarPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login");
redirectToLogin();
} else if (client && !supportsCalendar) {
router.push("/");
}
@@ -166,9 +173,18 @@ export default function CalendarPage() {
end: format(addDays(agendaStart, 30), "yyyy-MM-dd'T'23:59:59"),
};
}
case "tasks":
return null;
}
}, [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(() => {
if (client && calendars.length > 0 && dateRange) {
fetchEvents(client, dateRange.start, dateRange.end);
@@ -182,6 +198,7 @@ export default function CalendarPage() {
case "week": next = subWeeks(selectedDate, 1); break;
case "day": next = subDays(selectedDate, 1); break;
case "agenda": next = subMonths(selectedDate, 1); break;
case "tasks": return;
}
setSelectedDate(next);
setMiniMonth(next);
@@ -194,6 +211,7 @@ export default function CalendarPage() {
case "week": next = addWeeks(selectedDate, 1); break;
case "day": next = addDays(selectedDate, 1); break;
case "agenda": next = addMonths(selectedDate, 1); break;
case "tasks": return;
}
setSelectedDate(next);
setMiniMonth(next);
@@ -254,6 +272,34 @@ export default function CalendarPage() {
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 closeDetail = useCallback(() => {
@@ -424,9 +470,22 @@ export default function CalendarPage() {
try {
if (type === "edit" && updates) {
switch (scope) {
case "this":
await updateEvent(client, event.id, updates, sendScheduling);
case "this": {
// 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;
}
case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event);
if (!result) {
@@ -484,9 +543,20 @@ export default function CalendarPage() {
toast.success(t("notifications.event_updated"));
} else {
switch (scope) {
case "this":
await deleteEvent(client, event.id, sendScheduling);
case "this": {
// 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;
}
case "this_and_future": {
const result = await truncateRecurrenceAtEvent(event);
if (!result) {
@@ -598,6 +668,7 @@ export default function CalendarPage() {
const handleKey = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return;
if (target.getAttribute("contenteditable") === "true") return;
if (showEventModal || detailEvent) return;
switch (e.key) {
@@ -608,6 +679,7 @@ export default function CalendarPage() {
case "w": setViewMode("week"); break;
case "d": setViewMode("day"); break;
case "a": setViewMode("agenda"); break;
case "k": if (enableCalendarTasks) setViewMode("tasks"); break;
case "n": openCreateModal(); break;
}
};
@@ -668,6 +740,8 @@ export default function CalendarPage() {
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/>
);
case "day":
@@ -683,6 +757,8 @@ export default function CalendarPage() {
timeFormat={timeFormat}
isMobile={isMobile}
pendingPreview={pendingPreview}
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
/>
);
case "agenda":
@@ -697,6 +773,33 @@ export default function CalendarPage() {
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>
);
}
})();
@@ -721,7 +824,7 @@ export default function CalendarPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
@@ -751,6 +854,7 @@ export default function CalendarPage() {
onChangeMonth={handleMiniMonthChange}
events={events}
firstDayOfWeek={firstDayOfWeek}
showWeekNumbers={showWeekNumbers}
/>
<CalendarSidebarPanel
calendars={calendars}
@@ -791,6 +895,7 @@ export default function CalendarPage() {
calendars={calendars}
selectedCalendarIds={selectedCalendarIds}
onToggleVisibility={toggleCalendarVisibility}
enableCalendarTasks={enableCalendarTasks}
/>
<div
@@ -822,6 +927,21 @@ export default function CalendarPage() {
</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) */}
{isMobile && (
<Button
+4 -6
View File
@@ -1,7 +1,6 @@
"use client";
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
import { ArrowLeft, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -16,7 +15,7 @@ import { ContactsSidebar, type ContactCategory } from "@/components/contacts/con
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
import { exportContacts } from "@/components/contacts/contact-export";
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
import { useAuthStore } from "@/stores/auth-store";
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { toast } from "@/stores/toast-store";
import { cn } from "@/lib/utils";
@@ -39,7 +38,6 @@ type View =
| "bulk-add-to-group";
export default function ContactsPage() {
const router = useRouter();
const t = useTranslations("contacts");
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
@@ -109,9 +107,9 @@ export default function ContactsPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push("/login");
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
useEffect(() => {
if (client && supportsSync && !hasFetched.current) {
@@ -594,7 +592,7 @@ export default function ContactsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+4 -4
View File
@@ -7,7 +7,7 @@ import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/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 { useFileStore } from "@/stores/file-store";
import { toast } from "@/stores/toast-store";
@@ -112,9 +112,9 @@ export default function FilesPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
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
useEffect(() => {
@@ -357,7 +357,7 @@ export default function FilesPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+6 -3
View File
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
import { IntlProvider } from "@/components/providers/intl-provider";
import { ThemeProvider } from "@/components/providers/theme-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";
@@ -27,9 +28,11 @@ export default async function LocaleLayout({
<IntlProvider locale={locale} messages={messages}>
<ThemeProvider>
<CalendarAlertProvider>
<TourProvider>
{children}
</TourProvider>
<EmbeddedBridgeProvider>
<TourProvider>
{children}
</TourProvider>
</EmbeddedBridgeProvider>
</CalendarAlertProvider>
</ThemeProvider>
</IntlProvider>
+59 -2
View File
@@ -16,7 +16,7 @@ import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
const APP_VERSION = "1.4.3";
const APP_VERSION = "1.4.7";
const THEME_OPTIONS = [
{ value: "light" as const, icon: Sun, label: "Light" },
@@ -32,7 +32,7 @@ export default function LoginPage() {
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 { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, demoMode, 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 [formData, setFormData] = useState({
@@ -173,6 +173,63 @@ export default function LoginPage() {
});
}, [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") => {
setTheme(newTheme);
setShowThemeMenu(false);
+35 -12
View File
@@ -1,7 +1,6 @@
"use client";
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations } from "next-intl";
import { Sidebar } from "@/components/layout/sidebar";
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 { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
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 { useIdentityStore } from "@/stores/identity-store";
import { useUIStore } from "@/stores/ui-store";
@@ -48,7 +47,6 @@ import { Button } from "@/components/ui/button";
import { useConfig } from "@/hooks/use-config";
export default function Home() {
const router = useRouter();
const t = useTranslations();
const tCommon = useTranslations('common');
const { appName } = useConfig();
@@ -285,9 +283,9 @@ export default function Home() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
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)
useEffect(() => {
@@ -409,7 +407,10 @@ export default function Home() {
// Handle new email notifications - play sound
useEffect(() => {
if (newEmailNotification) {
playNotificationSound();
const { emailNotificationsEnabled, emailNotificationSound, notificationSoundChoice } = useSettingsStore.getState();
if (emailNotificationsEnabled && emailNotificationSound) {
playNotificationSound(notificationSoundChoice);
}
debug.log('New email received:', newEmailNotification.subject);
clearNewEmailNotification();
}
@@ -443,9 +444,27 @@ export default function Home() {
if (!client) return;
try {
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);
// 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
await fetchEmails(client, selectedMailbox);
} catch (error) {
@@ -768,12 +787,7 @@ export default function Home() {
}
};
const handleLogout = () => {
logout();
if (!useAuthStore.getState().isAuthenticated) {
router.push('/login');
}
};
const handleLogout = logout;
const handleSearch = async (query: string) => {
if (!client) return;
@@ -865,6 +879,8 @@ export default function Home() {
// Append signature from the primary identity
const finalBody = appendPlainTextSignature(body, primaryIdentity);
const originalEmailId = selectedEmail.id;
// Send reply with just the body text
await sendEmail(
client,
@@ -879,6 +895,13 @@ export default function Home() {
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
await fetchEmails(client, selectedMailbox);
};
+11 -6
View File
@@ -24,6 +24,7 @@ import {
BookUser,
KeyRound,
PanelLeftClose,
Bell,
type LucideIcon,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -44,7 +45,8 @@ import { FilesSettingsComponent } from '@/components/settings/files-settings';
import { ContactsSettings } from '@/components/settings/contacts-settings';
import { SmimeSettings } from '@/components/settings/smime-settings';
import { SidebarAppsSettings } from '@/components/settings/sidebar-apps-settings';
import { useAuthStore } from '@/stores/auth-store';
import { NotificationSettings } from '@/components/settings/notification-settings';
import { useAuthStore, redirectToLogin } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
import { useIsDesktop } from '@/hooks/use-media-query';
import { NavigationRail } from '@/components/layout/navigation-rail';
@@ -55,7 +57,7 @@ import { ResizeHandle } from '@/components/layout/resize-handle';
import { useConfig } from '@/hooks/use-config';
import { cn } from '@/lib/utils';
type Tab = 'appearance' | 'email' | 'account' | 'security' | 'identities' | 'encryption' | 'vacation' | 'calendar' | 'contacts' | 'filters' | 'templates' | 'folders' | 'keywords' | 'files' | 'sidebar_apps' | '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';
interface TabDef {
@@ -68,6 +70,7 @@ interface TabDef {
const tabIcons: Record<Tab, LucideIcon> = {
appearance: Palette,
email: Mail,
notifications: Bell,
account: User,
security: Shield,
identities: UserPen,
@@ -122,9 +125,9 @@ export default function SettingsPage() {
useEffect(() => {
if (initialCheckDone && !isAuthenticated && !authLoading) {
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
router.push('/login');
redirectToLogin();
}
}, [initialCheckDone, isAuthenticated, authLoading, router]);
}, [initialCheckDone, isAuthenticated, authLoading]);
if (!isAuthenticated) {
return null;
@@ -138,6 +141,7 @@ export default function SettingsPage() {
const tabs: TabDef[] = [
{ id: 'appearance', label: t('tabs.appearance'), icon: tabIcons.appearance, 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' },
...(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' },
@@ -177,6 +181,7 @@ export default function SettingsPage() {
<>
{activeTab === 'appearance' && <AppearanceSettings />}
{activeTab === 'email' && <EmailSettings />}
{activeTab === 'notifications' && <NotificationSettings />}
{activeTab === 'account' && <AccountSettings />}
{activeTab === 'security' && <AccountSecuritySettings />}
{activeTab === 'identities' && <IdentitySettings />}
@@ -286,7 +291,7 @@ export default function SettingsPage() {
{/* Logout */}
<div className="border-t border-border px-5 py-3">
<button
onClick={() => { logout(); if (!useAuthStore.getState().isAuthenticated) 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"
>
<LogOut className="w-4 h-4" />
@@ -317,7 +322,7 @@ export default function SettingsPage() {
collapsed
quota={quota}
isPushConnected={isPushConnected}
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
onLogout={logout}
onManageApps={handleManageApps}
onInlineApp={handleInlineApp}
onCloseInlineApp={closeInlineApp}
+2 -4
View File
@@ -3,12 +3,10 @@ import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
...getCookieOptions(),
maxAge: SESSION_COOKIE_MAX_AGE,
};
+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 });
}
}
+6 -78
View File
@@ -1,18 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
import { exchangeCodeForTokens, buildOAuthParams, getMetadata, getTokenEndpoint } from '@/lib/oauth/token-exchange';
import { getCookieOptions } from '@/lib/oauth/cookie-config';
function getSlot(request: NextRequest): number {
const raw = request.nextUrl.searchParams.get('slot');
@@ -22,44 +13,6 @@ function getSlot(request: NextRequest): number {
return slot;
}
function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
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) {
try {
const { code, code_verifier, redirect_uri, slot: bodySlot } = await request.json();
@@ -69,43 +22,18 @@ export async function POST(request: NextRequest) {
}
const slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
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 tokens = await exchangeCodeForTokens(code, code_verifier, redirect_uri);
const response = NextResponse.json({
access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600,
expires_in: tokens.expires_in,
});
if (tokens.refresh_token) {
const cookieName = refreshTokenCookieName(slot);
const cookieStore = await cookies();
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
return response;
@@ -154,7 +82,7 @@ export async function PUT(request: NextRequest) {
}
if (tokens.refresh_token) {
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
}
return NextResponse.json({
+3
View File
@@ -36,5 +36,8 @@ export async function GET() {
loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_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.
const MULTI_PART_TLDS = new Set([
"co.uk", "org.uk", "me.uk", "ac.uk", "gov.uk", "net.uk",
"co.jp", "or.jp", "ne.jp", "ac.jp", "go.jp",
"co.kr", "or.kr", "go.kr", "ac.kr",
"co.in", "net.in", "org.in", "ac.in", "gov.in",
"co.nz", "org.nz", "net.nz", "govt.nz", "ac.nz",
"co.za", "org.za", "net.za", "gov.za", "ac.za",
"com.au", "net.au", "org.au", "edu.au", "gov.au",
"com.br", "net.br", "org.br", "edu.br", "gov.br",
"com.cn", "net.cn", "org.cn", "gov.cn", "edu.cn",
"com.mx", "net.mx", "org.mx", "gob.mx", "edu.mx",
"com.ar", "net.ar", "org.ar", "gob.ar", "edu.ar",
"com.tw", "net.tw", "org.tw", "edu.tw", "gov.tw",
"com.hk", "net.hk", "org.hk", "edu.hk", "gov.hk",
"com.sg", "net.sg", "org.sg", "edu.sg", "gov.sg",
"com.my", "net.my", "org.my", "edu.my", "gov.my",
"com.ph", "net.ph", "org.ph", "edu.ph", "gov.ph",
"com.pk", "net.pk", "org.pk", "edu.pk", "gov.pk",
"com.ng", "net.ng", "org.ng", "edu.ng", "gov.ng",
"co.il", "org.il", "net.il", "ac.il", "gov.il",
"co.th", "or.th", "ac.th", "go.th", "in.th",
"co.id", "or.id", "ac.id", "go.id", "web.id",
"com.tr", "net.tr", "org.tr", "edu.tr", "gov.tr",
"com.ua", "net.ua", "org.ua", "edu.ua", "gov.ua",
"com.eg", "net.eg", "org.eg", "edu.eg", "gov.eg",
"com.sa", "net.sa", "org.sa", "edu.sa", "gov.sa",
"co.ke", "or.ke", "ac.ke", "go.ke", "ne.ke",
// .ac
"com.ac", "gov.ac", "mil.ac", "net.ac", "org.ac",
// .ae
"ac.ae", "co.ae", "gov.ae", "mil.ae", "name.ae", "net.ae", "org.ae", "pro.ae", "sch.ae",
// .af
"com.af", "edu.af", "gov.af", "net.af", "org.af",
// .al
"com.al", "edu.al", "gov.al", "mil.al", "net.al", "org.al",
// .ao
"co.ao", "ed.ao", "gv.ao", "it.ao", "og.ao", "pb.ao",
// .ar
"com.ar", "edu.ar", "gob.ar", "gov.ar", "int.ar", "mil.ar", "net.ar", "org.ar", "tur.ar",
// .at
"ac.at", "co.at", "gv.at", "or.at",
// .au
"asn.au", "com.au", "csiro.au", "edu.au", "gov.au", "id.au", "net.au", "org.au",
// .ba
"co.ba", "com.ba", "edu.ba", "gov.ba", "mil.ba", "net.ba", "org.ba", "rs.ba",
"unbi.ba", "unmo.ba", "unsa.ba", "untz.ba", "unze.ba",
// .bb
"biz.bb", "co.bb", "com.bb", "edu.bb", "gov.bb", "info.bb", "net.bb", "org.bb",
"store.bb", "tv.bb",
// .bh
"biz.bh", "cc.bh", "com.bh", "edu.bh", "gov.bh", "info.bh", "net.bh", "org.bh",
// .bn
"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 {
+92
View File
@@ -496,3 +496,95 @@ body {
-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;
}
+4
View File
@@ -31,10 +31,14 @@ export default async function RootLayout({
}) {
const locale = await getLocale();
const nonce = (await headers()).get("x-nonce") ?? "";
const parentOrigin = process.env.NEXT_PUBLIC_PARENT_ORIGIN || "";
return (
<html lang={locale} suppressHydrationWarning>
<head>
{parentOrigin && (
<meta name="parent-origin" content={parentOrigin} />
)}
<script
nonce={nonce}
suppressHydrationWarning
+72 -19
View File
@@ -4,10 +4,11 @@ import { useMemo, useEffect, useRef, useState } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { format, isSameDay, isToday, parseISO } from "date-fns";
import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
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 type { PendingEventPreview } from "./event-modal";
@@ -22,6 +23,8 @@ interface CalendarDayViewProps {
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
}
const HOUR_HEIGHT = 64;
@@ -38,6 +41,8 @@ export function CalendarDayView({
timeFormat = "24h",
isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarDayViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -68,6 +73,16 @@ export function CalendarDayView({
return { timedEvents: timed, allDayEvents: allDay };
}, [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(() => {
if (scrollRef.current) {
const now = new Date();
@@ -125,25 +140,63 @@ export function CalendarDayView({
</h3>
</div>
{allDayEvents.length > 0 && (
{(allDayEvents.length > 0 || dayTasks.length > 0) && (
<div className="px-4 py-2 border-b border-border">
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
<div className="space-y-1">
{allDayEvents.map((ev) => {
const calId = getPrimaryCalendarId(ev);
return (
<EventCard
key={ev.id}
event={ev}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="chip"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
onMouseLeave={onHoverLeave}
/>
);
})}
</div>
{allDayEvents.length > 0 && (
<>
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
<div className="space-y-1">
{allDayEvents.map((ev) => {
const calId = getPrimaryCalendarId(ev);
return (
<EventCard
key={ev.id}
event={ev}
calendar={calId ? calendarMap.get(calId) : undefined}
variant="chip"
onClick={(rect) => onSelectEvent(ev, rect)}
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
onMouseLeave={onHoverLeave}
/>
);
})}
</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>
)}
+26 -1
View File
@@ -2,12 +2,13 @@
import { useState, useRef, useEffect, useMemo } from "react";
import { useTranslations } from "next-intl";
import { Globe, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
import { Globe, ListTodo, Plus, RefreshCw, Share2, Trash2 } from "lucide-react";
import { cn, formatDateTime } from "@/lib/utils";
import type { Calendar } from "@/lib/jmap/types";
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
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 type { IJMAPClient } from '@/lib/jmap/client-interface';
@@ -35,6 +36,15 @@ export function CalendarSidebarPanel({
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
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 [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
@@ -209,6 +219,21 @@ export function CalendarSidebarPanel({
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>
+8 -2
View File
@@ -3,7 +3,7 @@
import { useState, useRef, useEffect } from "react";
import { useTranslations, useFormatter } from "next-intl";
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 { cn } from "@/lib/utils";
import type { CalendarViewMode } from "@/stores/calendar-store";
@@ -25,6 +25,7 @@ interface CalendarToolbarProps {
calendars?: Calendar[];
selectedCalendarIds?: string[];
onToggleVisibility?: (id: string) => void;
enableCalendarTasks?: boolean;
}
export function CalendarToolbar({
@@ -42,10 +43,13 @@ export function CalendarToolbar({
calendars,
selectedCalendarIds,
onToggleVisibility,
enableCalendarTasks,
}: CalendarToolbarProps) {
const t = useTranslations("calendar");
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 dropdownRef = useRef<HTMLDivElement>(null);
@@ -86,6 +90,8 @@ export function CalendarToolbar({
return isMobile
? formatter.dateTime(selectedDate, { month: "short", year: "numeric" })
: formatter.dateTime(selectedDate, { month: "long", year: "numeric" });
case "tasks":
return t("views.tasks");
}
};
+82 -6
View File
@@ -6,10 +6,11 @@ import {
startOfWeek, addDays, format, isSameDay, isToday, parseISO,
} from "date-fns";
import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import { EventCard, parseDuration } from "./event-card";
import { QuickEventInput } from "./quick-event-input";
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 type { PendingEventPreview } from "./event-modal";
@@ -26,6 +27,8 @@ interface CalendarWeekViewProps {
timeFormat?: "12h" | "24h";
isMobile?: boolean;
pendingPreview?: PendingEventPreview | null;
tasks?: CalendarTask[];
onToggleTaskComplete?: (task: CalendarTask) => void;
}
const HOUR_HEIGHT = 60;
@@ -44,6 +47,8 @@ export function CalendarWeekView({
timeFormat = "24h",
isMobile,
pendingPreview,
tasks,
onToggleTaskComplete,
}: CalendarWeekViewProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -96,9 +101,36 @@ export function CalendarWeekView({
return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0);
}, [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(() => {
return allDaySegments.length > 0;
}, [allDaySegments]);
return allDaySegments.length > 0 || taskRowCount > 0;
}, [allDaySegments, taskRowCount]);
useEffect(() => {
if (scrollRef.current) {
@@ -151,13 +183,13 @@ export function CalendarWeekView({
<div className="flex border-b border-border">
<div
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")}
</div>
<div
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) => (
<div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" />
@@ -191,6 +223,49 @@ export function CalendarWeekView({
);
})}
</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>
)}
@@ -373,7 +448,8 @@ export function CalendarWeekView({
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && (
(() => {
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
const endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
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))";
@@ -192,6 +192,10 @@ export function EventDetailPopover({
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
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) {
e.preventDefault();
onEdit();
+14 -8
View File
@@ -59,10 +59,12 @@ function buildDuration(startDate: Date, endDate: Date): string {
const minutes = totalMinutes % 60;
let dur = "P";
if (days > 0) dur += `${days}D`;
dur += "T";
if (hours > 0) dur += `${hours}H`;
if (minutes > 0) dur += `${minutes}M`;
if (dur === "PT") dur = "PT0M";
if (hours > 0 || minutes > 0) {
dur += "T";
if (hours > 0) dur += `${hours}H`;
if (minutes > 0) dur += `${minutes}M`;
}
if (dur === "P") dur = "PT0M";
return dur;
}
@@ -83,9 +85,9 @@ function getAlertLabel(event: CalendarEvent, t: ReturnType<typeof useTranslation
if (!first || first.trigger["@type"] !== "OffsetTrigger") return null;
const offset = first.trigger.offset;
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]) });
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]) });
const dayMatch = offset.match(/-?P(\d+)D/);
if (dayMatch) return t("alerts.days_before", { count: parseInt(dayMatch[1]) });
@@ -209,9 +211,9 @@ export function EventModal({
if (first.trigger["@type"] === "OffsetTrigger") {
const offset = first.trigger.offset;
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;
const hourMatch = offset.match(/-?PT?(\d+)H$/);
const hourMatch = offset.match(/-?PT(\d+)H$/);
if (hourMatch) return String(parseInt(hourMatch[1]) * 60) as AlertOption;
const dayMatch = offset.match(/-?P(\d+)D/);
if (dayMatch) return String(parseInt(dayMatch[1]) * 1440) as AlertOption;
@@ -384,7 +386,11 @@ export function EventModal({
if (!event || !onDuplicate) return;
const start = parseISO(event.start);
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> = {
uid: newUid,
title: event.title,
description: event.description,
start: format(newStart, "yyyy-MM-dd'T'HH:mm:ss"),
+46 -19
View File
@@ -1,12 +1,12 @@
"use client";
import { useState, useMemo } from "react";
import { useState, useMemo, Fragment } from "react";
import { useTranslations, useFormatter } from "next-intl";
import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react";
import {
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
addMonths, subMonths, addYears, subYears, setMonth, setYear,
eachDayOfInterval, getMonth, getYear,
eachDayOfInterval, getMonth, getYear, getISOWeek, getWeek,
isSameDay, isSameMonth, isToday, format,
} from "date-fns";
import { cn } from "@/lib/utils";
@@ -26,6 +26,7 @@ interface MiniCalendarProps {
onChangeMonth: (date: Date) => void;
events?: CalendarEvent[];
firstDayOfWeek?: number;
showWeekNumbers?: boolean;
}
export function MiniCalendar({
@@ -35,6 +36,7 @@ export function MiniCalendar({
onChangeMonth,
events = [],
firstDayOfWeek = 1,
showWeekNumbers = false,
}: MiniCalendarProps) {
const t = useTranslations("calendar");
const intlFormatter = useFormatter();
@@ -61,6 +63,17 @@ export function MiniCalendar({
? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] 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 currentMonth = getMonth(displayMonth);
const decadeStart = Math.floor(currentYear / 10) * 10;
@@ -135,35 +148,49 @@ export function MiniCalendar({
</div>
{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) => (
<div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1">
{t(`days.${d}`)}
</div>
))}
{days.map((day) => {
{days.map((day, index) => {
const inMonth = isSameMonth(day, displayMonth);
const selected = isSameDay(day, selectedDate);
const today = isToday(day);
const hasEvent = eventDates.has(format(day, "yyyy-MM-dd"));
const isFirstDayOfRow = index % 7 === 0;
return (
<button
key={day.toISOString()}
onClick={() => onSelectDate(day)}
className={cn(
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
!inMonth && "text-muted-foreground/40",
inMonth && !selected && "hover:bg-muted",
today && !selected && "font-bold text-primary",
selected && "bg-primary text-primary-foreground"
<Fragment key={day.toISOString()}>
{showWeekNumbers && isFirstDayOfRow && (
<div
key={`wk-${index}`}
className="flex items-center justify-center w-5 text-[9px] text-muted-foreground/60 font-medium"
>
{weekNumbers[index / 7]}
</div>
)}
>
{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>
<button
key={`day-${day.toISOString()}`}
onClick={() => onSelectDate(day)}
className={cn(
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
!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>
+50 -5
View File
@@ -1,9 +1,9 @@
"use client";
import { useMemo, useCallback } from "react";
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 } from "lucide-react";
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";
@@ -18,6 +18,7 @@ interface TaskListViewProps {
onSelectTask: (task: CalendarTask) => void;
onToggleComplete: (task: CalendarTask) => void;
selectedTaskId?: string | null;
onQuickCreate?: (title: string) => void;
}
function getTaskPriorityIcon(priority: number) {
@@ -69,9 +70,11 @@ export function TaskListView({
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 => {
@@ -128,15 +131,57 @@ export function TaskListView({
if (filteredTasks.length === 0) {
return (
<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 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]);
+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>
);
}
+72 -102
View File
@@ -28,6 +28,14 @@ import { TemplatePicker } from "@/components/templates/template-picker";
import { TemplateForm } from "@/components/templates/template-form";
import type { EmailTemplate } from "@/lib/template-types";
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
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 {
to: string;
@@ -125,23 +133,28 @@ export function EmailComposer({
};
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;
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
const from = replyTo.from?.[0];
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
// When HTML body is available, don't include quoted text in the textarea
// The HTML original will be shown separately below the textarea
// Build quoted content as HTML
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') {
return `${prefix}\n\n---------- Forwarded message ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ""}\n\n${replyTo.body}`;
} else if (mode === 'reply' || mode === 'replyAll') {
return `${prefix}\n\nOn ${date}, ${fromStr} wrote:\n> ${(replyTo.body || '').split('\n').join('\n> ')}`;
if (replyTo.body) {
const escapedOriginal = replyTo.body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
if (mode === 'forward') {
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;
};
@@ -157,18 +170,6 @@ export function EmailComposer({
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
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 fileInputRef = useRef<HTMLInputElement>(null);
const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({});
@@ -367,9 +368,12 @@ export function EmailComposer({
? substitutePlaceholders(template.body, filledValues)
: 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') {
setSubject(filledSubject);
setBody(filledBody);
setBody(htmlBody);
if (template.defaultRecipients?.to?.length) {
setTo(template.defaultRecipients.to.join(', ') + ', ');
}
@@ -382,7 +386,7 @@ export function EmailComposer({
setShowBcc(true);
}
} else {
setBody((prev) => filledBody + prev);
setBody((prev) => htmlBody + prev);
}
if (template.identityId) {
@@ -394,8 +398,10 @@ export function EmailComposer({
useEffect(() => {
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 (target?.getAttribute('contenteditable') === 'true') return;
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
setShowTemplatePicker(true);
@@ -445,6 +451,18 @@ export function EmailComposer({
}
}, [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>) => {
if (!event.target.files) return;
await addFiles(Array.from(event.target.files));
@@ -511,7 +529,7 @@ export function EmailComposer({
const ccAddresses = cc.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;
}
@@ -547,7 +565,7 @@ export function EmailComposer({
const savedDraftId = await client.createDraft(
toAddresses,
subject || t('no_subject'),
body,
htmlToPlainText(body),
ccAddresses,
bccAddresses,
currentIdentity?.id,
@@ -611,7 +629,8 @@ export function EmailComposer({
}, []);
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 getSendTooltip = (): string | undefined => {
@@ -660,26 +679,8 @@ export function EmailComposer({
: currentIdentity.email
: undefined;
// Append signature from the selected identity
let finalBody = appendPlainTextSignature(body, currentIdentity);
// Append quoted original text for the plain text part in reply/forward
if (replyTo && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
const originalText = replyTo.body || '';
if (originalText) {
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
const fromAddr = replyTo.from?.[0];
const fromStr = fromAddr ? `${fromAddr.name || fromAddr.email}` : tCommon('unknown');
if (mode === 'forward') {
finalBody += `\n\n---------- ${t('prefix.forward')} ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ''}\n\n${originalText}`;
} else {
finalBody += `\n\nOn ${date}, ${fromStr} wrote:\n> ${originalText.split('\n').join('\n> ')}`;
}
}
}
// Build HTML signature block (prefer htmlSignature, fall back to escaped textSignature)
// Body is already HTML from the rich text editor.
// Build HTML signature block
const buildSignatureHtml = (): string => {
if (currentIdentity?.htmlSignature) {
return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
@@ -690,26 +691,13 @@ export function EmailComposer({
return '';
};
// Build HTML body
let finalHtmlBody: string | undefined;
const signatureHtml = buildSignatureHtml();
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
// Reply/forward with original HTML content
const escapedBody = body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : '';
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>`;
// Build final HTML body: editor content + signature
const finalHtmlBody = `<div>${body}</div>${signatureHtml}`;
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>`;
} else if (signatureHtml) {
// New compose or plain-text reply — include HTML body with signature
const escapedBody = body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}`;
}
// Generate plain text version from the HTML body for multipart/alternative
const finalBody = appendPlainTextSignature(htmlToPlainText(body), currentIdentity);
try {
// S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
@@ -955,11 +943,16 @@ export function EmailComposer({
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"
>
{identities.map((identity) => (
<option key={identity.id} value={identity.id}>
{identity.name ? `${identity.name} <${identity.email}>` : identity.email}
</option>
))}
{identities.map((identity) => {
const displayEmail = subAddressTag
? generateSubAddress(identity.email, subAddressTag)
: identity.email;
return (
<option key={identity.id} value={identity.id}>
{identity.name ? `${identity.name} <${displayEmail}>` : displayEmail}
</option>
);
})}
</select>
) : (
<span className="text-sm text-foreground flex-1 truncate">
@@ -1107,23 +1100,17 @@ export function EmailComposer({
</div>
</div>
{/* Body */}
<div className="px-4 py-3">
<textarea
ref={textareaRef}
className={cn(
"w-full resize-none outline-none text-sm bg-transparent text-foreground placeholder:text-muted-foreground rounded min-h-[100px] overflow-hidden",
validationErrors.body && "ring-2 ring-red-500 dark:ring-red-400"
)}
placeholder={t('body_placeholder')}
value={body}
onChange={(e) => {
setBody(e.target.value);
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
}}
aria-invalid={validationErrors.body || undefined}
/>
</div>
{/* Body - Rich Text Editor */}
<RichTextEditor
content={body}
onChange={(html) => {
setBody(html);
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
}}
onImageUpload={handleImageUpload}
placeholder={t('body_placeholder')}
hasError={validationErrors.body}
/>
{composerSignatureHtml && (
<div
@@ -1131,23 +1118,6 @@ export function EmailComposer({
dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
/>
)}
{/* Quoted original HTML */}
{replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward') && (
<div className="border-t border-border">
<div className="px-4 py-2 text-xs text-muted-foreground">
{mode === 'forward'
? `---------- ${t('prefix.forward')} ----------`
: `${replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : ''}, ${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>
{/* Attachments */}
+15 -1
View File
@@ -6,7 +6,7 @@ import { formatDate } from "@/lib/utils";
import { Email } from "@/lib/jmap/types";
import { cn } from "@/lib/utils";
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 { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
import { useAuthStore } from "@/stores/auth-store";
@@ -41,6 +41,8 @@ export function EmailListItem({ email, selected, onClick, onContextMenu, onToggl
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
const isImportant = email.keywords?.["$important"];
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0];
// Resolve color tag using keyword definitions from settings
@@ -175,6 +177,18 @@ export function EmailListItem({ email, selected, onClick, onContextMenu, onToggl
</span>
)}
<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 && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)}
+1 -1
View File
@@ -4449,7 +4449,7 @@ export function EmailViewer({
<iframe
ref={iframeRef}
srcDoc={emailIframeSrcDoc}
sandbox="allow-same-origin allow-popups"
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
title="Email content"
className="w-full border-0 rounded"
style={{ minHeight: '100px', colorScheme: isDark && emailHasNativeDarkMode ? 'light dark' : 'light' }}
+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>
);
}
+15 -1
View File
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
import { Email } from "@/lib/jmap/types";
import { cn } from "@/lib/utils";
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 { useLongPress } from "@/hooks/use-long-press";
import { useEmailStore } from "@/stores/email-store";
@@ -29,6 +29,8 @@ export function ThreadEmailItem({
}: ThreadEmailItemProps) {
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0];
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
const density = useSettingsStore((state) => state.density);
@@ -151,6 +153,18 @@ export function ThreadEmailItem({
{isStarred && (
<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 && (
<Paperclip className="w-3 h-3 text-muted-foreground" />
)}
+28 -2
View File
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
import { Email, ThreadGroup } from "@/lib/jmap/types";
import { cn } from "@/lib/utils";
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 { useUIStore } from "@/stores/ui-store";
import { useEmailStore } from "@/stores/email-store";
@@ -53,6 +53,8 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }, ref) {
const isUnread = !email.keywords?.$seen;
const isStarred = email.keywords?.$flagged;
const isAnswered = email.keywords?.$answered;
const isForwarded = email.keywords?.$forwarded;
const sender = email.from?.[0];
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
@@ -182,6 +184,18 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
{isStarred && (
<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 && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)}
@@ -267,7 +281,7 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
const showPreview = useSettingsStore((state) => state.showPreview);
const density = useSettingsStore((state) => state.density);
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();
@@ -482,6 +496,18 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
{hasStarred && (
<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 && (
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
)}
+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 { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
import type { FileResource } from "@/stores/file-store";
type SortKey = "name" | "size" | "modified";
@@ -624,16 +625,20 @@ export function FileBrowser({
e.stopPropagation();
setIsDraggingOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
setIsUploading(true);
try {
await onUploadFiles(files);
} finally {
setIsUploading(false);
setIsUploading(true);
try {
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
if (files.length > 0) {
if (hasDirectories) {
await onUploadFolder(files);
} else {
await onUploadFiles(files);
}
}
} finally {
setIsUploading(false);
}
}, [onUploadFiles]);
}, [onUploadFiles, onUploadFolder]);
const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
@@ -945,6 +950,16 @@ export function FileBrowser({
>
<Upload className="w-4 h-4" />
</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
variant="ghost"
size="icon"
@@ -1195,6 +1210,14 @@ export function FileBrowser({
setIsUploading(false);
}
}}
onUploadFolder={async (files: File[]) => {
setIsUploading(true);
try {
await onUploadFolder(files);
} finally {
setIsUploading(false);
}
}}
onCreateFolder={() => setShowNewFolder(true)}
onCreateTextFile={() => setShowNewTextFile(true)}
/>
+11 -5
View File
@@ -2,16 +2,18 @@
import { useCallback, useState } from "react";
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 { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
interface FileUploadAreaProps {
onUpload: (files: File[]) => Promise<void>;
onUploadFolder?: (files: File[]) => Promise<void>;
onCreateFolder: () => void;
onCreateTextFile?: () => void;
}
export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
export function FileUploadArea({ onUpload, onUploadFolder, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
const t = useTranslations("files");
const [isDragging, setIsDragging] = useState(false);
@@ -32,11 +34,15 @@ export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: F
e.stopPropagation();
setIsDragging(false);
const files = Array.from(e.dataTransfer.files);
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
if (files.length > 0) {
await onUpload(files);
if (hasDirectories && onUploadFolder) {
await onUploadFolder(files);
} else {
await onUpload(files);
}
}
}, [onUpload]);
}, [onUpload, onUploadFolder]);
return (
<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]);
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 === "-") setZoom((z) => Math.max(z - 0.25, 0.25));
if (e.key === "r") setRotation((r) => r + 90);
-4
View File
@@ -101,15 +101,11 @@ export function AccountSwitcher({ variant = "rail", className }: AccountSwitcher
const handleLogout = () => {
setOpen(false);
logout();
if (useAccountStore.getState().accounts.length === 0) {
router.push("/login" as never);
}
};
const handleLogoutAll = () => {
setOpen(false);
logoutAll();
router.push("/login" as never);
};
const handleSetDefault = (accountId: string) => {
@@ -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}</>;
}
+24 -9
View File
@@ -3,29 +3,44 @@
import { useTranslations } from 'next-intl';
import { useAuthStore } from '@/stores/auth-store';
import { useEmailStore } from '@/stores/email-store';
import { useAccountStore } from '@/stores/account-store';
import { SettingsSection, SettingItem } from './settings-section';
import { formatFileSize } from '@/lib/utils';
export function AccountSettings() {
const t = useTranslations('settings.account');
const { username, serverUrl, isDemoMode, primaryIdentity } = useAuthStore();
const { username, serverUrl, isDemoMode, primaryIdentity, authMode, activeAccountId } = useAuthStore();
const { quota } = useEmailStore();
const account = useAccountStore((s) => activeAccountId ? s.getAccountById(activeAccountId) : undefined);
const quotaPercentage = quota ? Math.round((quota.used / quota.total) * 100) : 0;
const displayName = primaryIdentity?.name || (isDemoMode ? 'Demo User' : undefined);
const displayName = primaryIdentity?.name || account?.displayName || (isDemoMode ? 'Demo User' : undefined);
const email = primaryIdentity?.email || account?.email || username;
return (
<SettingsSection title={t('title')} description={t('description')}>
{/* Display Name (show in demo mode or when identity has a name) */}
{displayName && (
<SettingItem label={t('name_label')}>
<span className="text-sm text-foreground">{displayName}</span>
</SettingItem>
)}
{/* Display Name */}
<SettingItem label={t('name_label')}>
<span className="text-sm text-foreground">{displayName || t('../../common.unknown')}</span>
</SettingItem>
{/* Email Address */}
<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>
{/* Server */}
+22 -21
View File
@@ -15,9 +15,9 @@ export function CalendarSettings() {
timeFormat,
firstDayOfWeek,
showTimeInMonthView,
calendarNotificationsEnabled,
calendarNotificationSound,
calendarInvitationParsingEnabled,
showWeekNumbers,
enableCalendarTasks,
showTasksOnCalendar,
updateSetting,
} = useSettingsStore();
@@ -69,35 +69,36 @@ export function CalendarSettings() {
</SettingItem>
<SettingItem
label={t('notifications_enabled')}
description={t('notifications_enabled_desc')}
label={t('show_week_numbers')}
description={t('show_week_numbers_desc')}
>
<ToggleSwitch
checked={calendarNotificationsEnabled}
onChange={(checked) => updateSetting('calendarNotificationsEnabled', checked)}
checked={showWeekNumbers}
onChange={(checked) => updateSetting('showWeekNumbers', checked)}
/>
</SettingItem>
<SettingItem
label={t('notification_sound')}
description={t('notification_sound_desc')}
label={t('enable_tasks')}
description={t('enable_tasks_desc')}
>
<ToggleSwitch
checked={calendarNotificationSound}
onChange={(checked) => updateSetting('calendarNotificationSound', checked)}
disabled={!calendarNotificationsEnabled}
checked={enableCalendarTasks}
onChange={(checked) => updateSetting('enableCalendarTasks', checked)}
/>
</SettingItem>
<SettingItem
label={t('invitation_parsing')}
description={t('invitation_parsing_desc')}
>
<ToggleSwitch
checked={calendarInvitationParsingEnabled}
onChange={(checked) => updateSetting('calendarInvitationParsingEnabled', checked)}
/>
</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>
);
+36 -2
View File
@@ -1,7 +1,8 @@
"use client";
import { useState } from 'react';
import { useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { useConfig } from '@/hooks/use-config';
import { useSettingsStore } from '@/stores/settings-store';
import type { ArchiveMode, HoverAction } from '@/stores/settings-store';
import { ALL_HOVER_ACTIONS } from '@/stores/settings-store';
@@ -10,13 +11,26 @@ import { useEmailStore } from '@/stores/email-store';
import { cn } from '@/lib/utils';
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
import { TrustedSendersModal } from '@/components/trusted-senders-modal';
import { ChevronRight, AlertTriangle, FolderSync, Loader2 } from 'lucide-react';
import { ChevronRight, AlertTriangle, FolderSync, Loader2, Mail } from 'lucide-react';
export function EmailSettings() {
const t = useTranslations('settings.email_behavior');
const { appName } = useConfig();
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 {
markAsReadDelay,
@@ -249,6 +263,7 @@ export function EmailSettings() {
value={emailsPerPage.toString()}
onChange={(value) => updateSetting('emailsPerPage', parseInt(value))}
options={[
{ value: '10', label: t('emails_per_page.10') },
{ value: '25', label: t('emails_per_page.25') },
{ value: '50', label: t('emails_per_page.50') },
{ value: '100', label: t('emails_per_page.100') },
@@ -279,6 +294,25 @@ export function EmailSettings() {
/>
</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 */}
<SettingItem label={t('trusted_senders.label')} description={t('trusted_senders.description')}>
<button
+118 -31
View File
@@ -9,6 +9,7 @@ import { SieveEditorModal } from "@/components/filters/sieve-editor-modal";
import { useFilterStore } from "@/stores/filter-store";
import { useAuthStore } from "@/stores/auth-store";
import { useEmailStore } from "@/stores/email-store";
import { useSettingsStore } from "@/stores/settings-store";
import { toast } from "@/stores/toast-store";
import type { FilterRule } from "@/lib/jmap/sieve-types";
import {
@@ -25,31 +26,98 @@ import {
function RuleSummary({ rule }: { rule: FilterRule }) {
const t = useTranslations("settings.filters");
const conditionSummary = rule.conditions
.slice(0, 2)
.map((c) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return `${field} ${comparator} "${c.value}"`;
})
.join(rule.matchType === "all" ? ` ${t("and")} ` : ` ${t("or")} `);
const conditions = rule.conditions.slice(0, 2).map((c) => {
const field = t(`condition_fields.${c.field}`);
const comparator = t(`comparators.${c.comparator}`);
return `${field} ${comparator} "${c.value}"`;
});
const joiner = rule.matchType === "all" ? t("and") : t("or");
const extra = rule.conditions.length > 2
? ` (+${rule.conditions.length - 2})`
: "";
const actionSummary = rule.actions
.slice(0, 2)
.map((a) => {
const action = t(`action_types.${a.type}`);
return a.value ? `${action} "${a.value}"` : action;
})
.join(", ");
const actions = rule.actions.slice(0, 2).map((a) => {
const action = t(`action_types.${a.type}`);
return a.value ? `${action} "${a.value}"` : action;
});
return (
<span className="text-xs text-muted-foreground truncate">
{conditionSummary}{extra} {actionSummary}
</span>
<div className="text-xs text-muted-foreground break-words">
<span className="inline">
{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 { client } = useAuthStore();
const mailboxes = useEmailStore((s) => s.mailboxes);
const expandedFilterView = useSettingsStore((s) => s.expandedFilterView);
const updateSetting = useSettingsStore((s) => s.updateSetting);
const {
rules,
@@ -337,23 +407,25 @@ export function FilterSettings() {
onDragOver={(e) => handleDragOver(e, index)}
onDrop={(e) => handleDrop(e, index)}
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
? "border-primary bg-primary/5"
: "border-border hover:bg-muted/50"
} ${!rule.enabled ? "opacity-60" : ""}`}
>
<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")}
>
<GripVertical className="w-4 h-4" />
</div>
<ToggleSwitch
checked={rule.enabled}
onChange={() => handleToggle(rule.id)}
/>
<div className="pt-0.5">
<ToggleSwitch
checked={rule.enabled}
onChange={() => handleToggle(rule.id)}
/>
</div>
<div
className="flex-1 min-w-0 cursor-pointer"
@@ -374,7 +446,11 @@ export function FilterSettings() {
<p className="text-sm font-medium text-foreground truncate">
{rule.name}
</p>
<RuleSummary rule={rule} />
{expandedFilterView ? (
<VisualRuleSummary rule={rule} />
) : (
<RuleSummary rule={rule} />
)}
</div>
{deleteConfirmId === rule.id ? (
@@ -435,12 +511,23 @@ export function FilterSettings() {
</Button>
</div>
{isSaving && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />
{t("saving")}
</div>
)}
<div className="flex items-center gap-3">
{isSaving && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="w-4 h-4 animate-spin" />
{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>
{showRuleModal && (
@@ -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>
);
}
+36 -4
View File
@@ -5,9 +5,10 @@ import { useTranslations, useLocale } from 'next-intl';
import { useAuthStore } from '@/stores/auth-store';
import { useCalendarStore } from '@/stores/calendar-store';
import { useSettingsStore } from '@/stores/settings-store';
import { useTaskStore } from '@/stores/task-store';
import { useCalendarNotificationStore } from '@/stores/calendar-notification-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 type { CalendarEvent } from '@/lib/jmap/types';
@@ -18,7 +19,8 @@ const PROACTIVE_THROTTLE_MS = CHECK_INTERVAL_MS * 5;
export function useCalendarAlerts() {
const { isAuthenticated, client } = useAuthStore();
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 addToast = useToastStore((s) => s.addToast);
const t = useTranslations('calendar.notifications');
@@ -45,7 +47,7 @@ export function useCalendarAlerts() {
acknowledgeAlert(key, alert.fireTimeMs);
if (calendarNotificationSound) {
playNotificationSound();
playNotificationSound(notificationSoundChoice);
}
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 {
// Silently ignore alert evaluation errors
}
}, [
calendarNotificationsEnabled, calendarNotificationSound,
calendarNotificationsEnabled, calendarNotificationSound, notificationSoundChoice,
isAuthenticated, events, calendars, acknowledgedAlerts,
acknowledgeAlert, addToast, t, locale,
]);
+12
View File
@@ -23,6 +23,9 @@ interface ConfigData {
loginPrivacyPolicyUrl: string;
loginWebsiteUrl: string;
demoMode: boolean;
autoSsoEnabled: boolean;
embeddedMode: boolean;
parentOrigin: string;
}
interface AppConfig extends ConfigData {
@@ -93,6 +96,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '',
loginWebsiteUrl: configCache?.loginWebsiteUrl || '',
demoMode: configCache?.demoMode || false,
autoSsoEnabled: configCache?.autoSsoEnabled || false,
embeddedMode: configCache?.embeddedMode || false,
parentOrigin: configCache?.parentOrigin || '',
isLoading: !configCache,
error: null,
});
@@ -121,6 +127,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl,
loginWebsiteUrl: configCache.loginWebsiteUrl,
demoMode: configCache.demoMode,
autoSsoEnabled: configCache.autoSsoEnabled,
embeddedMode: configCache.embeddedMode,
parentOrigin: configCache.parentOrigin,
isLoading: false,
error: null,
});
@@ -150,6 +159,9 @@ export function useConfig(): AppConfig {
loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl,
loginWebsiteUrl: data.loginWebsiteUrl,
demoMode: data.demoMode,
autoSsoEnabled: data.autoSsoEnabled,
embeddedMode: data.embeddedMode,
parentOrigin: data.parentOrigin,
isLoading: false,
error: null,
});
+8 -3
View File
@@ -122,10 +122,15 @@ describe('JMAPClient contact methods', () => {
describe('getContacts', () => {
it('should return contacts from server', async () => {
const client = createClient();
mockFetch({
const spy = vi.spyOn(globalThis, 'fetch');
mockFetchOnce(spy, {
methodResponses: [
['ContactCard/query', { ids: ['contact-1'] }, '0'],
['ContactCard/get', { list: [mockContact] }, '1'],
['ContactCard/query', { ids: ['contact-1'] }, 'q'],
],
});
mockFetchOnce(spy, {
methodResponses: [
['ContactCard/get', { list: [mockContact] }, 'g'],
],
});
+24
View File
@@ -89,6 +89,22 @@ describe('groupEmailsByThread', () => {
expect(groupEmailsByThread(emails)[0].hasAttachment).toBe(true);
});
it('detects hasAnswered when an email has $answered', () => {
const emails = [
makeEmail({ id: 'e1', keywords: { $seen: true } }),
makeEmail({ id: 'e2', keywords: { $seen: true, $answered: true } }),
];
expect(groupEmailsByThread(emails)[0].hasAnswered).toBe(true);
});
it('detects hasForwarded when an email has $forwarded', () => {
const emails = [
makeEmail({ id: 'e1', keywords: { $seen: true } }),
makeEmail({ id: 'e2', keywords: { $seen: true, $forwarded: true } }),
];
expect(groupEmailsByThread(emails)[0].hasForwarded).toBe(true);
});
it('returns empty array for empty input', () => {
expect(groupEmailsByThread([])).toEqual([]);
});
@@ -110,6 +126,8 @@ describe('sortThreadGroups', () => {
hasUnread: false,
hasStarred: false,
hasAttachment: false,
hasAnswered: false,
hasForwarded: false,
emailCount: 1,
},
{
@@ -120,6 +138,8 @@ describe('sortThreadGroups', () => {
hasUnread: false,
hasStarred: false,
hasAttachment: false,
hasAnswered: false,
hasForwarded: false,
emailCount: 1,
},
];
@@ -169,6 +189,8 @@ describe('mergeThreadEmails', () => {
hasUnread: false,
hasStarred: false,
hasAttachment: false,
hasAnswered: false,
hasForwarded: false,
emailCount: 2,
};
const fetched = [
@@ -189,6 +211,8 @@ describe('mergeThreadEmails', () => {
hasUnread: false,
hasStarred: false,
hasAttachment: false,
hasAnswered: false,
hasForwarded: false,
emailCount: 1,
};
const fetched = [
+35
View File
@@ -48,3 +48,38 @@ export function decryptSession(token: string): { serverUrl: string; username: st
return null;
}
}
export function encryptPayload(payload: Record<string, unknown>): string {
const key = getKey();
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv);
const json = JSON.stringify(payload);
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString('base64');
}
export function decryptPayload(token: string): Record<string, unknown> | null {
try {
const key = getKey();
const data = Buffer.from(token, 'base64');
if (data.length < IV_LENGTH + TAG_LENGTH) return null;
const iv = data.subarray(0, IV_LENGTH);
const tag = data.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
const encrypted = data.subarray(IV_LENGTH + TAG_LENGTH);
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return JSON.parse(decrypted.toString('utf8'));
} catch (error) {
logger.warn('Payload decryption failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return null;
}
}
+44
View File
@@ -1,7 +1,51 @@
import { locales } from '@/i18n/routing';
export function replaceWindowLocation(url: string): void {
if (typeof window === 'undefined') {
return;
}
window.location.replace(url);
}
/**
* Returns the mount prefix from the current URL.
* When the app is served behind a reverse proxy at e.g. /bulwark,
* the browser sees /bulwark/en/login while Next.js sees /en/login.
*
* If a locale is supplied (e.g. from route params) it is used directly;
* otherwise the first path segment that matches a known locale is used.
*
* Returns '' when there is no prefix.
*/
export function getPathPrefix(locale?: string): string {
if (typeof window === 'undefined') return '';
const segments = window.location.pathname.split('/').filter(Boolean);
let localeIndex: number;
if (locale) {
localeIndex = segments.indexOf(locale);
} else {
localeIndex = segments.findIndex(s =>
(locales as readonly string[]).includes(s)
);
}
if (localeIndex <= 0) return '';
return '/' + segments.slice(0, localeIndex).join('/');
}
/**
* Extracts the locale from the current URL, skipping any mount prefix.
* Falls back to 'en' when no known locale segment is found.
*/
export function getLocaleFromPath(): string {
if (typeof window === 'undefined') return 'en';
const segments = window.location.pathname.split('/').filter(Boolean);
const locale = segments.find(s =>
(locales as readonly string[]).includes(s)
);
return locale || 'en';
}
+84 -9
View File
@@ -4,7 +4,9 @@ import type {
CalendarOffsetTrigger,
CalendarAbsoluteTrigger,
Calendar,
CalendarTask,
} from '@/lib/jmap/types';
import { parseDuration } from '@/components/calendar/event-card';
export interface PendingAlert {
eventId: string;
@@ -16,19 +18,20 @@ export interface PendingAlert {
const STALE_THRESHOLD_MS = 10 * 60 * 1000; // 10 minutes
const DURATION_RE = /^(-?)P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
const DURATION_RE = /^(-?)P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
export function parseAlertOffset(offset: string): number | null {
const match = DURATION_RE.exec(offset);
if (!match) return null;
const negative = match[1] === '-';
const days = parseInt(match[2] || '0', 10);
const hours = parseInt(match[3] || '0', 10);
const minutes = parseInt(match[4] || '0', 10);
const seconds = parseInt(match[5] || '0', 10);
const weeks = parseInt(match[2] || '0', 10);
const days = parseInt(match[3] || '0', 10);
const hours = parseInt(match[4] || '0', 10);
const minutes = parseInt(match[5] || '0', 10);
const seconds = parseInt(match[6] || '0', 10);
const ms = ((days * 24 * 60 * 60) + (hours * 60 * 60) + (minutes * 60) + seconds) * 1000;
const ms = ((weeks * 7 * 24 * 60 * 60) + (days * 24 * 60 * 60) + (hours * 60 * 60) + (minutes * 60) + seconds) * 1000;
return negative ? -ms : ms;
}
@@ -46,9 +49,15 @@ export function computeFireTime(
let baseTime: number;
if (trigger.relativeTo === 'end') {
baseTime = event.utcEnd
? new Date(event.utcEnd).getTime()
: new Date(event.start).getTime();
if (event.utcEnd) {
baseTime = new Date(event.utcEnd).getTime();
} else {
// Compute end from start + duration
const startMs = new Date(event.start).getTime();
if (Number.isNaN(startMs)) return null;
const durationMin = parseDuration(event.duration);
baseTime = startMs + durationMin * 60000;
}
} else {
baseTime = event.utcStart
? new Date(event.utcStart).getTime()
@@ -67,6 +76,7 @@ export function getEffectiveAlerts(
return event.alerts;
}
if (!event.calendarIds) return null;
const calendarId = Object.keys(event.calendarIds)[0];
if (!calendarId) return null;
@@ -121,3 +131,68 @@ export function getPendingAlerts(
return pending;
}
export interface PendingTaskAlert {
taskId: string;
alertId: string;
fireTimeMs: number;
task: CalendarTask;
calendarName: string | null;
}
export function computeTaskFireTime(
task: CalendarTask,
trigger: CalendarOffsetTrigger | CalendarAbsoluteTrigger
): number | null {
if (trigger['@type'] === 'AbsoluteTrigger') {
const t = new Date(trigger.when).getTime();
return Number.isNaN(t) ? null : t;
}
const offsetMs = parseAlertOffset(trigger.offset);
if (offsetMs === null) return null;
if (!task.due) return null;
const baseTime = new Date(task.due).getTime();
if (Number.isNaN(baseTime)) return null;
return baseTime + offsetMs;
}
export function getPendingTaskAlerts(
tasks: CalendarTask[],
calendars: Calendar[],
acknowledgedKeys: Set<string>,
now: number
): PendingTaskAlert[] {
const pending: PendingTaskAlert[] = [];
for (const task of tasks) {
if (!task.alerts) continue;
if (task.progress === 'completed' || task.progress === 'cancelled') continue;
const calendar = calendars.find(c => c.id === Object.keys(task.calendarIds)[0]) ?? null;
for (const [alertId, alert] of Object.entries(task.alerts)) {
if (alert.action !== 'display') continue;
if (alert.acknowledged) continue;
const fireTimeMs = computeTaskFireTime(task, alert.trigger);
if (fireTimeMs === null) continue;
if (fireTimeMs > now) continue;
if (fireTimeMs <= now - STALE_THRESHOLD_MS) continue;
const key = buildAlertKey(task.id, alertId, fireTimeMs);
if (acknowledgedKeys.has(key)) continue;
pending.push({
taskId: task.id,
alertId,
fireTimeMs,
task,
calendarName: calendar?.name ?? null,
});
}
}
return pending;
}
+29 -24
View File
@@ -251,10 +251,11 @@ function looksLikeReply(event: Partial<CalendarEvent>): boolean {
const participants = Object.values(event.participants);
const hasOrganizer = participants.some((participant) => isOrganizerParticipant(participant));
if (hasOrganizer) return false;
if (!hasOrganizer) return false;
return participants.some((participant) =>
participant.roles?.attendee
&& !isOrganizerParticipant(participant)
&& (
participant.participationStatus !== 'needs-action'
|| !!participant.participationComment
@@ -373,6 +374,10 @@ export function getInvitationMethod(
return 'cancel';
}
if (looksLikeReply(event)) {
return 'reply';
}
if (event.participants && Object.keys(event.participants).length > 0) {
const hasOrganizer = Object.values(event.participants).some(
(p: CalendarParticipant) => isOrganizerParticipant(p)
@@ -382,10 +387,6 @@ export function getInvitationMethod(
}
}
if (looksLikeReply(event)) {
return 'reply';
}
return 'unknown';
}
@@ -524,36 +525,40 @@ export function formatEventSummary(event: Partial<CalendarEvent>): EventSummary
}
function addDurationToDate(start: string, duration: string, _timeZone?: string | null): string | null {
const match = duration.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
const match = duration.match(/^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
if (!match) return null;
const days = parseInt(match[1] || '0');
const hours = parseInt(match[2] || '0');
const minutes = parseInt(match[3] || '0');
const seconds = parseInt(match[4] || '0');
const weeks = parseInt(match[1] || '0');
const days = parseInt(match[2] || '0') + weeks * 7;
const hours = parseInt(match[3] || '0');
const minutes = parseInt(match[4] || '0');
const seconds = parseInt(match[5] || '0');
const date = new Date(start);
if (isNaN(date.getTime())) return null;
const isUTC = start.endsWith('Z') || start.includes('+');
if (isUTC) {
date.setUTCDate(date.getUTCDate() + days);
date.setUTCHours(date.getUTCHours() + hours);
date.setUTCMinutes(date.getUTCMinutes() + minutes);
date.setUTCSeconds(date.getUTCSeconds() + seconds);
return date.toISOString();
}
date.setDate(date.getDate() + days);
date.setHours(date.getHours() + hours);
date.setMinutes(date.getMinutes() + minutes);
date.setSeconds(date.getSeconds() + seconds);
// If the input is a local datetime (no UTC 'Z' suffix), return a local
// format string so that all-day date arithmetic isn't shifted by the
// browser's UTC offset (toISOString converts to UTC).
if (!start.endsWith('Z') && !start.includes('+')) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
const h = String(date.getHours()).padStart(2, '0');
const min = String(date.getMinutes()).padStart(2, '0');
const s = String(date.getSeconds()).padStart(2, '0');
return `${y}-${m}-${d}T${h}:${min}:${s}`;
}
return date.toISOString();
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
const h = String(date.getHours()).padStart(2, '0');
const min = String(date.getMinutes()).padStart(2, '0');
const s = String(date.getSeconds()).padStart(2, '0');
return `${y}-${m}-${d}T${h}:${min}:${s}`;
}
export function findParticipantByEmail(
+45 -13
View File
@@ -15,11 +15,30 @@ export interface StatusCounts {
'needs-action': number;
}
/**
* Check if a participant matches any of the given email addresses.
* Checks p.email, p.calendarAddress (mailto:...), and p.sendTo values.
*/
function participantMatchesEmail(p: CalendarParticipant, lowerEmails: string[]): boolean {
if (p.email && lowerEmails.includes(p.email.toLowerCase())) return true;
if (p.calendarAddress) {
const addr = p.calendarAddress.replace(/^mailto:/i, '').toLowerCase();
if (addr && lowerEmails.includes(addr)) return true;
}
if (p.sendTo) {
for (const addr of Object.values(p.sendTo)) {
const normalized = addr.replace(/^mailto:/i, '').toLowerCase();
if (normalized && lowerEmails.includes(normalized)) return true;
}
}
return false;
}
export function isOrganizer(event: CalendarEvent, userEmails: string[]): boolean {
if (!event.participants) return false;
const lower = userEmails.map(e => e.toLowerCase());
return Object.values(event.participants).some(p =>
p.roles?.owner && lower.includes(p.email?.toLowerCase())
p.roles?.owner && participantMatchesEmail(p, lower)
);
}
@@ -27,7 +46,7 @@ export function getUserParticipantId(event: CalendarEvent, userEmails: string[])
if (!event.participants) return null;
const lower = userEmails.map(e => e.toLowerCase());
for (const [id, p] of Object.entries(event.participants)) {
if (lower.includes(p.email?.toLowerCase())) return id;
if (participantMatchesEmail(p, lower)) return id;
}
return null;
}
@@ -39,20 +58,29 @@ export function getUserStatus(
if (!event.participants) return null;
const lower = userEmails.map(e => e.toLowerCase());
for (const p of Object.values(event.participants)) {
if (lower.includes(p.email?.toLowerCase())) return p.participationStatus;
if (participantMatchesEmail(p, lower)) return p.participationStatus;
}
return null;
}
export function getParticipantList(event: CalendarEvent): ParticipantInfo[] {
if (!event.participants) return [];
return Object.entries(event.participants).map(([id, p]) => ({
id,
name: p.name || '',
email: p.email || '',
status: p.participationStatus || 'needs-action',
isOrganizer: !!p.roles?.owner,
}));
return Object.entries(event.participants).map(([id, p]) => {
let email = p.email || '';
if (!email && p.calendarAddress) {
email = p.calendarAddress.replace(/^mailto:/i, '');
}
if (!email && p.sendTo?.imip) {
email = p.sendTo.imip.replace(/^mailto:/i, '');
}
return {
id,
name: p.name || '',
email,
status: p.participationStatus || 'needs-action',
isOrganizer: !!p.roles?.owner,
};
});
}
export function getStatusCounts(event: CalendarEvent): StatusCounts {
@@ -76,7 +104,11 @@ export function buildParticipantMap(
): Record<string, Partial<CalendarParticipant>> {
const participants: Record<string, Partial<CalendarParticipant>> = {};
participants['organizer'] = {
const generateId = () => typeof crypto !== 'undefined' && crypto.randomUUID
? crypto.randomUUID()
: `p-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
participants[generateId()] = {
'@type': 'Participant',
name: organizer.name,
email: organizer.email,
@@ -88,8 +120,8 @@ export function buildParticipantMap(
kind: 'individual',
};
attendees.forEach((a, i) => {
participants[`attendee-${i}`] = {
attendees.forEach((a) => {
participants[generateId()] = {
'@type': 'Participant',
name: a.name,
email: a.email,
+5 -6
View File
@@ -40,9 +40,7 @@ export function normalizeAllDayDuration(duration: string | undefined): string |
}
export function buildAllDayDuration(start: Date, inclusiveEnd: Date): string {
const startDay = startOfDay(start);
const endDay = startOfDay(inclusiveEnd);
const dayCount = Math.max(1, Math.round((endDay.getTime() - startDay.getTime()) / 86400000) + 1);
const dayCount = Math.max(1, differenceInCalendarDays(startOfDay(inclusiveEnd), startOfDay(start)) + 1);
return `P${dayCount}D`;
}
@@ -113,7 +111,7 @@ export function layoutOverlappingEvents(
for (const event of sorted) {
const start = parseISO(event.start);
const startMin = start.getHours() * 60 + start.getMinutes();
const endMin = startMin + Math.max(15, parseDuration(event.duration));
const endMin = Math.min(1440, startMin + Math.max(15, parseDuration(event.duration)));
let placed = false;
for (let col = 0; col < columns.length; col++) {
if (columns[col].every(e => e.end <= startMin)) {
@@ -135,8 +133,9 @@ export function layoutOverlappingEvents(
}
export function formatSnapTime(minutes: number, timeFormat: "12h" | "24h"): string {
const h = Math.floor(minutes / 60);
const m = minutes % 60;
const clamped = Math.max(0, Math.min(1440, minutes));
const h = Math.floor(clamped / 60) % 24;
const m = clamped % 60;
if (timeFormat === "12h") {
return `${h % 12 || 12}:${String(m).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
}
+55 -1
View File
@@ -1,5 +1,5 @@
import type { IJMAPClient } from '@/lib/jmap/client-interface';
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode } from '@/lib/jmap/types';
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode } from '@/lib/jmap/types';
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
import { getDemoData, type DemoData } from './demo-data';
import { generateDemoId } from './demo-utils';
@@ -216,6 +216,11 @@ export class DemoJMAPClient implements IJMAPClient {
if (email) email.keywords = { ...email.keywords, ...keywords };
}
async setKeyword(emailId: string, keyword: string): Promise<void> {
const email = this.data.emails.find(e => e.id === emailId);
if (email) email.keywords[keyword] = true;
}
async migrateKeyword(oldKeyword: string, newKeyword: string): Promise<number> {
let count = 0;
for (const email of this.data.emails) {
@@ -621,6 +626,55 @@ export class DemoJMAPClient implements IJMAPClient {
return []; // no-op in demo
}
// ── Calendar Tasks ────────────────────────────────────────────
async getCalendarTasks(calendarIds?: string[]): Promise<CalendarTask[]> {
let tasks = this.data.calendarTasks || [];
if (calendarIds) {
tasks = tasks.filter(t => Object.keys(t.calendarIds).some(id => calendarIds.includes(id)));
}
return [...tasks];
}
async createCalendarTask(task: Partial<CalendarTask>): Promise<CalendarTask> {
const full: CalendarTask = {
id: generateDemoId('task'),
uid: generateDemoId('task-uid'),
'@type': 'Task',
calendarIds: task.calendarIds || { [this.data.calendars[0]?.id || 'cal-1']: true },
title: task.title || '',
description: task.description || '',
due: task.due || null,
start: task.start || null,
duration: task.duration || null,
timeZone: task.timeZone || null,
showWithoutTime: task.showWithoutTime ?? true,
progress: task.progress || 'needs-action',
progressUpdated: null,
priority: task.priority || 0,
privacy: task.privacy || 'public',
keywords: task.keywords || null,
categories: task.categories || null,
color: task.color || null,
created: new Date().toISOString(),
updated: new Date().toISOString(),
recurrenceRules: task.recurrenceRules || null,
alerts: task.alerts || null,
relatedTo: task.relatedTo || null,
};
this.data.calendarTasks.push(full);
return full;
}
async updateCalendarTask(taskId: string, updates: Partial<CalendarTask>): Promise<void> {
const task = this.data.calendarTasks.find(t => t.id === taskId);
if (task) Object.assign(task, updates, { updated: new Date().toISOString() });
}
async deleteCalendarTask(taskId: string): Promise<void> {
this.data.calendarTasks = this.data.calendarTasks.filter(t => t.id !== taskId);
}
// ── Sieve / Filters ──────────────────────────────────────────
getSieveAccountId(): string { return 'demo-account'; }
+4 -1
View File
@@ -3,12 +3,13 @@ import { createDemoMailboxes } from './fixtures/mailboxes';
import { createDemoEmails } from './fixtures/emails';
import { createDemoContacts, createDemoAddressBooks } from './fixtures/contacts';
import { createDemoCalendars, createDemoCalendarEvents } from './fixtures/calendars';
import { createDemoCalendarTasks } from './fixtures/tasks';
import { createDemoIdentities } from './fixtures/identities';
import { createDemoSieveScripts, createDemoSieveCapabilities, createDemoSieveContent } from './fixtures/filters';
import { createDemoFileNodes } from './fixtures/files';
import { createDemoVacationResponse } from './fixtures/vacation';
import type { Email, Mailbox, ContactCard, AddressBook, Calendar, CalendarEvent, Identity, VacationResponse, FileNode } from '@/lib/jmap/types';
import type { Email, Mailbox, ContactCard, AddressBook, Calendar, CalendarEvent, CalendarTask, Identity, VacationResponse, FileNode } from '@/lib/jmap/types';
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
export interface DemoData {
@@ -18,6 +19,7 @@ export interface DemoData {
addressBooks: AddressBook[];
calendars: Calendar[];
calendarEvents: CalendarEvent[];
calendarTasks: CalendarTask[];
identities: Identity[];
sieveScripts: SieveScript[];
sieveCapabilities: SieveCapabilities;
@@ -35,6 +37,7 @@ export function getDemoData(): DemoData {
addressBooks: createDemoAddressBooks(),
calendars: createDemoCalendars(),
calendarEvents: createDemoCalendarEvents(),
calendarTasks: createDemoCalendarTasks(),
identities: createDemoIdentities(),
sieveScripts: createDemoSieveScripts(),
sieveCapabilities: createDemoSieveCapabilities(),
+140
View File
@@ -0,0 +1,140 @@
import type { CalendarTask } from '@/lib/jmap/types';
import { demoDate } from '../demo-utils';
export function createDemoCalendarTasks(): CalendarTask[] {
return [
{
id: 'demo-task-1',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-1',
title: 'Buy groceries',
description: 'Milk, bread, eggs, and vegetables',
due: demoDate(0, 2),
start: null,
duration: null,
timeZone: null,
showWithoutTime: false,
progress: 'needs-action',
progressUpdated: null,
priority: 0,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-3),
updated: demoDate(-1),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-2',
calendarIds: { 'demo-calendar-work': true },
'@type': 'Task',
uid: 'demo-task-uid-2',
title: 'Prepare quarterly report',
description: 'Compile Q4 metrics and send to team',
due: demoDate(1, 4),
start: null,
duration: null,
timeZone: null,
showWithoutTime: false,
progress: 'in-process',
progressUpdated: demoDate(-1),
priority: 1,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-5),
updated: demoDate(0),
recurrenceRules: null,
alerts: {
'demo-alert-1': {
'@type': 'Alert',
trigger: { '@type': 'OffsetTrigger', offset: '-PT15M', relativeTo: 'start' },
action: 'display',
acknowledged: null,
relatedTo: null,
},
},
relatedTo: null,
},
{
id: 'demo-task-3',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-3',
title: 'Schedule dentist appointment',
description: '',
due: demoDate(3),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'needs-action',
progressUpdated: null,
priority: 5,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-2),
updated: demoDate(-2),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-4',
calendarIds: { 'demo-calendar-work': true },
'@type': 'Task',
uid: 'demo-task-uid-4',
title: 'Review pull requests',
description: 'Review open PRs from the team',
due: demoDate(-1),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'completed',
progressUpdated: demoDate(0),
priority: 0,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-4),
updated: demoDate(0),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
{
id: 'demo-task-5',
calendarIds: { 'demo-calendar-personal': true },
'@type': 'Task',
uid: 'demo-task-uid-5',
title: 'Pay electricity bill',
description: '',
due: demoDate(-2),
start: null,
duration: null,
timeZone: null,
showWithoutTime: true,
progress: 'needs-action',
progressUpdated: null,
priority: 1,
privacy: 'public',
keywords: null,
categories: null,
color: null,
created: demoDate(-7),
updated: demoDate(-7),
recurrenceRules: null,
alerts: null,
relatedTo: null,
},
];
}
+40
View File
@@ -0,0 +1,40 @@
const PARENT_ORIGIN = typeof window !== 'undefined'
? (document.querySelector('meta[name="parent-origin"]')?.getAttribute('content') || '')
: '';
export function isEmbedded(): boolean {
try {
return window.self !== window.top;
} catch {
return true;
}
}
export function notifyParent(type: string, payload: Record<string, unknown> = {}) {
if (!isEmbedded()) return;
const targetOrigin = PARENT_ORIGIN || '*';
try {
window.parent.postMessage({ source: 'bulwark', type, ...payload }, targetOrigin);
} catch {
// Cross-origin postMessage may fail in restricted contexts
}
}
export function listenFromParent(
handler: (msg: { type: string; [k: string]: unknown }) => void,
allowedOrigin?: string,
): () => void {
const listener = (event: MessageEvent) => {
// Validate origin if configured
if (allowedOrigin && event.origin !== allowedOrigin) return;
// Only accept messages from the portal
if (!event.data || event.data.source !== 'portal') return;
handler(event.data);
};
window.addEventListener('message', listener);
return () => window.removeEventListener('message', listener);
}
+8 -1
View File
@@ -1,4 +1,4 @@
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode } from "./types";
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode } from "./types";
import type { SieveScript, SieveCapabilities } from "./sieve-types";
/**
@@ -72,6 +72,7 @@ export interface IJMAPClient {
batchMarkAsRead(emailIds: string[], read?: boolean): Promise<void>;
toggleStar(emailId: string, starred: boolean): Promise<void>;
updateEmailKeywords(emailId: string, keywords: Record<string, boolean>): Promise<void>;
setKeyword(emailId: string, keyword: string): Promise<void>;
migrateKeyword(oldKeyword: string, newKeyword: string): Promise<number>;
deleteEmail(emailId: string): Promise<void>;
moveToTrash(emailId: string, trashMailboxId: string, accountId?: string): Promise<void>;
@@ -201,6 +202,12 @@ export interface IJMAPClient {
queryAllCalendarEvents(filter: CalendarEventFilter, sort?: Array<{ property: string; isAscending: boolean }>, limit?: number): Promise<CalendarEvent[]>;
parseCalendarEvents(accountId: string, blobId: string): Promise<Partial<CalendarEvent>[]>;
// ── Calendar Tasks ────────────────────────────────────────────
getCalendarTasks(calendarIds?: string[], targetAccountId?: string): Promise<CalendarTask[]>;
createCalendarTask(task: Partial<CalendarTask>, targetAccountId?: string): Promise<CalendarTask>;
updateCalendarTask(taskId: string, updates: Partial<CalendarTask>, targetAccountId?: string): Promise<void>;
deleteCalendarTask(taskId: string, targetAccountId?: string): Promise<void>;
// ── Sieve / Filters ──────────────────────────────────────────
getSieveAccountId(): string;
getSieveCapabilities(): SieveCapabilities | null;
+186 -12
View File
@@ -1,7 +1,8 @@
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, FileNode, FileNodeFilter } from "./types";
import type { Email, Mailbox, StateChange, AccountStates, Thread, Identity, EmailAddress, ContactCard, AddressBook, VacationResponse, Calendar, CalendarEvent, CalendarEventFilter, CalendarTask, FileNode, FileNodeFilter } from "./types";
import type { SieveScript, SieveCapabilities } from "./sieve-types";
import type { IJMAPClient } from "./client-interface";
import { toWildcardQuery } from "./search-utils";
import { debug } from "@/lib/debug";
// JMAP protocol types - these are intentionally flexible due to server variations
interface JMAPSession {
@@ -763,6 +764,19 @@ export class JMAPClient implements IJMAPClient {
]);
}
async setKeyword(emailId: string, keyword: string): Promise<void> {
await this.request([
["Email/set", {
accountId: this.accountId,
update: {
[emailId]: {
[`keywords/${keyword}`]: true,
},
},
}, "0"],
]);
}
async migrateKeyword(oldKeyword: string, newKeyword: string): Promise<number> {
// Query all email IDs that have the old keyword
const allIds: string[] = [];
@@ -1671,7 +1685,7 @@ export class JMAPClient implements IJMAPClient {
lines.push('END:VCALENDAR');
const icsContent = lines.join('\r\n') + '\r\n';
console.log('[iMIP DEBUG] Generated ICS:\n' + icsContent);
debug.log('[iMIP] Generated ICS:\n' + icsContent);
const statusLabels: Record<string, string> = {
ACCEPTED: 'Accepted',
@@ -1681,7 +1695,7 @@ export class JMAPClient implements IJMAPClient {
const statusLabel = statusLabels[opts.status] || opts.status;
const subject = `${statusLabel}: ${opts.summary || 'Event'}`;
console.log('[iMIP DEBUG] identityId:', finalIdentityId);
debug.log('[iMIP] identityId:', finalIdentityId);
const emailId = `imip-reply-${Date.now()}`;
const emailCreate: Record<string, unknown> = {
@@ -1714,27 +1728,27 @@ export class JMAPClient implements IJMAPClient {
}, "1"],
];
console.log('[iMIP DEBUG] Sending JMAP request with', methodCalls.length, 'method calls');
console.log('[iMIP DEBUG] Email create payload:', JSON.stringify(emailCreate, null, 2));
debug.log('[iMIP] Sending JMAP request with', methodCalls.length, 'method calls');
debug.log('[iMIP] Email create payload:', JSON.stringify(emailCreate, null, 2));
const response = await this.request(methodCalls);
console.log('[iMIP DEBUG] JMAP response:', JSON.stringify(response.methodResponses, null, 2));
debug.log('[iMIP] JMAP response:', JSON.stringify(response.methodResponses, null, 2));
if (response.methodResponses) {
for (const [methodName, result] of response.methodResponses) {
if (methodName.endsWith('/error')) {
console.error('[iMIP DEBUG] method error:', methodName, result);
debug.error('[iMIP] method error:', methodName, result);
throw new Error(result.description || `iMIP reply failed: ${result.type}`);
}
if (result.notCreated) {
const firstError = Object.values(result.notCreated)[0] as { description?: string; type?: string };
console.error('[iMIP DEBUG] create error:', JSON.stringify(result.notCreated, null, 2));
debug.error('[iMIP] create error:', JSON.stringify(result.notCreated, null, 2));
throw new Error(firstError?.description || firstError?.type || 'Failed to send iMIP reply');
}
}
}
console.log('[iMIP DEBUG] sendImipReply completed successfully');
debug.log('[iMIP] sendImipReply completed successfully');
}
/**
@@ -1810,6 +1824,9 @@ export class JMAPClient implements IJMAPClient {
const formatted = formatIcalDate(event.utcEnd, event.timeZone);
lines.push(formatted.startsWith('TZID=') ? `DTEND;${formatted}` : `DTEND:${formatted}`);
}
} else if (event.duration) {
// Fallback: emit DURATION when utcEnd is absent (RFC 5545 §3.6.1)
lines.push(`DURATION:${event.duration}`);
}
if (event.title) lines.push(`SUMMARY:${event.title}`);
@@ -1894,6 +1911,9 @@ export class JMAPClient implements IJMAPClient {
*/
async sendImipCancellation(event: CalendarEvent): Promise<void> {
if (!event.participants) return;
if (event.status && event.status !== 'cancelled') {
debug.warn('sendImipCancellation called on non-cancelled event, status:', event.status);
}
const mailboxes = await this.getMailboxes();
const sentMailbox = mailboxes.find(mb => mb.role === 'sent');
@@ -3173,6 +3193,49 @@ export class JMAPClient implements IJMAPClient {
return { destroyed, notDestroyed };
}
// ─── Calendar Tasks (JSCalendar Task objects via CalendarEvent endpoints) ───
async getCalendarTasks(calendarIds?: string[], targetAccountId?: string): Promise<CalendarTask[]> {
try {
const events = await this.getCalendarEvents(calendarIds, targetAccountId);
return events.filter((e) => {
const obj = e as unknown as Record<string, unknown>;
const type = obj['@type'];
// Explicit @type check (case-insensitive to handle server variations)
if (typeof type === 'string' && type.toLowerCase() === 'task') return true;
// Fallback: detect tasks created via CalDAV (e.g. Thunderbird) where @type
// may be missing. The "progress" property is exclusive to JSCalendar Task
// objects and never appears on Event objects.
if (type !== 'Event' && 'progress' in obj && typeof obj.progress === 'string') return true;
return false;
}).map((e) => {
const task = { ...e } as unknown as CalendarTask;
// Normalize @type for tasks detected by fallback heuristic
if (task['@type'] !== 'Task') {
(task as unknown as Record<string, unknown>)['@type'] = 'Task';
}
return task;
});
} catch (error) {
console.error('Failed to get calendar tasks:', error);
return [];
}
}
async createCalendarTask(task: Partial<CalendarTask>, targetAccountId?: string): Promise<CalendarTask> {
const event = { ...task, '@type': 'Task' } as unknown as Partial<CalendarEvent>;
const created = await this.createCalendarEvent(event, false, targetAccountId);
return created as unknown as CalendarTask;
}
async updateCalendarTask(taskId: string, updates: Partial<CalendarTask>, targetAccountId?: string): Promise<void> {
await this.updateCalendarEvent(taskId, updates as unknown as Partial<CalendarEvent>, false, targetAccountId);
}
async deleteCalendarTask(taskId: string, targetAccountId?: string): Promise<void> {
await this.deleteCalendarEvent(taskId, false, targetAccountId);
}
// ─── JMAP FileNode methods (draft-ietf-jmap-filenode) ───
supportsFiles(): boolean {
@@ -3451,6 +3514,8 @@ export class JMAPClient implements IJMAPClient {
private pollingInterval: NodeJS.Timeout | null = null;
private pollingStates: { [key: string]: string } = {};
private sseAbortController: AbortController | null = null;
private sseReconnectTimeout: NodeJS.Timeout | null = null;
private static readonly STATE_TYPE_MAP: Record<string, string> = {
'Mailbox/get': 'Mailbox',
@@ -3460,13 +3525,114 @@ export class JMAPClient implements IJMAPClient {
'SieveScript/get': 'SieveScript',
};
// Polling-based push since EventSource cannot send Authorization headers
private static readonly POLLING_INTERVAL = 3_000;
private static readonly SSE_RECONNECT_DELAY = 3_000;
setupPushNotifications(): boolean {
const eventSourceUrl = this.getEventSourceUrl();
if (eventSourceUrl) {
this.connectSSE(eventSourceUrl);
} else {
this.startPollingFallback();
}
return true;
}
private connectSSE(templateUrl: string): void {
const url = templateUrl
.replace('{types}', '*')
.replace('{closeafter}', 'no')
.replace('{ping}', '30');
this.sseAbortController = new AbortController();
fetch(url, {
headers: { 'Authorization': this.authHeader, 'Accept': 'text/event-stream' },
signal: this.sseAbortController.signal,
}).then(response => {
if (!response.ok || !response.body) {
this.fallbackToPolling();
return;
}
this.readSSEStream(response.body);
}).catch(() => {
this.fallbackToPolling();
});
}
private async readSSEStream(body: ReadableStream<Uint8Array>): Promise<void> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split('\n\n');
buffer = parts.pop() || '';
for (const part of parts) {
this.processSSEEvent(part);
}
}
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError') return;
}
// Stream ended — reconnect unless we were intentionally closed
if (this.sseAbortController && !this.sseAbortController.signal.aborted) {
this.scheduleSSEReconnect();
}
}
private processSSEEvent(raw: string): void {
let eventType = 'message';
let dataLines: string[] = [];
for (const line of raw.split('\n')) {
if (line.startsWith('event:')) {
eventType = line.slice(6).trim();
} else if (line.startsWith('data:')) {
dataLines.push(line.slice(5).trim());
}
}
if (eventType === 'state' && dataLines.length > 0) {
try {
const change = JSON.parse(dataLines.join('\n')) as StateChange;
this.stateChangeCallback?.(change);
} catch {
// Malformed SSE data — ignore
}
}
}
private scheduleSSEReconnect(): void {
const eventSourceUrl = this.getEventSourceUrl();
if (!eventSourceUrl) {
this.fallbackToPolling();
return;
}
this.sseReconnectTimeout = setTimeout(() => {
this.connectSSE(eventSourceUrl);
}, JMAPClient.SSE_RECONNECT_DELAY);
}
private fallbackToPolling(): void {
this.sseAbortController = null;
if (!this.pollingInterval) {
this.startPollingFallback();
}
}
private startPollingFallback(): void {
this.fetchCurrentStates();
this.pollingInterval = setInterval(() => {
this.checkForStateChanges();
}, 15_000);
return true;
}, JMAPClient.POLLING_INTERVAL);
}
private buildStatePollingRequest(): { using: string[]; methodCalls: JMAPMethodCall[] } {
@@ -3560,6 +3726,14 @@ export class JMAPClient implements IJMAPClient {
clearInterval(this.pollingInterval);
this.pollingInterval = null;
}
if (this.sseAbortController) {
this.sseAbortController.abort();
this.sseAbortController = null;
}
if (this.sseReconnectTimeout) {
clearTimeout(this.sseReconnectTimeout);
this.sseReconnectTimeout = null;
}
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
+2
View File
@@ -142,6 +142,8 @@ export interface ThreadGroup {
hasUnread: boolean; // Any unread emails in thread
hasStarred: boolean; // Any starred emails in thread
hasAttachment: boolean; // Any email has attachment
hasAnswered: boolean; // Any email has been replied to
hasForwarded: boolean; // Any email has been forwarded
emailCount: number; // Total emails in thread
}
+44 -14
View File
@@ -1,21 +1,51 @@
import { debug } from '@/lib/debug';
export function playNotificationSound() {
export type NotificationSoundChoice = 'default' | 'cheerful' | 'involved' | 'swift' | 'relax';
export const NOTIFICATION_SOUNDS: { id: NotificationSoundChoice; file?: string }[] = [
{ id: 'default' },
{ id: 'cheerful', file: '/notification/cheerful-527.mp3' },
{ id: 'involved', file: '/notification/involved-notification.mp3' },
{ id: 'swift', file: '/notification/notification-tone-swift-gesture.mp3' },
{ id: 'relax', file: '/notification/relax-message-tone.mp3' },
];
function playBeep() {
const audioContext = new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.value = 800;
oscillator.type = 'sine';
gainNode.gain.value = 0.1;
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.15);
oscillator.onended = () => audioContext.close();
}
function playFile(file: string) {
const audio = new Audio(file);
audio.volume = 0.3;
audio.play().catch((e) => {
debug.log('Could not play audio file, falling back to beep:', e);
playBeep();
});
}
export function playNotificationSound(sound?: NotificationSoundChoice) {
try {
const audioContext = new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
const choice = sound ?? 'default';
const entry = NOTIFICATION_SOUNDS.find((s) => s.id === choice);
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.value = 800;
oscillator.type = 'sine';
gainNode.gain.value = 0.1;
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.15);
oscillator.onended = () => audioContext.close();
if (entry?.file) {
playFile(entry.file);
} else {
playBeep();
}
} catch (e) {
debug.log('Could not play notification sound:', e);
}
+11
View File
@@ -0,0 +1,11 @@
const COOKIE_SAME_SITE = (process.env.COOKIE_SAME_SITE || 'lax') as 'lax' | 'none' | 'strict';
export function getCookieOptions() {
return {
httpOnly: true,
secure: COOKIE_SAME_SITE === 'none' ? true : process.env.NODE_ENV === 'production',
sameSite: COOKIE_SAME_SITE,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
}
+18
View File
@@ -0,0 +1,18 @@
import { randomBytes, createHash } from 'node:crypto';
function base64urlEncode(buffer: Buffer): string {
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function generateCodeVerifierServer(): string {
return base64urlEncode(randomBytes(32));
}
export function generateCodeChallengeServer(verifier: string): string {
const hash = createHash('sha256').update(verifier).digest();
return base64urlEncode(hash);
}
export function generateStateServer(): string {
return base64urlEncode(randomBytes(32));
}
+88
View File
@@ -0,0 +1,88 @@
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import type { OAuthMetadata } from '@/lib/oauth/discovery';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
export 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 };
}
export 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;
}
export async function getMetadata(): Promise<OAuthMetadata | null> {
const { discoveryUrl } = getRequiredConfig();
return discoverOAuth(discoveryUrl);
}
export 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 interface TokenResult {
access_token: string;
expires_in: number;
refresh_token?: string;
}
export async function exchangeCodeForTokens(
code: string,
codeVerifier: string,
redirectUri: string,
): Promise<TokenResult> {
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
});
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 });
throw new Error('Token exchange failed');
}
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
throw new Error('Invalid token response');
}
return {
access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600,
refresh_token: tokens.refresh_token,
};
}
+45 -3
View File
@@ -145,11 +145,50 @@ function passwordToBMP(password: ArrayBuffer): Uint8Array {
return bmp;
}
// ── CMS content encryption OIDs (for EnvelopedData decryption) ─────
const OID_DES_EDE3_CBC = '1.2.840.113549.3.7'; // des-EDE3-CBC (3DES)
const OID_DES_CBC = '1.3.14.3.2.7'; // desCBC
const OID_RC2_CBC = '1.2.840.113549.3.2'; // rc2CBC
/**
* Extended CryptoEngine that handles legacy PKCS#12 PBE algorithms.
* Falls through to the base CryptoEngine for everything else.
* Extended CryptoEngine that handles legacy algorithms (3DES, etc.)
* not recognized by pkijs's default CryptoEngine.
*
* - Adds OIDalgorithm mappings for DES-EDE3-CBC so that
* EnvelopedData.decrypt() can process 3DES-encrypted S/MIME messages.
* - Handles legacy PKCS#12 PBE algorithms via custom KDF.
*/
class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
/**
* Extend OIDalgorithm mapping with legacy algorithms that webcrypto-liner
* supports but pkijs does not know about.
*/
getAlgorithmByOID(oid: string, safety?: boolean, target?: string): object {
switch (oid) {
case OID_DES_EDE3_CBC:
return { name: 'DES-EDE3-CBC', length: 192 };
case OID_DES_CBC:
return { name: 'DES-CBC', length: 64 };
case OID_RC2_CBC:
return { name: 'RC2-CBC', length: 128 };
default:
return super.getAlgorithmByOID(oid, safety, target);
}
}
getOIDByAlgorithm(algorithm: { name: string; length?: number }, safety?: boolean, target?: string): string {
switch (algorithm.name.toUpperCase()) {
case 'DES-EDE3-CBC':
return OID_DES_EDE3_CBC;
case 'DES-CBC':
return OID_DES_CBC;
case 'RC2-CBC':
return OID_RC2_CBC;
default:
return super.getOIDByAlgorithm(algorithm, safety, target);
}
}
async decryptEncryptedContentInfo(
parameters: Parameters<pkijs.CryptoEngine['decryptEncryptedContentInfo']>[0],
): Promise<ArrayBuffer> {
@@ -182,9 +221,11 @@ class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
const ivBytes = await pkcs12KDF(bmpPassword, salt, iterations, 2, ivLen);
// Import key via webcrypto-liner (supports DES-EDE3-CBC)
const keyData = new Uint8Array(keyBytes.buffer as ArrayBuffer, keyBytes.byteOffset, keyBytes.byteLength);
const cryptoKey = await this.importKey(
'raw',
new Uint8Array(keyBytes.buffer as ArrayBuffer, keyBytes.byteOffset, keyBytes.byteLength) as unknown as BufferSource,
keyData,
// eslint-disable-next-line no-undef
{ name: algName, length: keyLen * 8 } as Algorithm,
false,
['decrypt'],
@@ -193,6 +234,7 @@ class Pkcs12CryptoEngine extends pkijs.CryptoEngine {
// Decrypt
const ciphertext = parameters.encryptedContentInfo.getEncryptedContent();
return this.decrypt(
// eslint-disable-next-line no-undef
{ name: algName, iv: ivBytes } as Algorithm,
cryptoKey,
ciphertext,
+16 -13
View File
@@ -8,7 +8,7 @@
import * as pkijs from 'pkijs';
import * as asn1js from 'asn1js';
import type { SmimeKeyRecord } from './types';
import { getLinerCryptoEngine } from './crypto-engine';
import { getLinerCryptoEngine, withLinerEngine } from './crypto-engine';
export interface DecryptionInput {
/** Raw CMS EnvelopedData bytes (DER) */
@@ -360,17 +360,20 @@ async function decryptWithKey(
const certAsn1 = asn1js.fromBER(keyRecord.certificate);
const cert = new pkijs.Certificate({ schema: certAsn1.result });
// Use webcrypto-liner engine for legacy algorithm support (e.g. 3DES)
const cryptoEngine = getLinerCryptoEngine();
// Use withLinerEngine to set the global pkijs engine to webcrypto-liner.
// This is required because pkijs internally may use getEngine() for
// OID lookups and crypto operations. Without this, 3DES-encrypted
// messages fail because the default engine doesn't know about DES-EDE3-CBC.
return withLinerEngine(async () => {
const cryptoEngine = getLinerCryptoEngine();
const result = await envelopedData.decrypt(
recipientIndex,
{
recipientCertificate: cert,
recipientPrivateKey: privateKey,
},
cryptoEngine,
);
return result;
return envelopedData.decrypt(
recipientIndex,
{
recipientCertificate: cert,
recipientPrivateKey: privateKey,
},
cryptoEngine,
);
});
}
+8
View File
@@ -38,6 +38,8 @@ export function groupEmailsByThread(emails: Email[]): ThreadGroup[] {
const hasUnread = sortedEmails.some(e => !e.keywords?.$seen);
const hasStarred = sortedEmails.some(e => e.keywords?.$flagged);
const hasAttachment = sortedEmails.some(e => e.hasAttachment);
const hasAnswered = sortedEmails.some(e => e.keywords?.$answered);
const hasForwarded = sortedEmails.some(e => e.keywords?.$forwarded);
threadGroups.push({
threadId,
@@ -47,6 +49,8 @@ export function groupEmailsByThread(emails: Email[]): ThreadGroup[] {
hasUnread,
hasStarred,
hasAttachment,
hasAnswered,
hasForwarded,
emailCount: sortedEmails.length,
});
}
@@ -123,6 +127,8 @@ export function mergeThreadEmails(
const hasUnread = mergedEmails.some(e => !e.keywords?.$seen);
const hasStarred = mergedEmails.some(e => e.keywords?.$flagged);
const hasAttachment = mergedEmails.some(e => e.hasAttachment);
const hasAnswered = mergedEmails.some(e => e.keywords?.$answered);
const hasForwarded = mergedEmails.some(e => e.keywords?.$forwarded);
return {
threadId: existingGroup.threadId,
@@ -132,6 +138,8 @@ export function mergeThreadEmails(
hasUnread,
hasStarred,
hasAttachment,
hasAnswered,
hasForwarded,
emailCount: mergedEmails.length,
};
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Utilities for handling drag-and-drop of files and folders.
* Uses the File and Directory Entries API (webkitGetAsEntry) to
* recursively read dropped directory trees, preserving relative paths.
*/
interface FileWithPath extends File {
readonly webkitRelativePath: string;
}
/**
* Read all File entries from a FileSystemDirectoryEntry recursively.
* Each returned File has its webkitRelativePath set to the relative path
* within the dropped folder (e.g. "folder/sub/file.txt").
*/
function readDirectoryEntries(dirEntry: FileSystemDirectoryEntry): Promise<FileWithPath[]> {
return new Promise((resolve, reject) => {
const reader = dirEntry.createReader();
const allEntries: FileSystemEntry[] = [];
// readEntries may return results in batches; keep reading until empty
const readBatch = () => {
reader.readEntries(
(entries) => {
if (entries.length === 0) {
resolveFiles(allEntries).then(resolve, reject);
} else {
allEntries.push(...entries);
readBatch();
}
},
reject,
);
};
readBatch();
});
}
function resolveFiles(entries: FileSystemEntry[]): Promise<FileWithPath[]> {
const promises = entries.map((entry) => {
if (entry.isFile) {
return new Promise<FileWithPath[]>((resolve, reject) => {
(entry as FileSystemFileEntry).file(
(file) => {
// Set webkitRelativePath directly on the original File object.
// The property lives on File.prototype as a getter, so defining
// an own data property on the instance safely shadows it.
try {
Object.defineProperty(file, 'webkitRelativePath', {
value: entry.fullPath.replace(/^\//, ''),
writable: false,
configurable: true,
});
} catch {
// Fallback: some environments may prevent overriding.
// The store also falls back to file.name, which still works
// for flat files (though nested paths would be lost).
}
resolve([file as unknown as FileWithPath]);
},
reject,
);
});
} else if (entry.isDirectory) {
return readDirectoryEntries(entry as FileSystemDirectoryEntry);
}
return Promise.resolve([]);
});
return Promise.all(promises).then((arrays) => arrays.flat());
}
/**
* Result of processing a drop event's DataTransfer.
*/
export interface DropResult {
files: File[];
hasDirectories: boolean;
}
/**
* Process a drop event's DataTransfer, detecting folders and recursively
* reading their contents. Returns the list of files and whether any
* directories were found.
*
* Falls back to e.dataTransfer.files when webkitGetAsEntry is unavailable.
*/
export async function getDroppedFilesAndFolders(dataTransfer: DataTransfer): Promise<DropResult> {
const items = dataTransfer.items;
// Check if the browser supports webkitGetAsEntry
if (items && items.length > 0 && typeof items[0].webkitGetAsEntry === 'function') {
const entries: FileSystemEntry[] = [];
for (let i = 0; i < items.length; i++) {
const entry = items[i].webkitGetAsEntry();
if (entry) entries.push(entry);
}
let hasDirectories = false;
const filePromises: Promise<FileWithPath[]>[] = [];
for (const entry of entries) {
if (entry.isDirectory) {
hasDirectories = true;
filePromises.push(readDirectoryEntries(entry as FileSystemDirectoryEntry));
} else if (entry.isFile) {
filePromises.push(
new Promise<FileWithPath[]>((resolve, reject) => {
(entry as FileSystemFileEntry).file(
(file) => resolve([file as FileWithPath]),
reject,
);
}),
);
}
}
const allFiles = (await Promise.all(filePromises)).flat();
return { files: allFiles, hasDirectories };
}
// Fallback: no entry API support
return {
files: Array.from(dataTransfer.files),
hasDirectories: false,
};
}
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Alle",
"no_icons_found": "Keine Symbole gefunden",
"inline_badge": "Eingebettet",
"tab_badge": "Tab"
"tab_badge": "Tab",
"show_on_mobile": "Auf Mobilgerät anzeigen"
},
"email_list": {
"no_emails": "Keine Nachrichten gefunden",
@@ -623,7 +624,8 @@
"encryption": "Verschlüsselung",
"files": "Dateien",
"contacts": "Contacts",
"sidebar_apps": "Sidebar-Apps"
"sidebar_apps": "Sidebar-Apps",
"notifications": "Benachrichtigungen"
},
"tab_groups": {
"general": "Allgemein",
@@ -691,7 +693,43 @@
"delete": "Schlüsselwort löschen",
"save": "Speichern",
"add": "Hinzufügen",
"cancel": "Abbrechen"
"cancel": "Abbrechen",
"migrating": "Schlüsselwort bei bestehenden E-Mails aktualisieren…",
"migration_error": "Schlüsselwort konnte bei bestehenden E-Mails nicht aktualisiert werden"
},
"notifications": {
"test_sound": "Benachrichtigungston testen",
"sounds": {
"default": "Standard (Piepton)",
"cheerful": "Fröhlich",
"involved": "Aufwendig",
"swift": "Schnelle Geste",
"relax": "Entspannt"
},
"sound_selection": {
"title": "Benachrichtigungston",
"description": "Wählen Sie den Ton für Benachrichtigungen",
"choose": "Ton",
"choose_desc": "Wählen Sie einen Benachrichtigungston und klicken Sie auf das Lautsprechersymbol zur Vorschau"
},
"email": {
"title": "E-Mail-Benachrichtigungen",
"description": "Benachrichtigungen für eingehende E-Mails konfigurieren",
"enabled": "E-Mail-Benachrichtigungen",
"enabled_desc": "Benachrichtigungen anzeigen, wenn neue E-Mails eintreffen",
"sound": "Benachrichtigungston",
"sound_desc": "Einen Ton abspielen, wenn neue E-Mails eintreffen"
},
"calendar": {
"title": "Kalender-Benachrichtigungen",
"description": "Benachrichtigungen für Kalendertermine konfigurieren",
"enabled": "Terminbenachrichtigungen",
"enabled_desc": "Erinnerungen für bevorstehende Kalendertermine anzeigen",
"sound": "Benachrichtigungston",
"sound_desc": "Einen Ton für Kalendererinnerungen abspielen",
"invitation_parsing": "E-Mail-Einladungen erkennen",
"invitation_parsing_desc": "Kalendereinladungen in E-Mail-Anhängen erkennen und Kalenderaktionen anzeigen"
}
},
"language_region": {
"title": "Sprache & Region",
@@ -771,6 +809,7 @@
"below-header": "Unter dem Header"
},
"emails_per_page": {
"10": "10 E-Mails",
"25": "25 E-Mails",
"50": "50 E-Mails",
"100": "100 E-Mails",
@@ -806,6 +845,24 @@
"close": "Schließen",
"invalid_email": "Bitte geben Sie eine gültige E-Mail-Adresse ein",
"already_added": "Dieser Absender ist bereits vertrauenswürdig"
},
"hover_actions": {
"label": "Schnelle Hover-Aktionen",
"description": "Wählen Sie, welche Schnellaktionen beim Überfahren einer E-Mail in der Liste angezeigt werden",
"delete": "Löschen",
"star": "Markieren / Markierung aufheben",
"mark_read": "Als gelesen / ungelesen markieren",
"archive": "Archivieren",
"tag": "Schlagwort",
"spam": "Als Spam markieren",
"none_selected": "Keine Aktionen ausgewählt"
},
"default_mail_program": {
"label": "Standard-E-Mail-Programm",
"description": "Registrieren Sie {appName} als Ihr Standard-E-Mail-Programm für mailto:-Links",
"button": "Als Standard festlegen",
"success": "Browser wurde aufgefordert, als Standard festzulegen",
"error": "Ihr Browser unterstützt diese Funktion nicht"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Konto",
"description": "Zeigen Sie Ihre Kontoinformationen an",
"name_label": "Anzeigename",
"username_label": "Benutzername",
"account_type_label": "Kontotyp",
"auth_method_label": "Authentifizierung",
"auth_method_oauth": "Single Sign-On (OAuth/OIDC)",
"auth_method_basic": "Passwort",
"demo_account": "Demokonto",
"email": {
"label": "E-Mail-Adresse",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Dieses Skript wurde außerhalb des visuellen Builders bearbeitet. Nur die Sieve-Skriptbearbeitung ist verfügbar.",
"open_sieve_editor": "Sieve-Skript-Editor öffnen",
"fetch_error": "Filter konnten nicht geladen werden",
"expanded_view": "Erweiterte Ansicht",
"expanded_view_description": "Filterregeln mit detaillierten Bedingungs- und Aktionsblöcken anzeigen",
"if": "Wenn",
"then": "Dann",
"match_all_conditions": "alle zutreffen",
"match_any_condition": "eine zutrifft",
"and": "und",
"or": "oder",
"cancel": "Abbrechen",
@@ -1842,7 +1909,11 @@
"notification_sound": "Benachrichtigungston",
"notification_sound_desc": "Ton für Kalenderbenachrichtigungen abspielen",
"invitation_parsing": "E-Mail-Einladungen verarbeiten",
"invitation_parsing_desc": "Kalendereinladungen in E-Mail-Anhängen erkennen und Kalenderaktionen anzeigen"
"invitation_parsing_desc": "Kalendereinladungen in E-Mail-Anhängen erkennen und Kalenderaktionen anzeigen",
"show_time_in_month_view": "Zeit in Monatsansicht anzeigen",
"show_time_in_month_view_desc": "Ereigniszeiten in der Monatskalenderansicht anzeigen",
"show_week_numbers": "Kalenderwochen anzeigen",
"show_week_numbers_desc": "Kalenderwochen im Minikalender anzeigen"
},
"days": {
"monday": "Montag",
@@ -2053,7 +2124,7 @@
"file": "Datei",
"parent_directory": "Übergeordnetes Verzeichnis",
"breadcrumb_root": "Startseite",
"drop_files_here": "Dateien hier ablegen zum Hochladen",
"drop_files_here": "Dateien oder Ordner hier ablegen zum Hochladen",
"uploading": "Wird hochgeladen...",
"upload_success": "{count, plural, one {1 Datei hochgeladen} other {# Dateien hochgeladen}}",
"upload_error": "Datei konnte nicht hochgeladen werden",
@@ -2238,8 +2309,14 @@
"settings_desc": "Passen Sie alles an: Design, Dichte, Signaturen, Filter, Tastaturkürzel, Kalender-Standards und mehr.",
"shortcuts_title": "Tastaturkürzel",
"shortcuts_desc": "Für Power-User. Drücken Sie jederzeit ?, um alle verfügbaren Kürzel anzuzeigen.",
"compose_open_title": "Der Editor",
"compose_open_desc": "Dies ist der E-Mail-Editor. Fügen Sie Empfänger hinzu, schreiben Sie Ihre Nachricht, hängen Sie Dateien an und verwenden Sie Rich-Text-Formatierung. Sie können auch Entwürfe speichern und Vorlagen verwenden.",
"calendar_view_title": "Ihr Kalender",
"calendar_view_desc": "Hier ist Ihr Kalender mit Beispielterminen. Wechseln Sie zwischen Tag-, Wochen-, Monats- und Agendaansicht.",
"create_event_title": "Ereignis erstellen",
"create_event_desc": "Klicken Sie auf diese Schaltfläche, um ein neues Kalenderereignis zu erstellen. Sie können Titel, Datum, Uhrzeit und Teilnehmer festlegen.",
"event_modal_title": "Ereignisdetails",
"event_modal_desc": "Hier ist das Ereignisformular. Geben Sie den Titel ein, wählen Sie Datum und Uhrzeit, fügen Sie einen Ort oder Teilnehmer hinzu. Klicken Sie auf Speichern, wenn Sie fertig sind — oder schließen Sie es und fahren Sie fort.",
"contacts_list_title": "Ihre Kontakte",
"contacts_list_desc": "Hier sind Ihre Kontakte. Klicken Sie auf einen Kontakt, um Details zu sehen. Sie können neue Kontakte erstellen oder vCards importieren.",
"files_title": "Dateispeicher",
+110 -7
View File
@@ -146,7 +146,8 @@
"show_all": "All",
"no_icons_found": "No icons found",
"inline_badge": "Inline",
"tab_badge": "Tab"
"tab_badge": "Tab",
"show_on_mobile": "Show on Mobile"
},
"email_list": {
"no_emails": "No messages found",
@@ -623,7 +624,8 @@
"files": "Files",
"contacts": "Contacts",
"encryption": "Encryption",
"sidebar_apps": "Sidebar Apps"
"sidebar_apps": "Sidebar Apps",
"notifications": "Notifications"
},
"tab_groups": {
"general": "General",
@@ -695,6 +697,40 @@
"migrating": "Updating keyword on existing emails…",
"migration_error": "Failed to update keyword on existing emails"
},
"notifications": {
"test_sound": "Test notification sound",
"sounds": {
"default": "Default (Beep)",
"cheerful": "Cheerful",
"involved": "Involved",
"swift": "Swift Gesture",
"relax": "Relax"
},
"sound_selection": {
"title": "Notification Sound",
"description": "Choose which sound to play for notifications",
"choose": "Sound",
"choose_desc": "Select a notification tone and click the speaker icon to preview it"
},
"email": {
"title": "Email Notifications",
"description": "Configure notifications for incoming emails",
"enabled": "Email notifications",
"enabled_desc": "Show notifications when new emails arrive",
"sound": "Notification sound",
"sound_desc": "Play an audio alert when new emails arrive"
},
"calendar": {
"title": "Calendar Notifications",
"description": "Configure notifications for calendar events",
"enabled": "Event notifications",
"enabled_desc": "Show alerts for upcoming calendar events",
"sound": "Notification sound",
"sound_desc": "Play an audio alert for calendar reminders",
"invitation_parsing": "Parse email invitations",
"invitation_parsing_desc": "Detect calendar invitations in email attachments and show calendar actions"
}
},
"language_region": {
"title": "Language & Region",
"description": "Configure language and regional preferences",
@@ -773,6 +809,7 @@
"below-header": "Below header"
},
"emails_per_page": {
"10": "10 emails",
"25": "25 emails",
"50": "50 emails",
"100": "100 emails",
@@ -819,6 +856,13 @@
"tag": "Tag",
"spam": "Mark as Spam",
"none_selected": "No actions selected"
},
"default_mail_program": {
"label": "Default Mail Program",
"description": "Register {appName} as your default mail program for mailto: links",
"button": "Set as Default",
"success": "Browser prompted to set as default",
"error": "Your browser does not support this feature"
}
},
"composer": {
@@ -870,7 +914,11 @@
"title": "Account",
"description": "View your account information",
"name_label": "Display Name",
"username_label": "Username",
"account_type_label": "Account Type",
"auth_method_label": "Authentication",
"auth_method_oauth": "Single Sign-On (OAuth/OIDC)",
"auth_method_basic": "Password",
"demo_account": "Demo Account",
"email": {
"label": "Email Address",
@@ -1182,6 +1230,12 @@
"opaque_warning": "This script was edited outside the visual builder. Only raw Sieve editing is available.",
"open_sieve_editor": "Open raw Sieve editor",
"fetch_error": "Failed to load filters",
"expanded_view": "Expanded view",
"expanded_view_description": "Show filter rules with detailed condition and action blocks",
"if": "If",
"then": "Then",
"match_all_conditions": "all match",
"match_any_condition": "any matches",
"and": "and",
"or": "or",
"cancel": "Cancel",
@@ -1746,7 +1800,9 @@
"month_hint": "Month (m)",
"week_hint": "Week (w)",
"day_hint": "Day (d)",
"agenda_hint": "Agenda (a)"
"agenda_hint": "Agenda (a)",
"tasks": "Tasks",
"tasks_hint": "Tasks (k)"
},
"events": {
"create": "Create event",
@@ -1855,7 +1911,15 @@
"notification_sound": "Notification sound",
"notification_sound_desc": "Play a sound for calendar alerts",
"invitation_parsing": "Parse email invitations",
"invitation_parsing_desc": "Detect calendar invitations in email attachments and show calendar actions"
"invitation_parsing_desc": "Detect calendar invitations in email attachments and show calendar actions",
"show_time_in_month_view": "Show time in month view",
"show_time_in_month_view_desc": "Display event times in the month calendar view",
"show_week_numbers": "Show week numbers",
"show_week_numbers_desc": "Display week numbers in the mini-calendar",
"enable_tasks": "Enable tasks",
"enable_tasks_desc": "Show a tasks view in the calendar for managing to-dos",
"show_tasks_on_calendar": "Show tasks on calendar",
"show_tasks_on_calendar_desc": "Display task chips on the day and week calendar views"
},
"days": {
"monday": "Monday",
@@ -1888,7 +1952,8 @@
"rsvp_updated": "Response updated",
"rsvp_error": "Failed to update response",
"event_duplicated": "Event duplicated",
"event_error": "Failed to save event"
"event_error": "Failed to save event",
"task_due": "Task due"
},
"status": {
"loading_calendars": "Loading calendars...",
@@ -1986,10 +2051,48 @@
"last_refreshed": "Last updated: {time}"
},
"tasks": {
"label": "Tasks",
"no_tasks": "No tasks",
"no_title": "(No title)",
"mark_complete": "Mark as complete",
"mark_incomplete": "Mark as incomplete"
"mark_incomplete": "Mark as incomplete",
"filter_all": "All",
"filter_pending": "Pending",
"filter_completed": "Completed",
"filter_overdue": "Overdue",
"show_completed": "Show completed",
"create": "New Task",
"edit": "Edit Task",
"title_placeholder": "Task title",
"description_placeholder": "Add a description...",
"due_date": "Due date",
"include_time": "Include time",
"priority": "Priority",
"priority_none": "None",
"priority_high": "High",
"priority_medium": "Medium",
"priority_low": "Low",
"progress": "Status",
"progress_needs_action": "Needs action",
"progress_in_process": "In process",
"progress_completed": "Completed",
"progress_cancelled": "Cancelled",
"calendar": "Calendar",
"alert": "Reminder",
"alert_none": "None",
"alert_at_time": "At time of due date",
"alert_5min": "5 minutes before",
"alert_15min": "15 minutes before",
"alert_30min": "30 minutes before",
"alert_1hr": "1 hour before",
"alert_1day": "1 day before",
"delete": "Delete",
"cancel": "Cancel",
"save": "Save",
"quick_add_placeholder": "Add a task...",
"due_today": "Today",
"due_tomorrow": "Tomorrow",
"overdue": "Overdue"
}
},
"advanced_search": {
@@ -2066,7 +2169,7 @@
"file": "File",
"parent_directory": "Parent directory",
"breadcrumb_root": "Home",
"drop_files_here": "Drop files here to upload",
"drop_files_here": "Drop files or folders here to upload",
"uploading": "Uploading...",
"upload_success": "{count, plural, one {1 file uploaded} other {# files uploaded}}",
"upload_error": "Failed to upload file",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Todos",
"no_icons_found": "No se encontraron iconos",
"inline_badge": "Integrado",
"tab_badge": "Pestaña"
"tab_badge": "Pestaña",
"show_on_mobile": "Mostrar en móvil"
},
"email_list": {
"no_emails": "No se encontraron mensajes",
@@ -623,7 +624,8 @@
"encryption": "Cifrado",
"files": "Archivos",
"contacts": "Contacts",
"sidebar_apps": "Apps de barra lateral"
"sidebar_apps": "Apps de barra lateral",
"notifications": "Notificaciones"
},
"tab_groups": {
"general": "General",
@@ -691,7 +693,43 @@
"delete": "Eliminar palabra clave",
"save": "Guardar",
"add": "Añadir",
"cancel": "Cancelar"
"cancel": "Cancelar",
"migrating": "Actualizando etiqueta en correos existentes…",
"migration_error": "Error al actualizar la etiqueta en correos existentes"
},
"notifications": {
"test_sound": "Probar sonido de notificación",
"sounds": {
"default": "Predeterminado (Pitido)",
"cheerful": "Alegre",
"involved": "Elaborado",
"swift": "Gesto rápido",
"relax": "Relajado"
},
"sound_selection": {
"title": "Sonido de notificación",
"description": "Elige qué sonido reproducir para las notificaciones",
"choose": "Sonido",
"choose_desc": "Selecciona un tono de notificación y haz clic en el icono del altavoz para previsualizarlo"
},
"email": {
"title": "Notificaciones de correo",
"description": "Configurar notificaciones para correos entrantes",
"enabled": "Notificaciones de correo",
"enabled_desc": "Mostrar notificaciones cuando lleguen nuevos correos",
"sound": "Sonido de notificación",
"sound_desc": "Reproducir un sonido cuando lleguen nuevos correos"
},
"calendar": {
"title": "Notificaciones de calendario",
"description": "Configurar notificaciones para eventos del calendario",
"enabled": "Notificaciones de eventos",
"enabled_desc": "Mostrar alertas para próximos eventos del calendario",
"sound": "Sonido de notificación",
"sound_desc": "Reproducir un sonido para recordatorios del calendario",
"invitation_parsing": "Analizar invitaciones por correo",
"invitation_parsing_desc": "Detectar invitaciones de calendario en archivos adjuntos y mostrar acciones de calendario"
}
},
"language_region": {
"title": "Idioma y Región",
@@ -771,6 +809,7 @@
"below-header": "Debajo del encabezado"
},
"emails_per_page": {
"10": "10 correos",
"25": "25 correos",
"50": "50 correos",
"100": "100 correos",
@@ -806,6 +845,24 @@
"close": "Cerrar",
"invalid_email": "Por favor ingrese una dirección de correo válida",
"already_added": "Este remitente ya es de confianza"
},
"hover_actions": {
"label": "Acciones rápidas al pasar el ratón",
"description": "Elige qué acciones rápidas aparecen al pasar el ratón sobre un correo en la lista",
"delete": "Eliminar",
"star": "Marcar / Desmarcar estrella",
"mark_read": "Marcar como leído / no leído",
"archive": "Archivar",
"tag": "Etiqueta",
"spam": "Marcar como spam",
"none_selected": "No hay acciones seleccionadas"
},
"default_mail_program": {
"label": "Programa de correo predeterminado",
"description": "Registrar {appName} como su programa de correo predeterminado para enlaces mailto:",
"button": "Establecer como predeterminado",
"success": "El navegador solicitó establecer como predeterminado",
"error": "Su navegador no admite esta función"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Cuenta",
"description": "Vea la información de su cuenta",
"name_label": "Nombre para mostrar",
"username_label": "Nombre de usuario",
"account_type_label": "Tipo de cuenta",
"auth_method_label": "Autenticación",
"auth_method_oauth": "Inicio de sesión único (OAuth/OIDC)",
"auth_method_basic": "Contraseña",
"demo_account": "Cuenta de demostración",
"email": {
"label": "Dirección de Correo",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Este script fue editado fuera del constructor visual. Solo está disponible la edición Sieve sin formato.",
"open_sieve_editor": "Abrir editor Sieve",
"fetch_error": "Error al cargar los filtros",
"expanded_view": "Vista expandida",
"expanded_view_description": "Mostrar reglas de filtro con bloques detallados de condiciones y acciones",
"if": "Si",
"then": "Entonces",
"match_all_conditions": "todas coinciden",
"match_any_condition": "alguna coincide",
"and": "y",
"or": "o",
"cancel": "Cancelar",
@@ -1842,7 +1909,11 @@
"notification_sound": "Sonido de notificación",
"notification_sound_desc": "Reproducir un sonido para las alertas del calendario",
"invitation_parsing": "Analizar invitaciones por correo",
"invitation_parsing_desc": "Detectar invitaciones de calendario en archivos adjuntos del correo y mostrar acciones del calendario"
"invitation_parsing_desc": "Detectar invitaciones de calendario en archivos adjuntos del correo y mostrar acciones del calendario",
"show_time_in_month_view": "Mostrar hora en vista mensual",
"show_time_in_month_view_desc": "Mostrar las horas de los eventos en la vista mensual del calendario",
"show_week_numbers": "Mostrar números de semana",
"show_week_numbers_desc": "Mostrar los números de semana en el minicalendario"
},
"days": {
"monday": "Lunes",
@@ -2053,7 +2124,7 @@
"file": "Archivo",
"parent_directory": "Directorio superior",
"breadcrumb_root": "Inicio",
"drop_files_here": "Suelte los archivos aquí para subirlos",
"drop_files_here": "Suelte archivos o carpetas aquí para subirlos",
"uploading": "Subiendo...",
"upload_success": "{count, plural, one {1 archivo subido} other {# archivos subidos}}",
"upload_error": "Error al subir el archivo",
@@ -2238,8 +2309,14 @@
"settings_desc": "Personaliza todo: tema, densidad, firmas, filtros, atajos de teclado, valores predeterminados del calendario y más.",
"shortcuts_title": "Atajos de teclado",
"shortcuts_desc": "Para usuarios avanzados. Pulsa ? en cualquier momento para ver todos los atajos disponibles.",
"compose_open_title": "El compositor",
"compose_open_desc": "Este es el compositor de correo. Añade destinatarios, escribe tu mensaje, adjunta archivos y usa formato de texto enriquecido. También puedes guardar borradores y usar plantillas.",
"calendar_view_title": "Tu calendario",
"calendar_view_desc": "Aquí está tu calendario con eventos de ejemplo. Cambia entre vistas de día, semana, mes y agenda.",
"create_event_title": "Crear un evento",
"create_event_desc": "Haz clic en este botón para crear un nuevo evento de calendario. Puedes establecer un título, fecha, hora y añadir participantes.",
"event_modal_title": "Detalles del evento",
"event_modal_desc": "Aquí está el formulario del evento. Rellena el título, elige una fecha y hora, añade una ubicación o participantes. Pulsa guardar cuando hayas terminado — o ciérralo y continúa.",
"contacts_list_title": "Tus contactos",
"contacts_list_desc": "Aquí están tus contactos. Haz clic en cualquier contacto para ver sus detalles. Puedes crear contactos nuevos o importar vCards.",
"files_title": "Almacenamiento de archivos",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Toutes",
"no_icons_found": "Aucune icône trouvée",
"inline_badge": "Intégré",
"tab_badge": "Onglet"
"tab_badge": "Onglet",
"show_on_mobile": "Afficher sur mobile"
},
"email_list": {
"no_emails": "Aucun message trouvé",
@@ -623,7 +624,8 @@
"encryption": "Chiffrement",
"files": "Fichiers",
"contacts": "Contacts",
"sidebar_apps": "Apps de la barre latérale"
"sidebar_apps": "Apps de la barre latérale",
"notifications": "Notifications"
},
"tab_groups": {
"general": "Général",
@@ -691,7 +693,43 @@
"delete": "Supprimer le mot-clé",
"save": "Enregistrer",
"add": "Ajouter",
"cancel": "Annuler"
"cancel": "Annuler",
"migrating": "Mise à jour du mot-clé sur les e-mails existants…",
"migration_error": "Échec de la mise à jour du mot-clé sur les e-mails existants"
},
"notifications": {
"test_sound": "Tester le son de notification",
"sounds": {
"default": "Par défaut (Bip)",
"cheerful": "Joyeux",
"involved": "Élaboré",
"swift": "Geste rapide",
"relax": "Détente"
},
"sound_selection": {
"title": "Son de notification",
"description": "Choisissez le son à jouer pour les notifications",
"choose": "Son",
"choose_desc": "Sélectionnez une sonnerie et cliquez sur l'icône du haut-parleur pour l'écouter"
},
"email": {
"title": "Notifications par e-mail",
"description": "Configurer les notifications pour les e-mails entrants",
"enabled": "Notifications par e-mail",
"enabled_desc": "Afficher des notifications à l'arrivée de nouveaux e-mails",
"sound": "Son de notification",
"sound_desc": "Jouer un son à l'arrivée de nouveaux e-mails"
},
"calendar": {
"title": "Notifications de calendrier",
"description": "Configurer les notifications pour les événements du calendrier",
"enabled": "Notifications d'événements",
"enabled_desc": "Afficher des alertes pour les événements à venir",
"sound": "Son de notification",
"sound_desc": "Jouer un son pour les rappels de calendrier",
"invitation_parsing": "Analyser les invitations par e-mail",
"invitation_parsing_desc": "Détecter les invitations de calendrier dans les pièces jointes et afficher les actions de calendrier"
}
},
"language_region": {
"title": "Langue et région",
@@ -771,6 +809,7 @@
"below-header": "Sous l'en-tête"
},
"emails_per_page": {
"10": "10 emails",
"25": "25 emails",
"50": "50 emails",
"100": "100 emails",
@@ -806,6 +845,24 @@
"close": "Fermer",
"invalid_email": "Veuillez entrer une adresse email valide",
"already_added": "Cet expéditeur est déjà de confiance"
},
"hover_actions": {
"label": "Actions rapides au survol",
"description": "Choisissez les actions rapides qui apparaissent au survol d'un e-mail dans la liste",
"delete": "Supprimer",
"star": "Étoile / Retirer l'étoile",
"mark_read": "Marquer lu / non lu",
"archive": "Archiver",
"tag": "Étiquette",
"spam": "Marquer comme spam",
"none_selected": "Aucune action sélectionnée"
},
"default_mail_program": {
"label": "Programme de messagerie par défaut",
"description": "Enregistrer {appName} comme programme de messagerie par défaut pour les liens mailto:",
"button": "Définir par défaut",
"success": "Le navigateur a été invité à définir par défaut",
"error": "Votre navigateur ne prend pas en charge cette fonctionnalité"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Compte",
"description": "Consultez les informations de votre compte",
"name_label": "Nom d'affichage",
"username_label": "Nom d'utilisateur",
"account_type_label": "Type de compte",
"auth_method_label": "Authentification",
"auth_method_oauth": "Authentification unique (OAuth/OIDC)",
"auth_method_basic": "Mot de passe",
"demo_account": "Compte de démonstration",
"email": {
"label": "Adresse email",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Ce script a été modifié en dehors du constructeur visuel. Seule l'édition Sieve brute est disponible.",
"open_sieve_editor": "Ouvrir l'éditeur Sieve brut",
"fetch_error": "Échec du chargement des filtres",
"expanded_view": "Vue étendue",
"expanded_view_description": "Afficher les règles de filtre avec des blocs de conditions et d'actions détaillés",
"if": "Si",
"then": "Alors",
"match_all_conditions": "toutes correspondent",
"match_any_condition": "une correspond",
"and": "et",
"or": "ou",
"cancel": "Annuler",
@@ -1842,7 +1909,11 @@
"notification_sound": "Son de notification",
"notification_sound_desc": "Jouer un son pour les alertes de calendrier",
"invitation_parsing": "Analyser les invitations par e-mail",
"invitation_parsing_desc": "Détecter les invitations de calendrier dans les pièces jointes des e-mails et afficher les actions du calendrier"
"invitation_parsing_desc": "Détecter les invitations de calendrier dans les pièces jointes des e-mails et afficher les actions du calendrier",
"show_time_in_month_view": "Afficher l'heure dans la vue mensuelle",
"show_time_in_month_view_desc": "Afficher les heures des événements dans la vue mensuelle du calendrier",
"show_week_numbers": "Afficher les numéros de semaine",
"show_week_numbers_desc": "Afficher les numéros de semaine dans le mini-calendrier"
},
"days": {
"monday": "Lundi",
@@ -2053,7 +2124,7 @@
"file": "Fichier",
"parent_directory": "Répertoire parent",
"breadcrumb_root": "Accueil",
"drop_files_here": "Déposez les fichiers ici pour les téléverser",
"drop_files_here": "Déposez des fichiers ou dossiers ici pour les téléverser",
"uploading": "Téléversement en cours...",
"upload_success": "{count, plural, one {1 fichier téléversé} other {# fichiers téléversés}}",
"upload_error": "Échec du téléversement du fichier",
@@ -2238,8 +2309,14 @@
"settings_desc": "Personnalisez tout : thème, densité, signatures, filtres, raccourcis clavier, paramètres du calendrier et plus encore.",
"shortcuts_title": "Raccourcis clavier",
"shortcuts_desc": "Les utilisateurs avancés adorent ça. Appuyez sur ? à tout moment pour voir tous les raccourcis disponibles. Naviguez, rédigez et gérez vos emails sans toucher à la souris.",
"compose_open_title": "Le compositeur",
"compose_open_desc": "Voici le compositeur d'e-mail. Ajoutez des destinataires, rédigez votre message, joignez des fichiers et utilisez la mise en forme enrichie. Vous pouvez aussi sauvegarder des brouillons et utiliser des modèles.",
"calendar_view_title": "Votre calendrier",
"calendar_view_desc": "Voici votre calendrier avec des événements exemples. Basculez entre les vues jour, semaine, mois et agenda avec la barre d'outils.",
"create_event_title": "Créer un événement",
"create_event_desc": "Cliquez sur ce bouton pour créer un nouvel événement. Vous pouvez définir un titre, une date, une heure et ajouter des participants.",
"event_modal_title": "Détails de l'événement",
"event_modal_desc": "Voici le formulaire de l'événement. Remplissez le titre, choisissez une date et une heure, ajoutez un lieu ou des participants. Cliquez sur enregistrer quand vous avez terminé — ou fermez-le et passez à autre chose.",
"contacts_list_title": "Vos contacts",
"contacts_list_desc": "Voici vos contacts. Cliquez sur un contact pour voir ses détails à droite. Vous pouvez aussi créer de nouveaux contacts, importer des vCards ou organiser les contacts en groupes.",
"files_title": "Stockage de fichiers",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Tutte",
"no_icons_found": "Nessuna icona trovata",
"inline_badge": "Integrato",
"tab_badge": "Scheda"
"tab_badge": "Scheda",
"show_on_mobile": "Mostra su mobile"
},
"email_list": {
"no_emails": "Nessun messaggio trovato",
@@ -623,7 +624,8 @@
"encryption": "Cifratura",
"files": "File",
"contacts": "Contacts",
"sidebar_apps": "App nella barra laterale"
"sidebar_apps": "App nella barra laterale",
"notifications": "Notifiche"
},
"tab_groups": {
"general": "Generale",
@@ -691,7 +693,43 @@
"delete": "Elimina parola chiave",
"save": "Salva",
"add": "Aggiungi",
"cancel": "Annulla"
"cancel": "Annulla",
"migrating": "Aggiornamento parola chiave sulle email esistenti…",
"migration_error": "Impossibile aggiornare la parola chiave sulle email esistenti"
},
"notifications": {
"test_sound": "Testa il suono di notifica",
"sounds": {
"default": "Predefinito (Bip)",
"cheerful": "Allegro",
"involved": "Elaborato",
"swift": "Gesto veloce",
"relax": "Rilassante"
},
"sound_selection": {
"title": "Suono di notifica",
"description": "Scegli quale suono riprodurre per le notifiche",
"choose": "Suono",
"choose_desc": "Seleziona un tono di notifica e clicca sull'icona dell'altoparlante per l'anteprima"
},
"email": {
"title": "Notifiche e-mail",
"description": "Configura le notifiche per le e-mail in arrivo",
"enabled": "Notifiche e-mail",
"enabled_desc": "Mostra notifiche all'arrivo di nuove e-mail",
"sound": "Suono di notifica",
"sound_desc": "Riproduci un suono all'arrivo di nuove e-mail"
},
"calendar": {
"title": "Notifiche calendario",
"description": "Configura le notifiche per gli eventi del calendario",
"enabled": "Notifiche eventi",
"enabled_desc": "Mostra avvisi per i prossimi eventi del calendario",
"sound": "Suono di notifica",
"sound_desc": "Riproduci un suono per i promemoria del calendario",
"invitation_parsing": "Analizza inviti via e-mail",
"invitation_parsing_desc": "Rileva inviti calendario negli allegati e mostra azioni calendario"
}
},
"language_region": {
"title": "Lingua e regione",
@@ -771,6 +809,7 @@
"below-header": "Sotto l'intestazione"
},
"emails_per_page": {
"10": "10 messaggi",
"25": "25 messaggi",
"50": "50 messaggi",
"100": "100 messaggi",
@@ -806,6 +845,24 @@
"close": "Chiudi",
"invalid_email": "Inserisci un indirizzo email valido",
"already_added": "Questo mittente è già attendibile"
},
"hover_actions": {
"label": "Azioni rapide al passaggio del mouse",
"description": "Scegli quali azioni rapide appaiono al passaggio del mouse su un'email nella lista",
"delete": "Elimina",
"star": "Segna / Rimuovi stella",
"mark_read": "Segna come letto / non letto",
"archive": "Archivia",
"tag": "Etichetta",
"spam": "Segna come spam",
"none_selected": "Nessuna azione selezionata"
},
"default_mail_program": {
"label": "Programma di posta predefinito",
"description": "Registra {appName} come programma di posta predefinito per i link mailto:",
"button": "Imposta come predefinito",
"success": "Il browser ha chiesto di impostare come predefinito",
"error": "Il tuo browser non supporta questa funzionalità"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Account",
"description": "Visualizza le informazioni del tuo account",
"name_label": "Nome visualizzato",
"username_label": "Nome utente",
"account_type_label": "Tipo di account",
"auth_method_label": "Autenticazione",
"auth_method_oauth": "Single Sign-On (OAuth/OIDC)",
"auth_method_basic": "Password",
"demo_account": "Account dimostrativo",
"email": {
"label": "Indirizzo email",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Questo script è stato modificato al di fuori del costruttore visuale. È disponibile solo la modifica Sieve grezza.",
"open_sieve_editor": "Apri editor Sieve",
"fetch_error": "Impossibile caricare i filtri",
"expanded_view": "Vista espansa",
"expanded_view_description": "Mostra le regole dei filtri con blocchi dettagliati di condizioni e azioni",
"if": "Se",
"then": "Allora",
"match_all_conditions": "tutte corrispondono",
"match_any_condition": "una corrisponde",
"and": "e",
"or": "o",
"cancel": "Annulla",
@@ -1842,7 +1909,11 @@
"notification_sound": "Suono di notifica",
"notification_sound_desc": "Riproduci un suono per gli avvisi del calendario",
"invitation_parsing": "Analizza gli inviti email",
"invitation_parsing_desc": "Rileva gli inviti del calendario negli allegati email e mostra le azioni del calendario"
"invitation_parsing_desc": "Rileva gli inviti del calendario negli allegati email e mostra le azioni del calendario",
"show_time_in_month_view": "Mostra orario nella vista mensile",
"show_time_in_month_view_desc": "Visualizza gli orari degli eventi nella vista mensile del calendario",
"show_week_numbers": "Mostra numeri di settimana",
"show_week_numbers_desc": "Mostra i numeri di settimana nel mini-calendario"
},
"days": {
"monday": "Lunedì",
@@ -2053,7 +2124,7 @@
"file": "File",
"parent_directory": "Directory superiore",
"breadcrumb_root": "Home",
"drop_files_here": "Trascina i file qui per caricarli",
"drop_files_here": "Trascina file o cartelle qui per caricarli",
"uploading": "Caricamento in corso...",
"upload_success": "{count, plural, one {1 file caricato} other {# file caricati}}",
"upload_error": "Caricamento del file non riuscito",
@@ -2238,8 +2309,14 @@
"settings_desc": "Personalizza tutto: tema, densità, firme, filtri, scorciatoie da tastiera, impostazioni del calendario e altro ancora.",
"shortcuts_title": "Scorciatoie da tastiera",
"shortcuts_desc": "Gli utenti esperti adorano questo. Premi ? in qualsiasi momento per vedere tutte le scorciatoie disponibili. Puoi navigare, comporre e gestire le email senza toccare il mouse.",
"compose_open_title": "Il compositore",
"compose_open_desc": "Questo è il compositore di email. Aggiungi destinatari, scrivi il tuo messaggio, allega file e usa la formattazione del testo. Puoi anche salvare bozze e usare modelli.",
"calendar_view_title": "Il tuo calendario",
"calendar_view_desc": "Ecco il tuo calendario con eventi di esempio. Puoi passare tra le viste giorno, settimana, mese e agenda usando la barra degli strumenti.",
"create_event_title": "Crea un evento",
"create_event_desc": "Fai clic su questo pulsante per creare un nuovo evento del calendario. Puoi impostare un titolo, data, ora e aggiungere partecipanti.",
"event_modal_title": "Dettagli evento",
"event_modal_desc": "Ecco il modulo dell'evento. Inserisci il titolo, scegli data e ora, aggiungi un luogo o partecipanti. Premi salva quando hai finito — o chiudilo e vai avanti.",
"contacts_list_title": "I tuoi contatti",
"contacts_list_desc": "Ecco i tuoi contatti. Clicca su un contatto per vedere i suoi dettagli a destra. Puoi anche creare nuovi contatti, importare vCard o organizzare i contatti in gruppi.",
"files_title": "Archiviazione file",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "すべて",
"no_icons_found": "アイコンが見つかりません",
"inline_badge": "埋め込み",
"tab_badge": "タブ"
"tab_badge": "タブ",
"show_on_mobile": "モバイルで表示"
},
"email_list": {
"no_emails": "メッセージが見つかりません",
@@ -623,7 +624,8 @@
"encryption": "暗号化",
"files": "ファイル",
"contacts": "Contacts",
"sidebar_apps": "サイドバーアプリ"
"sidebar_apps": "サイドバーアプリ",
"notifications": "通知"
},
"tab_groups": {
"general": "一般",
@@ -691,7 +693,43 @@
"delete": "キーワードを削除",
"save": "保存",
"add": "追加",
"cancel": "キャンセル"
"cancel": "キャンセル",
"migrating": "既存のメールでキーワードを更新中…",
"migration_error": "既存のメールでのキーワード更新に失敗しました"
},
"notifications": {
"test_sound": "通知音をテスト",
"sounds": {
"default": "デフォルト(ビープ)",
"cheerful": "チアフル",
"involved": "インボルブド",
"swift": "スウィフトジェスチャー",
"relax": "リラックス"
},
"sound_selection": {
"title": "通知音",
"description": "通知に使用する音を選択",
"choose": "サウンド",
"choose_desc": "通知音を選択し、スピーカーアイコンをクリックしてプレビュー"
},
"email": {
"title": "メール通知",
"description": "受信メールの通知を設定",
"enabled": "メール通知",
"enabled_desc": "新しいメールが届いたときに通知を表示",
"sound": "通知音",
"sound_desc": "新しいメールが届いたときに音を鳴らす"
},
"calendar": {
"title": "カレンダー通知",
"description": "カレンダーイベントの通知を設定",
"enabled": "イベント通知",
"enabled_desc": "今後のカレンダーイベントのアラートを表示",
"sound": "通知音",
"sound_desc": "カレンダーリマインダーの音を鳴らす",
"invitation_parsing": "メール招待を解析",
"invitation_parsing_desc": "メール添付ファイルのカレンダー招待を検出し、カレンダーアクションを表示"
}
},
"language_region": {
"title": "言語と地域",
@@ -771,6 +809,7 @@
"below-header": "ヘッダーの下"
},
"emails_per_page": {
"10": "10件",
"25": "25件",
"50": "50件",
"100": "100件",
@@ -806,6 +845,24 @@
"close": "閉じる",
"invalid_email": "有効なメールアドレスを入力してください",
"already_added": "この送信者はすでに信頼されています"
},
"hover_actions": {
"label": "ホバークイックアクション",
"description": "リスト内のメールにカーソルを合わせたときに表示するクイックアクションを選択",
"delete": "削除",
"star": "スター付け / 解除",
"mark_read": "既読 / 未読にする",
"archive": "アーカイブ",
"tag": "タグ",
"spam": "スパムとしてマーク",
"none_selected": "アクションが選択されていません"
},
"default_mail_program": {
"label": "既定のメールプログラム",
"description": "{appName}をmailto:リンクの既定のメールプログラムとして登録します",
"button": "既定に設定",
"success": "ブラウザに既定として設定するよう要求しました",
"error": "お使いのブラウザはこの機能をサポートしていません"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "アカウント",
"description": "アカウント情報を表示",
"name_label": "表示名",
"username_label": "ユーザー名",
"account_type_label": "アカウントタイプ",
"auth_method_label": "認証方法",
"auth_method_oauth": "シングルサインオン (OAuth/OIDC)",
"auth_method_basic": "パスワード",
"demo_account": "デモアカウント",
"email": {
"label": "メールアドレス",
@@ -1169,6 +1230,12 @@
"opaque_warning": "このスクリプトはビジュアルビルダーの外部で編集されました。Sieveスクリプトの直接編集のみ可能です。",
"open_sieve_editor": "Sieveスクリプトエディタを開く",
"fetch_error": "フィルターの読み込みに失敗しました",
"expanded_view": "詳細表示",
"expanded_view_description": "フィルタールールを条件とアクションのブロックで表示",
"if": "条件",
"then": "実行",
"match_all_conditions": "すべて一致",
"match_any_condition": "いずれか一致",
"and": "かつ",
"or": "または",
"cancel": "キャンセル",
@@ -1842,7 +1909,11 @@
"notification_sound": "通知音",
"notification_sound_desc": "カレンダーアラートの音を鳴らす",
"invitation_parsing": "メール招待を解析する",
"invitation_parsing_desc": "メール添付のカレンダー招待を検出してカレンダー操作を表示する"
"invitation_parsing_desc": "メール添付のカレンダー招待を検出してカレンダー操作を表示する",
"show_time_in_month_view": "月表示で時刻を表示",
"show_time_in_month_view_desc": "月カレンダー表示でイベントの時刻を表示する",
"show_week_numbers": "週番号を表示",
"show_week_numbers_desc": "ミニカレンダーに週番号を表示する"
},
"days": {
"monday": "月曜日",
@@ -2053,7 +2124,7 @@
"file": "ファイル",
"parent_directory": "親ディレクトリ",
"breadcrumb_root": "ホーム",
"drop_files_here": "ここにファイルをドロップしてアップロード",
"drop_files_here": "ここにファイルまたはフォルダをドロップしてアップロード",
"uploading": "アップロード中...",
"upload_success": "{count, plural, other {#件のファイルをアップロードしました}}",
"upload_error": "ファイルのアップロードに失敗しました",
@@ -2238,8 +2309,14 @@
"settings_desc": "すべてをカスタマイズできます:テーマ、表示密度、署名、フィルター、キーボードショートカット、カレンダー設定など。",
"shortcuts_title": "キーボードショートカット",
"shortcuts_desc": "パワーユーザー向けの機能です。いつでも ? を押すと利用可能なすべてのショートカットが表示されます。マウスを使わずにナビゲーション、作成、メール管理ができます。",
"compose_open_title": "メール作成画面",
"compose_open_desc": "これはメール作成画面です。宛先を追加し、メッセージを書き、ファイルを添付し、リッチテキスト書式を使用できます。下書きの保存やテンプレートの使用も可能です。",
"calendar_view_title": "カレンダー表示",
"calendar_view_desc": "サンプルイベント付きのカレンダーです。ツールバーで日、週、月、アジェンダビューを切り替えられます。",
"create_event_title": "イベントを作成",
"create_event_desc": "このボタンをクリックして新しいカレンダーイベントを作成します。タイトル、日付、時間を設定し、参加者を追加できます。",
"event_modal_title": "イベント詳細",
"event_modal_desc": "イベントフォームです。タイトルを入力し、日時を選択し、場所や参加者を追加してください。完了したら保存をクリック — または閉じて次に進みましょう。",
"contacts_list_title": "連絡先一覧",
"contacts_list_desc": "連絡先の一覧です。連絡先をクリックすると右側に詳細が表示されます。新しい連絡先の作成、vCardのインポート、グループへの整理もできます。",
"files_title": "ファイルストレージ",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Alle",
"no_icons_found": "Geen pictogrammen gevonden",
"inline_badge": "Ingesloten",
"tab_badge": "Tabblad"
"tab_badge": "Tabblad",
"show_on_mobile": "Weergeven op mobiel"
},
"email_list": {
"no_emails": "Geen berichten gevonden",
@@ -623,7 +624,8 @@
"encryption": "Versleuteling",
"files": "Bestanden",
"contacts": "Contacts",
"sidebar_apps": "Zijbalk-apps"
"sidebar_apps": "Zijbalk-apps",
"notifications": "Meldingen"
},
"tab_groups": {
"general": "Algemeen",
@@ -691,7 +693,43 @@
"delete": "Trefwoord verwijderen",
"save": "Opslaan",
"add": "Toevoegen",
"cancel": "Annuleren"
"cancel": "Annuleren",
"migrating": "Trefwoord bijwerken op bestaande e-mails…",
"migration_error": "Kan trefwoord niet bijwerken op bestaande e-mails"
},
"notifications": {
"test_sound": "Meldingsgeluid testen",
"sounds": {
"default": "Standaard (Pieptoon)",
"cheerful": "Vrolijk",
"involved": "Uitgebreid",
"swift": "Snel gebaar",
"relax": "Ontspannen"
},
"sound_selection": {
"title": "Meldingsgeluid",
"description": "Kies welk geluid wordt afgespeeld voor meldingen",
"choose": "Geluid",
"choose_desc": "Selecteer een meldingstoon en klik op het luidsprekerpictogram voor een voorbeeld"
},
"email": {
"title": "E-mailmeldingen",
"description": "Meldingen voor inkomende e-mails configureren",
"enabled": "E-mailmeldingen",
"enabled_desc": "Meldingen tonen wanneer nieuwe e-mails binnenkomen",
"sound": "Meldingsgeluid",
"sound_desc": "Een geluid afspelen wanneer nieuwe e-mails binnenkomen"
},
"calendar": {
"title": "Agendameldingen",
"description": "Meldingen voor agenda-evenementen configureren",
"enabled": "Evenementmeldingen",
"enabled_desc": "Waarschuwingen tonen voor aankomende agenda-evenementen",
"sound": "Meldingsgeluid",
"sound_desc": "Een geluid afspelen voor agendaherinneringen",
"invitation_parsing": "E-mailuitnodigingen herkennen",
"invitation_parsing_desc": "Agenda-uitnodigingen in e-mailbijlagen detecteren en agendaacties tonen"
}
},
"language_region": {
"title": "Taal & Regio",
@@ -771,6 +809,7 @@
"below-header": "Onder de kop"
},
"emails_per_page": {
"10": "10 e-mails",
"25": "25 e-mails",
"50": "50 e-mails",
"100": "100 e-mails",
@@ -806,6 +845,24 @@
"close": "Sluiten",
"invalid_email": "Voer een geldig e-mailadres in",
"already_added": "Deze afzender wordt al vertrouwd"
},
"hover_actions": {
"label": "Snelle hover-acties",
"description": "Kies welke snelle acties verschijnen wanneer u over een e-mail in de lijst beweegt",
"delete": "Verwijderen",
"star": "Ster aan / uit",
"mark_read": "Markeer gelezen / ongelezen",
"archive": "Archiveren",
"tag": "Label",
"spam": "Markeer als spam",
"none_selected": "Geen acties geselecteerd"
},
"default_mail_program": {
"label": "Standaard e-mailprogramma",
"description": "Registreer {appName} als uw standaard e-mailprogramma voor mailto:-links",
"button": "Instellen als standaard",
"success": "Browser gevraagd om als standaard in te stellen",
"error": "Uw browser ondersteunt deze functie niet"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Account",
"description": "Bekijk je accountinformatie",
"name_label": "Weergavenaam",
"username_label": "Gebruikersnaam",
"account_type_label": "Accounttype",
"auth_method_label": "Authenticatie",
"auth_method_oauth": "Single Sign-On (OAuth/OIDC)",
"auth_method_basic": "Wachtwoord",
"demo_account": "Demoaccount",
"email": {
"label": "E-mailadres",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Dit script is buiten de visuele builder bewerkt. Alleen Sieve-scriptbewerking is beschikbaar.",
"open_sieve_editor": "Sieve-scripteditor openen",
"fetch_error": "Filters konden niet worden geladen",
"expanded_view": "Uitgebreide weergave",
"expanded_view_description": "Filterregels weergeven met gedetailleerde voorwaarde- en actieblokken",
"if": "Als",
"then": "Dan",
"match_all_conditions": "alle overeenkomen",
"match_any_condition": "een overeenkomt",
"and": "en",
"or": "of",
"cancel": "Annuleren",
@@ -1842,7 +1909,11 @@
"notification_sound": "Meldingsgeluid",
"notification_sound_desc": "Geluid afspelen voor agendameldingen",
"invitation_parsing": "E-mailuitnodigingen verwerken",
"invitation_parsing_desc": "Kalenderuitnodigingen in e-mailbijlagen detecteren en kalenderacties tonen"
"invitation_parsing_desc": "Kalenderuitnodigingen in e-mailbijlagen detecteren en kalenderacties tonen",
"show_time_in_month_view": "Tijd weergeven in maandweergave",
"show_time_in_month_view_desc": "Evenementtijden weergeven in de maandkalenderweergave",
"show_week_numbers": "Weeknummers weergeven",
"show_week_numbers_desc": "Weeknummers weergeven in de minikalender"
},
"days": {
"monday": "Maandag",
@@ -2053,7 +2124,7 @@
"file": "Bestand",
"parent_directory": "Bovenliggende map",
"breadcrumb_root": "Start",
"drop_files_here": "Sleep bestanden hierheen om te uploaden",
"drop_files_here": "Sleep bestanden of mappen hierheen om te uploaden",
"uploading": "Uploaden...",
"upload_success": "{count, plural, one {1 bestand geüpload} other {# bestanden geüpload}}",
"upload_error": "Bestand uploaden mislukt",
@@ -2238,8 +2309,14 @@
"settings_desc": "Pas alles aan: thema, dichtheid, handtekeningen, filters, sneltoetsen, agendainstellingen en meer.",
"shortcuts_title": "Sneltoetsen",
"shortcuts_desc": "Ervaren gebruikers zijn hier dol op. Druk op ? om alle beschikbare sneltoetsen te bekijken. Navigeer, schrijf en beheer e-mails zonder de muis aan te raken.",
"compose_open_title": "De e-maileditor",
"compose_open_desc": "Dit is de e-maileditor. Voeg ontvangers toe, schrijf uw bericht, voeg bestanden bij en gebruik rijke tekstopmaak. U kunt ook concepten opslaan en sjablonen gebruiken.",
"calendar_view_title": "Uw agenda",
"calendar_view_desc": "Hier is uw agenda met voorbeeldevenementen. Schakel tussen dag-, week-, maand- en agendaweergave via de werkbalk.",
"create_event_title": "Evenement aanmaken",
"create_event_desc": "Klik op deze knop om een nieuw agenda-evenement aan te maken. U kunt een titel, datum, tijd en deelnemers instellen.",
"event_modal_title": "Evenementdetails",
"event_modal_desc": "Hier is het evenementformulier. Vul de titel in, kies een datum en tijd, voeg een locatie of deelnemers toe. Klik op opslaan als u klaar bent — of sluit het en ga verder.",
"contacts_list_title": "Uw contacten",
"contacts_list_desc": "Hier zijn uw contacten. Klik op een contact om de details rechts te bekijken. U kunt ook nieuwe contacten aanmaken, vCards importeren of contacten in groepen organiseren.",
"files_title": "Bestandsopslag",
+82 -5
View File
@@ -146,7 +146,8 @@
"show_all": "Todos",
"no_icons_found": "Nenhum ícone encontrado",
"inline_badge": "Integrado",
"tab_badge": "Aba"
"tab_badge": "Aba",
"show_on_mobile": "Mostrar no celular"
},
"email_list": {
"no_emails": "Nenhuma mensagem encontrada",
@@ -623,7 +624,8 @@
"encryption": "Criptografia",
"files": "Arquivos",
"contacts": "Contacts",
"sidebar_apps": "Apps da barra lateral"
"sidebar_apps": "Apps da barra lateral",
"notifications": "Notificações"
},
"tab_groups": {
"general": "Geral",
@@ -691,7 +693,43 @@
"delete": "Excluir palavra-chave",
"save": "Salvar",
"add": "Adicionar",
"cancel": "Cancelar"
"cancel": "Cancelar",
"migrating": "Atualizando etiqueta nos e-mails existentes…",
"migration_error": "Falha ao atualizar etiqueta nos e-mails existentes"
},
"notifications": {
"test_sound": "Testar som de notificação",
"sounds": {
"default": "Padrão (Bipe)",
"cheerful": "Alegre",
"involved": "Elaborado",
"swift": "Gesto rápido",
"relax": "Relaxante"
},
"sound_selection": {
"title": "Som de notificação",
"description": "Escolha qual som reproduzir para notificações",
"choose": "Som",
"choose_desc": "Selecione um toque de notificação e clique no ícone do alto-falante para pré-visualizar"
},
"email": {
"title": "Notificações de e-mail",
"description": "Configurar notificações para e-mails recebidos",
"enabled": "Notificações de e-mail",
"enabled_desc": "Mostrar notificações quando novos e-mails chegarem",
"sound": "Som de notificação",
"sound_desc": "Reproduzir um som quando novos e-mails chegarem"
},
"calendar": {
"title": "Notificações de calendário",
"description": "Configurar notificações para eventos do calendário",
"enabled": "Notificações de eventos",
"enabled_desc": "Mostrar alertas para próximos eventos do calendário",
"sound": "Som de notificação",
"sound_desc": "Reproduzir um som para lembretes do calendário",
"invitation_parsing": "Analisar convites por e-mail",
"invitation_parsing_desc": "Detectar convites de calendário em anexos de e-mail e mostrar ações de calendário"
}
},
"language_region": {
"title": "Idioma e Região",
@@ -771,6 +809,7 @@
"below-header": "Abaixo do cabeçalho"
},
"emails_per_page": {
"10": "10 e-mails",
"25": "25 e-mails",
"50": "50 e-mails",
"100": "100 e-mails",
@@ -806,6 +845,24 @@
"close": "Fechar",
"invalid_email": "Por favor, digite um endereço de e-mail válido",
"already_added": "Este remetente já é confiável"
},
"hover_actions": {
"label": "Ações rápidas ao passar o mouse",
"description": "Escolha quais ações rápidas aparecem ao passar o mouse sobre um e-mail na lista",
"delete": "Excluir",
"star": "Favoritar / Desfavoritar",
"mark_read": "Marcar como lido / não lido",
"archive": "Arquivar",
"tag": "Etiqueta",
"spam": "Marcar como spam",
"none_selected": "Nenhuma ação selecionada"
},
"default_mail_program": {
"label": "Programa de e-mail padrão",
"description": "Registrar {appName} como seu programa de e-mail padrão para links mailto:",
"button": "Definir como padrão",
"success": "O navegador solicitou definir como padrão",
"error": "Seu navegador não suporta esta funcionalidade"
}
},
"composer": {
@@ -857,7 +914,11 @@
"title": "Conta",
"description": "Visualize as informações da sua conta",
"name_label": "Nome de exibição",
"username_label": "Nome de usuário",
"account_type_label": "Tipo de conta",
"auth_method_label": "Autenticação",
"auth_method_oauth": "Login único (OAuth/OIDC)",
"auth_method_basic": "Senha",
"demo_account": "Conta de demonstração",
"email": {
"label": "Endereço de E-mail",
@@ -1169,6 +1230,12 @@
"opaque_warning": "Este script foi editado fora do construtor visual. Apenas a edição Sieve bruta está disponível.",
"open_sieve_editor": "Abrir editor Sieve",
"fetch_error": "Falha ao carregar filtros",
"expanded_view": "Vista expandida",
"expanded_view_description": "Mostrar regras de filtro com blocos detalhados de condições e ações",
"if": "Se",
"then": "Então",
"match_all_conditions": "todas correspondem",
"match_any_condition": "uma corresponde",
"and": "e",
"or": "ou",
"cancel": "Cancelar",
@@ -1842,7 +1909,11 @@
"notification_sound": "Som de notificação",
"notification_sound_desc": "Reproduzir um som para alertas do calendário",
"invitation_parsing": "Analisar convites por e-mail",
"invitation_parsing_desc": "Detectar convites de calendário em anexos de e-mail e mostrar ações do calendário"
"invitation_parsing_desc": "Detectar convites de calendário em anexos de e-mail e mostrar ações do calendário",
"show_time_in_month_view": "Mostrar horário na visualização mensal",
"show_time_in_month_view_desc": "Exibir horários dos eventos na visualização mensal do calendário",
"show_week_numbers": "Mostrar números da semana",
"show_week_numbers_desc": "Exibir números da semana no minicalendário"
},
"days": {
"monday": "Segunda-feira",
@@ -2053,7 +2124,7 @@
"file": "Ficheiro",
"parent_directory": "Diretório superior",
"breadcrumb_root": "Início",
"drop_files_here": "Largue os ficheiros aqui para carregar",
"drop_files_here": "Largue ficheiros ou pastas aqui para carregar",
"uploading": "A carregar...",
"upload_success": "{count, plural, one {1 ficheiro carregado} other {# ficheiros carregados}}",
"upload_error": "Falha ao carregar o ficheiro",
@@ -2238,8 +2309,14 @@
"settings_desc": "Personalize tudo: tema, densidade, assinaturas, filtros, atalhos de teclado, padrões do calendário e mais.",
"shortcuts_title": "Atalhos de teclado",
"shortcuts_desc": "Usuários avançados adoram isso. Pressione ? a qualquer momento para ver todos os atalhos disponíveis. Navegue, escreva e gerencie e-mails sem tocar no mouse.",
"compose_open_title": "O compositor",
"compose_open_desc": "Este é o compositor de e-mail. Adicione destinatários, escreva sua mensagem, anexe arquivos e use formatação de texto rico. Você também pode salvar rascunhos e usar modelos.",
"calendar_view_title": "Seu calendário",
"calendar_view_desc": "Aqui está seu calendário com eventos de exemplo. Você pode alternar entre as visualizações de dia, semana, mês e agenda usando a barra de ferramentas.",
"create_event_title": "Criar um evento",
"create_event_desc": "Clique neste botão para criar um novo evento no calendário. Você pode definir um título, data, hora e adicionar participantes.",
"event_modal_title": "Detalhes do evento",
"event_modal_desc": "Aqui está o formulário do evento. Preencha o título, escolha uma data e hora, adicione um local ou participantes. Clique em salvar quando terminar — ou feche e siga em frente.",
"contacts_list_title": "Seus contatos",
"contacts_list_desc": "Aqui estão seus contatos. Clique em qualquer contato para ver seus detalhes à direita. Você também pode criar novos contatos, importar vCards ou organizar contatos em grupos.",
"files_title": "Armazenamento de ficheiros",
+875 -7
View File
File diff suppressed because it is too large Load Diff
+15 -2
View File
@@ -1,6 +1,6 @@
{
"name": "bulwark-webmail",
"version": "1.4.6",
"version": "1.4.8",
"description": "Bulwark Webmail — a modern webmail client built for Stalwart Mail Server",
"author": "Bulwark Webmail <bulwark@rbm.systems>",
"license": "AGPL-3.0-only",
@@ -33,6 +33,16 @@
},
"dependencies": {
"@tanstack/react-virtual": "^3.13.18",
"@tiptap/extension-color": "^3.20.4",
"@tiptap/extension-image": "^3.20.4",
"@tiptap/extension-link": "^3.20.4",
"@tiptap/extension-placeholder": "^3.20.4",
"@tiptap/extension-text-align": "^3.20.4",
"@tiptap/extension-text-style": "^3.20.4",
"@tiptap/extension-underline": "^3.20.4",
"@tiptap/pm": "^3.20.4",
"@tiptap/react": "^3.20.4",
"@tiptap/starter-kit": "^3.20.4",
"asn1js": "^3.0.7",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
@@ -76,7 +86,10 @@
"vitest": "^4.0.16"
},
"overrides": {
"elliptic": "^6.6.1",
"elliptic": {
".": "^6.6.1",
"webcrypto-liner": "$elliptic"
},
"flatted": "^3.4.2",
"undici": "^7.24.0"
}
+10 -2
View File
@@ -14,6 +14,8 @@ export function proxy(request: NextRequest) {
const connectSrc = isDev ? `'self' https: ws: wss:` : `'self' https:`;
const frameAncestors = process.env.ALLOWED_FRAME_ANCESTORS?.trim() || "'none'";
const csp = [
`default-src 'self'`,
`script-src ${scriptSrc}`,
@@ -25,7 +27,7 @@ export function proxy(request: NextRequest) {
`object-src 'none'`,
`base-uri 'self'`,
`form-action 'self'`,
`frame-ancestors 'none'`,
`frame-ancestors ${frameAncestors}`,
].join("; ");
let intlResponse: ReturnType<typeof intlMiddleware> | null = null;
@@ -44,7 +46,13 @@ export function proxy(request: NextRequest) {
response.headers.set("x-middleware-request-x-nonce", nonce);
response.headers.set("X-Content-Type-Options", "nosniff");
response.headers.set("X-Frame-Options", "DENY");
// X-Frame-Options only supports DENY/SAMEORIGIN. When frame-ancestors
// specifies explicit origins, we rely solely on the CSP header.
if (frameAncestors === "'none'") {
response.headers.set("X-Frame-Options", "DENY");
}
response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
response.headers.set("X-XSS-Protection", "0");
response.headers.set(
Binary file not shown.
Binary file not shown.
Binary file not shown.
+215 -206
View File
@@ -12,7 +12,8 @@ import { useAccountStore } from './account-store';
import { fetchConfig } from '@/hooks/use-config';
import { debug } from '@/lib/debug';
import { generateAccountId } from '@/lib/account-utils';
import { replaceWindowLocation } from '@/lib/browser-navigation';
import { replaceWindowLocation, getPathPrefix, getLocaleFromPath } from '@/lib/browser-navigation';
import { notifyParent } from '@/lib/iframe-bridge';
import { snapshotAccount, restoreAccount, clearAllStores, evictAccount, evictAll } from '@/lib/account-state-manager';
import type { Identity } from '@/lib/jmap/types';
@@ -35,9 +36,10 @@ interface AuthState {
login: (serverUrl: string, username: string, password: string, totp?: string, rememberMe?: boolean) => Promise<boolean>;
loginWithOAuth: (serverUrl: string, code: string, codeVerifier: string, redirectUri: string) => Promise<boolean>;
loginWithServerSso: (code: string, state: string) => Promise<boolean>;
loginDemo: () => Promise<boolean>;
refreshAccessToken: () => Promise<string | null>;
logout: () => Promise<void>;
logout: () => void;
logoutAll: () => void;
switchAccount: (accountId: string) => Promise<void>;
checkAuth: () => Promise<void>;
@@ -105,9 +107,9 @@ function loadIdentities(rawIdentities: Identity[], username: string): { identiti
function getLocaleLoginPath(): string {
if (typeof window === 'undefined') return '/en/login';
const segments = window.location.pathname.split('/').filter(Boolean);
const locale = segments[0] || 'en';
return `/${locale}/login`;
const prefix = getPathPrefix();
const locale = getLocaleFromPath();
return `${prefix}/${locale}/login`;
}
function saveRedirectAfterLogin(): void {
@@ -125,7 +127,7 @@ function saveRedirectAfterLogin(): void {
}
}
function redirectToLogin(): void {
export function redirectToLogin(): void {
if (typeof window === 'undefined') return;
const loginPath = getLocaleLoginPath();
@@ -228,6 +230,39 @@ function clearAllRefreshTimers(): void {
refreshPromises.clear();
}
/**
* Synchronously clears all auth and feature store state.
* Called during full logout (no remaining accounts).
*/
function performFullLogout(set: (state: Partial<AuthState>) => void): void {
useSettingsStore.getState().disableSync();
set({
isAuthenticated: false,
isLoading: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
isDemoMode: false,
});
clearAllStores();
// Remove persisted state AFTER the final set() so the persist middleware
// doesn't re-write stale values.
try { localStorage.removeItem('auth-storage'); } catch { /* noop */ }
try { localStorage.removeItem('account-storage'); } catch { /* noop */ }
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
@@ -451,8 +486,12 @@ export const useAuthStore = create<AuthState>()(
});
await client.connect();
const username = client.getUsername();
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), username);
const jmapUsername = client.getUsername();
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), jmapUsername);
// For OAuth/OIDC, the JMAP session account name may be the
// preferred_username claim rather than the real email address.
// Prefer the email from the primary identity when available.
const username = primaryIdentity?.email || jmapUsername;
initializeFeatureStores(client);
// Register in account store
@@ -501,6 +540,8 @@ export const useAuthStore = create<AuthState>()(
scheduleRefresh(expires_in, get().refreshAccessToken, accountId);
notifyParent('sso:auth-success', { username });
// Sync settings from server (only if enabled)
fetchConfig().then(config => {
if (!config.settingsSyncEnabled) return;
@@ -517,9 +558,122 @@ export const useAuthStore = create<AuthState>()(
return true;
} catch (error) {
debug.error('OAuth login error:', error);
const errorMsg = error instanceof Error ? error.message : 'generic';
notifyParent('sso:auth-failure', { error: errorMsg });
set({
isLoading: false,
error: error instanceof Error ? error.message : 'generic',
error: errorMsg,
isAuthenticated: false,
client: null,
});
return false;
}
},
loginWithServerSso: async (code, state) => {
set({ isLoading: true, error: null });
try {
// Server-side SSO: the server holds the PKCE verifier in an encrypted cookie
const ssoRes = await fetch('/api/auth/sso/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ code, state }),
});
if (!ssoRes.ok) {
const errorData = await ssoRes.json().catch(() => ({ error: 'token_exchange_failed' }));
throw new Error(errorData.error || 'token_exchange_failed');
}
const { access_token, expires_in } = await ssoRes.json();
// We need the server URL from config
const config = await fetchConfig();
const ssoServerUrl = config.jmapServerUrl;
if (!ssoServerUrl) {
throw new Error('Server URL not configured');
}
const accountStore = useAccountStore.getState();
const refreshFn = get().refreshAccessToken;
const client = JMAPClient.withBearer(ssoServerUrl, access_token, '', () => refreshFn());
client.onConnectionChange((connected) => {
set({ connectionLost: !connected });
});
await client.connect();
const jmapUsername = client.getUsername();
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), jmapUsername);
// For SSO/OIDC, the JMAP session account name may be the
// preferred_username claim rather than the real email address.
// Prefer the email from the primary identity when available.
const username = primaryIdentity?.email || jmapUsername;
initializeFeatureStores(client);
const accountId = generateAccountId(username, ssoServerUrl);
const prevAccountId = get().activeAccountId;
if (prevAccountId && prevAccountId !== accountId) {
snapshotAccount(prevAccountId);
clearAllStores();
}
clients.set(accountId, client);
accountStore.addAccount({
label: primaryIdentity?.name || username,
serverUrl: ssoServerUrl,
username,
authMode: 'oauth',
rememberMe: true,
displayName: primaryIdentity?.name || username,
email: primaryIdentity?.email || username,
lastLoginAt: Date.now(),
isConnected: true,
hasError: false,
isDefault: accountStore.accounts.length === 0,
});
accountStore.setActiveAccount(accountId);
set({
isAuthenticated: true,
isLoading: false,
serverUrl: ssoServerUrl,
username,
client,
identities,
primaryIdentity,
authMode: 'oauth',
accessToken: access_token,
tokenExpiresAt: Date.now() + expires_in * 1000,
connectionLost: false,
error: null,
activeAccountId: accountId,
});
scheduleRefresh(expires_in, get().refreshAccessToken, accountId);
notifyParent('sso:auth-success', { username });
fetchConfig().then(cfg => {
if (!cfg.settingsSyncEnabled) return;
useSettingsStore.getState().loadFromServer(username, ssoServerUrl).finally(() => {
useSettingsStore.getState().enableSync(username, ssoServerUrl);
});
}).catch(() => {});
return true;
} catch (error) {
debug.error('Server SSO login error:', error);
const errorMsg = error instanceof Error ? error.message : 'generic';
notifyParent('sso:auth-failure', { error: errorMsg });
set({
isLoading: false,
error: errorMsg,
isAuthenticated: false,
client: null,
});
@@ -543,6 +697,7 @@ export const useAuthStore = create<AuthState>()(
const res = await fetch(`/api/auth/token?slot=${slot}`, { method: 'PUT' });
if (!res.ok) {
notifyParent('sso:session-expired');
markSessionExpired();
get().logout();
return null;
@@ -561,6 +716,7 @@ export const useAuthStore = create<AuthState>()(
return access_token;
} catch (error) {
debug.error('Token refresh failed:', error);
notifyParent('sso:session-expired');
markSessionExpired();
get().logout();
return null;
@@ -576,7 +732,7 @@ export const useAuthStore = create<AuthState>()(
return promise;
},
logout: async () => {
logout: () => {
const state = get();
const wasDemoMode = state.isDemoMode;
const wasOAuth = state.authMode === 'oauth';
@@ -585,39 +741,14 @@ export const useAuthStore = create<AuthState>()(
const account = accountId ? accountStore.getAccountById(accountId) : null;
const slot = account?.cookieSlot ?? 0;
// Demo mode: simple cleanup, no network calls
if (wasDemoMode) {
set({ client: null });
state.client?.disconnect();
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
isDemoMode: false,
});
localStorage.removeItem('auth-storage');
clearAllStores();
redirectToLogin();
return;
}
// Stop refresh timers immediately
clearRefreshTimer(accountId ?? undefined);
// Null out the client BEFORE disconnecting so the page doesn't fire
// data-loading effects with the stale disconnected client while
// stores are being cleared.
// Disconnect and null out the client BEFORE clearing stores so the
// page doesn't fire data-loading effects with the stale client.
const oldClient = state.client;
set({ client: null });
state.client?.disconnect();
oldClient?.disconnect();
// Remove client from multi-account map
if (accountId) {
@@ -630,61 +761,17 @@ export const useAuthStore = create<AuthState>()(
// Check if there are remaining accounts to switch to
const remainingAccounts = accountStore.accounts;
const shouldRedirectToLogin = remainingAccounts.length === 0;
if (remainingAccounts.length > 0) {
// Switch to the next account
if (remainingAccounts.length > 0 && !wasDemoMode) {
// Switch to the next account — this is the one path that stays in-app
const nextAccount = remainingAccounts[0];
// Clean current stores, then switch
clearAllStores();
// Restore next account
let nextClient = clients.get(nextAccount.id);
// If the client isn't in memory, try to restore it from the session
if (!nextClient) {
try {
if (nextAccount.authMode === 'oauth') {
const res = await fetch(`/api/auth/token?slot=${nextAccount.cookieSlot}`, { method: 'PUT' });
if (res.ok) {
const { access_token, expires_in } = await res.json();
const refreshFn = get().refreshAccessToken;
nextClient = JMAPClient.withBearer(nextAccount.serverUrl, access_token, nextAccount.username, () => refreshFn());
nextClient.onConnectionChange((connected) => {
if (get().activeAccountId === nextAccount.id) {
set({ connectionLost: !connected });
}
accountStore.updateAccount(nextAccount.id, { isConnected: connected });
});
await nextClient.connect();
clients.set(nextAccount.id, nextClient);
scheduleRefresh(expires_in, get().refreshAccessToken, nextAccount.id);
}
} else if (nextAccount.authMode === 'basic' && nextAccount.rememberMe) {
const res = await fetch(`/api/auth/session?slot=${nextAccount.cookieSlot}`);
if (res.ok) {
const { serverUrl: sUrl, username: uName, password: pwd } = await res.json();
nextClient = new JMAPClient(sUrl, uName, pwd);
nextClient.onConnectionChange((connected) => {
if (get().activeAccountId === nextAccount.id) {
set({ connectionLost: !connected });
}
accountStore.updateAccount(nextAccount.id, { isConnected: connected });
});
await nextClient.connect();
clients.set(nextAccount.id, nextClient);
}
}
} catch (err) {
debug.error(`Failed to restore next account ${nextAccount.id} during logout:`, err);
nextClient = undefined;
}
}
const nextClient = clients.get(nextAccount.id);
if (nextClient) {
const restored = restoreAccount(nextAccount.id);
accountStore.setActiveAccount(nextAccount.id);
// Build identity state up front so the name updates atomically
const restoredIdentities = restored ? useIdentityStore.getState().identities : [];
const restoredPrimary = restoredIdentities[0] ?? null;
@@ -711,132 +798,49 @@ export const useAuthStore = create<AuthState>()(
}).catch((err) => debug.error('Failed to load identities after switch:', err));
}
} else {
// Could not restore the next account — remove it and do a full logout
// Client not in memory — clear everything and redirect.
// Trying to async-restore during logout caused the original bug.
debug.error(`Cannot restore next account ${nextAccount.id}, performing full logout`);
evictAccount(nextAccount.id);
accountStore.removeAccount(nextAccount.id);
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
redirectToLogin();
performFullLogout(set);
}
} else {
// No accounts remaining — full logout
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
// Background cookie cleanup for the removed account
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
return;
}
// Clean up cookies for the removed account
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: shouldRedirectToLogin }).catch((err) => {
debug.error('Failed to clear session cookie:', err);
});
// No accounts remaining (or demo mode) — full logout + redirect
performFullLogout(set);
if (wasOAuth && shouldRedirectToLogin) {
let redirectCommitted = false;
const commitLoginRedirect = () => {
if (redirectCommitted) return;
redirectCommitted = true;
redirectToLogin();
};
notifyParent('sso:logout');
window.setTimeout(commitLoginRedirect, 0);
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true })
.then((res) => {
if (!res.ok) throw new Error(`Revocation failed: ${res.status}`);
return res.json();
})
.then((data) => {
if (redirectCommitted) return;
if (data.end_session_url) {
redirectCommitted = true;
const locale = window.location.pathname.split('/')[1] || 'en';
const redirectUri = `${window.location.origin}/${locale}/login`;
const url = new URL(data.end_session_url);
url.searchParams.set('post_logout_redirect_uri', redirectUri);
replaceWindowLocation(url.toString());
return;
}
commitLoginRedirect();
})
.catch((err) => {
debug.error('OAuth logout cleanup failed:', err);
commitLoginRedirect();
});
} else if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: false })
.catch((err) => {
debug.error('OAuth logout cleanup failed:', err);
});
} else if (shouldRedirectToLogin) {
redirectToLogin();
// Background cookie/token cleanup — keepalive ensures completion during navigation
if (!wasDemoMode) {
fetch(`/api/auth/session?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
if (wasOAuth) {
fetch(`/api/auth/token?slot=${slot}`, { method: 'DELETE', keepalive: true }).catch(() => {});
}
}
// Redirect to login — this is synchronous and happens AFTER all state is cleared
redirectToLogin();
},
logoutAll: () => {
// Disconnect all clients
for (const client of clients.values()) {
client.disconnect();
for (const c of clients.values()) {
c.disconnect();
}
clients.clear();
clearAllRefreshTimers();
evictAll();
useSettingsStore.getState().disableSync();
useAccountStore.getState().accounts.forEach(() => {});
set({
isAuthenticated: false,
serverUrl: null,
username: null,
client: null,
identities: [],
primaryIdentity: null,
authMode: 'basic',
rememberMe: false,
accessToken: null,
tokenExpiresAt: null,
connectionLost: false,
error: null,
activeAccountId: null,
});
localStorage.removeItem('auth-storage');
clearAllStores();
performFullLogout(set);
// Clear all accounts from registry
const accountStore = useAccountStore.getState();
@@ -845,9 +849,10 @@ export const useAuthStore = create<AuthState>()(
accountStore.removeAccount(account.id);
}
// Delete all cookies
// Background cookie/token cleanup
fetch('/api/auth/session?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
fetch('/api/auth/token?all=true', { method: 'DELETE', keepalive: true }).catch(() => {});
redirectToLogin();
},
@@ -1302,16 +1307,20 @@ export const useAuthStore = create<AuthState>()(
}),
{
name: 'auth-storage',
partialize: (state) => ({
serverUrl: state.serverUrl,
username: state.username,
authMode: state.authMode,
isAuthenticated: (state.authMode === 'oauth' || state.rememberMe)
? state.isAuthenticated
: undefined,
rememberMe: state.rememberMe,
activeAccountId: state.activeAccountId,
}),
partialize: (state) => {
// Don't persist unauthenticated state — prevents resurrecting stale sessions
if (!state.isAuthenticated) return {};
return {
serverUrl: state.serverUrl,
username: state.username,
authMode: state.authMode,
isAuthenticated: (state.authMode === 'oauth' || state.rememberMe)
? state.isAuthenticated
: undefined,
rememberMe: state.rememberMe,
activeAccountId: state.activeAccountId,
};
},
}
)
);
+147 -14
View File
@@ -5,9 +5,9 @@ import type { Calendar, CalendarEvent, CalendarParticipant } from '@/lib/jmap/ty
import { debug } from '@/lib/debug';
import { normalizeAllDayDuration } from '@/lib/calendar-utils';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda';
export type CalendarViewMode = 'month' | 'week' | 'day' | 'agenda' | 'tasks';
const CALENDAR_VIEW_MODES: CalendarViewMode[] = ['month', 'week', 'day', 'agenda'];
const CALENDAR_VIEW_MODES: CalendarViewMode[] = ['month', 'week', 'day', 'agenda', 'tasks'];
export function isCalendarViewMode(value: unknown): value is CalendarViewMode {
return typeof value === 'string' && CALENDAR_VIEW_MODES.includes(value as CalendarViewMode);
@@ -130,14 +130,17 @@ export const useCalendarStore = create<CalendarStore>()(
let targetAccountId = event.accountId;
const cleanEvent = { ...event };
if (event.calendarIds) {
const calId = Object.keys(event.calendarIds)[0];
if (calId) {
const remapped: Record<string, boolean> = {};
for (const calId of Object.keys(event.calendarIds)) {
const cal = get().calendars.find(c => c.id === calId);
if (cal?.isShared && cal.originalId) {
targetAccountId = cal.accountId;
cleanEvent.calendarIds = { [cal.originalId]: true };
remapped[cal.originalId] = true;
} else {
remapped[calId] = true;
}
}
cleanEvent.calendarIds = remapped;
}
if (event.originalCalendarIds) {
cleanEvent.calendarIds = event.originalCalendarIds;
@@ -169,7 +172,52 @@ export const useCalendarStore = create<CalendarStore>()(
}
cleanUpdates.calendarIds = remapped;
}
await client.updateCalendarEvent(realId, cleanUpdates, sendSchedulingMessages, targetAccountId);
try {
await client.updateCalendarEvent(realId, cleanUpdates, sendSchedulingMessages, targetAccountId);
} catch (updateError) {
// Stalwart rejects updates to "synthetic" JMAP IDs (CalDAV-created events
// or expanded recurring-event instances returned by expandRecurrences).
// Resolve the real event via a UID query and retry.
const message = updateError instanceof Error ? updateError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('Event has synthetic ID, resolving real ID via UID query');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: patch the master event's recurrenceOverrides.
// Escape recurrenceId per RFC 6901: ~ → ~0, / → ~1
const escapedRecurrenceId = storeEvent.recurrenceId.replace(/~/g, '~0').replace(/\//g, '~1');
// Build override object with all changed properties
const overrideObj: Record<string, unknown> = {};
for (const [key, value] of Object.entries(cleanUpdates as Record<string, unknown>)) {
if (['id', 'uid', '@type', 'calendarIds', 'recurrenceRules', 'recurrenceOverrides', 'excludedRecurrenceRules'].includes(key)) continue;
overrideObj[key] = value;
}
const patchUpdates: Record<string, unknown> = {
[`recurrenceOverrides/${escapedRecurrenceId}`]: overrideObj,
};
await client.updateCalendarEvent(
resolvedId,
patchUpdates as unknown as Partial<CalendarEvent>,
sendSchedulingMessages,
targetAccountId
);
} else {
// Non-recurring event with synthetic ID: retry with the real ID
await client.updateCalendarEvent(resolvedId, cleanUpdates, sendSchedulingMessages, targetAccountId);
}
set((state) => ({
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
}));
return;
}
}
throw updateError;
}
set((state) => ({
events: state.events.map(e => e.id === id ? { ...e, ...updates } : e),
}));
@@ -202,12 +250,65 @@ export const useCalendarStore = create<CalendarStore>()(
if (replyTo) {
patch.replyTo = replyTo;
}
await client.updateCalendarEvent(
realId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
try {
await client.updateCalendarEvent(
realId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
} catch (updateError) {
// Stalwart rejects updates to synthetic IDs. Resolve real ID via UID query.
const message = updateError instanceof Error ? updateError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('RSVP: Event has synthetic ID, resolving real ID via UID query');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: patch RSVP as recurrence override on master
// Escape recurrenceId per RFC 6901: ~ → ~0, / → ~1
const escapedRecId = storeEvent.recurrenceId.replace(/~/g, '~0').replace(/\//g, '~1');
const overrideObj: Record<string, unknown> = {
[patchKey]: status,
};
if (replyTo) {
overrideObj['replyTo'] = replyTo;
}
const overridePatch: Record<string, unknown> = {
[`recurrenceOverrides/${escapedRecId}`]: overrideObj,
};
await client.updateCalendarEvent(
resolvedId,
overridePatch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
} else {
// Non-recurring event: retry RSVP with real ID
await client.updateCalendarEvent(
resolvedId,
patch as unknown as Partial<CalendarEvent>,
true,
targetAccountId
);
}
set((state) => ({
events: state.events.map(e => e.id === eventId ? { ...e, participants: {
...e.participants,
...(e.participants?.[participantId] ? {
[participantId]: { ...e.participants[participantId], participationStatus: status as CalendarParticipant['participationStatus'] },
} : {}),
}} : e),
}));
return;
}
}
throw updateError;
}
set((state) => ({
events: state.events.map(e => {
if (e.id !== eventId || !e.participants?.[participantId]) return e;
@@ -305,7 +406,7 @@ export const useCalendarStore = create<CalendarStore>()(
imported++;
} catch (error) {
const msg = error instanceof Error ? error.message : '';
if (msg.includes('already exists') && src.uid) {
if ((msg.includes('already exists') || msg.includes('duplicate') || msg.includes('conflict')) && src.uid) {
const { events: storeEvents } = get();
const alreadyInStore = storeEvents.some((e) => e.uid === src.uid);
if (alreadyInStore) {
@@ -351,7 +452,39 @@ export const useCalendarStore = create<CalendarStore>()(
debug.error('Failed to send cancellation emails:', e);
}
}
await client.deleteCalendarEvent(realId, sendSchedulingMessages, targetAccountId);
try {
await client.deleteCalendarEvent(realId, sendSchedulingMessages, targetAccountId);
} catch (deleteError) {
// Stalwart rejects deletes on synthetic IDs (CalDAV-created events or
// expanded recurring instances). Resolve the real ID via UID query.
const message = deleteError instanceof Error ? deleteError.message : '';
if (message.toLowerCase().includes('synthetic') && storeEvent) {
debug.log('Event has synthetic ID, resolving real ID via UID query for delete');
const queryResults = await client.queryCalendarEvents(
{ uid: storeEvent.uid }, undefined, undefined, targetAccountId
);
const realEvent = queryResults.find(e => !e.recurrenceId) || queryResults[0];
if (realEvent) {
const resolvedId = realEvent.originalId || realEvent.id;
if (storeEvent.recurrenceId) {
// Recurring instance: exclude via recurrenceOverrides on master
await client.updateCalendarEvent(
resolvedId,
{ [`recurrenceOverrides/${storeEvent.recurrenceId}`]: { excluded: true } } as unknown as Partial<CalendarEvent>,
false,
targetAccountId
);
} else {
// Non-recurring event: delete using the real ID
await client.deleteCalendarEvent(resolvedId, sendSchedulingMessages, targetAccountId);
}
} else {
throw deleteError;
}
} else {
throw deleteError;
}
}
set((state) => ({
events: state.events.filter(e => e.id !== id),
selectedEventId: state.selectedEventId === id ? null : state.selectedEventId,
+6
View File
@@ -1102,6 +1102,12 @@ export const useEmailStore = create<EmailStore>((set, get) => ({
if (dateRange && selectedCalendarIds.length > 0) {
calendarStore.fetchEvents(client, dateRange.start, dateRange.end);
}
// Refresh tasks when calendar events change (e.g. task created via CalDAV)
const { useTaskStore } = await import('./task-store');
const taskStore = useTaskStore.getState();
if (taskStore.tasks.length > 0 || calendarStore.viewMode === 'tasks') {
taskStore.fetchTasks(client);
}
}
}
+3 -2
View File
@@ -371,10 +371,11 @@ export const useFileStore = create<FileState>((set, get) => ({
}
// Create directories as flat entries with prefixed names (no parentId nesting)
// Convert "/" separators from webkitRelativePath to PATH_SEP () for server names
const sortedDirs = [...dirs].sort((a, b) => a.split('/').length - b.split('/').length);
for (const dir of sortedDirs) {
if (abortController.signal.aborted) break;
const fullDirName = prefix + dir;
const fullDirName = prefix + dir.replace(/\//g, PATH_SEP);
try {
await client.createFileDirectory(fullDirName, null);
} catch {
@@ -387,7 +388,7 @@ export const useFileStore = create<FileState>((set, get) => ({
if (abortController.signal.aborted) break;
const file = files[i];
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
const fullName = prefix + relativePath;
const fullName = prefix + relativePath.replace(/\//g, PATH_SEP);
set({ uploadProgress: { name: relativePath, loaded: 0, total: file.size, current: i + 1, totalFiles } });
+34
View File
@@ -2,6 +2,7 @@ import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { useThemeStore } from './theme-store';
import { useLocaleStore } from './locale-store';
import type { NotificationSoundChoice } from '@/lib/notification-sound';
// Use console directly to avoid circular dependency with lib/debug.ts
// (debug.ts imports useSettingsStore for debugMode check)
@@ -119,8 +120,21 @@ interface SettingsState {
sessionTimeout: number; // minutes (0 = never)
trustedSenders: string[]; // Email addresses that can load external content
// Filters
expandedFilterView: boolean;
// Calendar
showTimeInMonthView: boolean;
showWeekNumbers: boolean;
// Calendar Tasks
enableCalendarTasks: boolean;
showTasksOnCalendar: boolean;
// Email Notifications
emailNotificationsEnabled: boolean;
emailNotificationSound: boolean;
notificationSoundChoice: NotificationSoundChoice;
// Calendar Notifications
calendarNotificationsEnabled: boolean;
@@ -219,8 +233,21 @@ const DEFAULT_SETTINGS = {
sessionTimeout: 0, // Never
trustedSenders: [] as string[],
// Filters
expandedFilterView: false,
// Calendar
showTimeInMonthView: false,
showWeekNumbers: false,
// Calendar Tasks
enableCalendarTasks: false,
showTasksOnCalendar: true,
// Email Notifications
emailNotificationsEnabled: true,
emailNotificationSound: true,
notificationSoundChoice: 'default' as NotificationSoundChoice,
// Calendar Notifications
calendarNotificationsEnabled: true,
@@ -303,10 +330,17 @@ export const useSettingsStore = create<SettingsState>()(
sendConfirmation: state.sendConfirmation,
defaultReplyMode: state.defaultReplyMode,
sessionTimeout: state.sessionTimeout,
emailNotificationsEnabled: state.emailNotificationsEnabled,
emailNotificationSound: state.emailNotificationSound,
notificationSoundChoice: state.notificationSoundChoice,
calendarNotificationsEnabled: state.calendarNotificationsEnabled,
calendarNotificationSound: state.calendarNotificationSound,
calendarInvitationParsingEnabled: state.calendarInvitationParsingEnabled,
enableCalendarTasks: state.enableCalendarTasks,
showTasksOnCalendar: state.showTasksOnCalendar,
expandedFilterView: state.expandedFilterView,
showTimeInMonthView: state.showTimeInMonthView,
showWeekNumbers: state.showWeekNumbers,
toolbarPosition: state.toolbarPosition,
senderFavicons: state.senderFavicons,
folderIcons: state.folderIcons,
+58 -1
View File
@@ -1,5 +1,6 @@
import { create } from 'zustand';
import type { CalendarTask } from '@/lib/jmap/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
export type TaskViewFilter = 'all' | 'pending' | 'completed' | 'overdue';
@@ -8,19 +9,75 @@ interface TaskStore {
selectedTaskId: string | null;
filter: TaskViewFilter;
showCompleted: boolean;
isLoading: boolean;
error: string | null;
setTasks: (tasks: CalendarTask[]) => void;
setSelectedTaskId: (id: string | null) => void;
setFilter: (filter: TaskViewFilter) => void;
setShowCompleted: (show: boolean) => void;
fetchTasks: (client: IJMAPClient, calendarIds?: string[]) => Promise<void>;
createTask: (client: IJMAPClient, task: Partial<CalendarTask>) => Promise<CalendarTask>;
updateTask: (client: IJMAPClient, id: string, updates: Partial<CalendarTask>) => Promise<void>;
deleteTask: (client: IJMAPClient, id: string) => Promise<void>;
toggleTaskComplete: (client: IJMAPClient, task: CalendarTask) => Promise<void>;
clearTasks: () => void;
}
export const useTaskStore = create<TaskStore>((set) => ({
export const useTaskStore = create<TaskStore>((set, get) => ({
tasks: [],
selectedTaskId: null,
filter: 'all',
showCompleted: false,
isLoading: false,
error: null,
setTasks: (tasks) => set({ tasks }),
setSelectedTaskId: (id) => set({ selectedTaskId: id }),
setFilter: (filter) => set({ filter }),
setShowCompleted: (show) => set({ showCompleted: show }),
fetchTasks: async (client, calendarIds) => {
set({ isLoading: true, error: null });
try {
const tasks = await client.getCalendarTasks(calendarIds);
set({ tasks, isLoading: false });
} catch (error) {
console.error('Failed to fetch tasks:', error);
set({ isLoading: false, error: 'Failed to fetch tasks' });
}
},
createTask: async (client, task) => {
const created = await client.createCalendarTask(task);
set({ tasks: [...get().tasks, created] });
return created;
},
updateTask: async (client, id, updates) => {
await client.updateCalendarTask(id, updates);
set({
tasks: get().tasks.map(t => t.id === id ? { ...t, ...updates, updated: new Date().toISOString() } : t),
});
},
deleteTask: async (client, id) => {
await client.deleteCalendarTask(id);
set({
tasks: get().tasks.filter(t => t.id !== id),
selectedTaskId: get().selectedTaskId === id ? null : get().selectedTaskId,
});
},
toggleTaskComplete: async (client, task) => {
const newProgress = task.progress === 'completed' ? 'needs-action' : 'completed';
const updates: Partial<CalendarTask> = {
progress: newProgress,
progressUpdated: new Date().toISOString(),
};
await client.updateCalendarTask(task.id, updates);
set({
tasks: get().tasks.map(t => t.id === task.id ? { ...t, ...updates, updated: new Date().toISOString() } : t),
});
},
clearTasks: () => set({ tasks: [], selectedTaskId: null, error: null }),
}));