Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97bc26a332 | ||
|
|
55c8d430ca | ||
|
|
ef45140d32 | ||
|
|
0effb97691 | ||
|
|
f7ee204262 | ||
|
|
0c1f182b6b | ||
|
|
13010c158d | ||
|
|
de26e6da2e | ||
|
|
ddb3422852 | ||
|
|
d9a2529261 | ||
|
|
e70224317d | ||
|
|
a9ecf164ab | ||
|
|
0db3cbc959 | ||
|
|
387273288c | ||
|
|
8eff9fdfab | ||
|
|
d915e5fb64 | ||
|
|
5530cfe7fe | ||
|
|
31eee4bab9 | ||
|
|
f04b97d52a | ||
|
|
df272e38ef | ||
|
|
a835af2d71 | ||
|
|
30284859c7 | ||
|
|
64c3d7e384 | ||
|
|
e6d09546b1 | ||
|
|
83a0a1e235 | ||
|
|
7c3c3b5f7b | ||
|
|
8b1b3ad57b | ||
|
|
afefbb8d46 | ||
|
|
4c2d185be4 | ||
|
|
c73940e22a | ||
|
|
09eda86d3f | ||
|
|
0d28d811a8 | ||
|
|
45a485a1fa | ||
|
|
bc202498d5 | ||
|
|
721556e777 | ||
|
|
8c9cf3a66b | ||
|
|
b88026de82 | ||
|
|
6ed8ae5812 | ||
|
|
089583a9ef | ||
|
|
2d834213ee | ||
|
|
439a4dbe8a | ||
|
|
8350bad2a6 | ||
|
|
2d56cc9be9 | ||
|
|
2547c10060 | ||
|
|
01779fa59e | ||
|
|
fc38427ed0 | ||
|
|
3cbfb70860 | ||
|
|
c32b740dac | ||
|
|
a02091a7ad | ||
|
|
bc311adf6a | ||
|
|
8aca1623f4 | ||
|
|
a8be40579e | ||
|
|
705b942800 | ||
|
|
d68b81e6b8 | ||
|
|
616e4d018d | ||
|
|
68e141b787 | ||
|
|
1e6f5e2c8c | ||
|
|
9495b34430 | ||
|
|
65fc489b9c | ||
|
|
bd686c092c | ||
|
|
6cff98ddb8 | ||
|
|
dcc35335f5 | ||
|
|
8a54ae2456 | ||
|
|
e26654a005 | ||
|
|
c1c06c68bb | ||
|
|
74cf642182 | ||
|
|
c5b1731a63 | ||
|
|
40cf164df3 | ||
|
|
ff56245db8 | ||
|
|
9b4de4d152 | ||
|
|
0c9e60db8b | ||
|
|
def8ee89fa | ||
|
|
e7e07a38d7 | ||
|
|
a009e5ae32 |
@@ -5,9 +5,7 @@ node_modules
|
|||||||
.env*
|
.env*
|
||||||
!.env.example
|
!.env.example
|
||||||
!.env.dev.example
|
!.env.dev.example
|
||||||
.claude/
|
|
||||||
scripts/
|
scripts/
|
||||||
TODO.md
|
TODO.md
|
||||||
CLAUDE.md
|
|
||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
|
|||||||
+4
-1
@@ -64,7 +64,10 @@ JMAP_SERVER_URL=https://your-jmap-server.com
|
|||||||
# SETTINGS_SYNC_ENABLED=true
|
# SETTINGS_SYNC_ENABLED=true
|
||||||
|
|
||||||
# Directory for storing encrypted settings files (default: ./data/settings).
|
# Directory for storing encrypted settings files (default: ./data/settings).
|
||||||
# For Docker, mount a persistent volume at this path.
|
# For Docker, the working directory is /app, so the default resolves to
|
||||||
|
# /app/data/settings — mount a persistent volume there:
|
||||||
|
# volumes:
|
||||||
|
# - bulwark-settings:/app/data/settings
|
||||||
# SETTINGS_DATA_DIR=./data/settings
|
# SETTINGS_DATA_DIR=./data/settings
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|||||||
@@ -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 }}
|
||||||
@@ -2,7 +2,9 @@ name: Publish Docker Image
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches:
|
||||||
|
- main
|
||||||
|
- dev
|
||||||
paths:
|
paths:
|
||||||
- "Dockerfile"
|
- "Dockerfile"
|
||||||
- ".dockerignore"
|
- ".dockerignore"
|
||||||
@@ -17,12 +19,22 @@ on:
|
|||||||
- "package.json"
|
- "package.json"
|
||||||
- "package-lock.json"
|
- "package-lock.json"
|
||||||
- ".github/workflows/docker-publish.yml"
|
- ".github/workflows/docker-publish.yml"
|
||||||
tags: ["v*.*.*"]
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
IMAGE_NAME: ghcr.io/${{ github.repository }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-and-push:
|
build:
|
||||||
runs-on: ubuntu-latest
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- platform: linux/amd64
|
||||||
|
runner: ubuntu-latest
|
||||||
|
- platform: linux/arm64
|
||||||
|
runner: ubuntu-24.04-arm
|
||||||
|
runs-on: ${{ matrix.runner }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
@@ -31,9 +43,6 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v3
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
@@ -48,21 +57,73 @@ jobs:
|
|||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v5
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
images: |
|
images: ${{ env.IMAGE_NAME }}
|
||||||
ghcr.io/${{ github.repository }}
|
|
||||||
tags: |
|
|
||||||
type=raw,value=latest,enable={{is_default_branch}}
|
|
||||||
type=semver,pattern={{version}}
|
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
|
||||||
type=sha,prefix=
|
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push by digest
|
||||||
|
id: build
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: ${{ matrix.platform }}
|
||||||
push: true
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
cache-from: type=gha
|
outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||||
cache-to: type=gha,mode=max
|
cache-from: type=gha,scope=${{ matrix.platform }}
|
||||||
|
cache-to: type=gha,mode=max,scope=${{ matrix.platform }}
|
||||||
|
|
||||||
|
- name: Export digest
|
||||||
|
run: |
|
||||||
|
mkdir -p /tmp/digests
|
||||||
|
digest="${{ steps.build.outputs.digest }}"
|
||||||
|
touch "/tmp/digests/${digest#sha256:}"
|
||||||
|
|
||||||
|
- name: Upload digest
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: digests-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
|
||||||
|
path: /tmp/digests/*
|
||||||
|
if-no-files-found: error
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
merge:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Download digests
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: /tmp/digests
|
||||||
|
pattern: digests-*
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Log in to GHCR
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=raw,value={{branch}}
|
||||||
|
type=sha,prefix={{branch}}-
|
||||||
|
|
||||||
|
- name: Create manifest list and push
|
||||||
|
working-directory: /tmp/digests
|
||||||
|
run: |
|
||||||
|
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||||
|
$(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *)
|
||||||
|
|
||||||
|
- name: Inspect image
|
||||||
|
run: |
|
||||||
|
docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
||||||
|
|||||||
@@ -42,9 +42,6 @@ yarn-error.log*
|
|||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
# claude code
|
|
||||||
.claude/
|
|
||||||
|
|
||||||
# settings sync data
|
# settings sync data
|
||||||
/data/
|
/data/
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,85 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 1.4.8 (2026-03-23)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Email**: Add support for marking emails as answered or forwarded and display status icons in email list and thread views
|
||||||
|
- **Email**: Enhance identity selection by supporting sub-addressing (plus addressing) in email composer
|
||||||
|
- **Settings**: Add notification settings with sound picker, preview playback, and configurable alert sounds
|
||||||
|
- **Settings**: Add default mail program settings with localization support across all locales
|
||||||
|
- **Auth**: Implement path prefix handling for OAuth callbacks and login redirects, enabling reverse proxy deployments
|
||||||
|
- **Validation**: Add all multi-part TLDs for domain validation in favicon API (#81)
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Calendar**: Fix bugs in duration parsing, RFC compliance, and event handling across calendar components
|
||||||
|
- **Calendar**: Detect tasks created by external CalDAV clients such as Thunderbird
|
||||||
|
- **Settings**: Enhance account settings with username and authentication method display (#90)
|
||||||
|
|
||||||
|
## 1.4.7 (2026-03-21)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Calendar**: Add task management features with task creation, editing, and status tracking
|
||||||
|
- **Calendar**: Add option to show week numbers in mini-calendar
|
||||||
|
- **Email**: Add resizable image component and rich text editor with image upload support
|
||||||
|
- **Files**: Support uploading folders via drag-and-drop and toolbar button
|
||||||
|
- **Filters**: Add expanded visual view for filter rules
|
||||||
|
- **Auth**: Add non-interactive SSO login flow for embedded/iframe deployments (#69)
|
||||||
|
- **DevOps**: Add separate Docker build workflow for releases and dev branch images
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Calendar**: Handle updates and deletions for synthetic JMAP IDs in calendar events with fallback to destroy and recreate
|
||||||
|
- **Security**: Extend CryptoEngine to support legacy algorithms and integrate with LinerEngine for decryption
|
||||||
|
- **Auth**: Refactor logout to use synchronous flow with full page redirect
|
||||||
|
- **Email**: Update iframe sandbox attributes to allow popups to escape sandbox
|
||||||
|
- **i18n**: Add missing translation keys across all locales
|
||||||
|
- **Docker**: Update .env.example to clarify Docker volume mounting for settings data directory
|
||||||
|
|
||||||
|
## 1.4.6 (2026-03-21)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Demo**: Add full demo mode with fixture data for emails, calendars, contacts, files, filters, identities, mailboxes, and vacation responses
|
||||||
|
- **Demo**: Implement JMAP client interface abstraction to support demo and live backends
|
||||||
|
- **Contacts**: Add no-category filter, drag-and-drop to category, and category combo box in contact form
|
||||||
|
- **Email**: Add hover actions for emails with configurable quick-action buttons
|
||||||
|
- **Settings**: Implement keyword migration functionality for upgrading legacy email tags
|
||||||
|
- **Security**: Enhance S/MIME certificate extraction and add legacy PBE (password-based encryption) support
|
||||||
|
- **Tour**: Add interactive guided tour overlay for new user onboarding
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Settings**: Add missing `showTimeInMonthView` and `showOnMobile` type definitions to settings store
|
||||||
|
- **UI**: Adjust padding and size of sidebar buttons for improved layout
|
||||||
|
|
||||||
|
## 1.4.5 (2026-03-20)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Calendar**: Add prev/next navigation buttons and date label to desktop calendar toolbar
|
||||||
|
- **Calendar**: Add pending event preview functionality to calendar views and event modal
|
||||||
|
- **Calendar**: Add setting to show event start time in month view
|
||||||
|
- **Contacts**: Implement pagination for fetching contacts with maxObjectsInGet capability
|
||||||
|
- **Email**: Add attachment position setting in email settings
|
||||||
|
- **Layout**: Add mobile visibility toggle for sidebar apps
|
||||||
|
- **Error**: Add NotFound component to handle 404 errors and redirect unauthenticated users
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- **Auth**: Enhance account switching logic and clear stores on account change
|
||||||
|
- **Auth**: Improve account restoration logic and handle stale accounts
|
||||||
|
- **Auth**: Improve draft handling in email composer and enhance session cookie verification
|
||||||
|
- **Calendar**: Expand recurring events in CalendarEvent/query so individual occurrences are returned (#65)
|
||||||
|
- **Calendar**: Validate event start field when fetching calendar events
|
||||||
|
- **Calendar**: Auto-scroll agenda view to today's events and include today's date in groups
|
||||||
|
- **Calendar**: Correct JSX syntax in CalendarToolbar component
|
||||||
|
- **Dependencies**: Update flatted to 3.4.2
|
||||||
|
- **DevOps**: Use native ARM runners instead of QEMU for Docker builds
|
||||||
|
- **DevOps**: Enhance health check with detailed memory diagnostics and stable liveness probe
|
||||||
|
|
||||||
## 1.4.4 (2026-03-19)
|
## 1.4.4 (2026-03-19)
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
@@ -11,9 +11,10 @@
|
|||||||
A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.art/).<br/>
|
A modern, self-hosted webmail client for [Stalwart Mail Server](https://stalw.art/).<br/>
|
||||||
Built with Next.js and the JMAP protocol.
|
Built with Next.js and the JMAP protocol.
|
||||||
|
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](CHANGELOG.md)
|
[](https://discord.gg/tYCujymGrT)
|
||||||
[](https://ghcr.io/bulwarkmail/webmail)
|
[](CHANGELOG.md)
|
||||||
|
[](https://ghcr.io/bulwarkmail/webmail)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { Suspense, useEffect, useState } from "react";
|
|||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { getPathPrefix } from "@/lib/browser-navigation";
|
||||||
import { Loader2, AlertCircle } from "lucide-react";
|
import { Loader2, AlertCircle } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useParams } from "next/navigation";
|
import { useParams } from "next/navigation";
|
||||||
@@ -13,7 +14,7 @@ function OAuthCallbackInner() {
|
|||||||
const params = useParams();
|
const params = useParams();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const t = useTranslations("login");
|
const t = useTranslations("login");
|
||||||
const { loginWithOAuth } = useAuthStore();
|
const { loginWithOAuth, loginWithServerSso } = useAuthStore();
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -32,44 +33,73 @@ function OAuthCallbackInner() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const savedState = sessionStorage.getItem("oauth_state");
|
const savedState = sessionStorage.getItem("oauth_state");
|
||||||
if (!state || state !== savedState) {
|
|
||||||
setError("invalid_state");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
|
if (savedState) {
|
||||||
const serverUrl = sessionStorage.getItem("oauth_server_url");
|
// Classic flow — sessionStorage has the PKCE state (same-tab OAuth)
|
||||||
|
if (!state || state !== savedState) {
|
||||||
|
setError("invalid_state");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!codeVerifier || !serverUrl) {
|
const codeVerifier = sessionStorage.getItem("oauth_code_verifier");
|
||||||
setError("missing_params");
|
const serverUrl = sessionStorage.getItem("oauth_server_url");
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
|
if (!codeVerifier || !serverUrl) {
|
||||||
|
setError("missing_params");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
|
const prefix = getPathPrefix(params.locale as string);
|
||||||
.then((success) => {
|
const redirectUri = `${window.location.origin}${prefix}/${params.locale}/auth/callback`;
|
||||||
if (success) {
|
|
||||||
sessionStorage.removeItem("oauth_state");
|
loginWithOAuth(serverUrl, code, codeVerifier, redirectUri)
|
||||||
sessionStorage.removeItem("oauth_code_verifier");
|
.then((success) => {
|
||||||
sessionStorage.removeItem("oauth_server_url");
|
if (success) {
|
||||||
sessionStorage.removeItem("oauth_add_account_mode");
|
sessionStorage.removeItem("oauth_state");
|
||||||
let redirectTo = `/${params.locale}`;
|
sessionStorage.removeItem("oauth_code_verifier");
|
||||||
try {
|
sessionStorage.removeItem("oauth_server_url");
|
||||||
const saved = sessionStorage.getItem('redirect_after_login');
|
sessionStorage.removeItem("oauth_add_account_mode");
|
||||||
if (saved) {
|
let redirectTo = `${prefix}/${params.locale}`;
|
||||||
sessionStorage.removeItem('redirect_after_login');
|
try {
|
||||||
redirectTo = saved;
|
const saved = sessionStorage.getItem('redirect_after_login');
|
||||||
}
|
if (saved) {
|
||||||
} catch { /* sessionStorage may be unavailable */ }
|
sessionStorage.removeItem('redirect_after_login');
|
||||||
router.push(redirectTo);
|
redirectTo = saved;
|
||||||
} else {
|
}
|
||||||
|
} catch { /* sessionStorage may be unavailable */ }
|
||||||
|
router.push(redirectTo);
|
||||||
|
} else {
|
||||||
|
setError("token_exchange_failed");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
setError("token_exchange_failed");
|
setError("token_exchange_failed");
|
||||||
}
|
});
|
||||||
})
|
} else if (state) {
|
||||||
.catch(() => {
|
// Server-side SSO flow — state was stored in encrypted httpOnly cookie
|
||||||
setError("token_exchange_failed");
|
const ssoPrefix = getPathPrefix(params.locale as string);
|
||||||
});
|
loginWithServerSso(code, state)
|
||||||
|
.then((success) => {
|
||||||
|
if (success) {
|
||||||
|
let redirectTo = `${ssoPrefix}/${params.locale}`;
|
||||||
|
try {
|
||||||
|
const saved = sessionStorage.getItem('redirect_after_login');
|
||||||
|
if (saved) {
|
||||||
|
sessionStorage.removeItem('redirect_after_login');
|
||||||
|
redirectTo = saved;
|
||||||
|
}
|
||||||
|
} catch { /* sessionStorage may be unavailable */ }
|
||||||
|
router.push(redirectTo);
|
||||||
|
} else {
|
||||||
|
setError("token_exchange_failed");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setError("token_exchange_failed");
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setError("invalid_state");
|
||||||
|
}
|
||||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -87,7 +117,7 @@ function OAuthCallbackInner() {
|
|||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => router.push(`/${params.locale}/login`)}
|
onClick={() => router.push(`${getPathPrefix(params.locale as string)}/${params.locale}/login`)}
|
||||||
>
|
>
|
||||||
{t("oauth_error.back_to_login")}
|
{t("oauth_error.back_to_login")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
+158
-25
@@ -7,11 +7,11 @@ import { Plus } from "lucide-react";
|
|||||||
import {
|
import {
|
||||||
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
|
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
|
||||||
addMonths, subMonths, addWeeks, subWeeks, addDays, subDays,
|
addMonths, subMonths, addWeeks, subWeeks, addDays, subDays,
|
||||||
format, parseISO,
|
startOfDay, format, parseISO,
|
||||||
} from "date-fns";
|
} from "date-fns";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
import { isCalendarViewMode } 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 { useEmailStore } from "@/stores/email-store";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { useIdentityStore } from "@/stores/identity-store";
|
import { useIdentityStore } from "@/stores/identity-store";
|
||||||
@@ -23,9 +23,12 @@ import { CalendarMonthView } from "@/components/calendar/calendar-month-view";
|
|||||||
import { CalendarWeekView } from "@/components/calendar/calendar-week-view";
|
import { CalendarWeekView } from "@/components/calendar/calendar-week-view";
|
||||||
import { CalendarDayView } from "@/components/calendar/calendar-day-view";
|
import { CalendarDayView } from "@/components/calendar/calendar-day-view";
|
||||||
import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view";
|
import { CalendarAgendaView } from "@/components/calendar/calendar-agenda-view";
|
||||||
|
import { TaskListView } from "@/components/calendar/task-list-view";
|
||||||
|
import { TaskToolbar } from "@/components/calendar/task-toolbar";
|
||||||
|
import { TaskModal } from "@/components/calendar/task-modal";
|
||||||
import { MiniCalendar } from "@/components/calendar/mini-calendar";
|
import { MiniCalendar } from "@/components/calendar/mini-calendar";
|
||||||
import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel";
|
import { CalendarSidebarPanel } from "@/components/calendar/calendar-sidebar-panel";
|
||||||
import { EventModal } from "@/components/calendar/event-modal";
|
import { EventModal, type PendingEventPreview } from "@/components/calendar/event-modal";
|
||||||
import { EventDetailPopover } from "@/components/calendar/event-detail-popover";
|
import { EventDetailPopover } from "@/components/calendar/event-detail-popover";
|
||||||
import { ICalImportModal } from "@/components/calendar/ical-import-modal";
|
import { ICalImportModal } from "@/components/calendar/ical-import-modal";
|
||||||
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
|
import { ICalSubscriptionModal } from "@/components/calendar/ical-subscription-modal";
|
||||||
@@ -35,6 +38,7 @@ import { SidebarAppsModal } from "@/components/layout/sidebar-apps-modal";
|
|||||||
import { InlineAppView } from "@/components/layout/inline-app-view";
|
import { InlineAppView } from "@/components/layout/inline-app-view";
|
||||||
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
import { useSidebarApps } from "@/hooks/use-sidebar-apps";
|
||||||
import { ResizeHandle } from "@/components/layout/resize-handle";
|
import { ResizeHandle } from "@/components/layout/resize-handle";
|
||||||
|
import { useTaskStore } from "@/stores/task-store";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
|
import type { CalendarEvent, CalendarParticipant } from "@/lib/jmap/types";
|
||||||
import { getUserParticipantId } from "@/lib/calendar-participants";
|
import { getUserParticipantId } from "@/lib/calendar-participants";
|
||||||
@@ -63,7 +67,8 @@ export default function CalendarPage() {
|
|||||||
setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar,
|
setSelectedDate, setViewMode, toggleCalendarVisibility, updateCalendar,
|
||||||
refreshAllSubscriptions,
|
refreshAllSubscriptions,
|
||||||
} = useCalendarStore();
|
} = useCalendarStore();
|
||||||
const { firstDayOfWeek, timeFormat } = useSettingsStore();
|
const { firstDayOfWeek, timeFormat, showWeekNumbers, enableCalendarTasks, showTasksOnCalendar } = useSettingsStore();
|
||||||
|
const taskStore = useTaskStore();
|
||||||
const { identities } = useIdentityStore();
|
const { identities } = useIdentityStore();
|
||||||
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
|
const normalizedViewMode = isCalendarViewMode(viewMode) ? viewMode : "month";
|
||||||
|
|
||||||
@@ -82,6 +87,9 @@ export default function CalendarPage() {
|
|||||||
const [pendingScopeAction, setPendingScopeAction] = useState<PendingScopeAction | null>(null);
|
const [pendingScopeAction, setPendingScopeAction] = useState<PendingScopeAction | null>(null);
|
||||||
const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null);
|
const [detailEvent, setDetailEvent] = useState<CalendarEvent | null>(null);
|
||||||
const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null);
|
const [detailAnchorRect, setDetailAnchorRect] = useState<DOMRect | null>(null);
|
||||||
|
const [pendingPreview, setPendingPreview] = useState<PendingEventPreview | null>(null);
|
||||||
|
const [showTaskModal, setShowTaskModal] = useState(false);
|
||||||
|
const [editTask, setEditTask] = useState<import("@/lib/jmap/types").CalendarTask | null>(null);
|
||||||
const hasFetched = useRef(false);
|
const hasFetched = useRef(false);
|
||||||
|
|
||||||
// Sidebar resize state
|
// Sidebar resize state
|
||||||
@@ -104,7 +112,7 @@ export default function CalendarPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
||||||
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
||||||
router.push("/login");
|
redirectToLogin();
|
||||||
} else if (client && !supportsCalendar) {
|
} else if (client && !supportsCalendar) {
|
||||||
router.push("/");
|
router.push("/");
|
||||||
}
|
}
|
||||||
@@ -156,14 +164,27 @@ export default function CalendarPage() {
|
|||||||
start: format(d, "yyyy-MM-dd'T'00:00:00"),
|
start: format(d, "yyyy-MM-dd'T'00:00:00"),
|
||||||
end: format(d, "yyyy-MM-dd'T'23:59:59"),
|
end: format(d, "yyyy-MM-dd'T'23:59:59"),
|
||||||
};
|
};
|
||||||
case "agenda":
|
case "agenda": {
|
||||||
|
// Agenda always starts from today at the earliest
|
||||||
|
const today = startOfDay(new Date());
|
||||||
|
const agendaStart = d >= today ? d : today;
|
||||||
return {
|
return {
|
||||||
start: format(d, "yyyy-MM-dd'T'00:00:00"),
|
start: format(agendaStart, "yyyy-MM-dd'T'00:00:00"),
|
||||||
end: format(addDays(d, 30), "yyyy-MM-dd'T'23:59:59"),
|
end: format(addDays(agendaStart, 30), "yyyy-MM-dd'T'23:59:59"),
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
case "tasks":
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}, [selectedDate, normalizedViewMode, firstDayOfWeek]);
|
}, [selectedDate, normalizedViewMode, firstDayOfWeek]);
|
||||||
|
|
||||||
|
// Fetch tasks when tasks view is active or when tasks are shown on calendar grid
|
||||||
|
useEffect(() => {
|
||||||
|
if (client && enableCalendarTasks && (normalizedViewMode === "tasks" || showTasksOnCalendar)) {
|
||||||
|
taskStore.fetchTasks(client);
|
||||||
|
}
|
||||||
|
}, [client, enableCalendarTasks, normalizedViewMode, showTasksOnCalendar]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (client && calendars.length > 0 && dateRange) {
|
if (client && calendars.length > 0 && dateRange) {
|
||||||
fetchEvents(client, dateRange.start, dateRange.end);
|
fetchEvents(client, dateRange.start, dateRange.end);
|
||||||
@@ -177,6 +198,7 @@ export default function CalendarPage() {
|
|||||||
case "week": next = subWeeks(selectedDate, 1); break;
|
case "week": next = subWeeks(selectedDate, 1); break;
|
||||||
case "day": next = subDays(selectedDate, 1); break;
|
case "day": next = subDays(selectedDate, 1); break;
|
||||||
case "agenda": next = subMonths(selectedDate, 1); break;
|
case "agenda": next = subMonths(selectedDate, 1); break;
|
||||||
|
case "tasks": return;
|
||||||
}
|
}
|
||||||
setSelectedDate(next);
|
setSelectedDate(next);
|
||||||
setMiniMonth(next);
|
setMiniMonth(next);
|
||||||
@@ -189,6 +211,7 @@ export default function CalendarPage() {
|
|||||||
case "week": next = addWeeks(selectedDate, 1); break;
|
case "week": next = addWeeks(selectedDate, 1); break;
|
||||||
case "day": next = addDays(selectedDate, 1); break;
|
case "day": next = addDays(selectedDate, 1); break;
|
||||||
case "agenda": next = addMonths(selectedDate, 1); break;
|
case "agenda": next = addMonths(selectedDate, 1); break;
|
||||||
|
case "tasks": return;
|
||||||
}
|
}
|
||||||
setSelectedDate(next);
|
setSelectedDate(next);
|
||||||
setMiniMonth(next);
|
setMiniMonth(next);
|
||||||
@@ -249,6 +272,34 @@ export default function CalendarPage() {
|
|||||||
setShowEventModal(true);
|
setShowEventModal(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const openCreateTaskModal = useCallback(() => {
|
||||||
|
setEditTask(null);
|
||||||
|
setShowTaskModal(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const openEditTaskModal = useCallback((task: import("@/lib/jmap/types").CalendarTask) => {
|
||||||
|
setEditTask(task);
|
||||||
|
setShowTaskModal(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSaveTask = useCallback(async (data: Partial<import("@/lib/jmap/types").CalendarTask>) => {
|
||||||
|
if (!client) return;
|
||||||
|
if (editTask) {
|
||||||
|
await taskStore.updateTask(client, editTask.id, data);
|
||||||
|
} else {
|
||||||
|
await taskStore.createTask(client, data);
|
||||||
|
}
|
||||||
|
setShowTaskModal(false);
|
||||||
|
setEditTask(null);
|
||||||
|
}, [client, editTask, taskStore]);
|
||||||
|
|
||||||
|
const handleDeleteTask = useCallback(async (id: string) => {
|
||||||
|
if (!client) return;
|
||||||
|
await taskStore.deleteTask(client, id);
|
||||||
|
setShowTaskModal(false);
|
||||||
|
setEditTask(null);
|
||||||
|
}, [client, taskStore]);
|
||||||
|
|
||||||
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
const closeDetail = useCallback(() => {
|
const closeDetail = useCallback(() => {
|
||||||
@@ -264,12 +315,13 @@ export default function CalendarPage() {
|
|||||||
}, [closeDetail, openEditModal]);
|
}, [closeDetail, openEditModal]);
|
||||||
|
|
||||||
const handleHoverEvent = useCallback((event: CalendarEvent, anchorRect: DOMRect) => {
|
const handleHoverEvent = useCallback((event: CalendarEvent, anchorRect: DOMRect) => {
|
||||||
|
if (isMobile) return;
|
||||||
if (hoverTimerRef.current) { clearTimeout(hoverTimerRef.current); hoverTimerRef.current = null; }
|
if (hoverTimerRef.current) { clearTimeout(hoverTimerRef.current); hoverTimerRef.current = null; }
|
||||||
// Don't show hover popover if the sidebar is already open for this event
|
// Don't show hover popover if the sidebar is already open for this event
|
||||||
if (showEventModal && editEvent?.id === event.id) return;
|
if (showEventModal && editEvent?.id === event.id) return;
|
||||||
setDetailEvent(event);
|
setDetailEvent(event);
|
||||||
setDetailAnchorRect(anchorRect);
|
setDetailAnchorRect(anchorRect);
|
||||||
}, [showEventModal, editEvent]);
|
}, [isMobile, showEventModal, editEvent]);
|
||||||
|
|
||||||
const handleHoverLeave = useCallback(() => {
|
const handleHoverLeave = useCallback(() => {
|
||||||
hoverTimerRef.current = setTimeout(() => {
|
hoverTimerRef.current = setTimeout(() => {
|
||||||
@@ -418,9 +470,22 @@ export default function CalendarPage() {
|
|||||||
try {
|
try {
|
||||||
if (type === "edit" && updates) {
|
if (type === "edit" && updates) {
|
||||||
switch (scope) {
|
switch (scope) {
|
||||||
case "this":
|
case "this": {
|
||||||
await updateEvent(client, event.id, updates, sendScheduling);
|
// Synthetic IDs (from expandRecurrences) can't be updated directly.
|
||||||
|
// Patch the master event's recurrenceOverrides instead.
|
||||||
|
const master = await findMasterEvent(event);
|
||||||
|
if (master && event.recurrenceId) {
|
||||||
|
const patchUpdates: Record<string, unknown> = {};
|
||||||
|
for (const [key, value] of Object.entries(updates)) {
|
||||||
|
if (['id', 'uid', '@type', 'calendarIds', 'recurrenceRules', 'recurrenceOverrides', 'excludedRecurrenceRules'].includes(key)) continue;
|
||||||
|
patchUpdates[`recurrenceOverrides/${event.recurrenceId}/${key}`] = value;
|
||||||
|
}
|
||||||
|
await updateEvent(client, master.id, patchUpdates as Partial<CalendarEvent>, sendScheduling);
|
||||||
|
} else {
|
||||||
|
await updateEvent(client, event.id, updates, sendScheduling);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case "this_and_future": {
|
case "this_and_future": {
|
||||||
const result = await truncateRecurrenceAtEvent(event);
|
const result = await truncateRecurrenceAtEvent(event);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
@@ -478,9 +543,20 @@ export default function CalendarPage() {
|
|||||||
toast.success(t("notifications.event_updated"));
|
toast.success(t("notifications.event_updated"));
|
||||||
} else {
|
} else {
|
||||||
switch (scope) {
|
switch (scope) {
|
||||||
case "this":
|
case "this": {
|
||||||
await deleteEvent(client, event.id, sendScheduling);
|
// Synthetic IDs (from expandRecurrences) can't be destroyed directly.
|
||||||
|
// Exclude the instance via recurrenceOverrides on the master event.
|
||||||
|
const delMaster = await findMasterEvent(event);
|
||||||
|
if (delMaster && event.recurrenceId) {
|
||||||
|
await updateEvent(
|
||||||
|
client, delMaster.id,
|
||||||
|
{ [`recurrenceOverrides/${event.recurrenceId}`]: { excluded: true } } as Partial<CalendarEvent>,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await deleteEvent(client, event.id, sendScheduling);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
case "this_and_future": {
|
case "this_and_future": {
|
||||||
const result = await truncateRecurrenceAtEvent(event);
|
const result = await truncateRecurrenceAtEvent(event);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
@@ -592,6 +668,7 @@ export default function CalendarPage() {
|
|||||||
const handleKey = (e: KeyboardEvent) => {
|
const handleKey = (e: KeyboardEvent) => {
|
||||||
const target = e.target as HTMLElement;
|
const target = e.target as HTMLElement;
|
||||||
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return;
|
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return;
|
||||||
|
if (target.getAttribute("contenteditable") === "true") return;
|
||||||
if (showEventModal || detailEvent) return;
|
if (showEventModal || detailEvent) return;
|
||||||
|
|
||||||
switch (e.key) {
|
switch (e.key) {
|
||||||
@@ -602,6 +679,7 @@ export default function CalendarPage() {
|
|||||||
case "w": setViewMode("week"); break;
|
case "w": setViewMode("week"); break;
|
||||||
case "d": setViewMode("day"); break;
|
case "d": setViewMode("day"); break;
|
||||||
case "a": setViewMode("agenda"); break;
|
case "a": setViewMode("agenda"); break;
|
||||||
|
case "k": if (enableCalendarTasks) setViewMode("tasks"); break;
|
||||||
case "n": openCreateModal(); break;
|
case "n": openCreateModal(); break;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -611,7 +689,7 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
const visibleEvents = useMemo(() =>
|
const visibleEvents = useMemo(() =>
|
||||||
events.filter((e) => {
|
events.filter((e) => {
|
||||||
if (!e.calendarIds) return false;
|
if (!e.start || !e.calendarIds) return false;
|
||||||
const calIds = Object.keys(e.calendarIds);
|
const calIds = Object.keys(e.calendarIds);
|
||||||
return calIds.some((id) => selectedCalendarIds.includes(id));
|
return calIds.some((id) => selectedCalendarIds.includes(id));
|
||||||
}),
|
}),
|
||||||
@@ -644,6 +722,7 @@ export default function CalendarPage() {
|
|||||||
onCreateAtTime={openCreateModal}
|
onCreateAtTime={openCreateModal}
|
||||||
firstDayOfWeek={firstDayOfWeek}
|
firstDayOfWeek={firstDayOfWeek}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
|
pendingPreview={pendingPreview}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "week":
|
case "week":
|
||||||
@@ -660,6 +739,9 @@ export default function CalendarPage() {
|
|||||||
firstDayOfWeek={firstDayOfWeek}
|
firstDayOfWeek={firstDayOfWeek}
|
||||||
timeFormat={timeFormat}
|
timeFormat={timeFormat}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
|
pendingPreview={pendingPreview}
|
||||||
|
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
|
||||||
|
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "day":
|
case "day":
|
||||||
@@ -674,6 +756,9 @@ export default function CalendarPage() {
|
|||||||
onCreateAtTime={openCreateModal}
|
onCreateAtTime={openCreateModal}
|
||||||
timeFormat={timeFormat}
|
timeFormat={timeFormat}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
|
pendingPreview={pendingPreview}
|
||||||
|
tasks={enableCalendarTasks && showTasksOnCalendar ? taskStore.tasks : undefined}
|
||||||
|
onToggleTaskComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case "agenda":
|
case "agenda":
|
||||||
@@ -688,6 +773,33 @@ export default function CalendarPage() {
|
|||||||
timeFormat={timeFormat}
|
timeFormat={timeFormat}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
case "tasks":
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<TaskToolbar
|
||||||
|
filter={taskStore.filter}
|
||||||
|
showCompleted={taskStore.showCompleted}
|
||||||
|
onFilterChange={taskStore.setFilter}
|
||||||
|
onShowCompletedChange={taskStore.setShowCompleted}
|
||||||
|
onCreateTask={openCreateTaskModal}
|
||||||
|
/>
|
||||||
|
<TaskListView
|
||||||
|
tasks={taskStore.tasks}
|
||||||
|
calendars={calendars}
|
||||||
|
selectedCalendarIds={selectedCalendarIds}
|
||||||
|
filter={taskStore.filter}
|
||||||
|
showCompleted={taskStore.showCompleted}
|
||||||
|
onSelectTask={openEditTaskModal}
|
||||||
|
onToggleComplete={(task) => { if (client) taskStore.toggleTaskComplete(client, task); }}
|
||||||
|
selectedTaskId={taskStore.selectedTaskId}
|
||||||
|
onQuickCreate={(title) => {
|
||||||
|
if (client) {
|
||||||
|
taskStore.createTask(client, { "@type": "Task", title, progress: "needs-action", calendarIds: { [calendars[0]?.id ?? ""]: true } });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -704,7 +816,7 @@ export default function CalendarPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh bg-background overflow-hidden">
|
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
|
||||||
{/* Left Navigation Rail */}
|
{/* Left Navigation Rail */}
|
||||||
{!isMobile && (
|
{!isMobile && (
|
||||||
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
|
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
|
||||||
@@ -712,7 +824,7 @@ export default function CalendarPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
onLogout={logout}
|
||||||
onManageApps={handleManageApps}
|
onManageApps={handleManageApps}
|
||||||
onInlineApp={handleInlineApp}
|
onInlineApp={handleInlineApp}
|
||||||
onCloseInlineApp={closeInlineApp}
|
onCloseInlineApp={closeInlineApp}
|
||||||
@@ -742,6 +854,7 @@ export default function CalendarPage() {
|
|||||||
onChangeMonth={handleMiniMonthChange}
|
onChangeMonth={handleMiniMonthChange}
|
||||||
events={events}
|
events={events}
|
||||||
firstDayOfWeek={firstDayOfWeek}
|
firstDayOfWeek={firstDayOfWeek}
|
||||||
|
showWeekNumbers={showWeekNumbers}
|
||||||
/>
|
/>
|
||||||
<CalendarSidebarPanel
|
<CalendarSidebarPanel
|
||||||
calendars={calendars}
|
calendars={calendars}
|
||||||
@@ -767,7 +880,7 @@ export default function CalendarPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{!inlineApp && (
|
{!inlineApp && (
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
<div className="flex flex-col flex-1 min-w-0 min-h-0">
|
||||||
<CalendarToolbar
|
<CalendarToolbar
|
||||||
selectedDate={selectedDate}
|
selectedDate={selectedDate}
|
||||||
viewMode={normalizedViewMode}
|
viewMode={normalizedViewMode}
|
||||||
@@ -782,10 +895,12 @@ export default function CalendarPage() {
|
|||||||
calendars={calendars}
|
calendars={calendars}
|
||||||
selectedCalendarIds={selectedCalendarIds}
|
selectedCalendarIds={selectedCalendarIds}
|
||||||
onToggleVisibility={toggleCalendarVisibility}
|
onToggleVisibility={toggleCalendarVisibility}
|
||||||
|
enableCalendarTasks={enableCalendarTasks}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="flex flex-1 overflow-hidden relative"
|
className="flex flex-1 overflow-hidden relative"
|
||||||
|
data-tour="calendar-view"
|
||||||
onTouchStart={handleTouchStart}
|
onTouchStart={handleTouchStart}
|
||||||
onTouchEnd={handleTouchEnd}
|
onTouchEnd={handleTouchEnd}
|
||||||
>
|
>
|
||||||
@@ -804,13 +919,29 @@ export default function CalendarPage() {
|
|||||||
onDelete={handleDeleteEvent}
|
onDelete={handleDeleteEvent}
|
||||||
onDuplicate={handleDuplicateEvent}
|
onDuplicate={handleDuplicateEvent}
|
||||||
onRsvp={handleRsvp}
|
onRsvp={handleRsvp}
|
||||||
onClose={() => { setShowEventModal(false); setEditEvent(null); }}
|
onClose={() => { setShowEventModal(false); setEditEvent(null); setPendingPreview(null); }}
|
||||||
|
onPreviewChange={setPendingPreview}
|
||||||
currentUserEmails={currentUserEmails}
|
currentUserEmails={currentUserEmails}
|
||||||
isMobile={false}
|
isMobile={false}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Desktop task panel */}
|
||||||
|
{!isMobile && showTaskModal && (
|
||||||
|
<div className="w-[400px] border-l border-border flex-shrink-0 overflow-hidden">
|
||||||
|
<TaskModal
|
||||||
|
key={editTask?.id ?? 'new-task'}
|
||||||
|
task={editTask}
|
||||||
|
calendars={calendars}
|
||||||
|
onSave={handleSaveTask}
|
||||||
|
onDelete={handleDeleteTask}
|
||||||
|
onClose={() => { setShowTaskModal(false); setEditTask(null); }}
|
||||||
|
isMobile={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Floating Create Event Button (mobile) */}
|
{/* Floating Create Event Button (mobile) */}
|
||||||
{isMobile && (
|
{isMobile && (
|
||||||
<Button
|
<Button
|
||||||
@@ -827,13 +958,15 @@ export default function CalendarPage() {
|
|||||||
|
|
||||||
{/* Mobile Bottom Navigation */}
|
{/* Mobile Bottom Navigation */}
|
||||||
{isMobile && (
|
{isMobile && (
|
||||||
<NavigationRail
|
<div className="shrink-0">
|
||||||
orientation="horizontal"
|
<NavigationRail
|
||||||
onManageApps={handleManageApps}
|
orientation="horizontal"
|
||||||
onInlineApp={handleInlineApp}
|
onManageApps={handleManageApps}
|
||||||
onCloseInlineApp={closeInlineApp}
|
onInlineApp={handleInlineApp}
|
||||||
activeAppId={inlineApp?.id ?? null}
|
onCloseInlineApp={closeInlineApp}
|
||||||
/>
|
activeAppId={inlineApp?.id ?? null}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{detailEvent && detailAnchorRect && (
|
{detailEvent && detailAnchorRect && (
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
|
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
|
||||||
import { useRouter } from "@/i18n/navigation";
|
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { ArrowLeft, Users } from "lucide-react";
|
import { ArrowLeft, Users } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -16,7 +15,7 @@ import { ContactsSidebar, type ContactCategory } from "@/components/contacts/con
|
|||||||
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
|
import { ContactImportDialog } from "@/components/contacts/contact-import-dialog";
|
||||||
import { exportContacts } from "@/components/contacts/contact-export";
|
import { exportContacts } from "@/components/contacts/contact-export";
|
||||||
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
|
import { useContactStore, getContactDisplayName } from "@/stores/contact-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -39,7 +38,6 @@ type View =
|
|||||||
| "bulk-add-to-group";
|
| "bulk-add-to-group";
|
||||||
|
|
||||||
export default function ContactsPage() {
|
export default function ContactsPage() {
|
||||||
const router = useRouter();
|
|
||||||
const t = useTranslations("contacts");
|
const t = useTranslations("contacts");
|
||||||
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
const { client, isAuthenticated, logout, checkAuth, isLoading: authLoading } = useAuthStore();
|
||||||
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
const { showAppsModal, inlineApp, loadedApps, handleManageApps, handleInlineApp, closeInlineApp, closeAppsModal } = useSidebarApps();
|
||||||
@@ -109,9 +107,9 @@ export default function ContactsPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
||||||
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
||||||
router.push("/login");
|
redirectToLogin();
|
||||||
}
|
}
|
||||||
}, [initialCheckDone, isAuthenticated, authLoading, router]);
|
}, [initialCheckDone, isAuthenticated, authLoading]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (client && supportsSync && !hasFetched.current) {
|
if (client && supportsSync && !hasFetched.current) {
|
||||||
@@ -126,9 +124,24 @@ export default function ContactsPage() {
|
|||||||
const selectedGroup = selectedGroupId ? contacts.find(c => c.id === selectedGroupId) || null : null;
|
const selectedGroup = selectedGroupId ? contacts.find(c => c.id === selectedGroupId) || null : null;
|
||||||
const selectedGroupMembers = selectedGroupId ? getGroupMembers(selectedGroupId) : [];
|
const selectedGroupMembers = selectedGroupId ? getGroupMembers(selectedGroupId) : [];
|
||||||
|
|
||||||
|
// Collect all unique keywords across contacts
|
||||||
|
const allKeywords = useMemo(() => {
|
||||||
|
const kws = new Set<string>();
|
||||||
|
for (const contact of individuals) {
|
||||||
|
if (!contact.keywords) continue;
|
||||||
|
for (const [kw, active] of Object.entries(contact.keywords)) {
|
||||||
|
if (active) kws.add(kw);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(kws).sort((a, b) => a.localeCompare(b));
|
||||||
|
}, [individuals]);
|
||||||
|
|
||||||
// Contacts to display based on active category
|
// Contacts to display based on active category
|
||||||
const displayedContacts = useMemo(() => {
|
const displayedContacts = useMemo(() => {
|
||||||
if (activeCategory === "all") return individuals;
|
if (activeCategory === "all") return individuals;
|
||||||
|
if (activeCategory === "uncategorized") {
|
||||||
|
return individuals.filter(c => !c.keywords || Object.keys(c.keywords).filter(k => c.keywords![k]).length === 0);
|
||||||
|
}
|
||||||
if ("addressBookId" in activeCategory) {
|
if ("addressBookId" in activeCategory) {
|
||||||
const bookId = activeCategory.addressBookId;
|
const bookId = activeCategory.addressBookId;
|
||||||
return individuals.filter(c => {
|
return individuals.filter(c => {
|
||||||
@@ -146,6 +159,7 @@ export default function ContactsPage() {
|
|||||||
// Label for the current category
|
// Label for the current category
|
||||||
const categoryLabel = useMemo(() => {
|
const categoryLabel = useMemo(() => {
|
||||||
if (activeCategory === "all") return t("tabs.all");
|
if (activeCategory === "all") return t("tabs.all");
|
||||||
|
if (activeCategory === "uncategorized") return t("no_category");
|
||||||
if ("addressBookId" in activeCategory) {
|
if ("addressBookId" in activeCategory) {
|
||||||
const book = addressBooks.find(b => b.id === activeCategory.addressBookId);
|
const book = addressBooks.find(b => b.id === activeCategory.addressBookId);
|
||||||
return book?.name || t("tabs.all");
|
return book?.name || t("tabs.all");
|
||||||
@@ -182,6 +196,31 @@ export default function ContactsPage() {
|
|||||||
}
|
}
|
||||||
}, [client, moveContactToAddressBook, t]);
|
}, [client, moveContactToAddressBook, t]);
|
||||||
|
|
||||||
|
const handleDropContactsToCategory = useCallback(async (contactIds: string[], keyword: string) => {
|
||||||
|
if (!client && supportsSync) return;
|
||||||
|
try {
|
||||||
|
for (const contactId of contactIds) {
|
||||||
|
const contact = contacts.find(c => c.id === contactId);
|
||||||
|
if (!contact) continue;
|
||||||
|
const existingKeywords = contact.keywords || {};
|
||||||
|
if (existingKeywords[keyword]) continue; // already has this keyword
|
||||||
|
const updatedKeywords = { ...existingKeywords, [keyword]: true };
|
||||||
|
if (supportsSync && client) {
|
||||||
|
await updateContact(client, contactId, { keywords: updatedKeywords });
|
||||||
|
} else {
|
||||||
|
updateLocalContact(contactId, { keywords: updatedKeywords });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const msg = contactIds.length === 1
|
||||||
|
? t("category_added", { name: keyword })
|
||||||
|
: t("category_added_plural", { count: contactIds.length, name: keyword });
|
||||||
|
toast.success(msg);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to add contacts to category:', error);
|
||||||
|
toast.error(t("toast.error_update"));
|
||||||
|
}
|
||||||
|
}, [client, supportsSync, contacts, updateContact, updateLocalContact, t]);
|
||||||
|
|
||||||
const handleImportContacts = useCallback(async (importedContacts: ContactCard[]) => {
|
const handleImportContacts = useCallback(async (importedContacts: ContactCard[]) => {
|
||||||
return importContacts(
|
return importContacts(
|
||||||
supportsSync && client ? client : null,
|
supportsSync && client ? client : null,
|
||||||
@@ -430,7 +469,7 @@ export default function ContactsPage() {
|
|||||||
const renderRightPanel = () => {
|
const renderRightPanel = () => {
|
||||||
switch (view) {
|
switch (view) {
|
||||||
case "create":
|
case "create":
|
||||||
return <ContactForm addressBooks={addressBooks} onSave={handleSaveNew} onCancel={handleCancel} />;
|
return <ContactForm addressBooks={addressBooks} allKeywords={allKeywords} onSave={handleSaveNew} onCancel={handleCancel} />;
|
||||||
|
|
||||||
case "edit":
|
case "edit":
|
||||||
if (!selectedContact) return null;
|
if (!selectedContact) return null;
|
||||||
@@ -438,6 +477,7 @@ export default function ContactsPage() {
|
|||||||
<ContactForm
|
<ContactForm
|
||||||
contact={selectedContact}
|
contact={selectedContact}
|
||||||
addressBooks={addressBooks}
|
addressBooks={addressBooks}
|
||||||
|
allKeywords={allKeywords}
|
||||||
onSave={handleSaveEdit}
|
onSave={handleSaveEdit}
|
||||||
onCancel={handleCancel}
|
onCancel={handleCancel}
|
||||||
/>
|
/>
|
||||||
@@ -544,7 +584,7 @@ export default function ContactsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh bg-background overflow-hidden">
|
<div className={cn("flex h-dvh bg-background overflow-hidden", isMobile && "flex-col")}>
|
||||||
{/* Navigation Rail - desktop only */}
|
{/* Navigation Rail - desktop only */}
|
||||||
{!isMobile && (
|
{!isMobile && (
|
||||||
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
|
<div className="w-14 bg-secondary flex flex-col flex-shrink-0" style={{ borderRight: '1px solid rgba(128, 128, 128, 0.3)' }}>
|
||||||
@@ -552,7 +592,7 @@ export default function ContactsPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
onLogout={logout}
|
||||||
onManageApps={handleManageApps}
|
onManageApps={handleManageApps}
|
||||||
onInlineApp={handleInlineApp}
|
onInlineApp={handleInlineApp}
|
||||||
onCloseInlineApp={closeInlineApp}
|
onCloseInlineApp={closeInlineApp}
|
||||||
@@ -590,6 +630,7 @@ export default function ContactsPage() {
|
|||||||
onEditGroup={handleEditGroupFromSidebar}
|
onEditGroup={handleEditGroupFromSidebar}
|
||||||
onDeleteGroup={handleDeleteGroupFromSidebar}
|
onDeleteGroup={handleDeleteGroupFromSidebar}
|
||||||
onDropContacts={handleDropContacts}
|
onDropContacts={handleDropContacts}
|
||||||
|
onDropContactsToCategory={handleDropContactsToCategory}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<ResizeHandle
|
<ResizeHandle
|
||||||
@@ -606,6 +647,7 @@ export default function ContactsPage() {
|
|||||||
|
|
||||||
{/* Panel 2: Contact list */}
|
{/* Panel 2: Contact list */}
|
||||||
<div
|
<div
|
||||||
|
data-tour="contacts-list"
|
||||||
className={cn(
|
className={cn(
|
||||||
"border-r border-border bg-background flex flex-col flex-shrink-0",
|
"border-r border-border bg-background flex flex-col flex-shrink-0",
|
||||||
isMobile ? "w-full" : "",
|
isMobile ? "w-full" : "",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { ArrowLeft } from "lucide-react";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
|
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
|
||||||
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
|
import { useConfirmDialog } from "@/hooks/use-confirm-dialog";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { useFileStore } from "@/stores/file-store";
|
import { useFileStore } from "@/stores/file-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
@@ -112,9 +112,9 @@ export default function FilesPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
||||||
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
||||||
router.push("/login");
|
redirectToLogin();
|
||||||
}
|
}
|
||||||
}, [initialCheckDone, isAuthenticated, authLoading, router]);
|
}, [initialCheckDone, isAuthenticated, authLoading]);
|
||||||
|
|
||||||
// Initialize JMAP files client
|
// Initialize JMAP files client
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -357,7 +357,7 @@ export default function FilesPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
onLogout={logout}
|
||||||
onManageApps={handleManageApps}
|
onManageApps={handleManageApps}
|
||||||
onInlineApp={handleInlineApp}
|
onInlineApp={handleInlineApp}
|
||||||
onCloseInlineApp={closeInlineApp}
|
onCloseInlineApp={closeInlineApp}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { notFound } from "next/navigation";
|
|||||||
import { IntlProvider } from "@/components/providers/intl-provider";
|
import { IntlProvider } from "@/components/providers/intl-provider";
|
||||||
import { ThemeProvider } from "@/components/providers/theme-provider";
|
import { ThemeProvider } from "@/components/providers/theme-provider";
|
||||||
import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider";
|
import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider";
|
||||||
|
import { EmbeddedBridgeProvider } from "@/components/providers/embedded-bridge-provider";
|
||||||
|
import { TourProvider } from "@/components/tour/tour-provider";
|
||||||
import { locales } from "@/i18n/routing";
|
import { locales } from "@/i18n/routing";
|
||||||
|
|
||||||
export default async function LocaleLayout({
|
export default async function LocaleLayout({
|
||||||
@@ -26,7 +28,11 @@ export default async function LocaleLayout({
|
|||||||
<IntlProvider locale={locale} messages={messages}>
|
<IntlProvider locale={locale} messages={messages}>
|
||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<CalendarAlertProvider>
|
<CalendarAlertProvider>
|
||||||
{children}
|
<EmbeddedBridgeProvider>
|
||||||
|
<TourProvider>
|
||||||
|
{children}
|
||||||
|
</TourProvider>
|
||||||
|
</EmbeddedBridgeProvider>
|
||||||
</CalendarAlertProvider>
|
</CalendarAlertProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</IntlProvider>
|
</IntlProvider>
|
||||||
|
|||||||
+249
-5
@@ -11,12 +11,12 @@ import { useThemeStore } from "@/stores/theme-store";
|
|||||||
import { useShallow } from "zustand/react/shallow";
|
import { useShallow } from "zustand/react/shallow";
|
||||||
import { useConfig } from "@/hooks/use-config";
|
import { useConfig } from "@/hooks/use-config";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Mail, AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield } from "lucide-react";
|
import { Mail, AlertCircle, Loader2, X, Info, Eye, EyeOff, LogIn, Sun, Moon, Monitor, Check, Shield, Play } from "lucide-react";
|
||||||
import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
|
import { discoverOAuth, type OAuthMetadata } from "@/lib/oauth/discovery";
|
||||||
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
|
import { generateCodeVerifier, generateCodeChallenge, generateState } from "@/lib/oauth/pkce";
|
||||||
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
|
import { OAUTH_SCOPES } from "@/lib/oauth/tokens";
|
||||||
|
|
||||||
const APP_VERSION = "1.4.3";
|
const APP_VERSION = "1.4.7";
|
||||||
|
|
||||||
const THEME_OPTIONS = [
|
const THEME_OPTIONS = [
|
||||||
{ value: "light" as const, icon: Sun, label: "Light" },
|
{ value: "light" as const, icon: Sun, label: "Light" },
|
||||||
@@ -30,9 +30,9 @@ export default function LoginPage() {
|
|||||||
const params = useParams();
|
const params = useParams();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const isAddAccountMode = searchParams.get("mode") === "add-account";
|
const isAddAccountMode = searchParams.get("mode") === "add-account";
|
||||||
const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore();
|
const { login, loginDemo, isLoading, error, clearError, isAuthenticated } = useAuthStore();
|
||||||
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
|
const { theme, setTheme, initializeTheme } = useThemeStore(useShallow((s) => ({ theme: s.theme, setTheme: s.setTheme, initializeTheme: s.initializeTheme })));
|
||||||
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError } = useConfig();
|
const { appName, jmapServerUrl: serverUrl, oauthEnabled, oauthOnly, oauthClientId, oauthIssuerUrl, rememberMeEnabled, devMode, demoMode, loginLogoLightUrl, loginLogoDarkUrl, loginCompanyName, loginImprintUrl, loginPrivacyPolicyUrl, loginWebsiteUrl, isLoading: configLoading, error: configError, autoSsoEnabled, embeddedMode: _embeddedMode } = useConfig();
|
||||||
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
|
const resolvedTheme = useThemeStore((s) => s.resolvedTheme);
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -54,6 +54,7 @@ export default function LoginPage() {
|
|||||||
const [oauthMetadata, setOauthMetadata] = useState<OAuthMetadata | null>(null);
|
const [oauthMetadata, setOauthMetadata] = useState<OAuthMetadata | null>(null);
|
||||||
const [oauthDiscoveryDone, setOauthDiscoveryDone] = useState(false);
|
const [oauthDiscoveryDone, setOauthDiscoveryDone] = useState(false);
|
||||||
const [oauthLoading, setOauthLoading] = useState(false);
|
const [oauthLoading, setOauthLoading] = useState(false);
|
||||||
|
const [demoLoading, setDemoLoading] = useState(false);
|
||||||
|
|
||||||
const suggestionsRef = useRef<HTMLDivElement>(null);
|
const suggestionsRef = useRef<HTMLDivElement>(null);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -172,6 +173,63 @@ export default function LoginPage() {
|
|||||||
});
|
});
|
||||||
}, [oauthEnabled, serverUrl, oauthIssuerUrl]);
|
}, [oauthEnabled, serverUrl, oauthIssuerUrl]);
|
||||||
|
|
||||||
|
// Auto-SSO: when enabled with OAUTH_ONLY, skip the login page entirely
|
||||||
|
const ssoError = searchParams.get("sso_error");
|
||||||
|
const autoSsoTriggered = useRef(false);
|
||||||
|
|
||||||
|
const startServerSideSso = useCallback(async () => {
|
||||||
|
setOauthLoading(true);
|
||||||
|
try {
|
||||||
|
const redirectUri = `${window.location.origin}/${params.locale}/auth/callback`;
|
||||||
|
const res = await fetch('/api/auth/sso/start', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'include',
|
||||||
|
body: JSON.stringify({ redirect_uri: redirectUri, locale: params.locale }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
setOauthLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { authorize_url } = await res.json();
|
||||||
|
|
||||||
|
// Navigate to the authorize URL
|
||||||
|
const isIframe = (() => { try { return window.self !== window.top; } catch { return true; } })();
|
||||||
|
if (isIframe) {
|
||||||
|
// In an iframe, try top-level navigation
|
||||||
|
try {
|
||||||
|
window.top!.location.href = authorize_url;
|
||||||
|
} catch {
|
||||||
|
// Cross-origin restriction — fall back to current frame
|
||||||
|
window.location.href = authorize_url;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
window.location.href = authorize_url;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setOauthLoading(false);
|
||||||
|
}
|
||||||
|
}, [params.locale]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!autoSsoEnabled || !oauthOnly || !oauthDiscoveryDone || !oauthMetadata) return;
|
||||||
|
if (ssoError || isAddAccountMode || isAuthenticated) return;
|
||||||
|
if (autoSsoTriggered.current) return;
|
||||||
|
|
||||||
|
// Guard against redirect loops
|
||||||
|
try {
|
||||||
|
if (sessionStorage.getItem("sso_attempted")) return;
|
||||||
|
sessionStorage.setItem("sso_attempted", "1");
|
||||||
|
// Clear the flag after 30 seconds so retries are possible
|
||||||
|
setTimeout(() => { try { sessionStorage.removeItem("sso_attempted"); } catch { /* ignore */ } }, 30000);
|
||||||
|
} catch { /* sessionStorage unavailable */ }
|
||||||
|
|
||||||
|
autoSsoTriggered.current = true;
|
||||||
|
startServerSideSso();
|
||||||
|
}, [autoSsoEnabled, oauthOnly, oauthDiscoveryDone, oauthMetadata, ssoError, isAddAccountMode, isAuthenticated, startServerSideSso]);
|
||||||
|
|
||||||
const handleThemeSelect = useCallback((newTheme: "light" | "dark" | "system") => {
|
const handleThemeSelect = useCallback((newTheme: "light" | "dark" | "system") => {
|
||||||
setTheme(newTheme);
|
setTheme(newTheme);
|
||||||
setShowThemeMenu(false);
|
setShowThemeMenu(false);
|
||||||
@@ -206,7 +264,7 @@ export default function LoginPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!serverUrl) {
|
if (!serverUrl && !demoMode) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/30">
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/30">
|
||||||
<div className="w-full max-w-md mx-auto px-4 text-center">
|
<div className="w-full max-w-md mx-auto px-4 text-center">
|
||||||
@@ -353,9 +411,167 @@ export default function LoginPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleDemoLogin = async () => {
|
||||||
|
setDemoLoading(true);
|
||||||
|
const success = await loginDemo();
|
||||||
|
if (success) {
|
||||||
|
router.push('/');
|
||||||
|
}
|
||||||
|
setDemoLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
const currentThemeOption = THEME_OPTIONS.find(o => o.value === theme) || THEME_OPTIONS[2];
|
const currentThemeOption = THEME_OPTIONS.find(o => o.value === theme) || THEME_OPTIONS[2];
|
||||||
const CurrentThemeIcon = currentThemeOption.icon;
|
const CurrentThemeIcon = currentThemeOption.icon;
|
||||||
|
|
||||||
|
// Demo-only mode: show only a large demo login button
|
||||||
|
if (demoMode && !isAddAccountMode) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4">
|
||||||
|
{/* Theme toggle */}
|
||||||
|
<div className="absolute top-5 right-5" ref={themeMenuRef} suppressHydrationWarning>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowThemeMenu(!showThemeMenu)}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-3 py-2 rounded-xl border text-sm transition-all duration-200",
|
||||||
|
showThemeMenu
|
||||||
|
? "bg-secondary border-border text-foreground shadow-md"
|
||||||
|
: "bg-background/60 backdrop-blur-sm border-border/50 text-muted-foreground hover:text-foreground hover:bg-secondary/80 hover:border-border"
|
||||||
|
)}
|
||||||
|
aria-label={`Theme: ${currentThemeOption.label}`}
|
||||||
|
aria-expanded={showThemeMenu}
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
>
|
||||||
|
<CurrentThemeIcon className="w-4 h-4" />
|
||||||
|
<span className="hidden sm:inline" suppressHydrationWarning>{currentThemeOption.label}</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{showThemeMenu && (
|
||||||
|
<div
|
||||||
|
className="absolute right-0 top-full mt-2 w-40 rounded-xl border border-border bg-background shadow-lg overflow-hidden animate-fade-in z-50"
|
||||||
|
role="listbox"
|
||||||
|
aria-label="Theme selection"
|
||||||
|
>
|
||||||
|
{THEME_OPTIONS.map((option) => {
|
||||||
|
const Icon = option.icon;
|
||||||
|
const isActive = theme === option.value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={option.value}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
aria-selected={isActive}
|
||||||
|
onClick={() => handleThemeSelect(option.value)}
|
||||||
|
className={cn(
|
||||||
|
"w-full flex items-center gap-3 px-3.5 py-2.5 text-sm transition-colors",
|
||||||
|
isActive
|
||||||
|
? "bg-primary/10 text-foreground font-medium"
|
||||||
|
: "text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="w-4 h-4" />
|
||||||
|
<span className="flex-1 text-left">{option.label}</span>
|
||||||
|
{isActive && <Check className="w-3.5 h-3.5 text-primary" />}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full max-w-[440px] mx-auto">
|
||||||
|
<div className="rounded-2xl border border-border/60 bg-background/80 backdrop-blur-sm shadow-xl shadow-black/5 dark:shadow-black/20 overflow-hidden">
|
||||||
|
{/* Header with logo */}
|
||||||
|
<div className="px-8 pt-12 pb-4 text-center">
|
||||||
|
<div className="inline-flex items-center justify-center w-20 h-20 mb-6">
|
||||||
|
<img
|
||||||
|
src={resolvedTheme === 'dark' ? loginLogoDarkUrl : loginLogoLightUrl}
|
||||||
|
alt={appName}
|
||||||
|
className="max-w-20 max-h-20 object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<h1 className="text-3xl font-bold text-foreground tracking-tight">
|
||||||
|
{appName}
|
||||||
|
</h1>
|
||||||
|
<p className="text-base text-muted-foreground mt-2 max-w-xs mx-auto leading-relaxed">
|
||||||
|
{t("demo_tagline")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Large demo button */}
|
||||||
|
<div className="px-8 pb-10 pt-4">
|
||||||
|
{error && (
|
||||||
|
<div className={cn(
|
||||||
|
"mb-5 p-3.5 bg-red-500/10 border border-red-500/20 rounded-xl flex items-start gap-3",
|
||||||
|
shakeError && "animate-shake"
|
||||||
|
)}>
|
||||||
|
<AlertCircle className="w-4.5 h-4.5 text-red-500 flex-shrink-0 mt-0.5" />
|
||||||
|
<p className="text-sm text-red-600 dark:text-red-400 leading-relaxed">
|
||||||
|
{t(`error.${error}`) || t("error.generic")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="w-full h-14 font-semibold text-lg bg-primary hover:bg-primary/90 transition-all duration-200 rounded-xl shadow-lg shadow-primary/25 hover:shadow-xl hover:shadow-primary/30 hover:scale-[1.02] active:scale-[0.98]"
|
||||||
|
onClick={handleDemoLogin}
|
||||||
|
disabled={demoLoading || isLoading}
|
||||||
|
>
|
||||||
|
{demoLoading ? (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Loader2 className="w-5 h-5 animate-spin" />
|
||||||
|
{t("demo_launching")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Play className="w-5 h-5" />
|
||||||
|
{t("demo_login_button")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<p className="text-center text-sm text-muted-foreground mt-4 leading-relaxed">
|
||||||
|
{t("demo_no_signup")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer */}
|
||||||
|
<div className="mt-6 flex flex-col items-center gap-2">
|
||||||
|
{loginCompanyName && (
|
||||||
|
<p className="text-center text-xs text-muted-foreground/60 font-medium">
|
||||||
|
{loginCompanyName}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{(loginImprintUrl || loginPrivacyPolicyUrl || loginWebsiteUrl) && (
|
||||||
|
<div className="flex items-center gap-3 flex-wrap justify-center">
|
||||||
|
{loginWebsiteUrl && (
|
||||||
|
<a href={loginWebsiteUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
|
||||||
|
{t("website")}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{loginImprintUrl && (
|
||||||
|
<a href={loginImprintUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
|
||||||
|
{t("imprint")}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{loginPrivacyPolicyUrl && (
|
||||||
|
<a href={loginPrivacyPolicyUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground/50 hover:text-muted-foreground transition-colors">
|
||||||
|
{t("privacy_policy")}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="text-center text-xs text-muted-foreground/40">
|
||||||
|
v{APP_VERSION}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4">
|
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-background via-muted/10 to-muted/30 relative px-4">
|
||||||
{/* Theme toggle - top right, dropdown style */}
|
{/* Theme toggle - top right, dropdown style */}
|
||||||
@@ -747,6 +963,34 @@ export default function LoginPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Demo Mode Button */}
|
||||||
|
{demoMode && !isAddAccountMode && (
|
||||||
|
<div className="mt-4 pt-4 border-t border-border/40">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="w-full h-11 font-medium text-[15px] rounded-xl border-border/60 hover:bg-muted/50"
|
||||||
|
onClick={handleDemoLogin}
|
||||||
|
disabled={demoLoading || isLoading}
|
||||||
|
>
|
||||||
|
{demoLoading ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
|
{t("demo_launching")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Play className="w-4 h-4" />
|
||||||
|
{t("try_demo")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<p className="text-center text-xs text-muted-foreground mt-2">
|
||||||
|
{t("demo_description")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+40
-16
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
|
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
|
||||||
import { useRouter } from "@/i18n/navigation";
|
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Sidebar } from "@/components/layout/sidebar";
|
import { Sidebar } from "@/components/layout/sidebar";
|
||||||
import { EmailList } from "@/components/email/email-list";
|
import { EmailList } from "@/components/email/email-list";
|
||||||
@@ -13,7 +12,7 @@ import { MobileHeader, MobileViewerHeader } from "@/components/layout/mobile-hea
|
|||||||
import { ThreadGroup, Email } from "@/lib/jmap/types";
|
import { ThreadGroup, Email } from "@/lib/jmap/types";
|
||||||
import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
|
import { KeyboardShortcutsModal } from "@/components/keyboard-shortcuts-modal";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore, redirectToLogin } from "@/stores/auth-store";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { useIdentityStore } from "@/stores/identity-store";
|
import { useIdentityStore } from "@/stores/identity-store";
|
||||||
import { useUIStore } from "@/stores/ui-store";
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
@@ -48,7 +47,6 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { useConfig } from "@/hooks/use-config";
|
import { useConfig } from "@/hooks/use-config";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const router = useRouter();
|
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const tCommon = useTranslations('common');
|
const tCommon = useTranslations('common');
|
||||||
const { appName } = useConfig();
|
const { appName } = useConfig();
|
||||||
@@ -285,9 +283,9 @@ export default function Home() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
||||||
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
||||||
router.push('/login');
|
redirectToLogin();
|
||||||
}
|
}
|
||||||
}, [initialCheckDone, isAuthenticated, authLoading, router]);
|
}, [initialCheckDone, isAuthenticated, authLoading]);
|
||||||
|
|
||||||
// Load mailboxes and emails when authenticated (only if not already loaded)
|
// Load mailboxes and emails when authenticated (only if not already loaded)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -409,7 +407,10 @@ export default function Home() {
|
|||||||
// Handle new email notifications - play sound
|
// Handle new email notifications - play sound
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (newEmailNotification) {
|
if (newEmailNotification) {
|
||||||
playNotificationSound();
|
const { emailNotificationsEnabled, emailNotificationSound, notificationSoundChoice } = useSettingsStore.getState();
|
||||||
|
if (emailNotificationsEnabled && emailNotificationSound) {
|
||||||
|
playNotificationSound(notificationSoundChoice);
|
||||||
|
}
|
||||||
debug.log('New email received:', newEmailNotification.subject);
|
debug.log('New email received:', newEmailNotification.subject);
|
||||||
clearNewEmailNotification();
|
clearNewEmailNotification();
|
||||||
}
|
}
|
||||||
@@ -443,9 +444,27 @@ export default function Home() {
|
|||||||
if (!client) return;
|
if (!client) return;
|
||||||
|
|
||||||
try {
|
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);
|
await sendEmail(client, data.to, data.subject, data.body, data.cc, data.bcc, data.identityId, data.fromEmail, data.draftId, data.fromName, data.htmlBody, data.attachments);
|
||||||
setShowComposer(false);
|
setShowComposer(false);
|
||||||
|
|
||||||
|
// Mark the original email with $answered or $forwarded keyword
|
||||||
|
if (originalEmailId && (effectiveMode === 'reply' || effectiveMode === 'replyAll')) {
|
||||||
|
try {
|
||||||
|
await client.setKeyword(originalEmailId, '$answered');
|
||||||
|
} catch (e) {
|
||||||
|
debug.error('Failed to set $answered keyword:', e);
|
||||||
|
}
|
||||||
|
} else if (originalEmailId && effectiveMode === 'forward') {
|
||||||
|
try {
|
||||||
|
await client.setKeyword(originalEmailId, '$forwarded');
|
||||||
|
} catch (e) {
|
||||||
|
debug.error('Failed to set $forwarded keyword:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Refresh the current mailbox to update the UI
|
// Refresh the current mailbox to update the UI
|
||||||
await fetchEmails(client, selectedMailbox);
|
await fetchEmails(client, selectedMailbox);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -768,12 +787,7 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = logout;
|
||||||
logout();
|
|
||||||
if (!useAuthStore.getState().isAuthenticated) {
|
|
||||||
router.push('/login');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSearch = async (query: string) => {
|
const handleSearch = async (query: string) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
@@ -816,13 +830,13 @@ export default function Home() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleDownloadAttachment = async (blobId: string, name: string, type?: string) => {
|
const handleDownloadAttachment = async (blobId: string, name: string, type?: string, forceDownload?: boolean) => {
|
||||||
if (!client) return;
|
if (!client) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { mailAttachmentAction } = useSettingsStore.getState();
|
const { mailAttachmentAction } = useSettingsStore.getState();
|
||||||
|
|
||||||
if (mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) {
|
if (!forceDownload && mailAttachmentAction === 'preview' && isFilePreviewable(name, type)) {
|
||||||
setPreviewAttachment({ blobId, name, type });
|
setPreviewAttachment({ blobId, name, type });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -865,6 +879,8 @@ export default function Home() {
|
|||||||
// Append signature from the primary identity
|
// Append signature from the primary identity
|
||||||
const finalBody = appendPlainTextSignature(body, primaryIdentity);
|
const finalBody = appendPlainTextSignature(body, primaryIdentity);
|
||||||
|
|
||||||
|
const originalEmailId = selectedEmail.id;
|
||||||
|
|
||||||
// Send reply with just the body text
|
// Send reply with just the body text
|
||||||
await sendEmail(
|
await sendEmail(
|
||||||
client,
|
client,
|
||||||
@@ -879,6 +895,13 @@ export default function Home() {
|
|||||||
primaryIdentity?.name || undefined
|
primaryIdentity?.name || undefined
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Mark the original email as answered
|
||||||
|
try {
|
||||||
|
await client.setKeyword(originalEmailId, '$answered');
|
||||||
|
} catch (e) {
|
||||||
|
debug.error('Failed to set $answered keyword:', e);
|
||||||
|
}
|
||||||
|
|
||||||
// Refresh emails to show the sent reply
|
// Refresh emails to show the sent reply
|
||||||
await fetchEmails(client, selectedMailbox);
|
await fetchEmails(client, selectedMailbox);
|
||||||
};
|
};
|
||||||
@@ -1174,6 +1197,7 @@ export default function Home() {
|
|||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
className={cn("pl-9 h-9", searchQuery && "pr-8")}
|
className={cn("pl-9 h-9", searchQuery && "pr-8")}
|
||||||
data-search-input
|
data-search-input
|
||||||
|
data-tour="search-input"
|
||||||
/>
|
/>
|
||||||
{searchQuery && (
|
{searchQuery && (
|
||||||
<button
|
<button
|
||||||
@@ -1579,8 +1603,8 @@ export default function Home() {
|
|||||||
onNavigatePrev={handleNavigatePrev}
|
onNavigatePrev={handleNavigatePrev}
|
||||||
onShowShortcuts={() => setShowShortcutsModal(true)}
|
onShowShortcuts={() => setShowShortcutsModal(true)}
|
||||||
onEditDraft={handleEditDraft}
|
onEditDraft={handleEditDraft}
|
||||||
currentUserEmail={client?.["username"]}
|
currentUserEmail={client?.getUsername()}
|
||||||
currentUserName={client?.["username"]?.split("@")[0]}
|
currentUserName={client?.getUsername()?.split("@")[0]}
|
||||||
currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role}
|
currentMailboxRole={mailboxes.find(m => m.id === selectedMailbox)?.role}
|
||||||
mailboxes={mailboxes}
|
mailboxes={mailboxes}
|
||||||
selectedMailbox={selectedMailbox}
|
selectedMailbox={selectedMailbox}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
BookUser,
|
BookUser,
|
||||||
KeyRound,
|
KeyRound,
|
||||||
PanelLeftClose,
|
PanelLeftClose,
|
||||||
|
Bell,
|
||||||
type LucideIcon,
|
type LucideIcon,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
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 { ContactsSettings } from '@/components/settings/contacts-settings';
|
||||||
import { SmimeSettings } from '@/components/settings/smime-settings';
|
import { SmimeSettings } from '@/components/settings/smime-settings';
|
||||||
import { SidebarAppsSettings } from '@/components/settings/sidebar-apps-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 { useEmailStore } from '@/stores/email-store';
|
||||||
import { useIsDesktop } from '@/hooks/use-media-query';
|
import { useIsDesktop } from '@/hooks/use-media-query';
|
||||||
import { NavigationRail } from '@/components/layout/navigation-rail';
|
import { NavigationRail } from '@/components/layout/navigation-rail';
|
||||||
@@ -55,7 +57,7 @@ import { ResizeHandle } from '@/components/layout/resize-handle';
|
|||||||
import { useConfig } from '@/hooks/use-config';
|
import { useConfig } from '@/hooks/use-config';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
type Tab = 'appearance' | 'email' | 'account' | 'security' | 'identities' | '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';
|
type TabGroup = 'general' | 'account' | 'organization' | 'apps' | 'system';
|
||||||
|
|
||||||
interface TabDef {
|
interface TabDef {
|
||||||
@@ -68,6 +70,7 @@ interface TabDef {
|
|||||||
const tabIcons: Record<Tab, LucideIcon> = {
|
const tabIcons: Record<Tab, LucideIcon> = {
|
||||||
appearance: Palette,
|
appearance: Palette,
|
||||||
email: Mail,
|
email: Mail,
|
||||||
|
notifications: Bell,
|
||||||
account: User,
|
account: User,
|
||||||
security: Shield,
|
security: Shield,
|
||||||
identities: UserPen,
|
identities: UserPen,
|
||||||
@@ -122,9 +125,9 @@ export default function SettingsPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
if (initialCheckDone && !isAuthenticated && !authLoading) {
|
||||||
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
try { sessionStorage.setItem('redirect_after_login', window.location.pathname); } catch { /* ignore */ }
|
||||||
router.push('/login');
|
redirectToLogin();
|
||||||
}
|
}
|
||||||
}, [initialCheckDone, isAuthenticated, authLoading, router]);
|
}, [initialCheckDone, isAuthenticated, authLoading]);
|
||||||
|
|
||||||
if (!isAuthenticated) {
|
if (!isAuthenticated) {
|
||||||
return null;
|
return null;
|
||||||
@@ -138,6 +141,7 @@ export default function SettingsPage() {
|
|||||||
const tabs: TabDef[] = [
|
const tabs: TabDef[] = [
|
||||||
{ id: 'appearance', label: t('tabs.appearance'), icon: tabIcons.appearance, group: 'general' },
|
{ id: 'appearance', label: t('tabs.appearance'), icon: tabIcons.appearance, group: 'general' },
|
||||||
{ id: 'email', label: t('tabs.email'), icon: tabIcons.email, group: 'general' },
|
{ id: 'email', label: t('tabs.email'), icon: tabIcons.email, group: 'general' },
|
||||||
|
{ id: 'notifications', label: t('tabs.notifications'), icon: tabIcons.notifications, group: 'general' },
|
||||||
{ id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' },
|
{ id: 'account', label: t('tabs.account'), icon: tabIcons.account, group: 'account' },
|
||||||
...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []),
|
...(stalwartFeaturesEnabled ? [{ id: 'security' as Tab, label: t('tabs.security'), icon: tabIcons.security, group: 'account' as TabGroup }] : []),
|
||||||
{ id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' },
|
{ id: 'identities', label: t('tabs.identities'), icon: tabIcons.identities, group: 'account' },
|
||||||
@@ -177,6 +181,7 @@ export default function SettingsPage() {
|
|||||||
<>
|
<>
|
||||||
{activeTab === 'appearance' && <AppearanceSettings />}
|
{activeTab === 'appearance' && <AppearanceSettings />}
|
||||||
{activeTab === 'email' && <EmailSettings />}
|
{activeTab === 'email' && <EmailSettings />}
|
||||||
|
{activeTab === 'notifications' && <NotificationSettings />}
|
||||||
{activeTab === 'account' && <AccountSettings />}
|
{activeTab === 'account' && <AccountSettings />}
|
||||||
{activeTab === 'security' && <AccountSecuritySettings />}
|
{activeTab === 'security' && <AccountSecuritySettings />}
|
||||||
{activeTab === 'identities' && <IdentitySettings />}
|
{activeTab === 'identities' && <IdentitySettings />}
|
||||||
@@ -286,7 +291,7 @@ export default function SettingsPage() {
|
|||||||
{/* Logout */}
|
{/* Logout */}
|
||||||
<div className="border-t border-border px-5 py-3">
|
<div className="border-t border-border px-5 py-3">
|
||||||
<button
|
<button
|
||||||
onClick={() => { logout(); 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"
|
className="w-full flex items-center gap-3 py-2.5 text-sm text-destructive hover:bg-muted rounded-md px-2 transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<LogOut className="w-4 h-4" />
|
<LogOut className="w-4 h-4" />
|
||||||
@@ -317,7 +322,7 @@ export default function SettingsPage() {
|
|||||||
collapsed
|
collapsed
|
||||||
quota={quota}
|
quota={quota}
|
||||||
isPushConnected={isPushConnected}
|
isPushConnected={isPushConnected}
|
||||||
onLogout={() => { logout(); if (!useAuthStore.getState().isAuthenticated) router.push('/login'); }}
|
onLogout={logout}
|
||||||
onManageApps={handleManageApps}
|
onManageApps={handleManageApps}
|
||||||
onInlineApp={handleInlineApp}
|
onInlineApp={handleInlineApp}
|
||||||
onCloseInlineApp={closeInlineApp}
|
onCloseInlineApp={closeInlineApp}
|
||||||
@@ -352,7 +357,7 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="flex-1 overflow-y-auto py-2">
|
<div className="flex-1 overflow-y-auto py-2" data-tour="settings-tabs">
|
||||||
<div className="px-2 space-y-0.5">
|
<div className="px-2 space-y-0.5">
|
||||||
{groupedTabs.map((group, groupIndex) => (
|
{groupedTabs.map((group, groupIndex) => (
|
||||||
<div key={group.group}>
|
<div key={group.group}>
|
||||||
|
|||||||
@@ -3,12 +3,10 @@ import { cookies } from 'next/headers';
|
|||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
|
import { encryptSession, decryptSession } from '@/lib/auth/crypto';
|
||||||
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
|
import { SESSION_COOKIE_MAX_AGE, sessionCookieName } from '@/lib/auth/session-cookie';
|
||||||
|
import { getCookieOptions } from '@/lib/oauth/cookie-config';
|
||||||
|
|
||||||
const COOKIE_OPTIONS = {
|
const COOKIE_OPTIONS = {
|
||||||
httpOnly: true,
|
...getCookieOptions(),
|
||||||
secure: process.env.NODE_ENV === 'production',
|
|
||||||
sameSite: 'lax' as const,
|
|
||||||
path: '/',
|
|
||||||
maxAge: SESSION_COOKIE_MAX_AGE,
|
maxAge: SESSION_COOKIE_MAX_AGE,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,9 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
import { discoverOAuth } from '@/lib/oauth/discovery';
|
|
||||||
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
|
import { refreshTokenCookieName } from '@/lib/oauth/tokens';
|
||||||
|
import { exchangeCodeForTokens, buildOAuthParams, getMetadata, getTokenEndpoint } from '@/lib/oauth/token-exchange';
|
||||||
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
|
import { getCookieOptions } from '@/lib/oauth/cookie-config';
|
||||||
|
|
||||||
const COOKIE_OPTIONS = {
|
|
||||||
httpOnly: true,
|
|
||||||
secure: process.env.NODE_ENV === 'production',
|
|
||||||
sameSite: 'lax' as const,
|
|
||||||
path: '/',
|
|
||||||
maxAge: 30 * 24 * 60 * 60,
|
|
||||||
};
|
|
||||||
|
|
||||||
function getSlot(request: NextRequest): number {
|
function getSlot(request: NextRequest): number {
|
||||||
const raw = request.nextUrl.searchParams.get('slot');
|
const raw = request.nextUrl.searchParams.get('slot');
|
||||||
@@ -22,44 +13,6 @@ function getSlot(request: NextRequest): number {
|
|||||||
return slot;
|
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) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const { code, code_verifier, redirect_uri, slot: bodySlot } = await request.json();
|
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 slot = typeof bodySlot === 'number' && bodySlot >= 0 && bodySlot <= 4 ? bodySlot : getSlot(request);
|
||||||
const tokenEndpoint = await getTokenEndpoint();
|
|
||||||
|
|
||||||
const params = buildOAuthParams({
|
const tokens = await exchangeCodeForTokens(code, code_verifier, redirect_uri);
|
||||||
grant_type: 'authorization_code',
|
|
||||||
code,
|
|
||||||
redirect_uri,
|
|
||||||
code_verifier,
|
|
||||||
});
|
|
||||||
|
|
||||||
const tokenResponse = await fetch(tokenEndpoint, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
||||||
body: params.toString(),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!tokenResponse.ok) {
|
|
||||||
const errorText = await tokenResponse.text();
|
|
||||||
logger.error('Token exchange failed', { status: tokenResponse.status, error: errorText });
|
|
||||||
return NextResponse.json({ error: 'Token exchange failed' }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const tokens = await tokenResponse.json();
|
|
||||||
|
|
||||||
if (!tokens.access_token) {
|
|
||||||
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
|
|
||||||
return NextResponse.json({ error: 'Invalid token response' }, { status: 502 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = NextResponse.json({
|
const response = NextResponse.json({
|
||||||
access_token: tokens.access_token,
|
access_token: tokens.access_token,
|
||||||
expires_in: tokens.expires_in || 3600,
|
expires_in: tokens.expires_in,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (tokens.refresh_token) {
|
if (tokens.refresh_token) {
|
||||||
const cookieName = refreshTokenCookieName(slot);
|
const cookieName = refreshTokenCookieName(slot);
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
|
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
@@ -154,7 +82,7 @@ export async function PUT(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (tokens.refresh_token) {
|
if (tokens.refresh_token) {
|
||||||
cookieStore.set(cookieName, tokens.refresh_token, COOKIE_OPTIONS);
|
cookieStore.set(cookieName, tokens.refresh_token, getCookieOptions());
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
|
|||||||
@@ -35,5 +35,9 @@ export async function GET() {
|
|||||||
loginImprintUrl: process.env.LOGIN_IMPRINT_URL || '',
|
loginImprintUrl: process.env.LOGIN_IMPRINT_URL || '',
|
||||||
loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_URL || '',
|
loginPrivacyPolicyUrl: process.env.LOGIN_PRIVACY_POLICY_URL || '',
|
||||||
loginWebsiteUrl: process.env.LOGIN_WEBSITE_URL || '',
|
loginWebsiteUrl: process.env.LOGIN_WEBSITE_URL || '',
|
||||||
|
demoMode: process.env.DEMO_MODE === 'true',
|
||||||
|
autoSsoEnabled: process.env.AUTO_SSO_ENABLED === 'true',
|
||||||
|
embeddedMode: !!process.env.ALLOWED_FRAME_ANCESTORS && process.env.ALLOWED_FRAME_ANCESTORS !== "'none'",
|
||||||
|
parentOrigin: process.env.NEXT_PUBLIC_PARENT_ORIGIN || '',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+352
-26
@@ -40,32 +40,358 @@ function isValidDomain(domain: string): boolean {
|
|||||||
|
|
||||||
// Known multi-part TLDs where the registrable domain includes one extra label.
|
// Known multi-part TLDs where the registrable domain includes one extra label.
|
||||||
const MULTI_PART_TLDS = new Set([
|
const MULTI_PART_TLDS = new Set([
|
||||||
"co.uk", "org.uk", "me.uk", "ac.uk", "gov.uk", "net.uk",
|
// .ac
|
||||||
"co.jp", "or.jp", "ne.jp", "ac.jp", "go.jp",
|
"com.ac", "gov.ac", "mil.ac", "net.ac", "org.ac",
|
||||||
"co.kr", "or.kr", "go.kr", "ac.kr",
|
// .ae
|
||||||
"co.in", "net.in", "org.in", "ac.in", "gov.in",
|
"ac.ae", "co.ae", "gov.ae", "mil.ae", "name.ae", "net.ae", "org.ae", "pro.ae", "sch.ae",
|
||||||
"co.nz", "org.nz", "net.nz", "govt.nz", "ac.nz",
|
// .af
|
||||||
"co.za", "org.za", "net.za", "gov.za", "ac.za",
|
"com.af", "edu.af", "gov.af", "net.af", "org.af",
|
||||||
"com.au", "net.au", "org.au", "edu.au", "gov.au",
|
// .al
|
||||||
"com.br", "net.br", "org.br", "edu.br", "gov.br",
|
"com.al", "edu.al", "gov.al", "mil.al", "net.al", "org.al",
|
||||||
"com.cn", "net.cn", "org.cn", "gov.cn", "edu.cn",
|
// .ao
|
||||||
"com.mx", "net.mx", "org.mx", "gob.mx", "edu.mx",
|
"co.ao", "ed.ao", "gv.ao", "it.ao", "og.ao", "pb.ao",
|
||||||
"com.ar", "net.ar", "org.ar", "gob.ar", "edu.ar",
|
// .ar
|
||||||
"com.tw", "net.tw", "org.tw", "edu.tw", "gov.tw",
|
"com.ar", "edu.ar", "gob.ar", "gov.ar", "int.ar", "mil.ar", "net.ar", "org.ar", "tur.ar",
|
||||||
"com.hk", "net.hk", "org.hk", "edu.hk", "gov.hk",
|
// .at
|
||||||
"com.sg", "net.sg", "org.sg", "edu.sg", "gov.sg",
|
"ac.at", "co.at", "gv.at", "or.at",
|
||||||
"com.my", "net.my", "org.my", "edu.my", "gov.my",
|
// .au
|
||||||
"com.ph", "net.ph", "org.ph", "edu.ph", "gov.ph",
|
"asn.au", "com.au", "csiro.au", "edu.au", "gov.au", "id.au", "net.au", "org.au",
|
||||||
"com.pk", "net.pk", "org.pk", "edu.pk", "gov.pk",
|
// .ba
|
||||||
"com.ng", "net.ng", "org.ng", "edu.ng", "gov.ng",
|
"co.ba", "com.ba", "edu.ba", "gov.ba", "mil.ba", "net.ba", "org.ba", "rs.ba",
|
||||||
"co.il", "org.il", "net.il", "ac.il", "gov.il",
|
"unbi.ba", "unmo.ba", "unsa.ba", "untz.ba", "unze.ba",
|
||||||
"co.th", "or.th", "ac.th", "go.th", "in.th",
|
// .bb
|
||||||
"co.id", "or.id", "ac.id", "go.id", "web.id",
|
"biz.bb", "co.bb", "com.bb", "edu.bb", "gov.bb", "info.bb", "net.bb", "org.bb",
|
||||||
"com.tr", "net.tr", "org.tr", "edu.tr", "gov.tr",
|
"store.bb", "tv.bb",
|
||||||
"com.ua", "net.ua", "org.ua", "edu.ua", "gov.ua",
|
// .bh
|
||||||
"com.eg", "net.eg", "org.eg", "edu.eg", "gov.eg",
|
"biz.bh", "cc.bh", "com.bh", "edu.bh", "gov.bh", "info.bh", "net.bh", "org.bh",
|
||||||
"com.sa", "net.sa", "org.sa", "edu.sa", "gov.sa",
|
// .bn
|
||||||
"co.ke", "or.ke", "ac.ke", "go.ke", "ne.ke",
|
"com.bn", "edu.bn", "gov.bn", "net.bn", "org.bn",
|
||||||
|
// .bo
|
||||||
|
"com.bo", "edu.bo", "gob.bo", "gov.bo", "int.bo", "mil.bo", "net.bo", "org.bo", "tv.bo",
|
||||||
|
// .br
|
||||||
|
"adm.br", "adv.br", "agr.br", "am.br", "arq.br", "art.br", "ato.br", "b.br",
|
||||||
|
"bio.br", "blog.br", "bmd.br", "cim.br", "cng.br", "cnt.br", "com.br", "coop.br",
|
||||||
|
"ecn.br", "edu.br", "eng.br", "esp.br", "etc.br", "eti.br", "far.br", "flog.br",
|
||||||
|
"fm.br", "fnd.br", "fot.br", "fst.br", "g12.br", "ggf.br", "gov.br", "imb.br",
|
||||||
|
"ind.br", "inf.br", "jor.br", "jus.br", "lel.br", "mat.br", "med.br", "mil.br",
|
||||||
|
"mus.br", "net.br", "nom.br", "not.br", "ntr.br", "odo.br", "org.br", "ppg.br",
|
||||||
|
"pro.br", "psc.br", "psi.br", "qsl.br", "rec.br", "slg.br", "srv.br", "tmp.br",
|
||||||
|
"trd.br", "tur.br", "tv.br", "vet.br", "vlog.br", "wiki.br", "zlg.br",
|
||||||
|
// .bs
|
||||||
|
"com.bs", "edu.bs", "gov.bs", "net.bs", "org.bs",
|
||||||
|
// .bz
|
||||||
|
"com.bz", "edu.bz", "gov.bz", "net.bz", "org.bz",
|
||||||
|
// .ca
|
||||||
|
"ab.ca", "bc.ca", "mb.ca", "nb.ca", "nf.ca", "nl.ca", "ns.ca", "nt.ca",
|
||||||
|
"nu.ca", "on.ca", "pe.ca", "qc.ca", "sk.ca", "yk.ca",
|
||||||
|
// .ck
|
||||||
|
"biz.ck", "co.ck", "edu.ck", "gen.ck", "gov.ck", "info.ck", "net.ck", "org.ck",
|
||||||
|
// .cn
|
||||||
|
"ac.cn", "ah.cn", "bj.cn", "com.cn", "cq.cn", "edu.cn", "fj.cn", "gd.cn",
|
||||||
|
"gov.cn", "gs.cn", "gx.cn", "gz.cn", "ha.cn", "hb.cn", "he.cn", "hi.cn",
|
||||||
|
"hl.cn", "hn.cn", "jl.cn", "js.cn", "jx.cn", "ln.cn", "mil.cn", "net.cn",
|
||||||
|
"nm.cn", "nx.cn", "org.cn", "qh.cn", "sc.cn", "sd.cn", "sh.cn", "sn.cn",
|
||||||
|
"sx.cn", "tj.cn", "tw.cn", "xj.cn", "xz.cn", "yn.cn", "zj.cn",
|
||||||
|
// .co
|
||||||
|
"com.co", "edu.co", "gov.co", "mil.co", "net.co", "nom.co", "org.co",
|
||||||
|
// .cr
|
||||||
|
"ac.cr", "co.cr", "ed.cr", "fi.cr", "go.cr", "or.cr", "sa.cr",
|
||||||
|
// .cy
|
||||||
|
"ac.cy", "biz.cy", "com.cy", "ekloges.cy", "gov.cy", "ltd.cy", "name.cy",
|
||||||
|
"net.cy", "org.cy", "parliament.cy", "press.cy", "pro.cy", "tm.cy",
|
||||||
|
// .do
|
||||||
|
"art.do", "com.do", "edu.do", "gob.do", "gov.do", "mil.do", "net.do", "org.do",
|
||||||
|
"sld.do", "web.do",
|
||||||
|
// .dz
|
||||||
|
"art.dz", "asso.dz", "com.dz", "edu.dz", "gov.dz", "net.dz", "org.dz", "pol.dz",
|
||||||
|
// .ec
|
||||||
|
"com.ec", "edu.ec", "fin.ec", "gov.ec", "info.ec", "med.ec", "mil.ec", "net.ec",
|
||||||
|
"org.ec", "pro.ec",
|
||||||
|
// .eg
|
||||||
|
"com.eg", "edu.eg", "eun.eg", "gov.eg", "mil.eg", "name.eg", "net.eg", "org.eg", "sci.eg",
|
||||||
|
// .er
|
||||||
|
"com.er", "edu.er", "gov.er", "ind.er", "mil.er", "net.er", "org.er", "rochest.er", "w.er",
|
||||||
|
// .es
|
||||||
|
"com.es", "edu.es", "gob.es", "nom.es", "org.es",
|
||||||
|
// .et
|
||||||
|
"biz.et", "com.et", "edu.et", "gov.et", "info.et", "name.et", "net.et", "org.et",
|
||||||
|
// .fj
|
||||||
|
"ac.fj", "biz.fj", "com.fj", "info.fj", "mil.fj", "name.fj", "net.fj", "org.fj", "pro.fj",
|
||||||
|
// .fk
|
||||||
|
"ac.fk", "co.fk", "gov.fk", "net.fk", "nom.fk", "org.fk",
|
||||||
|
// .fr
|
||||||
|
"asso.fr", "com.fr", "gouv.fr", "nom.fr", "prd.fr", "presse.fr", "tm.fr",
|
||||||
|
// .gg
|
||||||
|
"co.gg", "net.gg", "org.gg",
|
||||||
|
// .gh
|
||||||
|
"com.gh", "edu.gh", "gov.gh", "mil.gh", "org.gh",
|
||||||
|
// .gn
|
||||||
|
"ac.gn", "com.gn", "gov.gn", "net.gn", "org.gn",
|
||||||
|
// .gr
|
||||||
|
"com.gr", "edu.gr", "gov.gr", "mil.gr", "net.gr", "org.gr",
|
||||||
|
// .gt
|
||||||
|
"com.gt", "edu.gt", "gob.gt", "ind.gt", "mil.gt", "net.gt", "org.gt",
|
||||||
|
// .gu
|
||||||
|
"com.gu", "edu.gu", "gov.gu", "net.gu", "org.gu",
|
||||||
|
// .hk
|
||||||
|
"com.hk", "edu.hk", "gov.hk", "idv.hk", "net.hk", "org.hk",
|
||||||
|
// .id
|
||||||
|
"ac.id", "co.id", "go.id", "mil.id", "net.id", "or.id", "sch.id", "web.id",
|
||||||
|
// .il
|
||||||
|
"ac.il", "co.il", "gov.il", "idf.il", "k12.il", "muni.il", "net.il", "org.il",
|
||||||
|
// .in
|
||||||
|
"4fd.in", "ac.in", "co.in", "edu.in", "ernet.in", "firm.in", "gen.in", "gov.in",
|
||||||
|
"ind.in", "mil.in", "net.in", "nic.in", "org.in", "res.in",
|
||||||
|
// .iq
|
||||||
|
"com.iq", "edu.iq", "gov.iq", "mil.iq", "net.iq", "org.iq",
|
||||||
|
// .ir
|
||||||
|
"ac.ir", "co.ir", "dnssec.ir", "gov.ir", "id.ir", "net.ir", "org.ir", "sch.ir",
|
||||||
|
// .it
|
||||||
|
"edu.it", "gov.it",
|
||||||
|
// .je
|
||||||
|
"co.je", "net.je", "org.je",
|
||||||
|
// .jo
|
||||||
|
"com.jo", "edu.jo", "gov.jo", "mil.jo", "name.jo", "net.jo", "org.jo", "sch.jo",
|
||||||
|
// .jp
|
||||||
|
"ac.jp", "ad.jp", "co.jp", "ed.jp", "go.jp", "gr.jp", "lg.jp", "ne.jp", "or.jp",
|
||||||
|
// .ke
|
||||||
|
"ac.ke", "co.ke", "go.ke", "info.ke", "me.ke", "mobi.ke", "ne.ke", "or.ke", "sc.ke",
|
||||||
|
// .kh
|
||||||
|
"com.kh", "edu.kh", "gov.kh", "mil.kh", "net.kh", "org.kh", "per.kh",
|
||||||
|
// .ki
|
||||||
|
"biz.ki", "com.ki", "de.ki", "edu.ki", "gov.ki", "info.ki", "mob.ki", "net.ki",
|
||||||
|
"org.ki", "tel.ki",
|
||||||
|
// .km
|
||||||
|
"asso.km", "com.km", "coop.km", "edu.km", "gouv.km", "medecin.km", "mil.km",
|
||||||
|
"nom.km", "notaires.km", "pharmaciens.km", "presse.km", "tm.km", "veterinaire.km",
|
||||||
|
// .kn
|
||||||
|
"edu.kn", "gov.kn", "net.kn", "org.kn",
|
||||||
|
// .kr
|
||||||
|
"ac.kr", "busan.kr", "chungbuk.kr", "chungnam.kr", "co.kr", "daegu.kr",
|
||||||
|
"daejeon.kr", "es.kr", "gangwon.kr", "go.kr", "gwangju.kr", "gyeongbuk.kr",
|
||||||
|
"gyeonggi.kr", "gyeongnam.kr", "hs.kr", "incheon.kr", "jeju.kr", "jeonbuk.kr",
|
||||||
|
"jeonnam.kr", "kg.kr", "mil.kr", "ms.kr", "ne.kr", "or.kr", "pe.kr", "re.kr",
|
||||||
|
"sc.kr", "seoul.kr", "ulsan.kr",
|
||||||
|
// .kw
|
||||||
|
"com.kw", "edu.kw", "gov.kw", "net.kw", "org.kw",
|
||||||
|
// .ky
|
||||||
|
"com.ky", "edu.ky", "gov.ky", "net.ky", "org.ky",
|
||||||
|
// .kz
|
||||||
|
"com.kz", "edu.kz", "gov.kz", "mil.kz", "net.kz", "org.kz",
|
||||||
|
// .lb
|
||||||
|
"com.lb", "edu.lb", "gov.lb", "net.lb", "org.lb",
|
||||||
|
// .lk
|
||||||
|
"assn.lk", "com.lk", "edu.lk", "gov.lk", "grp.lk", "hotel.lk", "int.lk", "ltd.lk",
|
||||||
|
"net.lk", "ngo.lk", "org.lk", "sch.lk", "soc.lk", "web.lk",
|
||||||
|
// .lr
|
||||||
|
"com.lr", "edu.lr", "gov.lr", "net.lr", "org.lr",
|
||||||
|
// .lv
|
||||||
|
"asn.lv", "com.lv", "conf.lv", "edu.lv", "gov.lv", "id.lv", "mil.lv", "net.lv", "org.lv",
|
||||||
|
// .ly
|
||||||
|
"com.ly", "edu.ly", "gov.ly", "id.ly", "med.ly", "net.ly", "org.ly", "plc.ly", "sch.ly",
|
||||||
|
// .ma
|
||||||
|
"ac.ma", "co.ma", "gov.ma", "net.ma", "org.ma", "press.ma",
|
||||||
|
// .mc
|
||||||
|
"asso.mc", "tm.mc",
|
||||||
|
// .me
|
||||||
|
"ac.me", "co.me", "edu.me", "gov.me", "its.me", "net.me", "org.me", "priv.me",
|
||||||
|
// .mg
|
||||||
|
"com.mg", "edu.mg", "gov.mg", "mil.mg", "nom.mg", "org.mg", "prd.mg", "tm.mg",
|
||||||
|
// .mk
|
||||||
|
"com.mk", "edu.mk", "gov.mk", "inf.mk", "name.mk", "net.mk", "org.mk", "pro.mk",
|
||||||
|
// .ml
|
||||||
|
"com.ml", "edu.ml", "gov.ml", "net.ml", "org.ml", "presse.ml",
|
||||||
|
// .mn
|
||||||
|
"edu.mn", "gov.mn", "org.mn",
|
||||||
|
// .mo
|
||||||
|
"com.mo", "edu.mo", "gov.mo", "net.mo", "org.mo",
|
||||||
|
// .mt
|
||||||
|
"com.mt", "edu.mt", "gov.mt", "net.mt", "org.mt",
|
||||||
|
// .mu
|
||||||
|
"ac.mu", "co.mu", "com.mu", "gov.mu", "net.mu", "or.mu", "org.mu",
|
||||||
|
// .mv
|
||||||
|
"aero.mv", "biz.mv", "com.mv", "coop.mv", "edu.mv", "gov.mv", "info.mv",
|
||||||
|
"int.mv", "mil.mv", "museum.mv", "name.mv", "net.mv", "org.mv", "pro.mv",
|
||||||
|
// .mw
|
||||||
|
"ac.mw", "co.mw", "com.mw", "coop.mw", "edu.mw", "gov.mw", "int.mw",
|
||||||
|
"museum.mw", "net.mw", "org.mw",
|
||||||
|
// .mx
|
||||||
|
"com.mx", "edu.mx", "gob.mx", "net.mx", "org.mx",
|
||||||
|
// .my
|
||||||
|
"com.my", "edu.my", "gov.my", "mil.my", "name.my", "net.my", "org.my", "sch.my",
|
||||||
|
// .mz
|
||||||
|
"ac.mz", "co.mz", "edu.mz", "gov.mz", "org.mz",
|
||||||
|
// .na
|
||||||
|
"co.na", "com.na",
|
||||||
|
// .nf
|
||||||
|
"arts.nf", "com.nf", "firm.nf", "info.nf", "net.nf", "other.nf", "per.nf",
|
||||||
|
"rec.nf", "store.nf", "web.nf",
|
||||||
|
// .ng
|
||||||
|
"biz.ng", "com.ng", "edu.ng", "gov.ng", "mil.ng", "mobi.ng", "name.ng",
|
||||||
|
"net.ng", "org.ng", "sch.ng",
|
||||||
|
// .ni
|
||||||
|
"ac.ni", "co.ni", "com.ni", "edu.ni", "gob.ni", "mil.ni", "net.ni", "nom.ni", "org.ni",
|
||||||
|
// .np
|
||||||
|
"com.np", "edu.np", "gov.np", "mil.np", "net.np", "org.np",
|
||||||
|
// .nr
|
||||||
|
"biz.nr", "com.nr", "edu.nr", "gov.nr", "info.nr", "net.nr", "org.nr",
|
||||||
|
// .nz
|
||||||
|
"ac.nz", "co.nz", "cri.nz", "geek.nz", "gen.nz", "govt.nz", "health.nz",
|
||||||
|
"iwi.nz", "maori.nz", "mil.nz", "net.nz", "org.nz", "parliament.nz", "school.nz",
|
||||||
|
// .om
|
||||||
|
"ac.om", "biz.om", "co.om", "com.om", "edu.om", "gov.om", "med.om", "mil.om",
|
||||||
|
"museum.om", "net.om", "org.om", "pro.om", "sch.om",
|
||||||
|
// .pa
|
||||||
|
"abo.pa", "ac.pa", "com.pa", "edu.pa", "gob.pa", "ing.pa", "med.pa", "net.pa",
|
||||||
|
"nom.pa", "org.pa", "sld.pa",
|
||||||
|
// .pe
|
||||||
|
"com.pe", "edu.pe", "gob.pe", "mil.pe", "net.pe", "nom.pe", "org.pe", "sld.pe",
|
||||||
|
// .ph
|
||||||
|
"com.ph", "edu.ph", "gov.ph", "i.ph", "mil.ph", "net.ph", "ngo.ph", "org.ph",
|
||||||
|
// .pk
|
||||||
|
"biz.pk", "com.pk", "edu.pk", "fam.pk", "gob.pk", "gok.pk", "gon.pk", "gop.pk",
|
||||||
|
"gos.pk", "gov.pk", "net.pk", "org.pk", "web.pk",
|
||||||
|
// .pl
|
||||||
|
"art.pl", "bialystok.pl", "biz.pl", "com.pl", "edu.pl", "gda.pl", "gdansk.pl",
|
||||||
|
"gorzow.pl", "gov.pl", "info.pl", "katowice.pl", "krakow.pl", "lodz.pl",
|
||||||
|
"lublin.pl", "mil.pl", "net.pl", "ngo.pl", "olsztyn.pl", "org.pl", "poznan.pl",
|
||||||
|
"pwr.pl", "radom.pl", "slupsk.pl", "szczecin.pl", "torun.pl", "warszawa.pl",
|
||||||
|
"waw.pl", "wroc.pl", "wroclaw.pl", "zgora.pl",
|
||||||
|
// .pr
|
||||||
|
"ac.pr", "biz.pr", "com.pr", "edu.pr", "est.pr", "gov.pr", "info.pr", "isla.pr",
|
||||||
|
"name.pr", "net.pr", "org.pr", "pro.pr", "prof.pr",
|
||||||
|
// .ps
|
||||||
|
"com.ps", "edu.ps", "gov.ps", "net.ps", "org.ps", "plo.ps", "sec.ps",
|
||||||
|
// .pt
|
||||||
|
"com.pt", "edu.pt", "gov.pt", "int.pt", "net.pt", "nome.pt", "org.pt", "publ.pt",
|
||||||
|
// .pw
|
||||||
|
"belau.pw", "co.pw", "ed.pw", "go.pw", "ne.pw", "or.pw",
|
||||||
|
// .py
|
||||||
|
"com.py", "edu.py", "gov.py", "mil.py", "net.py", "org.py",
|
||||||
|
// .qa
|
||||||
|
"com.qa", "edu.qa", "gov.qa", "mil.qa", "net.qa", "org.qa",
|
||||||
|
// .re
|
||||||
|
"asso.re", "com.re", "nom.re",
|
||||||
|
// .ro
|
||||||
|
"arts.ro", "com.ro", "firm.ro", "info.ro", "nom.ro", "nt.ro", "org.ro",
|
||||||
|
"rec.ro", "store.ro", "tm.ro", "www.ro",
|
||||||
|
// .rs
|
||||||
|
"ac.rs", "co.rs", "edu.rs", "gov.rs", "in.rs", "org.rs",
|
||||||
|
// .ru
|
||||||
|
"ac.ru", "adygeya.ru", "altai.ru", "amur.ru", "arkhangelsk.ru", "astrakhan.ru",
|
||||||
|
"bashkiria.ru", "belgorod.ru", "bir.ru", "bryansk.ru", "buryatia.ru", "cbg.ru",
|
||||||
|
"chel.ru", "chelyabinsk.ru", "chita.ru", "chukotka.ru", "chuvashia.ru", "com.ru",
|
||||||
|
"dagestan.ru", "e-burg.ru", "edu.ru", "gov.ru", "grozny.ru", "int.ru",
|
||||||
|
"irkutsk.ru", "ivanovo.ru", "izhevsk.ru", "jar.ru", "joshkar-ola.ru",
|
||||||
|
"kalmykia.ru", "kaluga.ru", "kamchatka.ru", "karelia.ru", "kazan.ru", "kchr.ru",
|
||||||
|
"kemerovo.ru", "khabarovsk.ru", "khakassia.ru", "khv.ru", "kirov.ru",
|
||||||
|
"koenig.ru", "komi.ru", "kostroma.ru", "kranoyarsk.ru", "kuban.ru", "kurgan.ru",
|
||||||
|
"kursk.ru", "lipetsk.ru", "magadan.ru", "mari.ru", "mari-el.ru", "marine.ru",
|
||||||
|
"mil.ru", "mordovia.ru", "mosreg.ru", "msk.ru", "murmansk.ru", "nalchik.ru",
|
||||||
|
"net.ru", "nnov.ru", "nov.ru", "novosibirsk.ru", "nsk.ru", "omsk.ru",
|
||||||
|
"orenburg.ru", "org.ru", "oryol.ru", "penza.ru", "perm.ru", "pp.ru", "pskov.ru",
|
||||||
|
"ptz.ru", "rnd.ru", "ryazan.ru", "sakhalin.ru", "samara.ru", "saratov.ru",
|
||||||
|
"simbirsk.ru", "smolensk.ru", "spb.ru", "stavropol.ru", "stv.ru", "surgut.ru",
|
||||||
|
"tambov.ru", "tatarstan.ru", "tom.ru", "tomsk.ru", "tsaritsyn.ru", "tsk.ru",
|
||||||
|
"tula.ru", "tuva.ru", "tver.ru", "tyumen.ru", "udm.ru", "udmurtia.ru",
|
||||||
|
"ulan-ude.ru", "vladikavkaz.ru", "vladimir.ru", "vladivostok.ru", "volgograd.ru",
|
||||||
|
"vologda.ru", "voronezh.ru", "vrn.ru", "vyatka.ru", "yakutia.ru", "yamal.ru",
|
||||||
|
"yekaterinburg.ru", "yuzhno-sakhalinsk.ru",
|
||||||
|
// .rw
|
||||||
|
"ac.rw", "co.rw", "com.rw", "edu.rw", "gouv.rw", "gov.rw", "int.rw", "mil.rw", "net.rw",
|
||||||
|
// .sa
|
||||||
|
"com.sa", "edu.sa", "gov.sa", "med.sa", "net.sa", "org.sa", "pub.sa", "sch.sa",
|
||||||
|
// .sb
|
||||||
|
"com.sb", "edu.sb", "gov.sb", "net.sb", "org.sb",
|
||||||
|
// .sc
|
||||||
|
"com.sc", "edu.sc", "gov.sc", "net.sc", "org.sc",
|
||||||
|
// .sd
|
||||||
|
"com.sd", "edu.sd", "gov.sd", "info.sd", "med.sd", "net.sd", "org.sd", "tv.sd",
|
||||||
|
// .se
|
||||||
|
"a.se", "ac.se", "b.se", "bd.se", "c.se", "d.se", "e.se", "f.se", "g.se",
|
||||||
|
"h.se", "i.se", "k.se", "l.se", "m.se", "n.se", "o.se", "org.se", "p.se",
|
||||||
|
"parti.se", "pp.se", "press.se", "r.se", "s.se", "t.se", "tm.se", "u.se",
|
||||||
|
"w.se", "x.se", "y.se", "z.se",
|
||||||
|
// .sg
|
||||||
|
"com.sg", "edu.sg", "gov.sg", "idn.sg", "net.sg", "org.sg", "per.sg",
|
||||||
|
// .sh
|
||||||
|
"co.sh", "com.sh", "edu.sh", "gov.sh", "net.sh", "nom.sh", "org.sh",
|
||||||
|
// .sl
|
||||||
|
"com.sl", "edu.sl", "gov.sl", "net.sl", "org.sl",
|
||||||
|
// .sn
|
||||||
|
"art.sn", "com.sn", "edu.sn", "gouv.sn", "org.sn", "perso.sn", "univ.sn",
|
||||||
|
// .st
|
||||||
|
"co.st", "com.st", "consulado.st", "edu.st", "embaixada.st", "gov.st", "mil.st",
|
||||||
|
"net.st", "org.st", "principe.st", "saotome.st", "store.st",
|
||||||
|
// .sv
|
||||||
|
"com.sv", "edu.sv", "gob.sv", "org.sv", "red.sv",
|
||||||
|
// .sy
|
||||||
|
"com.sy", "edu.sy", "gov.sy", "mil.sy", "net.sy", "news.sy", "org.sy",
|
||||||
|
// .sz
|
||||||
|
"ac.sz", "co.sz", "org.sz",
|
||||||
|
// .th
|
||||||
|
"ac.th", "co.th", "go.th", "in.th", "mi.th", "net.th", "or.th",
|
||||||
|
// .tj
|
||||||
|
"ac.tj", "biz.tj", "co.tj", "com.tj", "edu.tj", "go.tj", "gov.tj", "info.tj",
|
||||||
|
"int.tj", "mil.tj", "name.tj", "net.tj", "nic.tj", "org.tj", "test.tj", "web.tj",
|
||||||
|
// .tn
|
||||||
|
"agrinet.tn", "com.tn", "defense.tn", "edunet.tn", "ens.tn", "fin.tn", "gov.tn",
|
||||||
|
"ind.tn", "info.tn", "intl.tn", "mincom.tn", "nat.tn", "net.tn", "org.tn",
|
||||||
|
"perso.tn", "rnrt.tn", "rns.tn", "rnu.tn", "tourism.tn",
|
||||||
|
// .tr
|
||||||
|
"av.tr", "bbs.tr", "bel.tr", "biz.tr", "com.tr", "dr.tr", "edu.tr", "gen.tr",
|
||||||
|
"gov.tr", "info.tr", "k12.tr", "name.tr", "net.tr", "org.tr", "pol.tr",
|
||||||
|
"tel.tr", "tsk.tr", "tv.tr", "web.tr",
|
||||||
|
// .tt
|
||||||
|
"aero.tt", "biz.tt", "cat.tt", "co.tt", "com.tt", "coop.tt", "edu.tt", "gov.tt",
|
||||||
|
"info.tt", "int.tt", "jobs.tt", "mil.tt", "mobi.tt", "museum.tt", "name.tt",
|
||||||
|
"net.tt", "org.tt", "pro.tt", "tel.tt", "travel.tt",
|
||||||
|
// .tw
|
||||||
|
"club.tw", "com.tw", "ebiz.tw", "edu.tw", "game.tw", "gov.tw", "idv.tw",
|
||||||
|
"mil.tw", "net.tw", "org.tw",
|
||||||
|
// .tz
|
||||||
|
"ac.tz", "co.tz", "go.tz", "ne.tz", "or.tz",
|
||||||
|
// .ua
|
||||||
|
"biz.ua", "cherkassy.ua", "chernigov.ua", "chernovtsy.ua", "ck.ua", "cn.ua",
|
||||||
|
"co.ua", "com.ua", "crimea.ua", "cv.ua", "dn.ua", "dnepropetrovsk.ua",
|
||||||
|
"donetsk.ua", "dp.ua", "edu.ua", "gov.ua", "if.ua", "in.ua",
|
||||||
|
"ivano-frankivsk.ua", "kh.ua", "kharkov.ua", "kherson.ua", "khmelnitskiy.ua",
|
||||||
|
"kiev.ua", "kirovograd.ua", "km.ua", "kr.ua", "ks.ua", "kv.ua", "lg.ua",
|
||||||
|
"lugansk.ua", "lutsk.ua", "lviv.ua", "me.ua", "mk.ua", "net.ua",
|
||||||
|
"nikolaev.ua", "od.ua", "odessa.ua", "org.ua", "pl.ua", "poltava.ua", "pp.ua",
|
||||||
|
"rovno.ua", "rv.ua", "sebastopol.ua", "sumy.ua", "te.ua", "ternopil.ua",
|
||||||
|
"uzhgorod.ua", "vinnica.ua", "vn.ua", "zaporizhzhe.ua", "zhitomir.ua",
|
||||||
|
"zp.ua", "zt.ua",
|
||||||
|
// .ug
|
||||||
|
"ac.ug", "co.ug", "go.ug", "ne.ug", "or.ug", "org.ug", "sc.ug",
|
||||||
|
// .uk
|
||||||
|
"ac.uk", "bl.uk", "british-library.uk", "co.uk", "cym.uk", "gov.uk", "govt.uk",
|
||||||
|
"icnet.uk", "jet.uk", "lea.uk", "ltd.uk", "me.uk", "mil.uk", "mod.uk",
|
||||||
|
"national-library-scotland.uk", "nel.uk", "net.uk", "nhs.uk", "nic.uk",
|
||||||
|
"nls.uk", "org.uk", "orgn.uk", "parliament.uk", "plc.uk", "police.uk",
|
||||||
|
"sch.uk", "scot.uk", "soc.uk",
|
||||||
|
// .us
|
||||||
|
"4fd.us", "dni.us", "fed.us", "isa.us", "kids.us", "nsn.us",
|
||||||
|
// .uy
|
||||||
|
"com.uy", "edu.uy", "gub.uy", "mil.uy", "net.uy", "org.uy",
|
||||||
|
// .ve
|
||||||
|
"co.ve", "com.ve", "edu.ve", "gob.ve", "info.ve", "mil.ve", "net.ve", "org.ve", "web.ve",
|
||||||
|
// .vi
|
||||||
|
"co.vi", "com.vi", "k12.vi", "net.vi", "org.vi",
|
||||||
|
// .vn
|
||||||
|
"ac.vn", "biz.vn", "com.vn", "edu.vn", "gov.vn", "health.vn", "info.vn",
|
||||||
|
"int.vn", "name.vn", "net.vn", "org.vn", "pro.vn",
|
||||||
|
// .ye
|
||||||
|
"co.ye", "com.ye", "gov.ye", "ltd.ye", "me.ye", "net.ye", "org.ye", "plc.ye",
|
||||||
|
// .yu
|
||||||
|
"ac.yu", "co.yu", "edu.yu", "gov.yu", "org.yu",
|
||||||
|
// .za
|
||||||
|
"ac.za", "agric.za", "alt.za", "bourse.za", "city.za", "co.za", "cybernet.za",
|
||||||
|
"db.za", "edu.za", "gov.za", "grondar.za", "iaccess.za", "imt.za", "inca.za",
|
||||||
|
"landesign.za", "law.za", "mil.za", "net.za", "ngo.za", "nis.za", "nom.za",
|
||||||
|
"olivetti.za", "org.za", "pix.za", "school.za", "tm.za", "web.za",
|
||||||
|
// .zm
|
||||||
|
"ac.zm", "co.zm", "com.zm", "edu.zm", "gov.zm", "net.zm", "org.zm", "sch.zm",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function getRootDomain(domain: string): string {
|
function getRootDomain(domain: string): string {
|
||||||
|
|||||||
+26
-35
@@ -1,10 +1,21 @@
|
|||||||
|
import v8 from 'node:v8';
|
||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import { NextRequest } from 'next/server';
|
import { NextRequest } from 'next/server';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
|
|
||||||
// Health check thresholds
|
const MEMORY_WARNING_THRESHOLD = 0.85;
|
||||||
const MEMORY_WARNING_THRESHOLD = 0.85; // 85% heap usage
|
const MEMORY_CRITICAL_THRESHOLD = 0.95;
|
||||||
const MEMORY_CRITICAL_THRESHOLD = 0.95; // 95% heap usage
|
|
||||||
|
function getHeapUsagePercent(heapUsed: number, heapTotal: number): number {
|
||||||
|
const heapSizeLimit = v8.getHeapStatistics().heap_size_limit;
|
||||||
|
const denominator = heapSizeLimit > 0 ? heapSizeLimit : heapTotal;
|
||||||
|
|
||||||
|
if (denominator <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (heapUsed / denominator) * 100;
|
||||||
|
}
|
||||||
|
|
||||||
interface HealthStatus {
|
interface HealthStatus {
|
||||||
status: 'healthy' | 'degraded' | 'unhealthy';
|
status: 'healthy' | 'degraded' | 'unhealthy';
|
||||||
@@ -14,6 +25,7 @@ interface HealthStatus {
|
|||||||
memory?: {
|
memory?: {
|
||||||
heapUsed: number;
|
heapUsed: number;
|
||||||
heapTotal: number;
|
heapTotal: number;
|
||||||
|
heapSizeLimit: number;
|
||||||
rss: number;
|
rss: number;
|
||||||
external: number;
|
external: number;
|
||||||
heapUsagePercent: number;
|
heapUsagePercent: number;
|
||||||
@@ -27,14 +39,9 @@ interface HealthStatus {
|
|||||||
/**
|
/**
|
||||||
* Health check endpoint for container orchestration
|
* Health check endpoint for container orchestration
|
||||||
*
|
*
|
||||||
* GET /api/health - Basic health check (returns 200 OK or 503 Service Unavailable)
|
* GET /api/health - Liveness probe for container orchestration
|
||||||
* GET /api/health?detailed=true - Detailed diagnostics with memory stats
|
* GET /api/health?detailed=true - Diagnostics with advisory memory warnings
|
||||||
* HEAD /api/health - Lightweight health check (status code only)
|
* HEAD /api/health - Lightweight liveness probe (status code only)
|
||||||
*
|
|
||||||
* Health status based on Node.js heap usage:
|
|
||||||
* - Healthy (200): < 85% heap usage
|
|
||||||
* - Degraded (200): 85-95% heap usage (warnings in detailed mode)
|
|
||||||
* - Unhealthy (503): > 95% heap usage
|
|
||||||
*/
|
*/
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const searchParams = request.nextUrl.searchParams;
|
const searchParams = request.nextUrl.searchParams;
|
||||||
@@ -43,38 +50,31 @@ export async function GET(request: NextRequest) {
|
|||||||
try {
|
try {
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
const memUsage = process.memoryUsage();
|
const memUsage = process.memoryUsage();
|
||||||
const heapUsagePercent = (memUsage.heapUsed / memUsage.heapTotal) * 100;
|
const heapSizeLimit = v8.getHeapStatistics().heap_size_limit;
|
||||||
|
const heapUsagePercent = getHeapUsagePercent(memUsage.heapUsed, memUsage.heapTotal);
|
||||||
// Determine health status based on memory usage
|
|
||||||
let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
|
let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
|
||||||
const warnings: string[] = [];
|
const warnings: string[] = [];
|
||||||
let httpStatus = 200;
|
|
||||||
|
|
||||||
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
|
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
|
||||||
status = 'unhealthy';
|
status = 'degraded';
|
||||||
httpStatus = 503;
|
warnings.push(`V8 heap usage is very high: ${heapUsagePercent.toFixed(1)}% of heap limit`);
|
||||||
} else if (heapUsagePercent >= MEMORY_WARNING_THRESHOLD * 100) {
|
} else if (heapUsagePercent >= MEMORY_WARNING_THRESHOLD * 100) {
|
||||||
status = 'degraded';
|
status = 'degraded';
|
||||||
warnings.push(`Memory usage high: ${heapUsagePercent.toFixed(1)}%`);
|
warnings.push(`V8 heap usage is high: ${heapUsagePercent.toFixed(1)}% of heap limit`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build response
|
|
||||||
const response: HealthStatus = {
|
const response: HealthStatus = {
|
||||||
status,
|
status: detailed ? status : 'healthy',
|
||||||
timestamp,
|
timestamp,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (status === 'unhealthy') {
|
|
||||||
response.reason = `Memory usage critical: ${heapUsagePercent.toFixed(1)}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add detailed information if requested
|
|
||||||
if (detailed) {
|
if (detailed) {
|
||||||
response.uptime = process.uptime();
|
response.uptime = process.uptime();
|
||||||
response.version = process.env.npm_package_version || '0.1.0';
|
response.version = process.env.npm_package_version || '0.1.0';
|
||||||
response.memory = {
|
response.memory = {
|
||||||
heapUsed: memUsage.heapUsed,
|
heapUsed: memUsage.heapUsed,
|
||||||
heapTotal: memUsage.heapTotal,
|
heapTotal: memUsage.heapTotal,
|
||||||
|
heapSizeLimit,
|
||||||
rss: memUsage.rss,
|
rss: memUsage.rss,
|
||||||
external: memUsage.external,
|
external: memUsage.external,
|
||||||
heapUsagePercent: Number(heapUsagePercent.toFixed(2)),
|
heapUsagePercent: Number(heapUsagePercent.toFixed(2)),
|
||||||
@@ -87,10 +87,8 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info('Health check', { status, detailed });
|
|
||||||
|
|
||||||
return NextResponse.json(response, {
|
return NextResponse.json(response, {
|
||||||
status: httpStatus,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
||||||
'Pragma': 'no-cache',
|
'Pragma': 'no-cache',
|
||||||
@@ -116,13 +114,6 @@ export async function GET(request: NextRequest) {
|
|||||||
*/
|
*/
|
||||||
export async function HEAD() {
|
export async function HEAD() {
|
||||||
try {
|
try {
|
||||||
const memUsage = process.memoryUsage();
|
|
||||||
const heapUsagePercent = (memUsage.heapUsed / memUsage.heapTotal) * 100;
|
|
||||||
|
|
||||||
if (heapUsagePercent >= MEMORY_CRITICAL_THRESHOLD * 100) {
|
|
||||||
return new Response(null, { status: 503 });
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Response(null, { status: 200 });
|
return new Response(null, { status: 200 });
|
||||||
} catch {
|
} catch {
|
||||||
return new Response(null, { status: 503 });
|
return new Response(null, { status: 503 });
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
|||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { logger } from '@/lib/logger';
|
import { logger } from '@/lib/logger';
|
||||||
import { decryptSession } from '@/lib/auth/crypto';
|
import { decryptSession } from '@/lib/auth/crypto';
|
||||||
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
|
import { sessionCookieName } from '@/lib/auth/session-cookie';
|
||||||
import { saveUserSettings, loadUserSettings, deleteUserSettings } from '@/lib/settings-sync';
|
import { saveUserSettings, loadUserSettings, deleteUserSettings } from '@/lib/settings-sync';
|
||||||
|
|
||||||
function isEnabled(): boolean {
|
function isEnabled(): boolean {
|
||||||
@@ -10,19 +10,30 @@ function isEnabled(): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verify identity against the session cookie if available.
|
* Verify identity against session cookies across all account slots.
|
||||||
* Returns true if no session cookie exists (can't verify) or if identity matches.
|
* With multi-account, the requesting account may be on any slot (0-4).
|
||||||
* Returns false if session cookie exists but identity doesn't match.
|
* Returns true if any slot matches OR if no session cookies exist at all.
|
||||||
*/
|
*/
|
||||||
async function verifyIdentity(username: string, serverUrl: string): Promise<boolean> {
|
async function verifyIdentity(username: string, serverUrl: string): Promise<boolean> {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const sessionToken = cookieStore.get(SESSION_COOKIE)?.value;
|
let hasAnyCookie = false;
|
||||||
if (!sessionToken) return true; // No session cookie, can't verify (same-origin protection applies)
|
|
||||||
|
|
||||||
const session = decryptSession(sessionToken);
|
for (let slot = 0; slot <= 4; slot++) {
|
||||||
if (!session) return true; // Invalid session cookie, skip verification
|
const token = cookieStore.get(sessionCookieName(slot))?.value;
|
||||||
|
if (!token) continue;
|
||||||
|
hasAnyCookie = true;
|
||||||
|
|
||||||
return session.username === username && session.serverUrl === serverUrl;
|
const session = decryptSession(token);
|
||||||
|
if (session && session.username === username && session.serverUrl === serverUrl) {
|
||||||
|
return true; // Found a matching slot
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No cookies at all → can't verify, allow (same-origin protection applies)
|
||||||
|
if (!hasAnyCookie) return true;
|
||||||
|
|
||||||
|
// Cookies exist but none matched → identity mismatch
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
|
|||||||
@@ -20,6 +20,8 @@
|
|||||||
--color-accent-foreground: #1e40af;
|
--color-accent-foreground: #1e40af;
|
||||||
--color-destructive: #ef4444;
|
--color-destructive: #ef4444;
|
||||||
--color-destructive-foreground: #ffffff;
|
--color-destructive-foreground: #ffffff;
|
||||||
|
--color-popover: #ffffff;
|
||||||
|
--color-popover-foreground: #0f172a;
|
||||||
|
|
||||||
/* Settings variables */
|
/* Settings variables */
|
||||||
--font-size-base: 16px;
|
--font-size-base: 16px;
|
||||||
@@ -50,6 +52,8 @@
|
|||||||
--color-accent-foreground: #dbeafe;
|
--color-accent-foreground: #dbeafe;
|
||||||
--color-destructive: #ef4444;
|
--color-destructive: #ef4444;
|
||||||
--color-destructive-foreground: #fafafa;
|
--color-destructive-foreground: #fafafa;
|
||||||
|
--color-popover: #1c1c1c;
|
||||||
|
--color-popover-foreground: #fafafa;
|
||||||
}
|
}
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
@@ -68,6 +72,8 @@
|
|||||||
--color-accent-foreground: var(--color-accent-foreground);
|
--color-accent-foreground: var(--color-accent-foreground);
|
||||||
--color-destructive: var(--color-destructive);
|
--color-destructive: var(--color-destructive);
|
||||||
--color-destructive-foreground: var(--color-destructive-foreground);
|
--color-destructive-foreground: var(--color-destructive-foreground);
|
||||||
|
--color-popover: var(--color-popover);
|
||||||
|
--color-popover-foreground: var(--color-popover-foreground);
|
||||||
}
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
@@ -490,3 +496,95 @@ body {
|
|||||||
-webkit-backdrop-filter: none !important;
|
-webkit-backdrop-filter: none !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* TipTap Rich Text Editor */
|
||||||
|
.tiptap {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap p {
|
||||||
|
margin: 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap h1 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap h2 {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap ul {
|
||||||
|
list-style-type: disc;
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
margin: 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap ol {
|
||||||
|
list-style-type: decimal;
|
||||||
|
padding-left: 1.5rem;
|
||||||
|
margin: 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap li {
|
||||||
|
margin: 0.125rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap blockquote {
|
||||||
|
border-left: 3px solid var(--color-border);
|
||||||
|
padding-left: 1rem;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
color: var(--color-muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap pre {
|
||||||
|
background-color: var(--color-muted);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap code {
|
||||||
|
background-color: var(--color-muted);
|
||||||
|
padding: 0.125rem 0.25rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap a {
|
||||||
|
color: var(--color-primary);
|
||||||
|
text-decoration: underline;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap img {
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap hr {
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
margin: 1rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap p.is-editor-empty:first-child::before {
|
||||||
|
content: attr(data-placeholder);
|
||||||
|
float: left;
|
||||||
|
color: var(--color-muted-foreground);
|
||||||
|
pointer-events: none;
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tiptap .ProseMirror-selectednode img {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|||||||
@@ -31,10 +31,14 @@ export default async function RootLayout({
|
|||||||
}) {
|
}) {
|
||||||
const locale = await getLocale();
|
const locale = await getLocale();
|
||||||
const nonce = (await headers()).get("x-nonce") ?? "";
|
const nonce = (await headers()).get("x-nonce") ?? "";
|
||||||
|
const parentOrigin = process.env.NEXT_PUBLIC_PARENT_ORIGIN || "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang={locale} suppressHydrationWarning>
|
<html lang={locale} suppressHydrationWarning>
|
||||||
<head>
|
<head>
|
||||||
|
{parentOrigin && (
|
||||||
|
<meta name="parent-origin" content={parentOrigin} />
|
||||||
|
)}
|
||||||
<script
|
<script
|
||||||
nonce={nonce}
|
nonce={nonce}
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
|
||||||
|
export default function NotFound() {
|
||||||
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
window.location.href = "/login";
|
||||||
|
}
|
||||||
|
}, [isAuthenticated]);
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||||
|
<div className="text-center max-w-md px-4">
|
||||||
|
<h1 className="text-4xl font-bold text-foreground mb-2">404</h1>
|
||||||
|
<p className="text-muted-foreground mb-6">This page could not be found.</p>
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
className="inline-flex items-center px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity"
|
||||||
|
>
|
||||||
|
Go home
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo } from "react";
|
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||||
import { useTranslations, useFormatter } from "next-intl";
|
import { useTranslations, useFormatter } from "next-intl";
|
||||||
import { format, parseISO, isToday, isTomorrow } from "date-fns";
|
import { format, parseISO, isToday, isTomorrow, startOfDay } from "date-fns";
|
||||||
import { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
|
import { Calendar as CalendarIcon, MapPin, Users } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { parseDuration, getEventColor } from "./event-card";
|
import { parseDuration, getEventColor } from "./event-card";
|
||||||
@@ -27,6 +27,7 @@ interface DayGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function CalendarAgendaView({
|
export function CalendarAgendaView({
|
||||||
|
selectedDate,
|
||||||
events,
|
events,
|
||||||
calendars,
|
calendars,
|
||||||
onSelectEvent,
|
onSelectEvent,
|
||||||
@@ -43,6 +44,9 @@ export function CalendarAgendaView({
|
|||||||
return map;
|
return map;
|
||||||
}, [calendars]);
|
}, [calendars]);
|
||||||
|
|
||||||
|
const todayRef = useRef<HTMLDivElement>(null);
|
||||||
|
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const grouped = useMemo(() => {
|
const grouped = useMemo(() => {
|
||||||
const sorted = [...events].sort((a, b) =>
|
const sorted = [...events].sort((a, b) =>
|
||||||
new Date(a.start).getTime() - new Date(b.start).getTime()
|
new Date(a.start).getTime() - new Date(b.start).getTime()
|
||||||
@@ -69,10 +73,38 @@ export function CalendarAgendaView({
|
|||||||
} catch { /* skip invalid dates */ }
|
} catch { /* skip invalid dates */ }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Always include today's date in the groups so the view has a "Today" anchor
|
||||||
|
const todayKey = format(new Date(), "yyyy-MM-dd");
|
||||||
|
if (!groupMap.has(todayKey)) {
|
||||||
|
const todayGroup = { date: startOfDay(new Date()), dateKey: todayKey, events: [] as CalendarEvent[] };
|
||||||
|
groupMap.set(todayKey, todayGroup);
|
||||||
|
groups.push(todayGroup);
|
||||||
|
}
|
||||||
|
|
||||||
groups.sort((a, b) => a.date.getTime() - b.date.getTime());
|
groups.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||||
return groups;
|
return groups;
|
||||||
}, [events]);
|
}, [events]);
|
||||||
|
|
||||||
|
// Auto-scroll to today's section on mount and when selectedDate changes to today
|
||||||
|
const scrollToToday = useCallback(() => {
|
||||||
|
if (todayRef.current) {
|
||||||
|
todayRef.current.scrollIntoView({ block: "start" });
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Scroll to today on mount
|
||||||
|
const frame = requestAnimationFrame(scrollToToday);
|
||||||
|
return () => cancelAnimationFrame(frame);
|
||||||
|
}, [scrollToToday]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Scroll to today when selectedDate changes to today
|
||||||
|
if (isToday(selectedDate)) {
|
||||||
|
scrollToToday();
|
||||||
|
}
|
||||||
|
}, [selectedDate, scrollToToday]);
|
||||||
|
|
||||||
const formatDateHeader = (date: Date): string => {
|
const formatDateHeader = (date: Date): string => {
|
||||||
if (isToday(date)) return t("events.today_header");
|
if (isToday(date)) return t("events.today_header");
|
||||||
if (isTomorrow(date)) return t("events.tomorrow_header");
|
if (isTomorrow(date)) return t("events.tomorrow_header");
|
||||||
@@ -86,19 +118,10 @@ export function CalendarAgendaView({
|
|||||||
return format(date, "HH:mm");
|
return format(date, "HH:mm");
|
||||||
};
|
};
|
||||||
|
|
||||||
if (grouped.length === 0) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground">
|
|
||||||
<CalendarIcon className="w-12 h-12 mb-3 opacity-30" />
|
|
||||||
<p className="text-sm">{t("events.no_events")}</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto" ref={scrollContainerRef}>
|
||||||
{grouped.map((group) => (
|
{grouped.map((group) => (
|
||||||
<div key={group.dateKey}>
|
<div key={group.dateKey} ref={isToday(group.date) ? todayRef : undefined}>
|
||||||
<div className="sticky top-0 bg-muted/80 backdrop-blur-sm px-4 py-2 border-b border-border">
|
<div className="sticky top-0 bg-muted/80 backdrop-blur-sm px-4 py-2 border-b border-border">
|
||||||
<span className={cn(
|
<span className={cn(
|
||||||
"text-sm font-medium",
|
"text-sm font-medium",
|
||||||
@@ -111,6 +134,11 @@ export function CalendarAgendaView({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{group.events.length === 0 ? (
|
||||||
|
<div className="px-4 py-6 text-center text-sm text-muted-foreground">
|
||||||
|
{t("events.no_events")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<div className="divide-y divide-border">
|
<div className="divide-y divide-border">
|
||||||
{group.events.map((ev) => {
|
{group.events.map((ev) => {
|
||||||
const calId = getPrimaryCalendarId(ev);
|
const calId = getPrimaryCalendarId(ev);
|
||||||
@@ -176,6 +204,7 @@ export function CalendarAgendaView({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,13 +2,15 @@
|
|||||||
|
|
||||||
import { useMemo, useEffect, useRef, useState } from "react";
|
import { useMemo, useEffect, useRef, useState } from "react";
|
||||||
import { useTranslations, useFormatter } from "next-intl";
|
import { useTranslations, useFormatter } from "next-intl";
|
||||||
import { format, isToday, parseISO } from "date-fns";
|
import { format, isSameDay, isToday, parseISO } from "date-fns";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Check } from "lucide-react";
|
||||||
import { EventCard, parseDuration } from "./event-card";
|
import { EventCard, parseDuration } from "./event-card";
|
||||||
import { QuickEventInput } from "./quick-event-input";
|
import { QuickEventInput } from "./quick-event-input";
|
||||||
import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
|
||||||
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
||||||
|
import type { PendingEventPreview } from "./event-modal";
|
||||||
|
|
||||||
interface CalendarDayViewProps {
|
interface CalendarDayViewProps {
|
||||||
selectedDate: Date;
|
selectedDate: Date;
|
||||||
@@ -20,6 +22,9 @@ interface CalendarDayViewProps {
|
|||||||
onCreateAtTime: (date: Date, endDate?: Date) => void;
|
onCreateAtTime: (date: Date, endDate?: Date) => void;
|
||||||
timeFormat?: "12h" | "24h";
|
timeFormat?: "12h" | "24h";
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
|
pendingPreview?: PendingEventPreview | null;
|
||||||
|
tasks?: CalendarTask[];
|
||||||
|
onToggleTaskComplete?: (task: CalendarTask) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const HOUR_HEIGHT = 64;
|
const HOUR_HEIGHT = 64;
|
||||||
@@ -35,6 +40,9 @@ export function CalendarDayView({
|
|||||||
onCreateAtTime,
|
onCreateAtTime,
|
||||||
timeFormat = "24h",
|
timeFormat = "24h",
|
||||||
isMobile,
|
isMobile,
|
||||||
|
pendingPreview,
|
||||||
|
tasks,
|
||||||
|
onToggleTaskComplete,
|
||||||
}: CalendarDayViewProps) {
|
}: CalendarDayViewProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const intlFormatter = useFormatter();
|
const intlFormatter = useFormatter();
|
||||||
@@ -65,6 +73,16 @@ export function CalendarDayView({
|
|||||||
return { timedEvents: timed, allDayEvents: allDay };
|
return { timedEvents: timed, allDayEvents: allDay };
|
||||||
}, [events, selectedDate]);
|
}, [events, selectedDate]);
|
||||||
|
|
||||||
|
const dayTasks = useMemo(() => {
|
||||||
|
if (!tasks?.length) return [];
|
||||||
|
return tasks.filter(task => {
|
||||||
|
if (!task.due) return false;
|
||||||
|
try {
|
||||||
|
return isSameDay(parseISO(task.due), selectedDate);
|
||||||
|
} catch { return false; }
|
||||||
|
});
|
||||||
|
}, [tasks, selectedDate]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (scrollRef.current) {
|
if (scrollRef.current) {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -122,25 +140,63 @@ export function CalendarDayView({
|
|||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{allDayEvents.length > 0 && (
|
{(allDayEvents.length > 0 || dayTasks.length > 0) && (
|
||||||
<div className="px-4 py-2 border-b border-border">
|
<div className="px-4 py-2 border-b border-border">
|
||||||
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
|
{allDayEvents.length > 0 && (
|
||||||
<div className="space-y-1">
|
<>
|
||||||
{allDayEvents.map((ev) => {
|
<div className="text-[10px] text-muted-foreground mb-1">{t("events.all_day")}</div>
|
||||||
const calId = getPrimaryCalendarId(ev);
|
<div className="space-y-1">
|
||||||
return (
|
{allDayEvents.map((ev) => {
|
||||||
<EventCard
|
const calId = getPrimaryCalendarId(ev);
|
||||||
key={ev.id}
|
return (
|
||||||
event={ev}
|
<EventCard
|
||||||
calendar={calId ? calendarMap.get(calId) : undefined}
|
key={ev.id}
|
||||||
variant="chip"
|
event={ev}
|
||||||
onClick={(rect) => onSelectEvent(ev, rect)}
|
calendar={calId ? calendarMap.get(calId) : undefined}
|
||||||
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
variant="chip"
|
||||||
onMouseLeave={onHoverLeave}
|
onClick={(rect) => onSelectEvent(ev, rect)}
|
||||||
/>
|
onMouseEnter={(rect) => onHoverEvent?.(ev, rect)}
|
||||||
);
|
onMouseLeave={onHoverLeave}
|
||||||
})}
|
/>
|
||||||
</div>
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{dayTasks.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className={cn("text-[10px] text-muted-foreground mb-1", allDayEvents.length > 0 && "mt-2")}>{t("tasks.label")}</div>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{dayTasks.map((task) => {
|
||||||
|
const isCompleted = task.progress === "completed";
|
||||||
|
const cal = calendars.find(c => task.calendarIds[c.id]);
|
||||||
|
const color = cal?.color || "#3b82f6";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={task.id}
|
||||||
|
className="flex items-center gap-1.5 px-1.5 py-0.5 rounded text-xs cursor-pointer hover:bg-muted/50 transition-colors"
|
||||||
|
style={{ borderLeft: `3px solid ${color}` }}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={(e) => { e.stopPropagation(); onToggleTaskComplete?.(task); }}
|
||||||
|
className={cn(
|
||||||
|
"flex-shrink-0 w-3.5 h-3.5 rounded-full border flex items-center justify-center",
|
||||||
|
isCompleted
|
||||||
|
? "bg-green-500 border-green-500 text-white"
|
||||||
|
: "border-muted-foreground/40 hover:border-primary"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{isCompleted && <Check className="h-2.5 w-2.5" />}
|
||||||
|
</button>
|
||||||
|
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
|
||||||
|
{task.title || t("tasks.no_title")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -274,6 +330,34 @@ export function CalendarDayView({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, selectedDate) && (
|
||||||
|
(() => {
|
||||||
|
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
|
||||||
|
const endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
|
||||||
|
const durationMin = Math.max(15, endMin - startMin);
|
||||||
|
const cal = calendars.find(c => c.id === pendingPreview.calendarId);
|
||||||
|
const color = cal?.color || "hsl(var(--primary))";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="absolute left-2 right-2 z-10 rounded-md pointer-events-none border-2 border-dashed overflow-hidden"
|
||||||
|
style={{
|
||||||
|
top: (startMin / 60) * HOUR_HEIGHT,
|
||||||
|
height: Math.max(24, (durationMin / 60) * HOUR_HEIGHT),
|
||||||
|
borderColor: color,
|
||||||
|
backgroundColor: `${color}10`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="text-[10px] font-medium px-1.5 py-0.5 truncate" style={{ color }}>
|
||||||
|
{pendingPreview.title}
|
||||||
|
</div>
|
||||||
|
<div className="text-[9px] px-1.5 opacity-70" style={{ color }}>
|
||||||
|
{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { buildWeekSegments, getEventDayBounds, getPrimaryCalendarId } from "@/li
|
|||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
|
import type { PendingEventPreview } from "./event-modal";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
|
|
||||||
interface CalendarMonthViewProps {
|
interface CalendarMonthViewProps {
|
||||||
@@ -25,6 +26,7 @@ interface CalendarMonthViewProps {
|
|||||||
onCreateAtTime?: (date: Date) => void;
|
onCreateAtTime?: (date: Date) => void;
|
||||||
firstDayOfWeek?: number;
|
firstDayOfWeek?: number;
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
|
pendingPreview?: PendingEventPreview | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CalendarMonthView({
|
export function CalendarMonthView({
|
||||||
@@ -38,6 +40,7 @@ export function CalendarMonthView({
|
|||||||
onCreateAtTime,
|
onCreateAtTime,
|
||||||
firstDayOfWeek = 1,
|
firstDayOfWeek = 1,
|
||||||
isMobile,
|
isMobile,
|
||||||
|
pendingPreview,
|
||||||
}: CalendarMonthViewProps) {
|
}: CalendarMonthViewProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const intlFormatter = useFormatter();
|
const intlFormatter = useFormatter();
|
||||||
@@ -194,31 +197,63 @@ export function CalendarMonthView({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{isMobile ? (
|
{isMobile ? (
|
||||||
dayEvents.length > 0 && (
|
<div className="flex items-center justify-center gap-0.5 flex-wrap">
|
||||||
<div className="flex items-center justify-center gap-0.5 flex-wrap">
|
{dayEvents.slice(0, 3).map((ev) => {
|
||||||
{dayEvents.slice(0, 3).map((ev) => {
|
const calId = getPrimaryCalendarId(ev);
|
||||||
const calId = getPrimaryCalendarId(ev);
|
const cal = calId ? calendarMap.get(calId) : undefined;
|
||||||
const cal = calId ? calendarMap.get(calId) : undefined;
|
const evColor = ev.color || cal?.color || "#3b82f6";
|
||||||
const evColor = ev.color || cal?.color || "#3b82f6";
|
return (
|
||||||
return (
|
<span
|
||||||
<span
|
key={ev.id}
|
||||||
key={ev.id}
|
className="w-1.5 h-1.5 rounded-full"
|
||||||
className="w-1.5 h-1.5 rounded-full"
|
style={{ backgroundColor: evColor }}
|
||||||
style={{ backgroundColor: evColor }}
|
/>
|
||||||
/>
|
);
|
||||||
);
|
})}
|
||||||
})}
|
{dayEvents.length > 3 && (
|
||||||
{dayEvents.length > 3 && (
|
<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
|
||||||
<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
|
)}
|
||||||
)}
|
{pendingPreview && isSameDay(pendingPreview.start, day) && (
|
||||||
</div>
|
<span
|
||||||
)
|
className="w-1.5 h-1.5 rounded-full border border-dashed"
|
||||||
|
style={{ borderColor: calendarMap.get(pendingPreview.calendarId)?.color || "#3b82f6" }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!isMobile && pendingPreview && (() => {
|
||||||
|
const previewDayIdx = week.findIndex(d => isSameDay(d, pendingPreview.start));
|
||||||
|
if (previewDayIdx === -1) return null;
|
||||||
|
const previewRow = rowCount;
|
||||||
|
const cal = calendarMap.get(pendingPreview.calendarId);
|
||||||
|
const color = cal?.color || "#3b82f6";
|
||||||
|
return (
|
||||||
|
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
|
||||||
|
<div
|
||||||
|
className="absolute px-0.5"
|
||||||
|
style={{
|
||||||
|
left: `calc(${(previewDayIdx / 7) * 100}% + 1px)`,
|
||||||
|
width: `calc(${(1 / 7) * 100}% - 2px)`,
|
||||||
|
top: previewRow * 22,
|
||||||
|
height: 20,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="h-full rounded text-[10px] leading-[20px] font-medium px-1.5 truncate border-2 border-dashed"
|
||||||
|
style={{ borderColor: color, color, backgroundColor: `${color}10` }}
|
||||||
|
>
|
||||||
|
{pendingPreview.title}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
|
||||||
{!isMobile && segments.length > 0 && (
|
{!isMobile && segments.length > 0 && (
|
||||||
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
|
<div className="absolute inset-x-0 pointer-events-none" style={{ top: 30 }}>
|
||||||
{segments.map((segment) => {
|
{segments.map((segment) => {
|
||||||
|
|||||||
@@ -2,14 +2,15 @@
|
|||||||
|
|
||||||
import { useState, useRef, useEffect, useMemo } from "react";
|
import { useState, useRef, useEffect, useMemo } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
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 { cn, formatDateTime } from "@/lib/utils";
|
||||||
import type { Calendar } from "@/lib/jmap/types";
|
import type { Calendar } from "@/lib/jmap/types";
|
||||||
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
import { useTaskStore } from "@/stores/task-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import type { JMAPClient } from "@/lib/jmap/client";
|
import type { IJMAPClient } from '@/lib/jmap/client-interface';
|
||||||
|
|
||||||
interface CalendarSidebarPanelProps {
|
interface CalendarSidebarPanelProps {
|
||||||
calendars: Calendar[];
|
calendars: Calendar[];
|
||||||
@@ -17,7 +18,7 @@ interface CalendarSidebarPanelProps {
|
|||||||
onToggleVisibility: (id: string) => void;
|
onToggleVisibility: (id: string) => void;
|
||||||
onColorChange?: (calendarId: string, color: string) => void;
|
onColorChange?: (calendarId: string, color: string) => void;
|
||||||
onSubscribe?: () => void;
|
onSubscribe?: () => void;
|
||||||
client?: JMAPClient | null;
|
client?: IJMAPClient | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CalendarSidebarPanel({
|
export function CalendarSidebarPanel({
|
||||||
@@ -35,6 +36,15 @@ export function CalendarSidebarPanel({
|
|||||||
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
|
const refreshICalSubscription = useCalendarStore((s) => s.refreshICalSubscription);
|
||||||
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
|
const removeICalSubscription = useCalendarStore((s) => s.removeICalSubscription);
|
||||||
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
const enableCalendarTasks = useSettingsStore((s) => s.enableCalendarTasks);
|
||||||
|
const tasks = useTaskStore((s) => s.tasks);
|
||||||
|
const setViewMode = useCalendarStore((s) => s.setViewMode);
|
||||||
|
|
||||||
|
const pendingTaskCount = useMemo(() => tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled').length, [tasks]);
|
||||||
|
const overdueTaskCount = useMemo(() => {
|
||||||
|
const now = new Date();
|
||||||
|
return tasks.filter(t => t.progress !== 'completed' && t.progress !== 'cancelled' && t.due && new Date(t.due) < now).length;
|
||||||
|
}, [tasks]);
|
||||||
|
|
||||||
const [colorPickerId, setColorPickerId] = useState<string | null>(null);
|
const [colorPickerId, setColorPickerId] = useState<string | null>(null);
|
||||||
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
|
const [contextMenuCalId, setContextMenuCalId] = useState<string | null>(null);
|
||||||
@@ -209,6 +219,21 @@ export function CalendarSidebarPanel({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-4">
|
<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">
|
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2 px-1">
|
||||||
{t("my_calendars")}
|
{t("my_calendars")}
|
||||||
</h3>
|
</h3>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useState, useRef, useEffect } from "react";
|
import { useState, useRef, useEffect } from "react";
|
||||||
import { useTranslations, useFormatter } from "next-intl";
|
import { useTranslations, useFormatter } from "next-intl";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown } from "lucide-react";
|
import { ChevronLeft, ChevronRight, Plus, Upload, CalendarDays, Globe, ChevronDown, ListTodo } from "lucide-react";
|
||||||
import { addDays, startOfWeek } from "date-fns";
|
import { addDays, startOfWeek } from "date-fns";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { CalendarViewMode } from "@/stores/calendar-store";
|
import type { CalendarViewMode } from "@/stores/calendar-store";
|
||||||
@@ -25,6 +25,7 @@ interface CalendarToolbarProps {
|
|||||||
calendars?: Calendar[];
|
calendars?: Calendar[];
|
||||||
selectedCalendarIds?: string[];
|
selectedCalendarIds?: string[];
|
||||||
onToggleVisibility?: (id: string) => void;
|
onToggleVisibility?: (id: string) => void;
|
||||||
|
enableCalendarTasks?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CalendarToolbar({
|
export function CalendarToolbar({
|
||||||
@@ -42,10 +43,13 @@ export function CalendarToolbar({
|
|||||||
calendars,
|
calendars,
|
||||||
selectedCalendarIds,
|
selectedCalendarIds,
|
||||||
onToggleVisibility,
|
onToggleVisibility,
|
||||||
|
enableCalendarTasks,
|
||||||
}: CalendarToolbarProps) {
|
}: CalendarToolbarProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const formatter = useFormatter();
|
const formatter = useFormatter();
|
||||||
const views: CalendarViewMode[] = ["month", "week", "day", "agenda"];
|
const views: CalendarViewMode[] = enableCalendarTasks
|
||||||
|
? ["month", "week", "day", "agenda", "tasks"]
|
||||||
|
: ["month", "week", "day", "agenda"];
|
||||||
const [showCalendarDropdown, setShowCalendarDropdown] = useState(false);
|
const [showCalendarDropdown, setShowCalendarDropdown] = useState(false);
|
||||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
@@ -86,6 +90,8 @@ export function CalendarToolbar({
|
|||||||
return isMobile
|
return isMobile
|
||||||
? formatter.dateTime(selectedDate, { month: "short", year: "numeric" })
|
? formatter.dateTime(selectedDate, { month: "short", year: "numeric" })
|
||||||
: formatter.dateTime(selectedDate, { month: "long", year: "numeric" });
|
: formatter.dateTime(selectedDate, { month: "long", year: "numeric" });
|
||||||
|
case "tasks":
|
||||||
|
return t("views.tasks");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -136,6 +142,20 @@ export function CalendarToolbar({
|
|||||||
{t("views.today")}
|
{t("views.today")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{!isMobile && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onPrev} aria-label={t("nav_prev")}>
|
||||||
|
<ChevronLeft className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onNext} aria-label={t("nav_next")}>
|
||||||
|
<ChevronRight className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<span className="text-base font-semibold ml-2 select-none">
|
||||||
|
{getDateLabel()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{isMobile && calendars && selectedCalendarIds && onToggleVisibility && (
|
{isMobile && calendars && selectedCalendarIds && onToggleVisibility && (
|
||||||
<div className="relative" ref={dropdownRef}>
|
<div className="relative" ref={dropdownRef}>
|
||||||
<Button
|
<Button
|
||||||
@@ -312,7 +332,7 @@ export function CalendarToolbar({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{!isMobile && (
|
{!isMobile && (
|
||||||
<Button size="sm" onClick={onCreateEvent}>
|
<Button size="sm" onClick={onCreateEvent} data-tour="create-event-button">
|
||||||
<Plus className="w-4 h-4 mr-1" />
|
<Plus className="w-4 h-4 mr-1" />
|
||||||
{t("events.create")}
|
{t("events.create")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ import {
|
|||||||
startOfWeek, addDays, format, isSameDay, isToday, parseISO,
|
startOfWeek, addDays, format, isSameDay, isToday, parseISO,
|
||||||
} from "date-fns";
|
} from "date-fns";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Check } from "lucide-react";
|
||||||
import { EventCard, parseDuration } from "./event-card";
|
import { EventCard, parseDuration } from "./event-card";
|
||||||
import { QuickEventInput } from "./quick-event-input";
|
import { QuickEventInput } from "./quick-event-input";
|
||||||
import { buildWeekSegments, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
import { buildWeekSegments, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, layoutOverlappingEvents } from "@/lib/calendar-utils";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types";
|
||||||
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
import { useTimeGridInteractions } from "@/hooks/use-time-grid-interactions";
|
||||||
|
import type { PendingEventPreview } from "./event-modal";
|
||||||
|
|
||||||
interface CalendarWeekViewProps {
|
interface CalendarWeekViewProps {
|
||||||
selectedDate: Date;
|
selectedDate: Date;
|
||||||
@@ -24,6 +26,9 @@ interface CalendarWeekViewProps {
|
|||||||
firstDayOfWeek?: number;
|
firstDayOfWeek?: number;
|
||||||
timeFormat?: "12h" | "24h";
|
timeFormat?: "12h" | "24h";
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
|
pendingPreview?: PendingEventPreview | null;
|
||||||
|
tasks?: CalendarTask[];
|
||||||
|
onToggleTaskComplete?: (task: CalendarTask) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const HOUR_HEIGHT = 60;
|
const HOUR_HEIGHT = 60;
|
||||||
@@ -41,6 +46,9 @@ export function CalendarWeekView({
|
|||||||
firstDayOfWeek = 1,
|
firstDayOfWeek = 1,
|
||||||
timeFormat = "24h",
|
timeFormat = "24h",
|
||||||
isMobile,
|
isMobile,
|
||||||
|
pendingPreview,
|
||||||
|
tasks,
|
||||||
|
onToggleTaskComplete,
|
||||||
}: CalendarWeekViewProps) {
|
}: CalendarWeekViewProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const intlFormatter = useFormatter();
|
const intlFormatter = useFormatter();
|
||||||
@@ -93,9 +101,36 @@ export function CalendarWeekView({
|
|||||||
return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0);
|
return allDaySegments.reduce((maxRows, segment) => Math.max(maxRows, segment.row + 1), 0);
|
||||||
}, [allDaySegments]);
|
}, [allDaySegments]);
|
||||||
|
|
||||||
|
// Tasks grouped by day for the week
|
||||||
|
const tasksByDay = useMemo(() => {
|
||||||
|
if (!tasks?.length) return new Map<string, CalendarTask[]>();
|
||||||
|
const map = new Map<string, CalendarTask[]>();
|
||||||
|
for (const task of tasks) {
|
||||||
|
if (!task.due) continue;
|
||||||
|
try {
|
||||||
|
const key = format(parseISO(task.due), "yyyy-MM-dd");
|
||||||
|
const existing = map.get(key) || [];
|
||||||
|
existing.push(task);
|
||||||
|
map.set(key, existing);
|
||||||
|
} catch { /* skip */ }
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [tasks]);
|
||||||
|
|
||||||
|
// Max tasks on any single day in this week
|
||||||
|
const taskRowCount = useMemo(() => {
|
||||||
|
let max = 0;
|
||||||
|
for (const day of weekDays) {
|
||||||
|
const key = format(day, "yyyy-MM-dd");
|
||||||
|
const count = tasksByDay.get(key)?.length ?? 0;
|
||||||
|
if (count > max) max = count;
|
||||||
|
}
|
||||||
|
return max;
|
||||||
|
}, [tasksByDay, weekDays]);
|
||||||
|
|
||||||
const hasAllDay = useMemo(() => {
|
const hasAllDay = useMemo(() => {
|
||||||
return allDaySegments.length > 0;
|
return allDaySegments.length > 0 || taskRowCount > 0;
|
||||||
}, [allDaySegments]);
|
}, [allDaySegments, taskRowCount]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (scrollRef.current) {
|
if (scrollRef.current) {
|
||||||
@@ -148,13 +183,13 @@ export function CalendarWeekView({
|
|||||||
<div className="flex border-b border-border">
|
<div className="flex border-b border-border">
|
||||||
<div
|
<div
|
||||||
className={cn("flex-shrink-0 text-[10px] text-muted-foreground p-1 text-right", isMobile ? "w-10" : "w-14")}
|
className={cn("flex-shrink-0 text-[10px] text-muted-foreground p-1 text-right", isMobile ? "w-10" : "w-14")}
|
||||||
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }}
|
style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
|
||||||
>
|
>
|
||||||
{t("events.all_day")}
|
{t("events.all_day")}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className={cn("flex-1 relative grid gap-px bg-border", isMobile ? "grid-cols-3" : "grid-cols-7")}
|
className={cn("flex-1 relative grid gap-px bg-border", isMobile ? "grid-cols-3" : "grid-cols-7")}
|
||||||
style={{ minHeight: Math.max(28, allDayRowCount * 24 + 4) }}
|
style={{ minHeight: Math.max(28, (allDayRowCount + taskRowCount) * 24 + 4) }}
|
||||||
>
|
>
|
||||||
{weekDays.map((day) => (
|
{weekDays.map((day) => (
|
||||||
<div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" />
|
<div key={format(day, "yyyy-MM-dd")} className="bg-background min-h-[28px]" />
|
||||||
@@ -188,6 +223,49 @@ export function CalendarWeekView({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Task chips in all-day area */}
|
||||||
|
{taskRowCount > 0 && (
|
||||||
|
<div className="absolute inset-x-0 pointer-events-none" style={{ top: allDayRowCount * 24 + 2 }}>
|
||||||
|
{weekDays.map((day, dayIndex) => {
|
||||||
|
const key = format(day, "yyyy-MM-dd");
|
||||||
|
const dayTasks = tasksByDay.get(key) || [];
|
||||||
|
return dayTasks.map((task, taskIndex) => {
|
||||||
|
const isCompleted = task.progress === "completed";
|
||||||
|
const cal = calendars.find(c => task.calendarIds[c.id]);
|
||||||
|
const color = cal?.color || "#3b82f6";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`task-${task.id}`}
|
||||||
|
className="absolute px-0.5 pointer-events-auto"
|
||||||
|
style={{
|
||||||
|
left: `calc(${(dayIndex / colCount) * 100}% + 1px)`,
|
||||||
|
width: `calc(${(1 / colCount) * 100}% - 2px)`,
|
||||||
|
top: taskIndex * 24,
|
||||||
|
height: 20,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="h-full rounded text-[10px] leading-[20px] font-medium px-1.5 truncate flex items-center gap-1 cursor-pointer hover:opacity-80"
|
||||||
|
style={{ backgroundColor: `${color}20`, borderLeft: `3px solid ${color}` }}
|
||||||
|
onClick={() => onToggleTaskComplete?.(task)}
|
||||||
|
>
|
||||||
|
<span className={cn(
|
||||||
|
"w-2.5 h-2.5 rounded-full border flex-shrink-0 flex items-center justify-center",
|
||||||
|
isCompleted ? "bg-green-500 border-green-500" : "border-current"
|
||||||
|
)}>
|
||||||
|
{isCompleted && <Check className="h-2 w-2 text-white" />}
|
||||||
|
</span>
|
||||||
|
<span className={cn("truncate", isCompleted && "line-through text-muted-foreground")}>
|
||||||
|
{task.title}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -366,6 +444,35 @@ export function CalendarWeekView({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && (
|
||||||
|
(() => {
|
||||||
|
const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes();
|
||||||
|
let endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes();
|
||||||
|
if (endMin <= startMin) endMin = 1440;
|
||||||
|
const durationMin = Math.max(15, endMin - startMin);
|
||||||
|
const cal = calendars.find(c => c.id === pendingPreview.calendarId);
|
||||||
|
const color = cal?.color || "hsl(var(--primary))";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="absolute left-1 right-1 z-10 rounded-md pointer-events-none border-2 border-dashed overflow-hidden"
|
||||||
|
style={{
|
||||||
|
top: (startMin / 60) * HOUR_HEIGHT,
|
||||||
|
height: Math.max(20, (durationMin / 60) * HOUR_HEIGHT),
|
||||||
|
borderColor: color,
|
||||||
|
backgroundColor: `${color}10`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="text-[10px] font-medium px-1.5 py-0.5 truncate" style={{ color }}>
|
||||||
|
{pendingPreview.title}
|
||||||
|
</div>
|
||||||
|
<div className="text-[9px] px-1.5 opacity-70" style={{ color }}>
|
||||||
|
{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})()
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
|
|||||||
const color = getEventColor(event, calendar);
|
const color = getEventColor(event, calendar);
|
||||||
const startDate = parseISO(event.start);
|
const startDate = parseISO(event.start);
|
||||||
const timeFormat = useSettingsStore((state) => state.timeFormat);
|
const timeFormat = useSettingsStore((state) => state.timeFormat);
|
||||||
|
const showTimeInMonthView = useSettingsStore((state) => state.showTimeInMonthView);
|
||||||
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
|
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
|
||||||
|
|
||||||
const calendarName = calendar?.name || "";
|
const calendarName = calendar?.name || "";
|
||||||
@@ -156,6 +157,9 @@ export function EventCard({ event, calendar, variant, onClick, onMouseEnter, onM
|
|||||||
style={{ backgroundColor: `${color}24`, borderLeft: `3px solid ${color}`, color, ...style }}
|
style={{ backgroundColor: `${color}24`, borderLeft: `3px solid ${color}`, color, ...style }}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-1 min-w-0">
|
<div className="flex items-center gap-1 min-w-0">
|
||||||
|
{showTimeInMonthView && !event.showWithoutTime && (
|
||||||
|
<span className="flex-shrink-0 opacity-80">{format(startDate, timeFmt)}</span>
|
||||||
|
)}
|
||||||
<span className="truncate font-medium">{event.title || t("events.no_title")}</span>
|
<span className="truncate font-medium">{event.title || t("events.no_title")}</span>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -192,6 +192,10 @@ export function EventDetailPopover({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleKey = (e: KeyboardEvent) => {
|
const handleKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") onClose();
|
if (e.key === "Escape") onClose();
|
||||||
|
const target = e.target as HTMLElement;
|
||||||
|
const tag = target?.tagName?.toLowerCase();
|
||||||
|
if (tag === "input" || tag === "textarea" || tag === "select") return;
|
||||||
|
if (target?.getAttribute("contenteditable") === "true") return;
|
||||||
if (e.key === "e" && !noteExpanded) {
|
if (e.key === "e" && !noteExpanded) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
onEdit();
|
onEdit();
|
||||||
|
|||||||
@@ -20,6 +20,14 @@ import {
|
|||||||
} from "@/lib/calendar-participants";
|
} from "@/lib/calendar-participants";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
|
||||||
|
export interface PendingEventPreview {
|
||||||
|
start: Date;
|
||||||
|
end: Date;
|
||||||
|
title: string;
|
||||||
|
allDay: boolean;
|
||||||
|
calendarId: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface EventModalProps {
|
interface EventModalProps {
|
||||||
event?: CalendarEvent | null;
|
event?: CalendarEvent | null;
|
||||||
calendars: Calendar[];
|
calendars: Calendar[];
|
||||||
@@ -30,6 +38,7 @@ interface EventModalProps {
|
|||||||
onDuplicate?: (data: Partial<CalendarEvent>) => void;
|
onDuplicate?: (data: Partial<CalendarEvent>) => void;
|
||||||
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
|
onRsvp?: (eventId: string, participantId: string, status: CalendarParticipant['participationStatus']) => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
onPreviewChange?: (preview: PendingEventPreview | null) => void;
|
||||||
currentUserEmails?: string[];
|
currentUserEmails?: string[];
|
||||||
isMobile?: boolean;
|
isMobile?: boolean;
|
||||||
}
|
}
|
||||||
@@ -50,10 +59,12 @@ function buildDuration(startDate: Date, endDate: Date): string {
|
|||||||
const minutes = totalMinutes % 60;
|
const minutes = totalMinutes % 60;
|
||||||
let dur = "P";
|
let dur = "P";
|
||||||
if (days > 0) dur += `${days}D`;
|
if (days > 0) dur += `${days}D`;
|
||||||
dur += "T";
|
if (hours > 0 || minutes > 0) {
|
||||||
if (hours > 0) dur += `${hours}H`;
|
dur += "T";
|
||||||
if (minutes > 0) dur += `${minutes}M`;
|
if (hours > 0) dur += `${hours}H`;
|
||||||
if (dur === "PT") dur = "PT0M";
|
if (minutes > 0) dur += `${minutes}M`;
|
||||||
|
}
|
||||||
|
if (dur === "P") dur = "PT0M";
|
||||||
return dur;
|
return dur;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,9 +85,9 @@ function getAlertLabel(event: CalendarEvent, t: ReturnType<typeof useTranslation
|
|||||||
if (!first || first.trigger["@type"] !== "OffsetTrigger") return null;
|
if (!first || first.trigger["@type"] !== "OffsetTrigger") return null;
|
||||||
const offset = first.trigger.offset;
|
const offset = first.trigger.offset;
|
||||||
if (offset === "PT0S") return t("alerts.at_time");
|
if (offset === "PT0S") return t("alerts.at_time");
|
||||||
const minMatch = offset.match(/-?PT?(\d+)M$/);
|
const minMatch = offset.match(/-?PT(\d+)M$/);
|
||||||
if (minMatch) return t("alerts.minutes_before", { count: parseInt(minMatch[1]) });
|
if (minMatch) return t("alerts.minutes_before", { count: parseInt(minMatch[1]) });
|
||||||
const hourMatch = offset.match(/-?PT?(\d+)H$/);
|
const hourMatch = offset.match(/-?PT(\d+)H$/);
|
||||||
if (hourMatch) return t("alerts.hours_before", { count: parseInt(hourMatch[1]) });
|
if (hourMatch) return t("alerts.hours_before", { count: parseInt(hourMatch[1]) });
|
||||||
const dayMatch = offset.match(/-?P(\d+)D/);
|
const dayMatch = offset.match(/-?P(\d+)D/);
|
||||||
if (dayMatch) return t("alerts.days_before", { count: parseInt(dayMatch[1]) });
|
if (dayMatch) return t("alerts.days_before", { count: parseInt(dayMatch[1]) });
|
||||||
@@ -105,6 +116,7 @@ export function EventModal({
|
|||||||
onDuplicate,
|
onDuplicate,
|
||||||
onRsvp,
|
onRsvp,
|
||||||
onClose,
|
onClose,
|
||||||
|
onPreviewChange,
|
||||||
currentUserEmails = [],
|
currentUserEmails = [],
|
||||||
isMobile = false,
|
isMobile = false,
|
||||||
}: EventModalProps) {
|
}: EventModalProps) {
|
||||||
@@ -199,9 +211,9 @@ export function EventModal({
|
|||||||
if (first.trigger["@type"] === "OffsetTrigger") {
|
if (first.trigger["@type"] === "OffsetTrigger") {
|
||||||
const offset = first.trigger.offset;
|
const offset = first.trigger.offset;
|
||||||
if (offset === "PT0S") return "at_time";
|
if (offset === "PT0S") return "at_time";
|
||||||
const minMatch = offset.match(/-?PT?(\d+)M$/);
|
const minMatch = offset.match(/-?PT(\d+)M$/);
|
||||||
if (minMatch) return minMatch[1] as AlertOption;
|
if (minMatch) return minMatch[1] as AlertOption;
|
||||||
const hourMatch = offset.match(/-?PT?(\d+)H$/);
|
const hourMatch = offset.match(/-?PT(\d+)H$/);
|
||||||
if (hourMatch) return String(parseInt(hourMatch[1]) * 60) as AlertOption;
|
if (hourMatch) return String(parseInt(hourMatch[1]) * 60) as AlertOption;
|
||||||
const dayMatch = offset.match(/-?P(\d+)D/);
|
const dayMatch = offset.match(/-?P(\d+)D/);
|
||||||
if (dayMatch) return String(parseInt(dayMatch[1]) * 1440) as AlertOption;
|
if (dayMatch) return String(parseInt(dayMatch[1]) * 1440) as AlertOption;
|
||||||
@@ -219,6 +231,18 @@ export function EventModal({
|
|||||||
});
|
});
|
||||||
const [sendInvitations, setSendInvitations] = useState(true);
|
const [sendInvitations, setSendInvitations] = useState(true);
|
||||||
|
|
||||||
|
// Report live preview to parent for grid outline
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onPreviewChange || isEdit) return;
|
||||||
|
const startStr = allDay ? `${startDate}T00:00:00` : `${startDate}T${startTime}:00`;
|
||||||
|
const endStr = allDay ? `${endDate}T23:59:59` : `${endDate}T${endTime}:00`;
|
||||||
|
const s = new Date(startStr);
|
||||||
|
const e = new Date(endStr);
|
||||||
|
if (isNaN(s.getTime()) || isNaN(e.getTime())) return;
|
||||||
|
onPreviewChange({ start: s, end: e, title: title || "(No title)", allDay, calendarId });
|
||||||
|
return () => onPreviewChange(null);
|
||||||
|
}, [startDate, startTime, endDate, endTime, allDay, title, calendarId, isEdit, onPreviewChange]);
|
||||||
|
|
||||||
const statusCounts = useMemo(() => {
|
const statusCounts = useMemo(() => {
|
||||||
if (!event?.participants) return null;
|
if (!event?.participants) return null;
|
||||||
return getStatusCounts(event);
|
return getStatusCounts(event);
|
||||||
@@ -362,7 +386,11 @@ export function EventModal({
|
|||||||
if (!event || !onDuplicate) return;
|
if (!event || !onDuplicate) return;
|
||||||
const start = parseISO(event.start);
|
const start = parseISO(event.start);
|
||||||
const newStart = addDays(start, 1);
|
const newStart = addDays(start, 1);
|
||||||
|
const newUid = typeof crypto !== 'undefined' && crypto.randomUUID
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
||||||
const data: Partial<CalendarEvent> = {
|
const data: Partial<CalendarEvent> = {
|
||||||
|
uid: newUid,
|
||||||
title: event.title,
|
title: event.title,
|
||||||
description: event.description,
|
description: event.description,
|
||||||
start: format(newStart, "yyyy-MM-dd'T'HH:mm:ss"),
|
start: format(newStart, "yyyy-MM-dd'T'HH:mm:ss"),
|
||||||
@@ -707,7 +735,7 @@ export function EventModal({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={modalRef} role="dialog" aria-modal={isMobile || undefined} aria-label={isEdit ? t("events.edit") : t("events.create")} className={isMobile ? "fixed inset-0 z-50 flex flex-col bg-background" : "flex flex-col h-full bg-background"}>
|
<div ref={modalRef} role="dialog" aria-modal={isMobile || undefined} aria-label={isEdit ? t("events.edit") : t("events.create")} data-tour="event-modal" className={isMobile ? "fixed inset-0 z-50 flex flex-col bg-background" : "flex flex-col h-full bg-background"}>
|
||||||
<div className="flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0">
|
<div className="flex items-center justify-between px-6 py-4 border-b border-border flex-shrink-0">
|
||||||
<h2 className="text-lg font-semibold">
|
<h2 className="text-lg font-semibold">
|
||||||
{isEdit ? t("events.edit") : t("events.create")}
|
{isEdit ? t("events.edit") : t("events.create")}
|
||||||
|
|||||||
@@ -6,14 +6,14 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { X, Upload, Check, Loader2, RefreshCw, Globe } from "lucide-react";
|
import { X, Upload, Check, Loader2, RefreshCw, Globe } from "lucide-react";
|
||||||
import { format, parseISO } from "date-fns";
|
import { format, parseISO } from "date-fns";
|
||||||
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
import type { CalendarEvent, Calendar } from "@/lib/jmap/types";
|
||||||
import type { JMAPClient } from "@/lib/jmap/client";
|
import type { IJMAPClient } from '@/lib/jmap/client-interface';
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
import { useSettingsStore } from "@/stores/settings-store";
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
|
|
||||||
interface ICalImportModalProps {
|
interface ICalImportModalProps {
|
||||||
calendars: Calendar[];
|
calendars: Calendar[];
|
||||||
client: JMAPClient;
|
client: IJMAPClient;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import { useState, useRef, useEffect, useCallback } from "react";
|
|||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { X, Loader2, Globe } from "lucide-react";
|
import { X, Loader2, Globe } from "lucide-react";
|
||||||
import type { JMAPClient } from "@/lib/jmap/client";
|
import type { IJMAPClient } from '@/lib/jmap/client-interface';
|
||||||
import { useCalendarStore } from "@/stores/calendar-store";
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
import { CalendarColorPicker } from "@/components/settings/calendar-management-settings";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
|
|
||||||
interface ICalSubscriptionModalProps {
|
interface ICalSubscriptionModalProps {
|
||||||
client: JMAPClient;
|
client: IJMAPClient;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo, Fragment } from "react";
|
||||||
import { useTranslations, useFormatter } from "next-intl";
|
import { useTranslations, useFormatter } from "next-intl";
|
||||||
import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react";
|
import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
|
startOfMonth, endOfMonth, startOfWeek, endOfWeek,
|
||||||
addMonths, subMonths, addYears, subYears, setMonth, setYear,
|
addMonths, subMonths, addYears, subYears, setMonth, setYear,
|
||||||
eachDayOfInterval, getMonth, getYear,
|
eachDayOfInterval, getMonth, getYear, getISOWeek, getWeek,
|
||||||
isSameDay, isSameMonth, isToday, format,
|
isSameDay, isSameMonth, isToday, format,
|
||||||
} from "date-fns";
|
} from "date-fns";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -26,6 +26,7 @@ interface MiniCalendarProps {
|
|||||||
onChangeMonth: (date: Date) => void;
|
onChangeMonth: (date: Date) => void;
|
||||||
events?: CalendarEvent[];
|
events?: CalendarEvent[];
|
||||||
firstDayOfWeek?: number;
|
firstDayOfWeek?: number;
|
||||||
|
showWeekNumbers?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MiniCalendar({
|
export function MiniCalendar({
|
||||||
@@ -35,6 +36,7 @@ export function MiniCalendar({
|
|||||||
onChangeMonth,
|
onChangeMonth,
|
||||||
events = [],
|
events = [],
|
||||||
firstDayOfWeek = 1,
|
firstDayOfWeek = 1,
|
||||||
|
showWeekNumbers = false,
|
||||||
}: MiniCalendarProps) {
|
}: MiniCalendarProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const intlFormatter = useFormatter();
|
const intlFormatter = useFormatter();
|
||||||
@@ -61,6 +63,17 @@ export function MiniCalendar({
|
|||||||
? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const
|
? ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const
|
||||||
: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
|
: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
|
||||||
|
|
||||||
|
// Compute week numbers for each row (one per 7-day chunk)
|
||||||
|
const weekNumbers = useMemo(() => {
|
||||||
|
if (!showWeekNumbers) return [];
|
||||||
|
const nums: number[] = [];
|
||||||
|
for (let i = 0; i < days.length; i += 7) {
|
||||||
|
// Use the first day of each row to determine the week number
|
||||||
|
nums.push(weekStart === 1 ? getISOWeek(days[i]) : getWeek(days[i], { weekStartsOn: 0 }));
|
||||||
|
}
|
||||||
|
return nums;
|
||||||
|
}, [days, showWeekNumbers, weekStart]);
|
||||||
|
|
||||||
const currentYear = getYear(displayMonth);
|
const currentYear = getYear(displayMonth);
|
||||||
const currentMonth = getMonth(displayMonth);
|
const currentMonth = getMonth(displayMonth);
|
||||||
const decadeStart = Math.floor(currentYear / 10) * 10;
|
const decadeStart = Math.floor(currentYear / 10) * 10;
|
||||||
@@ -135,35 +148,49 @@ export function MiniCalendar({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{pickerView === "days" && (
|
{pickerView === "days" && (
|
||||||
<div className="grid grid-cols-7 gap-0">
|
<div className={cn("grid gap-0", showWeekNumbers ? "grid-cols-[auto_repeat(7,1fr)]" : "grid-cols-7")}>
|
||||||
|
{showWeekNumbers && (
|
||||||
|
<div className="text-center text-[10px] font-medium text-muted-foreground py-1 w-5" />
|
||||||
|
)}
|
||||||
{dayHeaders.map((d) => (
|
{dayHeaders.map((d) => (
|
||||||
<div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1">
|
<div key={d} className="text-center text-[10px] font-medium text-muted-foreground py-1">
|
||||||
{t(`days.${d}`)}
|
{t(`days.${d}`)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{days.map((day) => {
|
{days.map((day, index) => {
|
||||||
const inMonth = isSameMonth(day, displayMonth);
|
const inMonth = isSameMonth(day, displayMonth);
|
||||||
const selected = isSameDay(day, selectedDate);
|
const selected = isSameDay(day, selectedDate);
|
||||||
const today = isToday(day);
|
const today = isToday(day);
|
||||||
const hasEvent = eventDates.has(format(day, "yyyy-MM-dd"));
|
const hasEvent = eventDates.has(format(day, "yyyy-MM-dd"));
|
||||||
|
const isFirstDayOfRow = index % 7 === 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<Fragment key={day.toISOString()}>
|
||||||
key={day.toISOString()}
|
{showWeekNumbers && isFirstDayOfRow && (
|
||||||
onClick={() => onSelectDate(day)}
|
<div
|
||||||
className={cn(
|
key={`wk-${index}`}
|
||||||
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
|
className="flex items-center justify-center w-5 text-[9px] text-muted-foreground/60 font-medium"
|
||||||
!inMonth && "text-muted-foreground/40",
|
>
|
||||||
inMonth && !selected && "hover:bg-muted",
|
{weekNumbers[index / 7]}
|
||||||
today && !selected && "font-bold text-primary",
|
</div>
|
||||||
selected && "bg-primary text-primary-foreground"
|
|
||||||
)}
|
)}
|
||||||
>
|
<button
|
||||||
{format(day, "d")}
|
key={`day-${day.toISOString()}`}
|
||||||
{hasEvent && !selected && (
|
onClick={() => onSelectDate(day)}
|
||||||
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" />
|
className={cn(
|
||||||
)}
|
"relative flex items-center justify-center w-7 h-7 text-xs rounded-full transition-colors",
|
||||||
</button>
|
!inMonth && "text-muted-foreground/40",
|
||||||
|
inMonth && !selected && "hover:bg-muted",
|
||||||
|
today && !selected && "font-bold text-primary",
|
||||||
|
selected && "bg-primary text-primary-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{format(day, "d")}
|
||||||
|
{hasEvent && !selected && (
|
||||||
|
<span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-primary" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</Fragment>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo, useCallback } from "react";
|
import { useMemo, useCallback, useState } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { format, parseISO, isPast, isToday, isTomorrow } from "date-fns";
|
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 { cn } from "@/lib/utils";
|
||||||
import type { CalendarTask, Calendar } from "@/lib/jmap/types";
|
import type { CalendarTask, Calendar } from "@/lib/jmap/types";
|
||||||
import type { TaskViewFilter } from "@/stores/task-store";
|
import type { TaskViewFilter } from "@/stores/task-store";
|
||||||
@@ -18,6 +18,7 @@ interface TaskListViewProps {
|
|||||||
onSelectTask: (task: CalendarTask) => void;
|
onSelectTask: (task: CalendarTask) => void;
|
||||||
onToggleComplete: (task: CalendarTask) => void;
|
onToggleComplete: (task: CalendarTask) => void;
|
||||||
selectedTaskId?: string | null;
|
selectedTaskId?: string | null;
|
||||||
|
onQuickCreate?: (title: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTaskPriorityIcon(priority: number) {
|
function getTaskPriorityIcon(priority: number) {
|
||||||
@@ -69,9 +70,11 @@ export function TaskListView({
|
|||||||
onSelectTask,
|
onSelectTask,
|
||||||
onToggleComplete,
|
onToggleComplete,
|
||||||
selectedTaskId,
|
selectedTaskId,
|
||||||
|
onQuickCreate,
|
||||||
}: TaskListViewProps) {
|
}: TaskListViewProps) {
|
||||||
const t = useTranslations("calendar");
|
const t = useTranslations("calendar");
|
||||||
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
const timeFormat = useSettingsStore((s) => s.timeFormat);
|
||||||
|
const [quickAddTitle, setQuickAddTitle] = useState("");
|
||||||
|
|
||||||
const filteredTasks = useMemo(() => {
|
const filteredTasks = useMemo(() => {
|
||||||
let result = tasks.filter(task => {
|
let result = tasks.filter(task => {
|
||||||
@@ -128,15 +131,57 @@ export function TaskListView({
|
|||||||
|
|
||||||
if (filteredTasks.length === 0) {
|
if (filteredTasks.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center flex-1 text-muted-foreground py-12">
|
<div className="flex flex-col flex-1">
|
||||||
<ListTodo className="h-12 w-12 mb-3 opacity-30" />
|
{onQuickCreate && (
|
||||||
<p className="text-sm">{t("tasks.no_tasks")}</p>
|
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 overflow-y-auto">
|
<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">
|
<div className="divide-y divide-border">
|
||||||
{filteredTasks.map(task => {
|
{filteredTasks.map(task => {
|
||||||
const cal = calendars.find(c => task.calendarIds[c.id]);
|
const cal = calendars.find(c => task.calendarIds[c.id]);
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle, Book } from "lucide-react";
|
import { X, Plus, ChevronDown, ChevronRight, User, Building, MapPin, Globe, Cake, Heart, Tag, StickyNote, Mail, Phone, Calendar, UserCircle, Book } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -48,6 +48,7 @@ interface AddressEntry {
|
|||||||
interface ContactFormProps {
|
interface ContactFormProps {
|
||||||
contact?: ContactCard | null;
|
contact?: ContactCard | null;
|
||||||
addressBooks?: AddressBook[];
|
addressBooks?: AddressBook[];
|
||||||
|
allKeywords?: string[];
|
||||||
onSave: (data: Partial<ContactCard>) => Promise<void>;
|
onSave: (data: Partial<ContactCard>) => Promise<void>;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
}
|
}
|
||||||
@@ -123,7 +124,7 @@ function Select({ value, onChange, children, className }: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ContactForm({ contact, addressBooks, onSave, onCancel }: ContactFormProps) {
|
export function ContactForm({ contact, addressBooks, allKeywords, onSave, onCancel }: ContactFormProps) {
|
||||||
const t = useTranslations("contacts.form");
|
const t = useTranslations("contacts.form");
|
||||||
const isEditing = !!contact;
|
const isEditing = !!contact;
|
||||||
|
|
||||||
@@ -819,14 +820,14 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
|
|
||||||
{/* Categories */}
|
{/* Categories */}
|
||||||
<FormSection icon={Tag} title={t("categories")} collapsible defaultOpen category="digital">
|
<FormSection icon={Tag} title={t("categories")} collapsible defaultOpen category="digital">
|
||||||
<div>
|
<CategoryComboBox
|
||||||
<Input
|
keywordsStr={keywordsStr}
|
||||||
value={keywordsStr}
|
onChange={setKeywordsStr}
|
||||||
onChange={(e) => setKeywordsStr(e.target.value)}
|
allKeywords={allKeywords || []}
|
||||||
placeholder={t("categories_placeholder")}
|
placeholder={t("categories_placeholder")}
|
||||||
/>
|
hint={t("categories_hint")}
|
||||||
<p className="text-xs text-muted-foreground mt-1.5">{t("categories_hint")}</p>
|
addLabel={t("category_add")}
|
||||||
</div>
|
/>
|
||||||
</FormSection>
|
</FormSection>
|
||||||
|
|
||||||
{/* Gender */}
|
{/* Gender */}
|
||||||
@@ -895,3 +896,142 @@ export function ContactForm({ contact, addressBooks, onSave, onCancel }: Contact
|
|||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function CategoryComboBox({
|
||||||
|
keywordsStr,
|
||||||
|
onChange,
|
||||||
|
allKeywords,
|
||||||
|
placeholder,
|
||||||
|
hint,
|
||||||
|
addLabel,
|
||||||
|
}: {
|
||||||
|
keywordsStr: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
allKeywords: string[];
|
||||||
|
placeholder: string;
|
||||||
|
hint: string;
|
||||||
|
addLabel: string;
|
||||||
|
}) {
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const [inputValue, setInputValue] = useState("");
|
||||||
|
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
// Parse current keywords from comma-separated string
|
||||||
|
const currentKeywords = useMemo(() => {
|
||||||
|
return keywordsStr.split(",").map(k => k.trim()).filter(Boolean);
|
||||||
|
}, [keywordsStr]);
|
||||||
|
|
||||||
|
// Suggestions: existing keywords not already selected
|
||||||
|
const suggestions = useMemo(() => {
|
||||||
|
const lower = inputValue.toLowerCase();
|
||||||
|
return allKeywords.filter(kw =>
|
||||||
|
!currentKeywords.includes(kw) &&
|
||||||
|
(!lower || kw.toLowerCase().includes(lower))
|
||||||
|
);
|
||||||
|
}, [allKeywords, currentKeywords, inputValue]);
|
||||||
|
|
||||||
|
// Can add a new keyword if typed text is non-empty and not already in the list
|
||||||
|
const canAddNew = inputValue.trim() &&
|
||||||
|
!currentKeywords.includes(inputValue.trim()) &&
|
||||||
|
!allKeywords.some(kw => kw.toLowerCase() === inputValue.trim().toLowerCase());
|
||||||
|
|
||||||
|
const addKeyword = useCallback((keyword: string) => {
|
||||||
|
const trimmed = keyword.trim();
|
||||||
|
if (!trimmed || currentKeywords.includes(trimmed)) return;
|
||||||
|
const next = [...currentKeywords, trimmed].join(", ");
|
||||||
|
onChange(next);
|
||||||
|
setInputValue("");
|
||||||
|
}, [currentKeywords, onChange]);
|
||||||
|
|
||||||
|
const removeKeyword = useCallback((keyword: string) => {
|
||||||
|
const next = currentKeywords.filter(k => k !== keyword).join(", ");
|
||||||
|
onChange(next);
|
||||||
|
}, [currentKeywords, onChange]);
|
||||||
|
|
||||||
|
// Close dropdown on outside click
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return;
|
||||||
|
const handler = (e: MouseEvent) => {
|
||||||
|
if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", handler);
|
||||||
|
return () => document.removeEventListener("mousedown", handler);
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
if (inputValue.trim()) {
|
||||||
|
addKeyword(inputValue);
|
||||||
|
}
|
||||||
|
} else if (e.key === "Escape") {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={wrapperRef} className="relative">
|
||||||
|
{/* Keyword badges */}
|
||||||
|
{currentKeywords.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-1.5 mb-2">
|
||||||
|
{currentKeywords.map(kw => (
|
||||||
|
<span
|
||||||
|
key={kw}
|
||||||
|
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary border border-primary/20"
|
||||||
|
>
|
||||||
|
{kw}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeKeyword(kw)}
|
||||||
|
className="hover:text-destructive transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Input with dropdown */}
|
||||||
|
<Input
|
||||||
|
ref={inputRef}
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => { setInputValue(e.target.value); setIsOpen(true); }}
|
||||||
|
onFocus={() => setIsOpen(true)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder={currentKeywords.length === 0 ? placeholder : ""}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1.5">{hint}</p>
|
||||||
|
|
||||||
|
{/* Dropdown */}
|
||||||
|
{isOpen && (suggestions.length > 0 || canAddNew) && (
|
||||||
|
<div className="absolute left-0 right-0 top-[calc(100%-1.5rem)] mt-1 rounded-md border border-border bg-popover text-popover-foreground shadow-md z-50 max-h-48 overflow-y-auto py-1">
|
||||||
|
{suggestions.map(kw => (
|
||||||
|
<button
|
||||||
|
key={kw}
|
||||||
|
type="button"
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left"
|
||||||
|
onClick={() => { addKeyword(kw); inputRef.current?.focus(); }}
|
||||||
|
>
|
||||||
|
<Tag className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
|
||||||
|
{kw}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{canAddNew && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors text-left text-primary"
|
||||||
|
onClick={() => { addKeyword(inputValue); inputRef.current?.focus(); }}
|
||||||
|
>
|
||||||
|
<Plus className="w-3.5 h-3.5 flex-shrink-0" />
|
||||||
|
{addLabel}: "{inputValue.trim()}"
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export function ContactListItem({ contact, isSelected, isChecked, hasSelection,
|
|||||||
? Array.from(selectedContactIds)
|
? Array.from(selectedContactIds)
|
||||||
: [contact.id];
|
: [contact.id];
|
||||||
|
|
||||||
e.dataTransfer.effectAllowed = "move";
|
e.dataTransfer.effectAllowed = "copyMove";
|
||||||
e.dataTransfer.setData("application/x-contact-ids", JSON.stringify(ids));
|
e.dataTransfer.setData("application/x-contact-ids", JSON.stringify(ids));
|
||||||
e.dataTransfer.setData("text/plain", name || email || contact.id);
|
e.dataTransfer.setData("text/plain", name || email || contact.id);
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { cn } from "@/lib/utils";
|
|||||||
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
|
import type { ContactCard, AddressBook } from "@/lib/jmap/types";
|
||||||
import { getContactDisplayName } from "@/stores/contact-store";
|
import { getContactDisplayName } from "@/stores/contact-store";
|
||||||
|
|
||||||
export type ContactCategory = "all" | { groupId: string } | { addressBookId: string } | { keyword: string };
|
export type ContactCategory = "all" | { groupId: string } | { addressBookId: string } | { keyword: string } | "uncategorized";
|
||||||
|
|
||||||
interface ContactsSidebarProps {
|
interface ContactsSidebarProps {
|
||||||
groups: ContactCard[];
|
groups: ContactCard[];
|
||||||
@@ -24,6 +24,7 @@ interface ContactsSidebarProps {
|
|||||||
onEditGroup?: (groupId: string) => void;
|
onEditGroup?: (groupId: string) => void;
|
||||||
onDeleteGroup?: (groupId: string) => void;
|
onDeleteGroup?: (groupId: string) => void;
|
||||||
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
|
onDropContacts?: (contactIds: string[], addressBook: AddressBook) => void;
|
||||||
|
onDropContactsToCategory?: (contactIds: string[], keyword: string) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,6 +57,7 @@ export function ContactsSidebar({
|
|||||||
onEditGroup,
|
onEditGroup,
|
||||||
onDeleteGroup,
|
onDeleteGroup,
|
||||||
onDropContacts,
|
onDropContacts,
|
||||||
|
onDropContactsToCategory,
|
||||||
className,
|
className,
|
||||||
}: ContactsSidebarProps) {
|
}: ContactsSidebarProps) {
|
||||||
const t = useTranslations("contacts");
|
const t = useTranslations("contacts");
|
||||||
@@ -146,6 +148,11 @@ export function ContactsSidebar({
|
|||||||
return Object.entries(counts).sort(([a], [b]) => a.localeCompare(b));
|
return Object.entries(counts).sort(([a], [b]) => a.localeCompare(b));
|
||||||
}, [individuals]);
|
}, [individuals]);
|
||||||
|
|
||||||
|
// Count of contacts without any keywords
|
||||||
|
const uncategorizedCount = useMemo(() => {
|
||||||
|
return individuals.filter(c => !c.keywords || Object.keys(c.keywords).filter(k => c.keywords![k]).length === 0).length;
|
||||||
|
}, [individuals]);
|
||||||
|
|
||||||
// Resolve actual group member counts against living contacts
|
// Resolve actual group member counts against living contacts
|
||||||
const memberCountByGroup = useMemo(() => {
|
const memberCountByGroup = useMemo(() => {
|
||||||
const counts: Record<string, number> = {};
|
const counts: Record<string, number> = {};
|
||||||
@@ -311,46 +318,56 @@ export function ContactsSidebar({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Categories section (from contact keywords) */}
|
{/* Categories section (from contact keywords) */}
|
||||||
{allKeywords.length > 0 && (
|
<div className="mt-2">
|
||||||
<div className="mt-2">
|
<button
|
||||||
<button
|
onClick={() => toggleSection("categories")}
|
||||||
onClick={() => toggleSection("categories")}
|
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
||||||
className="flex items-center gap-1 px-3 py-1 w-full text-left group"
|
>
|
||||||
>
|
{collapsed.categories ? (
|
||||||
{collapsed.categories ? (
|
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
||||||
<ChevronRight className="w-3 h-3 text-muted-foreground" />
|
) : (
|
||||||
) : (
|
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
||||||
<ChevronDown className="w-3 h-3 text-muted-foreground" />
|
)}
|
||||||
)}
|
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||||
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
{t("detail.categories")}
|
||||||
{t("detail.categories")}
|
</span>
|
||||||
</span>
|
</button>
|
||||||
</button>
|
|
||||||
|
|
||||||
{!collapsed.categories && allKeywords.map(([keyword, count]) => {
|
{!collapsed.categories && (
|
||||||
const isActive = typeof activeCategory === "object" && "keyword" in activeCategory && activeCategory.keyword === keyword;
|
<>
|
||||||
return (
|
{/* No Category item */}
|
||||||
<button
|
<button
|
||||||
key={keyword}
|
onClick={() => onSelectCategory("uncategorized")}
|
||||||
onClick={() => onSelectCategory({ keyword })}
|
className={cn(
|
||||||
className={cn(
|
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
||||||
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
activeCategory === "uncategorized"
|
||||||
isActive
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
? "bg-accent text-accent-foreground font-medium"
|
: "text-foreground/80 hover:bg-muted"
|
||||||
: "text-foreground/80 hover:bg-muted"
|
)}
|
||||||
)}
|
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
|
||||||
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
|
>
|
||||||
>
|
<Tag className="w-3.5 h-3.5 flex-shrink-0 opacity-50" />
|
||||||
<Tag className="w-3.5 h-3.5 flex-shrink-0" />
|
<span className="truncate italic">{t("no_category")}</span>
|
||||||
<span className="truncate">{keyword}</span>
|
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
|
||||||
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
|
{uncategorizedCount}
|
||||||
{count}
|
</span>
|
||||||
</span>
|
</button>
|
||||||
</button>
|
{allKeywords.map(([keyword, count]) => {
|
||||||
);
|
const isActive = typeof activeCategory === "object" && "keyword" in activeCategory && activeCategory.keyword === keyword;
|
||||||
})}
|
return (
|
||||||
</div>
|
<CategoryItem
|
||||||
)}
|
key={keyword}
|
||||||
|
keyword={keyword}
|
||||||
|
count={count}
|
||||||
|
isActive={isActive}
|
||||||
|
onSelect={() => onSelectCategory({ keyword })}
|
||||||
|
onDropContacts={onDropContactsToCategory}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Shared accounts with address books */}
|
{/* Shared accounts with address books */}
|
||||||
{sharedBookGroups.map((group) => (
|
{sharedBookGroups.map((group) => (
|
||||||
@@ -415,6 +432,71 @@ export function ContactsSidebar({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function CategoryItem({
|
||||||
|
keyword,
|
||||||
|
count,
|
||||||
|
isActive,
|
||||||
|
onSelect,
|
||||||
|
onDropContacts,
|
||||||
|
}: {
|
||||||
|
keyword: string;
|
||||||
|
count: number;
|
||||||
|
isActive: boolean;
|
||||||
|
onSelect: () => void;
|
||||||
|
onDropContacts?: (contactIds: string[], keyword: string) => void;
|
||||||
|
}) {
|
||||||
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
|
||||||
|
const handleDragOver = useCallback((e: DragEvent<HTMLButtonElement>) => {
|
||||||
|
if (!e.dataTransfer.types.includes("application/x-contact-ids")) return;
|
||||||
|
e.preventDefault();
|
||||||
|
e.dataTransfer.dropEffect = "copy";
|
||||||
|
setIsDragOver(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeave = useCallback(() => {
|
||||||
|
setIsDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDrop = useCallback((e: DragEvent<HTMLButtonElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
const data = e.dataTransfer.getData("application/x-contact-ids");
|
||||||
|
if (!data || !onDropContacts) return;
|
||||||
|
try {
|
||||||
|
const contactIds = JSON.parse(data) as string[];
|
||||||
|
if (contactIds.length > 0) {
|
||||||
|
onDropContacts(contactIds, keyword);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore invalid data
|
||||||
|
}
|
||||||
|
}, [keyword, onDropContacts]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={onSelect}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
"w-full flex items-center gap-2 pl-5 pr-3 text-sm transition-colors",
|
||||||
|
isActive
|
||||||
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
|
: "text-foreground/80 hover:bg-muted",
|
||||||
|
isDragOver && "bg-primary/20 ring-2 ring-primary/50"
|
||||||
|
)}
|
||||||
|
style={{ paddingBlock: 'var(--density-sidebar-py, 4px)', minHeight: '32px' }}
|
||||||
|
>
|
||||||
|
<Tag className="w-3.5 h-3.5 flex-shrink-0" />
|
||||||
|
<span className="truncate">{keyword}</span>
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground tabular-nums">
|
||||||
|
{count}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function AddressBookItem({
|
function AddressBookItem({
|
||||||
book,
|
book,
|
||||||
isActive,
|
isActive,
|
||||||
|
|||||||
@@ -28,6 +28,14 @@ import { TemplatePicker } from "@/components/templates/template-picker";
|
|||||||
import { TemplateForm } from "@/components/templates/template-form";
|
import { TemplateForm } from "@/components/templates/template-form";
|
||||||
import type { EmailTemplate } from "@/lib/template-types";
|
import type { EmailTemplate } from "@/lib/template-types";
|
||||||
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
|
import { appendPlainTextSignature, getPlainTextSignature } from "@/lib/signature-utils";
|
||||||
|
import { RichTextEditor } from "@/components/email/rich-text-editor";
|
||||||
|
|
||||||
|
/** Strip HTML tags and decode entities to get a plain-text version */
|
||||||
|
function htmlToPlainText(html: string): string {
|
||||||
|
const tmp = document.createElement('div');
|
||||||
|
tmp.innerHTML = html;
|
||||||
|
return tmp.textContent || tmp.innerText || '';
|
||||||
|
}
|
||||||
|
|
||||||
export interface ComposerDraftData {
|
export interface ComposerDraftData {
|
||||||
to: string;
|
to: string;
|
||||||
@@ -125,23 +133,28 @@ export function EmailComposer({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getInitialBody = () => {
|
const getInitialBody = () => {
|
||||||
const prefix = initialDraftText || "";
|
const prefix = initialDraftText ? `<p>${initialDraftText.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}</p>` : "";
|
||||||
if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
|
if (!replyTo?.body && !replyTo?.htmlBody) return prefix;
|
||||||
|
|
||||||
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
|
const date = replyTo.receivedAt ? formatDateTime(replyTo.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' }) : "";
|
||||||
const from = replyTo.from?.[0];
|
const from = replyTo.from?.[0];
|
||||||
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
|
const fromStr = from ? `${from.name || from.email}` : tCommon('unknown');
|
||||||
|
|
||||||
// When HTML body is available, don't include quoted text in the textarea
|
// Build quoted content as HTML
|
||||||
// The HTML original will be shown separately below the textarea
|
|
||||||
if (replyTo.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
if (replyTo.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
||||||
return prefix;
|
const quoteHeader = mode === 'forward'
|
||||||
|
? `---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>`
|
||||||
|
: `On ${date}, ${fromStr} wrote:<br>`;
|
||||||
|
return `${prefix}<br><div>${quoteHeader}</div><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${replyTo.htmlBody}</blockquote>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mode === 'forward') {
|
if (replyTo.body) {
|
||||||
return `${prefix}\n\n---------- Forwarded message ----------\nFrom: ${fromStr}\nDate: ${date}\nSubject: ${replyTo.subject || ""}\n\n${replyTo.body}`;
|
const escapedOriginal = replyTo.body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
|
||||||
} else if (mode === 'reply' || mode === 'replyAll') {
|
if (mode === 'forward') {
|
||||||
return `${prefix}\n\nOn ${date}, ${fromStr} wrote:\n> ${(replyTo.body || '').split('\n').join('\n> ')}`;
|
return `${prefix}<br><br>---------- Forwarded message ----------<br>From: ${fromStr}<br>Date: ${date}<br>Subject: ${replyTo.subject || ''}<br><br>${escapedOriginal}`;
|
||||||
|
} else if (mode === 'reply' || mode === 'replyAll') {
|
||||||
|
return `${prefix}<br><br>On ${date}, ${fromStr} wrote:<br><blockquote style="margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex">${escapedOriginal}</blockquote>`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return prefix;
|
return prefix;
|
||||||
};
|
};
|
||||||
@@ -157,18 +170,6 @@ export function EmailComposer({
|
|||||||
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
||||||
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
const lastSavedDataRef = useRef<string>("");
|
const lastSavedDataRef = useRef<string>("");
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
|
||||||
|
|
||||||
const autoResizeTextarea = useCallback(() => {
|
|
||||||
const el = textareaRef.current;
|
|
||||||
if (!el) return;
|
|
||||||
el.style.height = 'auto';
|
|
||||||
el.style.height = el.scrollHeight + 'px';
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
autoResizeTextarea();
|
|
||||||
}, [body, autoResizeTextarea]);
|
|
||||||
const [attachments, setAttachments] = useState<Array<{ file: File; blobId?: string; uploading?: boolean; error?: boolean; abortController?: AbortController }>>([]);
|
const [attachments, setAttachments] = useState<Array<{ file: File; blobId?: string; uploading?: boolean; error?: boolean; abortController?: AbortController }>>([]);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({});
|
const [validationErrors, setValidationErrors] = useState<{ to?: boolean; subject?: boolean; body?: boolean }>({});
|
||||||
@@ -367,9 +368,12 @@ export function EmailComposer({
|
|||||||
? substitutePlaceholders(template.body, filledValues)
|
? substitutePlaceholders(template.body, filledValues)
|
||||||
: template.body;
|
: template.body;
|
||||||
|
|
||||||
|
// Convert template plain text body to HTML for the rich text editor
|
||||||
|
const htmlBody = `<p>${filledBody.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}</p>`;
|
||||||
|
|
||||||
if (mode === 'compose') {
|
if (mode === 'compose') {
|
||||||
setSubject(filledSubject);
|
setSubject(filledSubject);
|
||||||
setBody(filledBody);
|
setBody(htmlBody);
|
||||||
if (template.defaultRecipients?.to?.length) {
|
if (template.defaultRecipients?.to?.length) {
|
||||||
setTo(template.defaultRecipients.to.join(', ') + ', ');
|
setTo(template.defaultRecipients.to.join(', ') + ', ');
|
||||||
}
|
}
|
||||||
@@ -382,7 +386,7 @@ export function EmailComposer({
|
|||||||
setShowBcc(true);
|
setShowBcc(true);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setBody((prev) => filledBody + prev);
|
setBody((prev) => htmlBody + prev);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (template.identityId) {
|
if (template.identityId) {
|
||||||
@@ -394,8 +398,10 @@ export function EmailComposer({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleTemplateKey = (e: KeyboardEvent) => {
|
const handleTemplateKey = (e: KeyboardEvent) => {
|
||||||
const tag = (e.target as HTMLElement)?.tagName?.toLowerCase();
|
const target = e.target as HTMLElement;
|
||||||
|
const tag = target?.tagName?.toLowerCase();
|
||||||
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
||||||
|
if (target?.getAttribute('contenteditable') === 'true') return;
|
||||||
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
if (e.key === 't' && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setShowTemplatePicker(true);
|
setShowTemplatePicker(true);
|
||||||
@@ -445,6 +451,18 @@ export function EmailComposer({
|
|||||||
}
|
}
|
||||||
}, [client, t]);
|
}, [client, t]);
|
||||||
|
|
||||||
|
const handleImageUpload = useCallback(async (file: File): Promise<string | null> => {
|
||||||
|
if (!client) return null;
|
||||||
|
try {
|
||||||
|
const { blobId } = await client.uploadBlob(file);
|
||||||
|
return await client.fetchBlobAsObjectUrl(blobId, file.name, file.type);
|
||||||
|
} catch (error) {
|
||||||
|
debug.error(`Failed to upload inline image ${file.name}:`, error);
|
||||||
|
toast.error(t('upload_failed', { filename: file.name }));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, [client, t]);
|
||||||
|
|
||||||
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
if (!event.target.files) return;
|
if (!event.target.files) return;
|
||||||
await addFiles(Array.from(event.target.files));
|
await addFiles(Array.from(event.target.files));
|
||||||
@@ -511,7 +529,7 @@ export function EmailComposer({
|
|||||||
const ccAddresses = cc.split(",").map(e => e.trim()).filter(Boolean);
|
const ccAddresses = cc.split(",").map(e => e.trim()).filter(Boolean);
|
||||||
const bccAddresses = bcc.split(",").map(e => e.trim()).filter(Boolean);
|
const bccAddresses = bcc.split(",").map(e => e.trim()).filter(Boolean);
|
||||||
|
|
||||||
if (!toAddresses.length && !subject && !body) {
|
if (!toAddresses.length && !subject && !htmlToPlainText(body).trim()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -547,7 +565,7 @@ export function EmailComposer({
|
|||||||
const savedDraftId = await client.createDraft(
|
const savedDraftId = await client.createDraft(
|
||||||
toAddresses,
|
toAddresses,
|
||||||
subject || t('no_subject'),
|
subject || t('no_subject'),
|
||||||
body,
|
htmlToPlainText(body),
|
||||||
ccAddresses,
|
ccAddresses,
|
||||||
bccAddresses,
|
bccAddresses,
|
||||||
currentIdentity?.id,
|
currentIdentity?.id,
|
||||||
@@ -611,7 +629,8 @@ export function EmailComposer({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const toAddresses = to.split(",").map(e => e.trim()).filter(Boolean);
|
const toAddresses = to.split(",").map(e => e.trim()).filter(Boolean);
|
||||||
const hasContent = body || attachments.some(att => att.blobId && !att.uploading);
|
const bodyPlainText = htmlToPlainText(body).trim();
|
||||||
|
const hasContent = bodyPlainText || attachments.some(att => att.blobId && !att.uploading);
|
||||||
const canSend = toAddresses.length > 0 && !!subject && hasContent;
|
const canSend = toAddresses.length > 0 && !!subject && hasContent;
|
||||||
|
|
||||||
const getSendTooltip = (): string | undefined => {
|
const getSendTooltip = (): string | undefined => {
|
||||||
@@ -660,26 +679,8 @@ export function EmailComposer({
|
|||||||
: currentIdentity.email
|
: currentIdentity.email
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
// Append signature from the selected identity
|
// Body is already HTML from the rich text editor.
|
||||||
let finalBody = appendPlainTextSignature(body, currentIdentity);
|
// Build HTML signature block
|
||||||
|
|
||||||
// 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)
|
|
||||||
const buildSignatureHtml = (): string => {
|
const buildSignatureHtml = (): string => {
|
||||||
if (currentIdentity?.htmlSignature) {
|
if (currentIdentity?.htmlSignature) {
|
||||||
return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
|
return `<br><br>-- <br>${sanitizeEmailHtml(currentIdentity.htmlSignature)}`;
|
||||||
@@ -690,26 +691,13 @@ export function EmailComposer({
|
|||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
// Build HTML body
|
|
||||||
let finalHtmlBody: string | undefined;
|
|
||||||
const signatureHtml = buildSignatureHtml();
|
const signatureHtml = buildSignatureHtml();
|
||||||
|
|
||||||
if (replyTo?.htmlBody && (mode === 'reply' || mode === 'replyAll' || mode === 'forward')) {
|
// Build final HTML body: editor content + signature
|
||||||
// Reply/forward with original HTML content
|
const finalHtmlBody = `<div>${body}</div>${signatureHtml}`;
|
||||||
const escapedBody = body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').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>`;
|
|
||||||
|
|
||||||
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>`;
|
// Generate plain text version from the HTML body for multipart/alternative
|
||||||
} else if (signatureHtml) {
|
const finalBody = appendPlainTextSignature(htmlToPlainText(body), currentIdentity);
|
||||||
// New compose or plain-text reply — include HTML body with signature
|
|
||||||
const escapedBody = body.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>');
|
|
||||||
finalHtmlBody = `<div>${escapedBody}</div>${signatureHtml}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
|
// S/MIME send pipeline: build raw MIME → sign → encrypt → sendRawEmail
|
||||||
@@ -886,6 +874,7 @@ export function EmailComposer({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn("flex flex-col h-full bg-background relative", className)}
|
className={cn("flex flex-col h-full bg-background relative", className)}
|
||||||
|
data-tour="composer"
|
||||||
onDragEnter={handleDragEnter}
|
onDragEnter={handleDragEnter}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
@@ -954,11 +943,16 @@ export function EmailComposer({
|
|||||||
onChange={(e) => setSelectedIdentityId(e.target.value)}
|
onChange={(e) => setSelectedIdentityId(e.target.value)}
|
||||||
className="flex-1 bg-transparent text-sm text-foreground outline-none cursor-pointer hover:text-muted-foreground transition-colors min-w-0 truncate"
|
className="flex-1 bg-transparent text-sm text-foreground outline-none cursor-pointer hover:text-muted-foreground transition-colors min-w-0 truncate"
|
||||||
>
|
>
|
||||||
{identities.map((identity) => (
|
{identities.map((identity) => {
|
||||||
<option key={identity.id} value={identity.id}>
|
const displayEmail = subAddressTag
|
||||||
{identity.name ? `${identity.name} <${identity.email}>` : identity.email}
|
? generateSubAddress(identity.email, subAddressTag)
|
||||||
</option>
|
: identity.email;
|
||||||
))}
|
return (
|
||||||
|
<option key={identity.id} value={identity.id}>
|
||||||
|
{identity.name ? `${identity.name} <${displayEmail}>` : displayEmail}
|
||||||
|
</option>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</select>
|
</select>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-sm text-foreground flex-1 truncate">
|
<span className="text-sm text-foreground flex-1 truncate">
|
||||||
@@ -1106,23 +1100,17 @@ export function EmailComposer({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Body */}
|
{/* Body - Rich Text Editor */}
|
||||||
<div className="px-4 py-3">
|
<RichTextEditor
|
||||||
<textarea
|
content={body}
|
||||||
ref={textareaRef}
|
onChange={(html) => {
|
||||||
className={cn(
|
setBody(html);
|
||||||
"w-full resize-none outline-none text-sm bg-transparent text-foreground placeholder:text-muted-foreground rounded min-h-[100px] overflow-hidden",
|
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
|
||||||
validationErrors.body && "ring-2 ring-red-500 dark:ring-red-400"
|
}}
|
||||||
)}
|
onImageUpload={handleImageUpload}
|
||||||
placeholder={t('body_placeholder')}
|
placeholder={t('body_placeholder')}
|
||||||
value={body}
|
hasError={validationErrors.body}
|
||||||
onChange={(e) => {
|
/>
|
||||||
setBody(e.target.value);
|
|
||||||
if (validationErrors.body) setValidationErrors(prev => ({ ...prev, body: false }));
|
|
||||||
}}
|
|
||||||
aria-invalid={validationErrors.body || undefined}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{composerSignatureHtml && (
|
{composerSignatureHtml && (
|
||||||
<div
|
<div
|
||||||
@@ -1130,23 +1118,6 @@ export function EmailComposer({
|
|||||||
dangerouslySetInnerHTML={{ __html: `<div>-- </div>${composerSignatureHtml}` }}
|
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>
|
</div>
|
||||||
|
|
||||||
{/* Attachments */}
|
{/* Attachments */}
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Email } from "@/lib/jmap/types";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
|
import type { HoverAction } from "@/stores/settings-store";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Trash2, Star, Mail, MailOpen, Archive, Tag, ShieldAlert } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
|
||||||
|
interface EmailHoverActionsProps {
|
||||||
|
email: Email;
|
||||||
|
onToggleStar?: () => void;
|
||||||
|
onMarkAsRead?: (read: boolean) => void;
|
||||||
|
onDelete?: () => void;
|
||||||
|
onArchive?: () => void;
|
||||||
|
onSetColorTag?: (color: string | null) => void;
|
||||||
|
onMarkAsSpam?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ACTION_CONFIG: Record<HoverAction, {
|
||||||
|
icon: typeof Trash2;
|
||||||
|
titleKey: string;
|
||||||
|
className?: string;
|
||||||
|
}> = {
|
||||||
|
delete: {
|
||||||
|
icon: Trash2,
|
||||||
|
titleKey: "delete",
|
||||||
|
className: "hover:text-red-600 dark:hover:text-red-400",
|
||||||
|
},
|
||||||
|
star: {
|
||||||
|
icon: Star,
|
||||||
|
titleKey: "star",
|
||||||
|
className: "hover:text-amber-500 dark:hover:text-amber-400",
|
||||||
|
},
|
||||||
|
markRead: {
|
||||||
|
icon: Mail,
|
||||||
|
titleKey: "mark_read",
|
||||||
|
className: "hover:text-blue-600 dark:hover:text-blue-400",
|
||||||
|
},
|
||||||
|
archive: {
|
||||||
|
icon: Archive,
|
||||||
|
titleKey: "archive",
|
||||||
|
className: "hover:text-green-600 dark:hover:text-green-400",
|
||||||
|
},
|
||||||
|
tag: {
|
||||||
|
icon: Tag,
|
||||||
|
titleKey: "tag",
|
||||||
|
className: "hover:text-purple-600 dark:hover:text-purple-400",
|
||||||
|
},
|
||||||
|
spam: {
|
||||||
|
icon: ShieldAlert,
|
||||||
|
titleKey: "spam",
|
||||||
|
className: "hover:text-orange-600 dark:hover:text-orange-400",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function EmailHoverActions({
|
||||||
|
email,
|
||||||
|
onToggleStar,
|
||||||
|
onMarkAsRead,
|
||||||
|
onDelete,
|
||||||
|
onArchive,
|
||||||
|
onSetColorTag,
|
||||||
|
onMarkAsSpam,
|
||||||
|
}: EmailHoverActionsProps) {
|
||||||
|
const hoverActions = useSettingsStore((state) => state.hoverActions);
|
||||||
|
const t = useTranslations("settings.email_behavior.hover_actions");
|
||||||
|
|
||||||
|
const isUnread = !email.keywords?.$seen;
|
||||||
|
const isStarred = email.keywords?.$flagged;
|
||||||
|
|
||||||
|
if (hoverActions.length === 0) return null;
|
||||||
|
|
||||||
|
const handleAction = (e: React.MouseEvent, action: HoverAction) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
e.preventDefault();
|
||||||
|
switch (action) {
|
||||||
|
case "delete":
|
||||||
|
onDelete?.();
|
||||||
|
break;
|
||||||
|
case "star":
|
||||||
|
onToggleStar?.();
|
||||||
|
break;
|
||||||
|
case "markRead":
|
||||||
|
onMarkAsRead?.(!isUnread);
|
||||||
|
break;
|
||||||
|
case "archive":
|
||||||
|
onArchive?.();
|
||||||
|
break;
|
||||||
|
case "tag":
|
||||||
|
onSetColorTag?.(null);
|
||||||
|
break;
|
||||||
|
case "spam":
|
||||||
|
onMarkAsSpam?.();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="absolute right-0 top-0 bottom-0 z-10 hidden group-hover:flex items-center"
|
||||||
|
>
|
||||||
|
<div className="w-8 h-full bg-gradient-to-r from-transparent to-muted" />
|
||||||
|
<div className="flex items-center gap-0.5 h-full bg-muted pr-3 pl-0.5">
|
||||||
|
{hoverActions.map((actionId) => {
|
||||||
|
const config = ACTION_CONFIG[actionId];
|
||||||
|
if (!config) return null;
|
||||||
|
const Icon = config.icon;
|
||||||
|
|
||||||
|
const DisplayIcon = actionId === "markRead"
|
||||||
|
? (isUnread ? MailOpen : Mail)
|
||||||
|
: actionId === "star" && isStarred
|
||||||
|
? Star
|
||||||
|
: Icon;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={actionId}
|
||||||
|
onClick={(e) => handleAction(e, actionId)}
|
||||||
|
title={t(config.titleKey)}
|
||||||
|
className={cn(
|
||||||
|
"p-1.5 rounded-md transition-colors duration-100 text-muted-foreground hover:bg-black/5 dark:hover:bg-white/10",
|
||||||
|
config.className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<DisplayIcon
|
||||||
|
className={cn(
|
||||||
|
"w-4 h-4",
|
||||||
|
actionId === "star" && isStarred && "fill-amber-400 text-amber-400",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import { formatDate } from "@/lib/utils";
|
|||||||
import { Email } from "@/lib/jmap/types";
|
import { Email } from "@/lib/jmap/types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { Paperclip, Star, Circle, CheckSquare, Square, Tag } from "lucide-react";
|
import { Paperclip, Star, Circle, CheckSquare, Square, Tag, Reply, Forward } from "lucide-react";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
@@ -14,6 +14,7 @@ import { useEmailDrag } from "@/hooks/use-email-drag";
|
|||||||
import { useLongPress } from "@/hooks/use-long-press";
|
import { useLongPress } from "@/hooks/use-long-press";
|
||||||
import { useUIStore } from "@/stores/ui-store";
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
import { EmailIdentityBadge } from "./email-identity-badge";
|
import { EmailIdentityBadge } from "./email-identity-badge";
|
||||||
|
import { EmailHoverActions } from "./email-hover-actions";
|
||||||
import { getEmailColorTag } from "@/lib/thread-utils";
|
import { getEmailColorTag } from "@/lib/thread-utils";
|
||||||
|
|
||||||
interface EmailListItemProps {
|
interface EmailListItemProps {
|
||||||
@@ -21,9 +22,15 @@ interface EmailListItemProps {
|
|||||||
selected?: boolean;
|
selected?: boolean;
|
||||||
onClick?: () => void;
|
onClick?: () => void;
|
||||||
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
||||||
|
onToggleStar?: () => void;
|
||||||
|
onMarkAsRead?: (read: boolean) => void;
|
||||||
|
onDelete?: () => void;
|
||||||
|
onArchive?: () => void;
|
||||||
|
onSetColorTag?: (color: string | null) => void;
|
||||||
|
onMarkAsSpam?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function EmailListItem({ email, selected, onClick, onContextMenu }: EmailListItemProps) {
|
export function EmailListItem({ email, selected, onClick, onContextMenu, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }: EmailListItemProps) {
|
||||||
const t = useTranslations('email_viewer');
|
const t = useTranslations('email_viewer');
|
||||||
const { selectedEmailIds, toggleEmailSelection, selectRangeEmails, selectedMailbox, clearSelection } = useEmailStore();
|
const { selectedEmailIds, toggleEmailSelection, selectRangeEmails, selectedMailbox, clearSelection } = useEmailStore();
|
||||||
const showPreview = useSettingsStore((state) => state.showPreview);
|
const showPreview = useSettingsStore((state) => state.showPreview);
|
||||||
@@ -34,6 +41,8 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
|
|||||||
const isUnread = !email.keywords?.$seen;
|
const isUnread = !email.keywords?.$seen;
|
||||||
const isStarred = email.keywords?.$flagged;
|
const isStarred = email.keywords?.$flagged;
|
||||||
const isImportant = email.keywords?.["$important"];
|
const isImportant = email.keywords?.["$important"];
|
||||||
|
const isAnswered = email.keywords?.$answered;
|
||||||
|
const isForwarded = email.keywords?.$forwarded;
|
||||||
const sender = email.from?.[0];
|
const sender = email.from?.[0];
|
||||||
|
|
||||||
// Resolve color tag using keyword definitions from settings
|
// Resolve color tag using keyword definitions from settings
|
||||||
@@ -74,7 +83,7 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
|
|||||||
{...dragHandlers}
|
{...dragHandlers}
|
||||||
{...longPressHandlers}
|
{...longPressHandlers}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative group cursor-pointer select-none transition-all duration-200 border-b border-border",
|
"relative group cursor-pointer select-none transition-shadow duration-200 border-b border-border overflow-hidden",
|
||||||
// Apply color tag as background, with selected and unread states
|
// Apply color tag as background, with selected and unread states
|
||||||
colorTag ? colorTag : (
|
colorTag ? colorTag : (
|
||||||
selected
|
selected
|
||||||
@@ -168,6 +177,18 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<EmailIdentityBadge email={email} identities={identities} compact={true} />
|
<EmailIdentityBadge email={email} identities={identities} compact={true} />
|
||||||
|
{isAnswered && !isForwarded && (
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isForwarded && !isAnswered && (
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isAnswered && isForwarded && (
|
||||||
|
<>
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{email.hasAttachment && (
|
{email.hasAttachment && (
|
||||||
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
@@ -217,6 +238,17 @@ export function EmailListItem({ email, selected, onClick, onContextMenu }: Email
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Hover Quick Actions */}
|
||||||
|
<EmailHoverActions
|
||||||
|
email={email}
|
||||||
|
onToggleStar={onToggleStar}
|
||||||
|
onMarkAsRead={onMarkAsRead}
|
||||||
|
onDelete={onDelete}
|
||||||
|
onArchive={onArchive}
|
||||||
|
onSetColorTag={onSetColorTag}
|
||||||
|
onMarkAsSpam={onMarkAsSpam}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -358,7 +358,7 @@ export function EmailList({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Email List */}
|
{/* Email List */}
|
||||||
<div ref={parentRef} className="flex-1 overflow-y-auto bg-background relative">
|
<div ref={parentRef} className="flex-1 overflow-y-auto bg-background relative" data-tour="email-list">
|
||||||
{/* Loading overlay */}
|
{/* Loading overlay */}
|
||||||
{isLoading && emails.length > 0 && (
|
{isLoading && emails.length > 0 && (
|
||||||
<div className="absolute inset-0 bg-background/50 z-10 flex items-center justify-center animate-in fade-in duration-150">
|
<div className="absolute inset-0 bg-background/50 z-10 flex items-center justify-center animate-in fade-in duration-150">
|
||||||
@@ -422,6 +422,12 @@ export function EmailList({
|
|||||||
onEmailSelect={(email) => onEmailSelect?.(email)}
|
onEmailSelect={(email) => onEmailSelect?.(email)}
|
||||||
onContextMenu={openContextMenu}
|
onContextMenu={openContextMenu}
|
||||||
onOpenConversation={onOpenConversation}
|
onOpenConversation={onOpenConversation}
|
||||||
|
onToggleStar={onToggleStar ? (email) => onToggleStar(email) : undefined}
|
||||||
|
onMarkAsRead={onMarkAsRead ? (email, read) => onMarkAsRead(email, read) : undefined}
|
||||||
|
onDelete={onDelete ? (email) => onDelete(email) : undefined}
|
||||||
|
onArchive={onArchive ? (email) => onArchive(email) : undefined}
|
||||||
|
onSetColorTag={onSetColorTag}
|
||||||
|
onMarkAsSpam={onMarkAsSpam ? (email) => onMarkAsSpam(email) : undefined}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+484
-137
@@ -66,6 +66,7 @@ import {
|
|||||||
Moon,
|
Moon,
|
||||||
HelpCircle,
|
HelpCircle,
|
||||||
EditIcon,
|
EditIcon,
|
||||||
|
PlayCircle,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import type { Attachment as PostalMimeAttachment } from 'postal-mime';
|
import type { Attachment as PostalMimeAttachment } from 'postal-mime';
|
||||||
@@ -80,6 +81,7 @@ import { useThemeStore } from "@/stores/theme-store";
|
|||||||
import { EmailIdentityBadge } from "./email-identity-badge";
|
import { EmailIdentityBadge } from "./email-identity-badge";
|
||||||
import { UnsubscribeBanner } from "./unsubscribe-banner";
|
import { UnsubscribeBanner } from "./unsubscribe-banner";
|
||||||
import { CalendarInvitationBanner } from "./calendar-invitation-banner";
|
import { CalendarInvitationBanner } from "./calendar-invitation-banner";
|
||||||
|
import { useTour } from "@/components/tour/tour-provider";
|
||||||
import { SmimePassphraseDialog } from "@/components/settings/smime-passphrase-dialog";
|
import { SmimePassphraseDialog } from "@/components/settings/smime-passphrase-dialog";
|
||||||
import { findCalendarAttachment } from "@/lib/calendar-invitation";
|
import { findCalendarAttachment } from "@/lib/calendar-invitation";
|
||||||
import { RecipientPopover } from "./recipient-popover";
|
import { RecipientPopover } from "./recipient-popover";
|
||||||
@@ -105,7 +107,7 @@ interface EmailViewerProps {
|
|||||||
onToggleStar?: () => void;
|
onToggleStar?: () => void;
|
||||||
onMarkAsRead?: (emailId: string, read: boolean) => void;
|
onMarkAsRead?: (emailId: string, read: boolean) => void;
|
||||||
onSetColorTag?: (emailId: string, color: string | null) => void;
|
onSetColorTag?: (emailId: string, color: string | null) => void;
|
||||||
onDownloadAttachment?: (blobId: string, name: string, type?: string) => void;
|
onDownloadAttachment?: (blobId: string, name: string, type?: string, forceDownload?: boolean) => void;
|
||||||
onQuickReply?: (body: string) => Promise<void>;
|
onQuickReply?: (body: string) => Promise<void>;
|
||||||
onMarkAsSpam?: () => void;
|
onMarkAsSpam?: () => void;
|
||||||
onUndoSpam?: () => void;
|
onUndoSpam?: () => void;
|
||||||
@@ -149,6 +151,42 @@ const getFileIcon = (name?: string, type?: string) => {
|
|||||||
return File;
|
return File;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MIME_TYPE_LABELS: Record<string, string> = {
|
||||||
|
'application/pdf': 'Document.pdf',
|
||||||
|
'application/zip': 'Archive.zip',
|
||||||
|
'application/x-zip-compressed': 'Archive.zip',
|
||||||
|
'application/gzip': 'Archive.gz',
|
||||||
|
'application/x-rar-compressed': 'Archive.rar',
|
||||||
|
'application/x-7z-compressed': 'Archive.7z',
|
||||||
|
'application/msword': 'Document.doc',
|
||||||
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Document.docx',
|
||||||
|
'application/vnd.ms-excel': 'Spreadsheet.xls',
|
||||||
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Spreadsheet.xlsx',
|
||||||
|
'application/vnd.ms-powerpoint': 'Presentation.ppt',
|
||||||
|
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'Presentation.pptx',
|
||||||
|
'text/plain': 'Text.txt',
|
||||||
|
'text/html': 'Document.html',
|
||||||
|
'text/csv': 'Data.csv',
|
||||||
|
'application/json': 'Data.json',
|
||||||
|
'application/xml': 'Data.xml',
|
||||||
|
'application/octet-stream': 'Attachment',
|
||||||
|
'message/rfc822': 'Email.eml',
|
||||||
|
};
|
||||||
|
|
||||||
|
const getAttachmentDisplayName = (name: string | null | undefined, mimeType?: string): string => {
|
||||||
|
if (name) return name;
|
||||||
|
if (mimeType) {
|
||||||
|
const label = MIME_TYPE_LABELS[mimeType.toLowerCase()];
|
||||||
|
if (label) return label;
|
||||||
|
const sub = mimeType.split('/')[1];
|
||||||
|
if (sub) {
|
||||||
|
const clean = sub.replace(/^x-/, '').replace(/^vnd\./, '');
|
||||||
|
return `Attachment.${clean}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'Attachment';
|
||||||
|
};
|
||||||
|
|
||||||
const getCurrentColor = (keywords: Record<string, boolean> | undefined) => {
|
const getCurrentColor = (keywords: Record<string, boolean> | undefined) => {
|
||||||
if (!keywords) return null;
|
if (!keywords) return null;
|
||||||
for (const key of Object.keys(keywords)) {
|
for (const key of Object.keys(keywords)) {
|
||||||
@@ -835,8 +873,11 @@ export function EmailViewer({
|
|||||||
const tCommon = useTranslations('common');
|
const tCommon = useTranslations('common');
|
||||||
const tSmime = useTranslations('smime');
|
const tSmime = useTranslations('smime');
|
||||||
const tFiles = useTranslations('files');
|
const tFiles = useTranslations('files');
|
||||||
|
const tDemoWelcome = useTranslations('demo_welcome');
|
||||||
|
const tWelcome = useTranslations('welcome');
|
||||||
const externalContentPolicy = useSettingsStore((state) => state.externalContentPolicy);
|
const externalContentPolicy = useSettingsStore((state) => state.externalContentPolicy);
|
||||||
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
|
const mailAttachmentAction = useSettingsStore((state) => state.mailAttachmentAction);
|
||||||
|
const attachmentPosition = useSettingsStore((state) => state.attachmentPosition);
|
||||||
const addTrustedSender = useSettingsStore((state) => state.addTrustedSender);
|
const addTrustedSender = useSettingsStore((state) => state.addTrustedSender);
|
||||||
const isSenderTrusted = useSettingsStore((state) => state.isSenderTrusted);
|
const isSenderTrusted = useSettingsStore((state) => state.isSenderTrusted);
|
||||||
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
||||||
@@ -861,9 +902,12 @@ export function EmailViewer({
|
|||||||
// Tablet list visibility
|
// Tablet list visibility
|
||||||
const { isTablet, isMobile } = useDeviceDetection();
|
const { isTablet, isMobile } = useDeviceDetection();
|
||||||
const { tabletListVisible } = useUIStore();
|
const { tabletListVisible } = useUIStore();
|
||||||
const { identities, client } = useAuthStore();
|
const { identities, client, isDemoMode } = useAuthStore();
|
||||||
const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
|
const resolvedTheme = useThemeStore((state) => state.resolvedTheme);
|
||||||
|
const { startTour } = useTour();
|
||||||
const [showFullHeaders, setShowFullHeaders] = useState(false);
|
const [showFullHeaders, setShowFullHeaders] = useState(false);
|
||||||
|
const [showAllBesideAttachments, setShowAllBesideAttachments] = useState(false);
|
||||||
|
const [showAllMobileAttachments, setShowAllMobileAttachments] = useState(false);
|
||||||
const [allowExternalContent, setAllowExternalContent] = useState(false);
|
const [allowExternalContent, setAllowExternalContent] = useState(false);
|
||||||
const [hasBlockedContent, setHasBlockedContent] = useState(false);
|
const [hasBlockedContent, setHasBlockedContent] = useState(false);
|
||||||
const [cidBlobUrls, setCidBlobUrls] = useState<Record<string, string>>({});
|
const [cidBlobUrls, setCidBlobUrls] = useState<Record<string, string>>({});
|
||||||
@@ -2394,6 +2438,44 @@ export function EmailViewer({
|
|||||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
|
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
|
||||||
}, [mailAttachmentAction, onDownloadAttachment]);
|
}, [mailAttachmentAction, onDownloadAttachment]);
|
||||||
|
|
||||||
|
const handleEffectiveAttachmentDownload = useCallback((attachment: EffectiveAttachment) => {
|
||||||
|
if (attachment.blobId && onDownloadAttachment) {
|
||||||
|
onDownloadAttachment(attachment.blobId, attachment.name || 'download', attachment.type, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attachment.tnefData) {
|
||||||
|
const buffer = attachment.tnefData.buffer.slice(
|
||||||
|
attachment.tnefData.byteOffset,
|
||||||
|
attachment.tnefData.byteOffset + attachment.tnefData.byteLength,
|
||||||
|
) as ArrayBuffer;
|
||||||
|
const blob = new Blob([buffer], { type: attachment.type || 'application/octet-stream' });
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = objectUrl;
|
||||||
|
anchor.download = attachment.name || 'download';
|
||||||
|
document.body.appendChild(anchor);
|
||||||
|
anchor.click();
|
||||||
|
anchor.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(objectUrl), 60000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!attachment.decryptedAttachment) return;
|
||||||
|
const bytes = getAttachmentContentBytes(attachment.decryptedAttachment);
|
||||||
|
if (!bytes || bytes.byteLength === 0) return;
|
||||||
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
||||||
|
const blob = new Blob([buffer], { type: attachment.type || 'application/octet-stream' });
|
||||||
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = objectUrl;
|
||||||
|
anchor.download = attachment.name || 'download';
|
||||||
|
document.body.appendChild(anchor);
|
||||||
|
anchor.click();
|
||||||
|
anchor.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
|
||||||
|
}, [onDownloadAttachment]);
|
||||||
|
|
||||||
// Iframe for rendering HTML emails true-to-life
|
// Iframe for rendering HTML emails true-to-life
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
|
|
||||||
@@ -2607,6 +2689,52 @@ export function EmailViewer({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
|
if (isDemoMode) {
|
||||||
|
const logoSrc = resolvedTheme === 'dark'
|
||||||
|
? '/branding/Bulwark_Logo_with_Lettering_White_and_Color.svg'
|
||||||
|
: '/branding/Bulwark_Logo_with_Lettering_Dark_Color.svg';
|
||||||
|
return (
|
||||||
|
<div className={cn("flex-1 flex flex-col items-center justify-center bg-gradient-to-br from-muted/30 to-muted/50", className)}>
|
||||||
|
<div className="text-center p-8 max-w-md">
|
||||||
|
<img
|
||||||
|
src={logoSrc}
|
||||||
|
alt="Bulwark Mail"
|
||||||
|
className="h-12 mx-auto mb-6"
|
||||||
|
/>
|
||||||
|
<h3 className="text-xl font-semibold text-foreground mb-3">{tDemoWelcome('title')}</h3>
|
||||||
|
<p className="text-sm text-muted-foreground mb-6 leading-relaxed">{tDemoWelcome('description')}</p>
|
||||||
|
<div className="flex flex-col gap-3 items-center">
|
||||||
|
<div className="grid grid-cols-2 gap-3 text-left text-sm text-muted-foreground w-full">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Mail className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span>{tDemoWelcome('feature_email')}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Star className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span>{tDemoWelcome('feature_organize')}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Keyboard className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span>{tDemoWelcome('feature_shortcuts')}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Shield className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span>{tDemoWelcome('feature_privacy')}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={startTour}
|
||||||
|
className="mt-4 inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors text-sm font-medium"
|
||||||
|
>
|
||||||
|
<PlayCircle className="w-4 h-4" />
|
||||||
|
{tWelcome('start_tour')}
|
||||||
|
</button>
|
||||||
|
<p className="text-xs text-muted-foreground/60 mt-2">{tDemoWelcome('hint')}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex-1 flex flex-col items-center justify-center bg-gradient-to-br from-muted/30 to-muted/50", className)}>
|
<div className={cn("flex-1 flex flex-col items-center justify-center bg-gradient-to-br from-muted/30 to-muted/50", className)}>
|
||||||
<div className="text-center p-8">
|
<div className="text-center p-8">
|
||||||
@@ -2913,6 +3041,21 @@ export function EmailViewer({
|
|||||||
<Code className="w-4 h-4" />
|
<Code className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Dark/light mode toggle for HTML emails */}
|
||||||
|
{effectiveEmailContent.isHtml && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev)}
|
||||||
|
data-overflow-item
|
||||||
|
data-overflow-priority="11"
|
||||||
|
className="hidden sm:inline-flex h-8 gap-1.5"
|
||||||
|
title={isDark ? 'View in light mode' : 'View in dark mode'}
|
||||||
|
>
|
||||||
|
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* More menu — click-based */}
|
{/* More menu — click-based */}
|
||||||
<div ref={moreMenuRef} className="relative">
|
<div ref={moreMenuRef} className="relative">
|
||||||
<Button
|
<Button
|
||||||
@@ -3095,6 +3238,16 @@ export function EmailViewer({
|
|||||||
<Code className="w-4 h-4" />
|
<Code className="w-4 h-4" />
|
||||||
{t('view_source')}
|
{t('view_source')}
|
||||||
</button>
|
</button>
|
||||||
|
{/* Overflow: dark/light mode toggle */}
|
||||||
|
{effectiveEmailContent.isHtml && (
|
||||||
|
<button
|
||||||
|
onClick={() => { setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev); setMoreMenuOpen(false); setMoreMenuSub(null); }}
|
||||||
|
className={cn("w-full px-3 py-1.5 text-sm text-left hover:bg-muted text-foreground flex items-center gap-2", hiddenPriorities.has(11) ? "" : "sm:hidden")}
|
||||||
|
>
|
||||||
|
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
|
||||||
|
{isDark ? 'View in light mode' : 'View in dark mode'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div className="h-px bg-border my-1" />
|
<div className="h-px bg-border my-1" />
|
||||||
{/* Export email */}
|
{/* Export email */}
|
||||||
<button
|
<button
|
||||||
@@ -3131,6 +3284,7 @@ export function EmailViewer({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={email.id}
|
key={email.id}
|
||||||
|
data-tour="email-viewer"
|
||||||
className={cn("flex-1 flex flex-row h-full bg-background overflow-hidden animate-in fade-in duration-300 relative", className)}
|
className={cn("flex-1 flex flex-row h-full bg-background overflow-hidden animate-in fade-in duration-300 relative", className)}
|
||||||
>
|
>
|
||||||
{/* Mobile More menu sidebar overlay */}
|
{/* Mobile More menu sidebar overlay */}
|
||||||
@@ -3268,6 +3422,15 @@ export function EmailViewer({
|
|||||||
<Code className="w-5 h-5" />
|
<Code className="w-5 h-5" />
|
||||||
{t('view_source')}
|
{t('view_source')}
|
||||||
</button>
|
</button>
|
||||||
|
{effectiveEmailContent.isHtml && (
|
||||||
|
<button
|
||||||
|
onClick={() => { setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev); setMoreMenuOpen(false); }}
|
||||||
|
className="w-full px-4 py-3 min-h-[44px] text-sm text-left hover:bg-muted text-foreground flex items-center gap-3"
|
||||||
|
>
|
||||||
|
{isDark ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
|
||||||
|
{isDark ? 'View in light mode' : 'View in dark mode'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div className="h-px bg-border my-1" />
|
<div className="h-px bg-border my-1" />
|
||||||
<button
|
<button
|
||||||
onClick={() => { handleExportEmail(); setMoreMenuOpen(false); }}
|
onClick={() => { handleExportEmail(); setMoreMenuOpen(false); }}
|
||||||
@@ -3341,7 +3504,7 @@ export function EmailViewer({
|
|||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-start gap-2">
|
<div className="flex items-start gap-2">
|
||||||
<h1 className="text-lg lg:text-2xl font-bold text-foreground tracking-tight break-words min-w-0">
|
<h1 className="text-lg lg:text-xl font-bold text-foreground tracking-tight break-words min-w-0">
|
||||||
{email.subject || t('no_subject')}
|
{email.subject || t('no_subject')}
|
||||||
</h1>
|
</h1>
|
||||||
{/* Star inline with subject (top toolbar mode) */}
|
{/* Star inline with subject (top toolbar mode) */}
|
||||||
@@ -3365,19 +3528,24 @@ export function EmailViewer({
|
|||||||
<span className={cn("w-2.5 h-2.5 rounded-full flex-shrink-0", dotClass)} title={kw!.label} />
|
<span className={cn("w-2.5 h-2.5 rounded-full flex-shrink-0", dotClass)} title={kw!.label} />
|
||||||
) : null;
|
) : null;
|
||||||
})()}
|
})()}
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2 lg:gap-3 mt-1 lg:mt-1.5 text-xs lg:text-sm text-muted-foreground">
|
|
||||||
<span className="flex items-center gap-1 lg:gap-1.5 whitespace-nowrap">
|
|
||||||
<Clock className="w-3.5 h-3.5 lg:w-4 lg:h-4" />
|
|
||||||
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
|
|
||||||
</span>
|
|
||||||
{isImportant && (
|
{isImportant && (
|
||||||
<span className="px-1.5 lg:px-2 py-0.5 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-full text-xs font-medium whitespace-nowrap">
|
<span className="px-1.5 lg:px-2 py-0.5 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-full text-xs font-medium whitespace-nowrap flex-shrink-0 self-center">
|
||||||
{t('important')}
|
{t('important')}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{/* Date/time on the right of subject row */}
|
||||||
|
<div className="flex-shrink-0 text-right">
|
||||||
|
<span className="text-xs lg:text-sm text-muted-foreground whitespace-nowrap">
|
||||||
|
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
|
||||||
|
</span>
|
||||||
|
{email.size > 0 && (
|
||||||
|
<div className="text-xs text-muted-foreground/60">
|
||||||
|
{formatFileSize(email.size)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -3408,13 +3576,14 @@ export function EmailViewer({
|
|||||||
name={sender?.name}
|
name={sender?.name}
|
||||||
email={sender?.email}
|
email={sender?.email}
|
||||||
size="lg"
|
size="lg"
|
||||||
className="shadow-sm w-12 h-12 group-hover:ring-2 group-hover:ring-primary/30 transition-all"
|
className="shadow-sm w-10 h-10 group-hover:ring-2 group-hover:ring-primary/30 transition-all"
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0 flex gap-4">
|
||||||
{/* Sender line with email and badges */}
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-start justify-between gap-4">
|
{/* Row 1: Sender name + badges */}
|
||||||
|
<div>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<button
|
<button
|
||||||
@@ -3425,103 +3594,80 @@ export function EmailViewer({
|
|||||||
{sender?.name || sender?.email || t('unknown_sender')}
|
{sender?.name || sender?.email || t('unknown_sender')}
|
||||||
</button>
|
</button>
|
||||||
<EmailIdentityBadge email={email} identities={identities} />
|
<EmailIdentityBadge email={email} identities={identities} />
|
||||||
|
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
|
||||||
|
<UnsubscribeBanner
|
||||||
|
listUnsubscribe={listHeaders.listUnsubscribe}
|
||||||
|
senderEmail={email?.from?.[0]?.email || ''}
|
||||||
|
onDismiss={() => {
|
||||||
|
const messageId = email?.messageId || '';
|
||||||
|
const newSet = new Set(dismissedUnsubBanners).add(messageId);
|
||||||
|
setDismissedUnsubBanners(newSet);
|
||||||
|
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{sender?.email && (
|
{/* Email address under name */}
|
||||||
<div className="text-sm text-muted-foreground mt-0.5 flex items-center min-w-0">
|
{sender?.email && sender?.name && (
|
||||||
<span className="truncate">{sender.email}</span>
|
<div className="text-sm text-muted-foreground mt-0.5 truncate">{sender.email}</div>
|
||||||
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
|
|
||||||
<UnsubscribeBanner
|
|
||||||
listUnsubscribe={listHeaders.listUnsubscribe}
|
|
||||||
senderEmail={email?.from?.[0]?.email || ''}
|
|
||||||
onDismiss={() => {
|
|
||||||
const messageId = email?.messageId || '';
|
|
||||||
const newSet = new Set(dismissedUnsubBanners).add(messageId);
|
|
||||||
setDismissedUnsubBanners(newSet);
|
|
||||||
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* Date and size on the right */}
|
|
||||||
<div className="text-right flex-shrink-0">
|
|
||||||
<div className="text-sm text-muted-foreground whitespace-nowrap">
|
|
||||||
{formatDateTime(email.receivedAt, timeFormat, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' })}
|
|
||||||
</div>
|
|
||||||
{email.size > 0 && (
|
|
||||||
<div className="text-xs text-muted-foreground/70 mt-0.5">
|
|
||||||
{formatFileSize(email.size)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{effectiveEmailContent.isHtml && (
|
|
||||||
<button
|
|
||||||
onClick={() => setEmailViewDarkOverride(prev => prev === null ? !(resolvedTheme === 'dark') : !prev)}
|
|
||||||
className="inline-flex items-center rounded-full p-1 mt-1 text-muted-foreground/70 hover:text-foreground transition-colors hover:bg-muted"
|
|
||||||
title={isDark ? 'View in light mode' : 'View in dark mode'}
|
|
||||||
>
|
|
||||||
{isDark ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Recipient section - separate line */}
|
{/* Row 2: Recipients + Show details */}
|
||||||
<div className="mt-2 space-y-1">
|
<div className="mt-1 flex items-center gap-2 text-sm text-muted-foreground flex-wrap">
|
||||||
{email.to && email.to.length > 0 && (
|
{email.to && email.to.length > 0 && (
|
||||||
<div className="flex flex-wrap items-center gap-1 text-sm">
|
<>
|
||||||
<span className="text-muted-foreground">{t('recipient_to_prefix')}</span>
|
<span>{t('recipient_to_prefix')}</span>
|
||||||
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
|
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
|
||||||
{email.to.length > 2 && (
|
{email.to.length > 2 && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowFullHeaders(!showFullHeaders)}
|
onClick={() => setShowFullHeaders(!showFullHeaders)}
|
||||||
className="ml-1 text-blue-600 dark:text-blue-400 hover:underline text-sm"
|
className="text-blue-600 dark:text-blue-400 hover:underline text-sm"
|
||||||
>
|
>
|
||||||
{t('more_count', { count: email.to.length - 2 })}
|
{t('more_count', { count: email.to.length - 2 })}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{email.cc && email.cc.length > 0 && (
|
{email.cc && email.cc.length > 0 && (
|
||||||
<div className="flex flex-wrap items-center gap-1 text-sm">
|
<>
|
||||||
<span className="text-muted-foreground">CC:</span>
|
<span className="text-muted-foreground/50">|</span>
|
||||||
|
<span>CC:</span>
|
||||||
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
|
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
|
||||||
{email.cc.length > 2 && (
|
{email.cc.length > 2 && (
|
||||||
<span className="text-muted-foreground text-sm">+{email.cc.length - 2}</span>
|
<span className="text-muted-foreground">+{email.cc.length - 2}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{email.bcc && email.bcc.length > 0 && (
|
{email.bcc && email.bcc.length > 0 && (
|
||||||
<div className="flex flex-wrap items-center gap-1 text-sm">
|
<>
|
||||||
<span className="text-muted-foreground">{t('bcc')}:</span>
|
<span className="text-muted-foreground/50">|</span>
|
||||||
|
<span>{t('bcc')}:</span>
|
||||||
{renderClickableRecipients(email.bcc, currentUserEmail, t, handleViewContactSidebar)}
|
{renderClickableRecipients(email.bcc, currentUserEmail, t, handleViewContactSidebar)}
|
||||||
{email.bcc.length > 2 && (
|
{email.bcc.length > 2 && (
|
||||||
<span className="text-muted-foreground text-sm">+{email.bcc.length - 2}</span>
|
<span className="text-muted-foreground">+{email.bcc.length - 2}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => setShowFullHeaders(!showFullHeaders)}
|
||||||
|
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-0.5 transition-colors ml-1"
|
||||||
|
>
|
||||||
|
{showFullHeaders ? (
|
||||||
|
<>
|
||||||
|
<ChevronUp className="w-3 h-3" />
|
||||||
|
{t('hide_details')}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ChevronDown className="w-3 h-3" />
|
||||||
|
{t('show_details')}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Details toggle - stays in place when expanded */}
|
|
||||||
<button
|
|
||||||
onClick={() => setShowFullHeaders(!showFullHeaders)}
|
|
||||||
className="mt-3 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
|
|
||||||
>
|
|
||||||
{showFullHeaders ? (
|
|
||||||
<>
|
|
||||||
<ChevronUp className="w-3 h-3" />
|
|
||||||
{t('hide_details')}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<ChevronDown className="w-3 h-3" />
|
|
||||||
{t('show_details')}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Expandable Details */}
|
{/* Expandable Details */}
|
||||||
{showFullHeaders && (
|
{showFullHeaders && (
|
||||||
<div className="mt-3 space-y-3">
|
<div className="mt-3 space-y-3">
|
||||||
@@ -3893,46 +4039,248 @@ export function EmailViewer({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
</div>
|
||||||
|
{/* Attachments on the right (beside-sender mode) */}
|
||||||
|
{attachmentPosition === 'beside-sender' && effectiveAttachments.length > 0 && (
|
||||||
|
<div className="relative flex flex-col items-end justify-start gap-1 flex-shrink-0 max-w-[50%]">
|
||||||
|
{effectiveAttachments.slice(0, 2).map((attachment) => {
|
||||||
|
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
||||||
|
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
||||||
|
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={attachment.id}
|
||||||
|
className="inline-flex items-center gap-1.5 px-2 py-1 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
|
||||||
|
>
|
||||||
|
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
|
||||||
|
<span className="text-xs text-foreground truncate max-w-[140px]">
|
||||||
|
{getAttachmentDisplayName(attachment.name, attachment.type)}
|
||||||
|
</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground">
|
||||||
|
{formatFileSize(attachment.size)}
|
||||||
|
</span>
|
||||||
|
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={t('download')}
|
||||||
|
onClick={() => handleEffectiveAttachmentDownload(attachment)}
|
||||||
|
>
|
||||||
|
<Download className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
{opensPreview && (
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={tFiles('preview')}
|
||||||
|
onClick={() => handleEffectiveAttachmentOpen(attachment)}
|
||||||
|
>
|
||||||
|
<Eye className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{effectiveAttachments.length > 2 && (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAllBesideAttachments(!showAllBesideAttachments)}
|
||||||
|
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-0.5"
|
||||||
|
>
|
||||||
|
+{effectiveAttachments.length - 2} {t('more')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{/* Floating popup for remaining attachments */}
|
||||||
|
{showAllBesideAttachments && effectiveAttachments.length > 2 && (
|
||||||
|
<>
|
||||||
|
<div className="fixed inset-0 z-40" onClick={() => setShowAllBesideAttachments(false)} />
|
||||||
|
<div className="absolute top-full right-0 mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-2 flex flex-col gap-1 min-w-[220px]">
|
||||||
|
{effectiveAttachments.slice(2).map((attachment) => {
|
||||||
|
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
||||||
|
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
||||||
|
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={attachment.id}
|
||||||
|
className="flex items-center gap-1.5 px-2 py-1 rounded-md group relative cursor-default w-full"
|
||||||
|
>
|
||||||
|
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
|
||||||
|
<span className="text-xs text-foreground truncate max-w-[180px]">
|
||||||
|
{getAttachmentDisplayName(attachment.name, attachment.type)}
|
||||||
|
</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground ml-auto flex-shrink-0">
|
||||||
|
{formatFileSize(attachment.size)}
|
||||||
|
</span>
|
||||||
|
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={t('download')}
|
||||||
|
onClick={() => { handleEffectiveAttachmentDownload(attachment); setShowAllBesideAttachments(false); }}
|
||||||
|
>
|
||||||
|
<Download className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
{opensPreview && (
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={tFiles('preview')}
|
||||||
|
onClick={() => { handleEffectiveAttachmentOpen(attachment); setShowAllBesideAttachments(false); }}
|
||||||
|
>
|
||||||
|
<Eye className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* === ATTACHMENTS (integrated into header) === */}
|
{/* === ATTACHMENTS below header (below-header mode, desktop only) === */}
|
||||||
{effectiveAttachments.length > 0 && (
|
{attachmentPosition === 'below-header' && effectiveAttachments.length > 0 && (
|
||||||
<div className="bg-background border-b border-border px-4 lg:px-6 py-3">
|
<div className="hidden lg:block bg-background border-b border-border px-4 lg:px-6 py-2">
|
||||||
<div className="flex items-start gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
{effectiveAttachments.map((attachment) => {
|
{effectiveAttachments.map((attachment) => {
|
||||||
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
||||||
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
||||||
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
||||||
return (
|
return (
|
||||||
<button
|
<div
|
||||||
key={attachment.id}
|
key={attachment.id}
|
||||||
className="inline-flex items-center gap-2 px-3 py-2 bg-muted/60 hover:bg-accent rounded-lg transition-colors group border border-border/50"
|
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
|
||||||
title={`${opensPreview ? tFiles('preview') : t('download')} ${attachment.name || 'Unnamed'} (${formatFileSize(attachment.size)})`}
|
|
||||||
onClick={() => handleEffectiveAttachmentOpen(attachment)}
|
|
||||||
>
|
>
|
||||||
<FileIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
<FileIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||||
<div className="flex flex-col items-start min-w-0">
|
<span className="text-sm text-foreground truncate max-w-[200px]">
|
||||||
<span className="text-sm text-foreground truncate max-w-[200px]">
|
{getAttachmentDisplayName(attachment.name, attachment.type)}
|
||||||
{attachment.name || "Unnamed"}
|
</span>
|
||||||
</span>
|
<span className="text-xs text-muted-foreground">
|
||||||
<span className="text-xs text-muted-foreground">
|
{formatFileSize(attachment.size)}
|
||||||
{formatFileSize(attachment.size)}
|
</span>
|
||||||
</span>
|
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={t('download')}
|
||||||
|
onClick={() => handleEffectiveAttachmentDownload(attachment)}
|
||||||
|
>
|
||||||
|
<Download className="w-4 h-4 text-foreground" />
|
||||||
|
</button>
|
||||||
|
{opensPreview && (
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={tFiles('preview')}
|
||||||
|
onClick={() => handleEffectiveAttachmentOpen(attachment)}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4 text-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{opensPreview ? (
|
</div>
|
||||||
<Eye className="w-3.5 h-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
|
|
||||||
) : (
|
|
||||||
<Download className="w-3.5 h-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Mobile/Tablet Attachments */}
|
||||||
|
{effectiveAttachments.length > 0 && (
|
||||||
|
<div className="lg:hidden bg-background border-b border-border px-4 py-2">
|
||||||
|
<div className="relative flex items-center gap-1.5 flex-wrap">
|
||||||
|
{effectiveAttachments.slice(0, 2).map((attachment) => {
|
||||||
|
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
||||||
|
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
||||||
|
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={attachment.id}
|
||||||
|
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-muted/60 rounded-md border border-border/50 group relative cursor-default"
|
||||||
|
>
|
||||||
|
<FileIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||||
|
<span className="text-sm text-foreground truncate max-w-[200px]">
|
||||||
|
{getAttachmentDisplayName(attachment.name, attachment.type)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{formatFileSize(attachment.size)}
|
||||||
|
</span>
|
||||||
|
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={t('download')}
|
||||||
|
onClick={() => handleEffectiveAttachmentDownload(attachment)}
|
||||||
|
>
|
||||||
|
<Download className="w-4 h-4 text-foreground" />
|
||||||
|
</button>
|
||||||
|
{opensPreview && (
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={tFiles('preview')}
|
||||||
|
onClick={() => handleEffectiveAttachmentOpen(attachment)}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4 text-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{effectiveAttachments.length > 2 && (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAllMobileAttachments(!showAllMobileAttachments)}
|
||||||
|
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-0.5"
|
||||||
|
>
|
||||||
|
+{effectiveAttachments.length - 2} {t('more')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{showAllMobileAttachments && effectiveAttachments.length > 2 && (
|
||||||
|
<>
|
||||||
|
<div className="fixed inset-0 z-40" onClick={() => setShowAllMobileAttachments(false)} />
|
||||||
|
<div className="absolute top-full left-0 mt-1 z-50 bg-background border border-border rounded-lg shadow-lg p-2 flex flex-col gap-1 min-w-[220px]">
|
||||||
|
{effectiveAttachments.slice(2).map((attachment) => {
|
||||||
|
const FileIcon = getFileIcon(attachment.name || undefined, attachment.type);
|
||||||
|
const isPreviewable = isFilePreviewable(attachment.name || undefined, attachment.type);
|
||||||
|
const opensPreview = isPreviewable && mailAttachmentAction === 'preview';
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={attachment.id}
|
||||||
|
className="flex items-center gap-1.5 px-2 py-1 rounded-md group relative cursor-default w-full"
|
||||||
|
>
|
||||||
|
<FileIcon className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
|
||||||
|
<span className="text-xs text-foreground truncate max-w-[180px]">
|
||||||
|
{getAttachmentDisplayName(attachment.name, attachment.type)}
|
||||||
|
</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground ml-auto flex-shrink-0">
|
||||||
|
{formatFileSize(attachment.size)}
|
||||||
|
</span>
|
||||||
|
<div className="absolute inset-y-0 right-0 rounded-r-md bg-background/95 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 px-1.5">
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={t('download')}
|
||||||
|
onClick={() => { handleEffectiveAttachmentDownload(attachment); setShowAllMobileAttachments(false); }}
|
||||||
|
>
|
||||||
|
<Download className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
{opensPreview && (
|
||||||
|
<button
|
||||||
|
className="p-1 hover:bg-accent rounded transition-colors"
|
||||||
|
title={tFiles('preview')}
|
||||||
|
onClick={() => { handleEffectiveAttachmentOpen(attachment); setShowAllMobileAttachments(false); }}
|
||||||
|
>
|
||||||
|
<Eye className="w-3.5 h-3.5 text-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Mobile/Tablet Sender Info - scrolls with content */}
|
{/* Mobile/Tablet Sender Info - scrolls with content */}
|
||||||
<div className="lg:hidden bg-background border-b border-border px-4" style={{ paddingBlock: 'var(--density-header-py)' }}>
|
<div className="lg:hidden bg-background border-b border-border px-4" style={{ paddingBlock: 'var(--density-header-py)' }}>
|
||||||
<div className="flex items-start" style={{ gap: 'var(--density-item-gap)' }}>
|
<div className="flex items-start" style={{ gap: 'var(--density-item-gap)' }}>
|
||||||
@@ -3949,8 +4297,8 @@ export function EmailViewer({
|
|||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
{/* Mobile 2-line layout */}
|
{/* Row 1: Sender name + badges */}
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
<button
|
<button
|
||||||
onClick={() => sender?.email && handleViewContactSidebar(null, sender.email)}
|
onClick={() => sender?.email && handleViewContactSidebar(null, sender.email)}
|
||||||
className="text-sm font-semibold text-foreground hover:text-primary hover:underline transition-colors cursor-pointer text-left"
|
className="text-sm font-semibold text-foreground hover:text-primary hover:underline transition-colors cursor-pointer text-left"
|
||||||
@@ -3958,43 +4306,42 @@ export function EmailViewer({
|
|||||||
{sender?.name || sender?.email || t('unknown_sender')}
|
{sender?.name || sender?.email || t('unknown_sender')}
|
||||||
</button>
|
</button>
|
||||||
<EmailIdentityBadge email={email} identities={identities} />
|
<EmailIdentityBadge email={email} identities={identities} />
|
||||||
</div>
|
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
|
||||||
<div className="mt-1 flex items-center gap-1 text-sm text-muted-foreground flex-wrap">
|
<UnsubscribeBanner
|
||||||
{sender?.email && sender?.name && (
|
listUnsubscribe={listHeaders.listUnsubscribe}
|
||||||
<>
|
senderEmail={email?.from?.[0]?.email || ''}
|
||||||
<span className="truncate">{sender.email}</span>
|
onDismiss={() => {
|
||||||
{shouldShowUnsubBanner && listHeaders?.listUnsubscribe && (
|
const messageId = email?.messageId || '';
|
||||||
<UnsubscribeBanner
|
const newSet = new Set(dismissedUnsubBanners).add(messageId);
|
||||||
listUnsubscribe={listHeaders.listUnsubscribe}
|
setDismissedUnsubBanners(newSet);
|
||||||
senderEmail={email?.from?.[0]?.email || ''}
|
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
|
||||||
onDismiss={() => {
|
}}
|
||||||
const messageId = email?.messageId || '';
|
/>
|
||||||
const newSet = new Set(dismissedUnsubBanners).add(messageId);
|
|
||||||
setDismissedUnsubBanners(newSet);
|
|
||||||
localStorage.setItem('dismissed-unsub-banners', JSON.stringify([...newSet]));
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<span>·</span>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
{/* Email address under name */}
|
||||||
|
{sender?.email && sender?.name && (
|
||||||
|
<div className="text-xs text-muted-foreground mt-0.5 truncate">{sender.email}</div>
|
||||||
|
)}
|
||||||
|
{/* Row 2: Recipients */}
|
||||||
|
<div className="mt-0.5 flex items-center gap-1 text-sm text-muted-foreground flex-wrap">
|
||||||
{email.to && email.to.length > 0 && (
|
{email.to && email.to.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<span>→ {t('recipient_to_prefix')}</span>
|
<span>→ {t('recipient_to_prefix')}</span>
|
||||||
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
|
{renderClickableRecipients(email.to, currentUserEmail, t, handleViewContactSidebar)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{email.cc && email.cc.length > 0 && (
|
||||||
|
<>
|
||||||
|
<span className="text-muted-foreground/50">|</span>
|
||||||
|
<span>CC:</span>
|
||||||
|
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
|
||||||
|
{email.cc.length > 2 && (
|
||||||
|
<span>+{email.cc.length - 2}</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{/* CC line (mobile - only if present) */}
|
|
||||||
{email.cc && email.cc.length > 0 && (
|
|
||||||
<div className="mt-1 flex items-center gap-1 text-sm">
|
|
||||||
<span className="text-muted-foreground">CC:</span>
|
|
||||||
{renderClickableRecipients(email.cc, currentUserEmail, t, handleViewContactSidebar)}
|
|
||||||
{email.cc.length > 2 && (
|
|
||||||
<span className="text-muted-foreground">+{email.cc.length - 2}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -4102,7 +4449,7 @@ export function EmailViewer({
|
|||||||
<iframe
|
<iframe
|
||||||
ref={iframeRef}
|
ref={iframeRef}
|
||||||
srcDoc={emailIframeSrcDoc}
|
srcDoc={emailIframeSrcDoc}
|
||||||
sandbox="allow-same-origin allow-popups"
|
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
|
||||||
title="Email content"
|
title="Email content"
|
||||||
className="w-full border-0 rounded"
|
className="w-full border-0 rounded"
|
||||||
style={{ minHeight: '100px', colorScheme: isDark && emailHasNativeDarkMode ? 'light dark' : 'light' }}
|
style={{ minHeight: '100px', colorScheme: isDark && emailHasNativeDarkMode ? 'light dark' : 'light' }}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
|
|||||||
import { Email } from "@/lib/jmap/types";
|
import { Email } from "@/lib/jmap/types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { Paperclip, Star, Circle, CheckSquare, Square } from "lucide-react";
|
import { Paperclip, Star, Circle, CheckSquare, Square, Reply, Forward } from "lucide-react";
|
||||||
import { useEmailDrag } from "@/hooks/use-email-drag";
|
import { useEmailDrag } from "@/hooks/use-email-drag";
|
||||||
import { useLongPress } from "@/hooks/use-long-press";
|
import { useLongPress } from "@/hooks/use-long-press";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
@@ -29,6 +29,8 @@ export function ThreadEmailItem({
|
|||||||
}: ThreadEmailItemProps) {
|
}: ThreadEmailItemProps) {
|
||||||
const isUnread = !email.keywords?.$seen;
|
const isUnread = !email.keywords?.$seen;
|
||||||
const isStarred = email.keywords?.$flagged;
|
const isStarred = email.keywords?.$flagged;
|
||||||
|
const isAnswered = email.keywords?.$answered;
|
||||||
|
const isForwarded = email.keywords?.$forwarded;
|
||||||
const sender = email.from?.[0];
|
const sender = email.from?.[0];
|
||||||
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
||||||
const density = useSettingsStore((state) => state.density);
|
const density = useSettingsStore((state) => state.density);
|
||||||
@@ -151,6 +153,18 @@ export function ThreadEmailItem({
|
|||||||
{isStarred && (
|
{isStarred && (
|
||||||
<Star className="w-3 h-3 fill-amber-400 text-amber-400" />
|
<Star className="w-3 h-3 fill-amber-400 text-amber-400" />
|
||||||
)}
|
)}
|
||||||
|
{isAnswered && !isForwarded && (
|
||||||
|
<Reply className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isForwarded && !isAnswered && (
|
||||||
|
<Forward className="w-3 h-3 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isAnswered && isForwarded && (
|
||||||
|
<>
|
||||||
|
<Reply className="w-3 h-3 text-muted-foreground" />
|
||||||
|
<Forward className="w-3 h-3 text-muted-foreground" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{email.hasAttachment && (
|
{email.hasAttachment && (
|
||||||
<Paperclip className="w-3 h-3 text-muted-foreground" />
|
<Paperclip className="w-3 h-3 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { formatDate } from "@/lib/utils";
|
|||||||
import { Email, ThreadGroup } from "@/lib/jmap/types";
|
import { Email, ThreadGroup } from "@/lib/jmap/types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Avatar } from "@/components/ui/avatar";
|
import { Avatar } from "@/components/ui/avatar";
|
||||||
import { Paperclip, Star, Circle, ChevronRight, ChevronDown, Loader2, MessageSquare, CheckSquare, Square } from "lucide-react";
|
import { Paperclip, Star, Circle, ChevronRight, ChevronDown, Loader2, MessageSquare, CheckSquare, Square, Reply, Forward } from "lucide-react";
|
||||||
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
import { useSettingsStore, KEYWORD_PALETTE } from "@/stores/settings-store";
|
||||||
import { useUIStore } from "@/stores/ui-store";
|
import { useUIStore } from "@/stores/ui-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
@@ -13,6 +13,7 @@ import { getThreadColorTag, getEmailColorTag } from "@/lib/thread-utils";
|
|||||||
import { useEmailDrag } from "@/hooks/use-email-drag";
|
import { useEmailDrag } from "@/hooks/use-email-drag";
|
||||||
import { useLongPress } from "@/hooks/use-long-press";
|
import { useLongPress } from "@/hooks/use-long-press";
|
||||||
import { ThreadEmailItem } from "./thread-email-item";
|
import { ThreadEmailItem } from "./thread-email-item";
|
||||||
|
import { EmailHoverActions } from "./email-hover-actions";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
|
|
||||||
interface ThreadListItemProps {
|
interface ThreadListItemProps {
|
||||||
@@ -25,6 +26,12 @@ interface ThreadListItemProps {
|
|||||||
onEmailSelect: (email: Email) => void;
|
onEmailSelect: (email: Email) => void;
|
||||||
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
||||||
onOpenConversation?: (thread: ThreadGroup) => void;
|
onOpenConversation?: (thread: ThreadGroup) => void;
|
||||||
|
onToggleStar?: (email: Email) => void;
|
||||||
|
onMarkAsRead?: (email: Email, read: boolean) => void;
|
||||||
|
onDelete?: (email: Email) => void;
|
||||||
|
onArchive?: (email: Email) => void;
|
||||||
|
onSetColorTag?: (emailId: string, color: string | null) => void;
|
||||||
|
onMarkAsSpam?: (email: Email) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SingleEmailItemProps {
|
interface SingleEmailItemProps {
|
||||||
@@ -34,12 +41,20 @@ interface SingleEmailItemProps {
|
|||||||
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
onContextMenu?: (e: React.MouseEvent, email: Email) => void;
|
||||||
showPreview: boolean;
|
showPreview: boolean;
|
||||||
colorTag: string | null;
|
colorTag: string | null;
|
||||||
|
onToggleStar?: () => void;
|
||||||
|
onMarkAsRead?: (read: boolean) => void;
|
||||||
|
onDelete?: () => void;
|
||||||
|
onArchive?: () => void;
|
||||||
|
onSetColorTag?: (color: string | null) => void;
|
||||||
|
onMarkAsSpam?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
|
const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
|
||||||
function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag }, ref) {
|
function SingleEmailItem({ email, selected, onClick, onContextMenu, showPreview, colorTag, onToggleStar, onMarkAsRead, onDelete, onArchive, onSetColorTag, onMarkAsSpam }, ref) {
|
||||||
const isUnread = !email.keywords?.$seen;
|
const isUnread = !email.keywords?.$seen;
|
||||||
const isStarred = email.keywords?.$flagged;
|
const isStarred = email.keywords?.$flagged;
|
||||||
|
const isAnswered = email.keywords?.$answered;
|
||||||
|
const isForwarded = email.keywords?.$forwarded;
|
||||||
const sender = email.from?.[0];
|
const sender = email.from?.[0];
|
||||||
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
||||||
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
const emailKeywords = useSettingsStore((state) => state.emailKeywords);
|
||||||
@@ -100,7 +115,7 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
|
|||||||
{...dragHandlers}
|
{...dragHandlers}
|
||||||
{...longPressHandlers}
|
{...longPressHandlers}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative group cursor-pointer select-none transition-all duration-200 border-b border-border",
|
"relative group cursor-pointer select-none transition-shadow duration-200 border-b border-border overflow-hidden",
|
||||||
resolvedColorTag ? resolvedColorTag : (
|
resolvedColorTag ? resolvedColorTag : (
|
||||||
selected
|
selected
|
||||||
? "bg-accent"
|
? "bg-accent"
|
||||||
@@ -169,6 +184,18 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
|
|||||||
{isStarred && (
|
{isStarred && (
|
||||||
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
|
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
|
||||||
)}
|
)}
|
||||||
|
{isAnswered && !isForwarded && (
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isForwarded && !isAnswered && (
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{isAnswered && isForwarded && (
|
||||||
|
<>
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{email.hasAttachment && (
|
{email.hasAttachment && (
|
||||||
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
@@ -216,6 +243,17 @@ const SingleEmailItem = React.forwardRef<HTMLDivElement, SingleEmailItemProps>(
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Hover Quick Actions */}
|
||||||
|
<EmailHoverActions
|
||||||
|
email={email}
|
||||||
|
onToggleStar={onToggleStar}
|
||||||
|
onMarkAsRead={onMarkAsRead}
|
||||||
|
onDelete={onDelete}
|
||||||
|
onArchive={onArchive}
|
||||||
|
onSetColorTag={onSetColorTag}
|
||||||
|
onMarkAsSpam={onMarkAsSpam}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -232,12 +270,18 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
|
|||||||
onEmailSelect,
|
onEmailSelect,
|
||||||
onContextMenu,
|
onContextMenu,
|
||||||
onOpenConversation,
|
onOpenConversation,
|
||||||
|
onToggleStar,
|
||||||
|
onMarkAsRead,
|
||||||
|
onDelete,
|
||||||
|
onArchive,
|
||||||
|
onSetColorTag,
|
||||||
|
onMarkAsSpam,
|
||||||
}, ref) {
|
}, ref) {
|
||||||
const t = useTranslations('threads');
|
const t = useTranslations('threads');
|
||||||
const showPreview = useSettingsStore((state) => state.showPreview);
|
const showPreview = useSettingsStore((state) => state.showPreview);
|
||||||
const density = useSettingsStore((state) => state.density);
|
const density = useSettingsStore((state) => state.density);
|
||||||
const isMobile = useUIStore((state) => state.isMobile);
|
const isMobile = useUIStore((state) => state.isMobile);
|
||||||
const { latestEmail, participantNames, hasUnread, hasStarred, hasAttachment, emailCount } = thread;
|
const { latestEmail, participantNames, hasUnread, hasStarred, hasAttachment, hasAnswered, hasForwarded, emailCount } = thread;
|
||||||
|
|
||||||
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
const { selectedMailbox, selectedEmailIds, toggleEmailSelection, selectRangeEmails, clearSelection } = useEmailStore();
|
||||||
|
|
||||||
@@ -278,6 +322,12 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
|
|||||||
onContextMenu={onContextMenu}
|
onContextMenu={onContextMenu}
|
||||||
showPreview={showPreview}
|
showPreview={showPreview}
|
||||||
colorTag={colorTag}
|
colorTag={colorTag}
|
||||||
|
onToggleStar={onToggleStar ? () => onToggleStar(latestEmail) : undefined}
|
||||||
|
onMarkAsRead={onMarkAsRead ? (read) => onMarkAsRead(latestEmail, read) : undefined}
|
||||||
|
onDelete={onDelete ? () => onDelete(latestEmail) : undefined}
|
||||||
|
onArchive={onArchive ? () => onArchive(latestEmail) : undefined}
|
||||||
|
onSetColorTag={onSetColorTag ? (color) => onSetColorTag(latestEmail.id, color) : undefined}
|
||||||
|
onMarkAsSpam={onMarkAsSpam ? () => onMarkAsSpam(latestEmail) : undefined}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -339,7 +389,7 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
|
|||||||
{...dragHandlers}
|
{...dragHandlers}
|
||||||
{...threadLongPressHandlers}
|
{...threadLongPressHandlers}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative group cursor-pointer select-none transition-all duration-200",
|
"relative group cursor-pointer select-none transition-shadow duration-200 overflow-hidden",
|
||||||
colorTag ? colorTag : (
|
colorTag ? colorTag : (
|
||||||
isSelected
|
isSelected
|
||||||
? "bg-accent"
|
? "bg-accent"
|
||||||
@@ -446,6 +496,18 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
|
|||||||
{hasStarred && (
|
{hasStarred && (
|
||||||
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
|
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
|
||||||
)}
|
)}
|
||||||
|
{hasAnswered && !hasForwarded && (
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{hasForwarded && !hasAnswered && (
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
{hasAnswered && hasForwarded && (
|
||||||
|
<>
|
||||||
|
<Reply className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
<Forward className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{hasAttachment && (
|
{hasAttachment && (
|
||||||
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
<Paperclip className="w-3.5 h-3.5 text-muted-foreground" />
|
||||||
)}
|
)}
|
||||||
@@ -493,6 +555,17 @@ export const ThreadListItem = React.forwardRef<HTMLDivElement, ThreadListItemPro
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Hover Quick Actions for thread header */}
|
||||||
|
<EmailHoverActions
|
||||||
|
email={latestEmail}
|
||||||
|
onToggleStar={onToggleStar ? () => onToggleStar(latestEmail) : undefined}
|
||||||
|
onMarkAsRead={onMarkAsRead ? (read) => onMarkAsRead(latestEmail, read) : undefined}
|
||||||
|
onDelete={onDelete ? () => onDelete(latestEmail) : undefined}
|
||||||
|
onArchive={onArchive ? () => onArchive(latestEmail) : undefined}
|
||||||
|
onSetColorTag={onSetColorTag ? (color) => onSetColorTag(latestEmail.id, color) : undefined}
|
||||||
|
onMarkAsSpam={onMarkAsSpam ? () => onMarkAsSpam(latestEmail) : undefined}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isExpanded && !isMobile && (
|
{isExpanded && !isMobile && (
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { loadFilesSettings } from "@/components/files/files-settings-dialog";
|
|||||||
import type { FolderLayout } from "@/components/files/files-settings-dialog";
|
import type { FolderLayout } from "@/components/files/files-settings-dialog";
|
||||||
import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar";
|
import { FolderTreeSidebar } from "@/components/files/folder-tree-sidebar";
|
||||||
import { ResizeHandle } from "@/components/layout/resize-handle";
|
import { ResizeHandle } from "@/components/layout/resize-handle";
|
||||||
|
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
|
||||||
import type { FileResource } from "@/stores/file-store";
|
import type { FileResource } from "@/stores/file-store";
|
||||||
|
|
||||||
type SortKey = "name" | "size" | "modified";
|
type SortKey = "name" | "size" | "modified";
|
||||||
@@ -624,16 +625,20 @@ export function FileBrowser({
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setIsDraggingOver(false);
|
setIsDraggingOver(false);
|
||||||
|
|
||||||
const files = Array.from(e.dataTransfer.files);
|
setIsUploading(true);
|
||||||
if (files.length > 0) {
|
try {
|
||||||
setIsUploading(true);
|
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
|
||||||
try {
|
if (files.length > 0) {
|
||||||
await onUploadFiles(files);
|
if (hasDirectories) {
|
||||||
} finally {
|
await onUploadFolder(files);
|
||||||
setIsUploading(false);
|
} else {
|
||||||
|
await onUploadFiles(files);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
setIsUploading(false);
|
||||||
}
|
}
|
||||||
}, [onUploadFiles]);
|
}, [onUploadFiles, onUploadFolder]);
|
||||||
|
|
||||||
const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const files = Array.from(e.target.files || []);
|
const files = Array.from(e.target.files || []);
|
||||||
@@ -945,6 +950,16 @@ export function FileBrowser({
|
|||||||
>
|
>
|
||||||
<Upload className="w-4 h-4" />
|
<Upload className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => folderInputRef.current?.click()}
|
||||||
|
title={t("upload_folder")}
|
||||||
|
disabled={isUploading}
|
||||||
|
>
|
||||||
|
<FolderUp className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
@@ -1195,6 +1210,14 @@ export function FileBrowser({
|
|||||||
setIsUploading(false);
|
setIsUploading(false);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
onUploadFolder={async (files: File[]) => {
|
||||||
|
setIsUploading(true);
|
||||||
|
try {
|
||||||
|
await onUploadFolder(files);
|
||||||
|
} finally {
|
||||||
|
setIsUploading(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
onCreateFolder={() => setShowNewFolder(true)}
|
onCreateFolder={() => setShowNewFolder(true)}
|
||||||
onCreateTextFile={() => setShowNewTextFile(true)}
|
onCreateTextFile={() => setShowNewTextFile(true)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -2,16 +2,18 @@
|
|||||||
|
|
||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Upload, FolderPlus, FilePlus } from "lucide-react";
|
import { Upload, FolderPlus, FilePlus, FolderUp } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { getDroppedFilesAndFolders } from "@/lib/webdav/drop-utils";
|
||||||
|
|
||||||
interface FileUploadAreaProps {
|
interface FileUploadAreaProps {
|
||||||
onUpload: (files: File[]) => Promise<void>;
|
onUpload: (files: File[]) => Promise<void>;
|
||||||
|
onUploadFolder?: (files: File[]) => Promise<void>;
|
||||||
onCreateFolder: () => void;
|
onCreateFolder: () => void;
|
||||||
onCreateTextFile?: () => void;
|
onCreateTextFile?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
|
export function FileUploadArea({ onUpload, onUploadFolder, onCreateFolder, onCreateTextFile }: FileUploadAreaProps) {
|
||||||
const t = useTranslations("files");
|
const t = useTranslations("files");
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
|
|
||||||
@@ -32,11 +34,15 @@ export function FileUploadArea({ onUpload, onCreateFolder, onCreateTextFile }: F
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setIsDragging(false);
|
setIsDragging(false);
|
||||||
|
|
||||||
const files = Array.from(e.dataTransfer.files);
|
const { files, hasDirectories } = await getDroppedFilesAndFolders(e.dataTransfer);
|
||||||
if (files.length > 0) {
|
if (files.length > 0) {
|
||||||
await onUpload(files);
|
if (hasDirectories && onUploadFolder) {
|
||||||
|
await onUploadFolder(files);
|
||||||
|
} else {
|
||||||
|
await onUpload(files);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [onUpload]);
|
}, [onUpload, onUploadFolder]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center h-full p-8">
|
<div className="flex items-center justify-center h-full p-8">
|
||||||
|
|||||||
@@ -42,7 +42,11 @@ export function ImagePreviewModal({ name, onClose, onDownload, getImageUrl }: Im
|
|||||||
}, [name, getImageUrl]);
|
}, [name, getImageUrl]);
|
||||||
|
|
||||||
const handleKeyDown = useCallback((e: KeyboardEvent) => {
|
const handleKeyDown = useCallback((e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") onClose();
|
if (e.key === "Escape") { onClose(); return; }
|
||||||
|
const target = e.target as HTMLElement;
|
||||||
|
const tag = target?.tagName?.toLowerCase();
|
||||||
|
if (tag === "input" || tag === "textarea" || tag === "select") return;
|
||||||
|
if (target?.getAttribute("contenteditable") === "true") return;
|
||||||
if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 5));
|
if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 5));
|
||||||
if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25));
|
if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25));
|
||||||
if (e.key === "r") setRotation((r) => r + 90);
|
if (e.key === "r") setRotation((r) => r + 90);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { X, Keyboard } from "lucide-react";
|
|||||||
import { KEYBOARD_SHORTCUTS } from "@/hooks/use-keyboard-shortcuts";
|
import { KEYBOARD_SHORTCUTS } from "@/hooks/use-keyboard-shortcuts";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useFocusTrap } from "@/hooks/use-focus-trap";
|
import { useFocusTrap } from "@/hooks/use-focus-trap";
|
||||||
|
import { useTour } from "@/components/tour/tour-provider";
|
||||||
|
|
||||||
interface KeyboardShortcutsModalProps {
|
interface KeyboardShortcutsModalProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -13,6 +14,7 @@ interface KeyboardShortcutsModalProps {
|
|||||||
|
|
||||||
export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsModalProps) {
|
export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsModalProps) {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
|
const { startTour } = useTour();
|
||||||
|
|
||||||
const modalRef = useFocusTrap({
|
const modalRef = useFocusTrap({
|
||||||
isActive: isOpen,
|
isActive: isOpen,
|
||||||
@@ -144,6 +146,14 @@ export function KeyboardShortcutsModal({ isOpen, onClose }: KeyboardShortcutsMod
|
|||||||
<p className="text-sm text-muted-foreground text-center">
|
<p className="text-sm text-muted-foreground text-center">
|
||||||
{t("shortcuts.tip")}
|
{t("shortcuts.tip")}
|
||||||
</p>
|
</p>
|
||||||
|
<p className="text-sm text-center mt-2">
|
||||||
|
<button
|
||||||
|
onClick={() => { onClose(); startTour(); }}
|
||||||
|
className="text-primary hover:text-primary/80 underline underline-offset-2 transition-colors"
|
||||||
|
>
|
||||||
|
{t("tour.take_a_tour")}
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -101,15 +101,11 @@ export function AccountSwitcher({ variant = "rail", className }: AccountSwitcher
|
|||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
logout();
|
logout();
|
||||||
if (useAccountStore.getState().accounts.length === 0) {
|
|
||||||
router.push("/login" as never);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLogoutAll = () => {
|
const handleLogoutAll = () => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
logoutAll();
|
logoutAll();
|
||||||
router.push("/login" as never);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSetDefault = (accountId: string) => {
|
const handleSetDefault = (accountId: string) => {
|
||||||
|
|||||||
@@ -217,8 +217,8 @@ export function NavigationRail({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{/* Custom sidebar apps */}
|
{/* Custom sidebar apps (per-app mobile visibility) */}
|
||||||
{sidebarApps.map((app) => {
|
{sidebarApps.filter((app) => app.showOnMobile).map((app) => {
|
||||||
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
const AppIcon = lucideIcons[app.icon as keyof typeof lucideIcons] as LucideIcon | undefined;
|
||||||
const isActive = activeAppId === app.id;
|
const isActive = activeAppId === app.id;
|
||||||
return (
|
return (
|
||||||
@@ -252,16 +252,27 @@ export function NavigationRail({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
{/* Manage apps button */}
|
{/* Settings */}
|
||||||
{onManageApps && (
|
<Link
|
||||||
<button
|
href="/settings"
|
||||||
onClick={onManageApps}
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
className="flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px] transition-colors duration-150 text-muted-foreground hover:text-foreground"
|
className={cn(
|
||||||
>
|
"flex flex-col items-center justify-center gap-1 py-2 px-3 min-w-[64px] min-h-[44px]",
|
||||||
<Plus className="w-5 h-5" />
|
"transition-colors duration-150",
|
||||||
<span className="text-[10px] font-medium leading-tight">{t("add_app")}</span>
|
isSettingsActive
|
||||||
</button>
|
? "text-primary"
|
||||||
)}
|
: "text-muted-foreground hover:text-foreground"
|
||||||
|
)}
|
||||||
|
aria-current={isSettingsActive ? "page" : undefined}
|
||||||
|
>
|
||||||
|
<div className="relative">
|
||||||
|
<Settings className="w-5 h-5" />
|
||||||
|
{isSettingsActive && (
|
||||||
|
<span className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-4 h-0.5 rounded-full bg-primary" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] font-medium leading-tight">{t("settings")}</span>
|
||||||
|
</Link>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -292,6 +303,7 @@ export function NavigationRail({
|
|||||||
key={item.id}
|
key={item.id}
|
||||||
href={item.href}
|
href={item.href}
|
||||||
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
|
data-tour={`nav-${item.id}`}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
"relative flex items-center gap-2.5 rounded-md transition-colors duration-150",
|
||||||
collapsed
|
collapsed
|
||||||
@@ -390,6 +402,7 @@ export function NavigationRail({
|
|||||||
<Link
|
<Link
|
||||||
href="/settings"
|
href="/settings"
|
||||||
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
onClick={activeAppId ? () => onCloseInlineApp?.() : undefined}
|
||||||
|
data-tour="nav-settings"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex items-center justify-center w-10 h-10 rounded-md transition-colors",
|
"flex items-center justify-center w-10 h-10 rounded-md transition-colors",
|
||||||
isSettingsActive
|
isSettingsActive
|
||||||
@@ -407,6 +420,7 @@ export function NavigationRail({
|
|||||||
{onShowShortcuts && (
|
{onShowShortcuts && (
|
||||||
<button
|
<button
|
||||||
onClick={onShowShortcuts}
|
onClick={onShowShortcuts}
|
||||||
|
data-tour="nav-shortcuts"
|
||||||
className="flex items-center justify-center w-10 h-10 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
|
className="flex items-center justify-center w-10 h-10 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
|
||||||
title={t("keyboard_shortcuts")}
|
title={t("keyboard_shortcuts")}
|
||||||
>
|
>
|
||||||
@@ -415,7 +429,9 @@ export function NavigationRail({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{quota && quota.total > 0 && (
|
{quota && quota.total > 0 && (
|
||||||
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} />
|
<div data-tour="storage-quota">
|
||||||
|
<StorageQuotaCircle quota={quota} usagePercent={quotaUsagePercent} />
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isPushConnected != null && (
|
{isPushConnected != null && (
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ interface SidebarAppFormData {
|
|||||||
url: string;
|
url: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
openMode: 'tab' | 'inline';
|
openMode: 'tab' | 'inline';
|
||||||
|
showOnMobile: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SidebarAppForm({
|
function SidebarAppForm({
|
||||||
@@ -37,6 +38,7 @@ function SidebarAppForm({
|
|||||||
url: app?.url || '',
|
url: app?.url || '',
|
||||||
icon: app?.icon || 'Globe',
|
icon: app?.icon || 'Globe',
|
||||||
openMode: app?.openMode || 'tab',
|
openMode: app?.openMode || 'tab',
|
||||||
|
showOnMobile: app?.showOnMobile ?? false,
|
||||||
});
|
});
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ import {
|
|||||||
Settings,
|
Settings,
|
||||||
X,
|
X,
|
||||||
Tag,
|
Tag,
|
||||||
|
RotateCcw,
|
||||||
|
FlaskConical,
|
||||||
|
PlayCircle,
|
||||||
|
Loader2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
|
import { cn, buildMailboxTree, MailboxNode } from "@/lib/utils";
|
||||||
import { Mailbox } from "@/lib/jmap/types";
|
import { Mailbox } from "@/lib/jmap/types";
|
||||||
@@ -40,6 +44,7 @@ import { debug } from "@/lib/debug";
|
|||||||
import { useConfig } from "@/hooks/use-config";
|
import { useConfig } from "@/hooks/use-config";
|
||||||
import { useThemeStore } from "@/stores/theme-store";
|
import { useThemeStore } from "@/stores/theme-store";
|
||||||
import { AccountSwitcher } from "./account-switcher";
|
import { AccountSwitcher } from "./account-switcher";
|
||||||
|
import { useTour } from "@/components/tour/tour-provider";
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
mailboxes: Mailbox[];
|
mailboxes: Mailbox[];
|
||||||
@@ -328,6 +333,68 @@ function TagItem({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DemoBanner() {
|
||||||
|
const t = useTranslations('sidebar');
|
||||||
|
const { isDemoMode, loginDemo } = useAuthStore();
|
||||||
|
const { startTour, resetTourCompletion } = useTour();
|
||||||
|
const router = useRouter();
|
||||||
|
const [isResetting, setIsResetting] = useState(false);
|
||||||
|
|
||||||
|
if (!isDemoMode) return null;
|
||||||
|
|
||||||
|
const handleReset = async () => {
|
||||||
|
setIsResetting(true);
|
||||||
|
// Navigate to home first so the mail page re-fetches data
|
||||||
|
router.push('/');
|
||||||
|
await loginDemo();
|
||||||
|
setIsResetting(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartTour = () => {
|
||||||
|
resetTourCompletion();
|
||||||
|
router.push('/');
|
||||||
|
setTimeout(() => startTour(), 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-tour="demo-banner"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-1.5 w-full px-3 py-2 text-xs",
|
||||||
|
"bg-primary/10 dark:bg-primary/10 text-primary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<FlaskConical className="w-3.5 h-3.5 flex-shrink-0" />
|
||||||
|
<span className="truncate font-medium">{t("demo_banner")}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<button
|
||||||
|
onClick={handleStartTour}
|
||||||
|
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 hover:bg-primary/20 transition-colors"
|
||||||
|
title={t("demo_tour")}
|
||||||
|
>
|
||||||
|
<PlayCircle className="w-3 h-3" />
|
||||||
|
{t("demo_tour")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleReset}
|
||||||
|
disabled={isResetting}
|
||||||
|
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 hover:bg-primary/20 transition-colors disabled:opacity-50"
|
||||||
|
title={t("demo_reset")}
|
||||||
|
>
|
||||||
|
{isResetting ? (
|
||||||
|
<Loader2 className="w-3 h-3 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<RotateCcw className="w-3 h-3" />
|
||||||
|
)}
|
||||||
|
{t("demo_reset")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function VacationBanner() {
|
function VacationBanner() {
|
||||||
const t = useTranslations('sidebar');
|
const t = useTranslations('sidebar');
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -454,12 +521,12 @@ export function Sidebar({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className={cn("flex items-center border-b border-border", isCollapsed ? "justify-center px-2 py-3" : "gap-2 px-4 py-3")}>
|
<div className={cn("flex items-center border-b border-border", isCollapsed ? "justify-center px-2 py-2" : "gap-1 px-2 py-2")}>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={onSidebarClose}
|
onClick={onSidebarClose}
|
||||||
className="lg:hidden h-11 w-11 flex-shrink-0"
|
className="lg:hidden h-9 w-9 flex-shrink-0"
|
||||||
aria-label={t("close")}
|
aria-label={t("close")}
|
||||||
>
|
>
|
||||||
<X className="w-5 h-5" />
|
<X className="w-5 h-5" />
|
||||||
@@ -480,7 +547,7 @@ export function Sidebar({
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={toggleSidebarCollapsed}
|
onClick={toggleSidebarCollapsed}
|
||||||
className="hidden lg:flex flex-shrink-0"
|
className="hidden lg:flex h-8 w-8 flex-shrink-0"
|
||||||
title={isCollapsed ? t("expand_tooltip") : t("collapse_tooltip")}
|
title={isCollapsed ? t("expand_tooltip") : t("collapse_tooltip")}
|
||||||
>
|
>
|
||||||
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
|
{isCollapsed ? <ChevronsRight className="w-4 h-4" /> : <ChevronsLeft className="w-4 h-4" />}
|
||||||
@@ -491,11 +558,14 @@ export function Sidebar({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Demo Banner */}
|
||||||
|
{!isCollapsed && <DemoBanner />}
|
||||||
|
|
||||||
{/* Vacation Banner */}
|
{/* Vacation Banner */}
|
||||||
{!isCollapsed && <VacationBanner />}
|
{!isCollapsed && <VacationBanner />}
|
||||||
|
|
||||||
{/* Mailbox List */}
|
{/* Mailbox List */}
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto" data-tour="sidebar">
|
||||||
<div className="py-1">
|
<div className="py-1">
|
||||||
{mailboxes.length === 0 ? (
|
{mailboxes.length === 0 ? (
|
||||||
<div className="px-4 py-2 text-sm text-muted-foreground">
|
<div className="px-4 py-2 text-sm text-muted-foreground">
|
||||||
@@ -582,7 +652,7 @@ export function Sidebar({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{((tagsExpanded && !isCollapsed) || isCollapsed) && (
|
{((tagsExpanded && !isCollapsed) || isCollapsed) && (
|
||||||
<div className="relative">
|
<div className="relative" data-tour="keyword-tags">
|
||||||
{emailKeywords.map((kw) => {
|
{emailKeywords.map((kw) => {
|
||||||
const isSelected = selectedKeyword === kw.id;
|
const isSelected = selectedKeyword === kw.id;
|
||||||
return (
|
return (
|
||||||
@@ -606,11 +676,11 @@ export function Sidebar({
|
|||||||
{/* Compose Button */}
|
{/* Compose Button */}
|
||||||
<div className={cn("border-t border-border", isCollapsed ? "flex justify-center py-3" : "px-3 py-3")}>
|
<div className={cn("border-t border-border", isCollapsed ? "flex justify-center py-3" : "px-3 py-3")}>
|
||||||
{isCollapsed ? (
|
{isCollapsed ? (
|
||||||
<Button onClick={onCompose} variant="ghost" size="icon" title={t("compose_hint")}>
|
<Button onClick={onCompose} variant="ghost" size="icon" title={t("compose_hint")} data-tour="compose-button">
|
||||||
<PenSquare className="w-5 h-5" />
|
<PenSquare className="w-5 h-5" />
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<Button onClick={onCompose} className="w-full" title={t("compose_hint")}>
|
<Button onClick={onCompose} className="w-full" title={t("compose_hint")} data-tour="compose-button">
|
||||||
<PenSquare className="w-4 h-4 mr-2" />
|
<PenSquare className="w-4 h-4 mr-2" />
|
||||||
{t("compose")}
|
{t("compose")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { isEmbedded, listenFromParent } from "@/lib/iframe-bridge";
|
||||||
|
import { getPathPrefix, getLocaleFromPath } from "@/lib/browser-navigation";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { useConfig } from "@/hooks/use-config";
|
||||||
|
|
||||||
|
export function EmbeddedBridgeProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const { parentOrigin, embeddedMode } = useConfig();
|
||||||
|
const logout = useAuthStore((s) => s.logout);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!embeddedMode || !isEmbedded()) return;
|
||||||
|
|
||||||
|
const unsubscribe = listenFromParent((msg) => {
|
||||||
|
switch (msg.type) {
|
||||||
|
case "sso:trigger-login": {
|
||||||
|
// Navigate to login page to start SSO flow
|
||||||
|
const prefix = getPathPrefix();
|
||||||
|
const locale = getLocaleFromPath();
|
||||||
|
window.location.href = `${prefix}/${locale}/login`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "sso:trigger-logout":
|
||||||
|
logout();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}, parentOrigin || undefined);
|
||||||
|
|
||||||
|
return unsubscribe;
|
||||||
|
}, [embeddedMode, parentOrigin, logout]);
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -3,21 +3,44 @@
|
|||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useAuthStore } from '@/stores/auth-store';
|
import { useAuthStore } from '@/stores/auth-store';
|
||||||
import { useEmailStore } from '@/stores/email-store';
|
import { useEmailStore } from '@/stores/email-store';
|
||||||
|
import { useAccountStore } from '@/stores/account-store';
|
||||||
import { SettingsSection, SettingItem } from './settings-section';
|
import { SettingsSection, SettingItem } from './settings-section';
|
||||||
import { formatFileSize } from '@/lib/utils';
|
import { formatFileSize } from '@/lib/utils';
|
||||||
|
|
||||||
export function AccountSettings() {
|
export function AccountSettings() {
|
||||||
const t = useTranslations('settings.account');
|
const t = useTranslations('settings.account');
|
||||||
const { username, serverUrl } = useAuthStore();
|
const { username, serverUrl, isDemoMode, primaryIdentity, authMode, activeAccountId } = useAuthStore();
|
||||||
const { quota } = useEmailStore();
|
const { quota } = useEmailStore();
|
||||||
|
const account = useAccountStore((s) => activeAccountId ? s.getAccountById(activeAccountId) : undefined);
|
||||||
|
|
||||||
const quotaPercentage = quota ? Math.round((quota.used / quota.total) * 100) : 0;
|
const quotaPercentage = quota ? Math.round((quota.used / quota.total) * 100) : 0;
|
||||||
|
const displayName = primaryIdentity?.name || account?.displayName || (isDemoMode ? 'Demo User' : undefined);
|
||||||
|
const email = primaryIdentity?.email || account?.email || username;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingsSection title={t('title')} description={t('description')}>
|
<SettingsSection title={t('title')} description={t('description')}>
|
||||||
|
{/* Display Name */}
|
||||||
|
<SettingItem label={t('name_label')}>
|
||||||
|
<span className="text-sm text-foreground">{displayName || t('../../common.unknown')}</span>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
{/* Email Address */}
|
{/* Email Address */}
|
||||||
<SettingItem label={t('email.label')}>
|
<SettingItem label={t('email.label')}>
|
||||||
<span className="text-sm text-foreground">{username || t('../../common.unknown')}</span>
|
<span className="text-sm text-foreground">{email || t('../../common.unknown')}</span>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Username / Login (show when it differs from email) */}
|
||||||
|
{username && username !== email && (
|
||||||
|
<SettingItem label={t('username_label')}>
|
||||||
|
<span className="text-sm text-foreground">{username}</span>
|
||||||
|
</SettingItem>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Authentication Method */}
|
||||||
|
<SettingItem label={t('auth_method_label')}>
|
||||||
|
<span className="text-sm text-foreground">
|
||||||
|
{authMode === 'oauth' ? t('auth_method_oauth') : t('auth_method_basic')}
|
||||||
|
</span>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
{/* Server */}
|
{/* Server */}
|
||||||
@@ -49,6 +72,16 @@ export function AccountSettings() {
|
|||||||
</div>
|
</div>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Demo mode indicator */}
|
||||||
|
{isDemoMode && (
|
||||||
|
<SettingItem label={t('account_type_label')}>
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-sm font-medium text-amber-600 dark:text-amber-400">
|
||||||
|
<span className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" />
|
||||||
|
{t('demo_account')}
|
||||||
|
</span>
|
||||||
|
</SettingItem>
|
||||||
|
)}
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import { useSettingsStore, type ToolbarPosition, type Density } from '@/stores/s
|
|||||||
import { LanguageSwitcher } from '@/components/ui/language-switcher';
|
import { LanguageSwitcher } from '@/components/ui/language-switcher';
|
||||||
import { SettingsSection, SettingItem, RadioGroup, ToggleSwitch } from './settings-section';
|
import { SettingsSection, SettingItem, RadioGroup, ToggleSwitch } from './settings-section';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { useTour } from '@/components/tour/tour-provider';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { PlayCircle } from 'lucide-react';
|
||||||
|
|
||||||
const DENSITY_PREVIEW: Record<Density, { py: string; gap: string; showAvatar: boolean; showPreview: boolean }> = {
|
const DENSITY_PREVIEW: Record<Density, { py: string; gap: string; showAvatar: boolean; showPreview: boolean }> = {
|
||||||
'extra-compact': { py: 'py-0.5', gap: 'gap-1.5', showAvatar: false, showPreview: false },
|
'extra-compact': { py: 'py-0.5', gap: 'gap-1.5', showAvatar: false, showPreview: false },
|
||||||
@@ -61,8 +64,10 @@ function DensityPreview({ density }: { density: Density }) {
|
|||||||
|
|
||||||
export function AppearanceSettings() {
|
export function AppearanceSettings() {
|
||||||
const t = useTranslations('settings.appearance');
|
const t = useTranslations('settings.appearance');
|
||||||
|
const tTour = useTranslations('tour');
|
||||||
const { theme, setTheme } = useThemeStore();
|
const { theme, setTheme } = useThemeStore();
|
||||||
const { fontSize, density, animationsEnabled, toolbarPosition, showToolbarLabels, updateSetting } = useSettingsStore();
|
const { fontSize, density, animationsEnabled, toolbarPosition, showToolbarLabels, updateSetting } = useSettingsStore();
|
||||||
|
const { startTour, resetTourCompletion } = useTour();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingsSection title={t('title')} description={t('description')}>
|
<SettingsSection title={t('title')} description={t('description')}>
|
||||||
@@ -141,6 +146,19 @@ export function AppearanceSettings() {
|
|||||||
onChange={(checked) => updateSetting('animationsEnabled', checked)}
|
onChange={(checked) => updateSetting('animationsEnabled', checked)}
|
||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Restart Tour */}
|
||||||
|
<SettingItem label={tTour('restart_title')} description={tTour('restart_desc')}>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => { resetTourCompletion(); startTour(); }}
|
||||||
|
className="text-xs h-7"
|
||||||
|
>
|
||||||
|
<PlayCircle className="w-3.5 h-3.5 mr-1" />
|
||||||
|
{tTour('restart_button')}
|
||||||
|
</Button>
|
||||||
|
</SettingItem>
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,9 +14,10 @@ export function CalendarSettings() {
|
|||||||
const {
|
const {
|
||||||
timeFormat,
|
timeFormat,
|
||||||
firstDayOfWeek,
|
firstDayOfWeek,
|
||||||
calendarNotificationsEnabled,
|
showTimeInMonthView,
|
||||||
calendarNotificationSound,
|
showWeekNumbers,
|
||||||
calendarInvitationParsingEnabled,
|
enableCalendarTasks,
|
||||||
|
showTasksOnCalendar,
|
||||||
updateSetting,
|
updateSetting,
|
||||||
} = useSettingsStore();
|
} = useSettingsStore();
|
||||||
|
|
||||||
@@ -58,36 +59,47 @@ export function CalendarSettings() {
|
|||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem
|
<SettingItem
|
||||||
label={t('notifications_enabled')}
|
label={t('show_time_in_month_view')}
|
||||||
description={t('notifications_enabled_desc')}
|
description={t('show_time_in_month_view_desc')}
|
||||||
>
|
>
|
||||||
<ToggleSwitch
|
<ToggleSwitch
|
||||||
checked={calendarNotificationsEnabled}
|
checked={showTimeInMonthView}
|
||||||
onChange={(checked) => updateSetting('calendarNotificationsEnabled', checked)}
|
onChange={(checked) => updateSetting('showTimeInMonthView', checked)}
|
||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem
|
<SettingItem
|
||||||
label={t('notification_sound')}
|
label={t('show_week_numbers')}
|
||||||
description={t('notification_sound_desc')}
|
description={t('show_week_numbers_desc')}
|
||||||
>
|
>
|
||||||
<ToggleSwitch
|
<ToggleSwitch
|
||||||
checked={calendarNotificationSound}
|
checked={showWeekNumbers}
|
||||||
onChange={(checked) => updateSetting('calendarNotificationSound', checked)}
|
onChange={(checked) => updateSetting('showWeekNumbers', checked)}
|
||||||
disabled={!calendarNotificationsEnabled}
|
|
||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem
|
<SettingItem
|
||||||
label={t('invitation_parsing')}
|
label={t('enable_tasks')}
|
||||||
description={t('invitation_parsing_desc')}
|
description={t('enable_tasks_desc')}
|
||||||
>
|
>
|
||||||
<ToggleSwitch
|
<ToggleSwitch
|
||||||
checked={calendarInvitationParsingEnabled}
|
checked={enableCalendarTasks}
|
||||||
onChange={(checked) => updateSetting('calendarInvitationParsingEnabled', checked)}
|
onChange={(checked) => updateSetting('enableCalendarTasks', checked)}
|
||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{enableCalendarTasks && (
|
||||||
|
<SettingItem
|
||||||
|
label={t('show_tasks_on_calendar')}
|
||||||
|
description={t('show_tasks_on_calendar_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={showTasksOnCalendar}
|
||||||
|
onChange={(checked) => updateSetting('showTasksOnCalendar', checked)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
)}
|
||||||
|
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,36 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState, useCallback } from 'react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { useConfig } from '@/hooks/use-config';
|
||||||
import { useSettingsStore } from '@/stores/settings-store';
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
import type { ArchiveMode } from '@/stores/settings-store';
|
import type { ArchiveMode, HoverAction } from '@/stores/settings-store';
|
||||||
|
import { ALL_HOVER_ACTIONS } from '@/stores/settings-store';
|
||||||
import { useAuthStore } from '@/stores/auth-store';
|
import { useAuthStore } from '@/stores/auth-store';
|
||||||
import { useEmailStore } from '@/stores/email-store';
|
import { useEmailStore } from '@/stores/email-store';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
|
import { SettingsSection, SettingItem, Select, ToggleSwitch } from './settings-section';
|
||||||
import { TrustedSendersModal } from '@/components/trusted-senders-modal';
|
import { TrustedSendersModal } from '@/components/trusted-senders-modal';
|
||||||
import { ChevronRight, AlertTriangle, FolderSync, Loader2 } from 'lucide-react';
|
import { ChevronRight, AlertTriangle, FolderSync, Loader2, Mail } from 'lucide-react';
|
||||||
|
|
||||||
export function EmailSettings() {
|
export function EmailSettings() {
|
||||||
const t = useTranslations('settings.email_behavior');
|
const t = useTranslations('settings.email_behavior');
|
||||||
|
const { appName } = useConfig();
|
||||||
const [showTrustedModal, setShowTrustedModal] = useState(false);
|
const [showTrustedModal, setShowTrustedModal] = useState(false);
|
||||||
const [isReorganizing, setIsReorganizing] = useState(false);
|
const [isReorganizing, setIsReorganizing] = useState(false);
|
||||||
const [reorganizeResult, setReorganizeResult] = useState<string | null>(null);
|
const [reorganizeResult, setReorganizeResult] = useState<string | null>(null);
|
||||||
|
const [defaultMailStatus, setDefaultMailStatus] = useState<'idle' | 'success' | 'error'>('idle');
|
||||||
|
|
||||||
|
const handleSetDefaultMailProgram = useCallback(() => {
|
||||||
|
try {
|
||||||
|
if (typeof navigator !== 'undefined' && navigator.registerProtocolHandler) {
|
||||||
|
navigator.registerProtocolHandler('mailto', `${window.location.origin}/compose?mailto=%s`);
|
||||||
|
setDefaultMailStatus('success');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setDefaultMailStatus('error');
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
markAsReadDelay,
|
markAsReadDelay,
|
||||||
@@ -24,8 +40,10 @@ export function EmailSettings() {
|
|||||||
emailsPerPage,
|
emailsPerPage,
|
||||||
externalContentPolicy,
|
externalContentPolicy,
|
||||||
mailAttachmentAction,
|
mailAttachmentAction,
|
||||||
|
attachmentPosition,
|
||||||
emailAlwaysLightMode,
|
emailAlwaysLightMode,
|
||||||
archiveMode,
|
archiveMode,
|
||||||
|
hoverActions,
|
||||||
trustedSenders,
|
trustedSenders,
|
||||||
updateSetting,
|
updateSetting,
|
||||||
} = useSettingsStore();
|
} = useSettingsStore();
|
||||||
@@ -184,6 +202,39 @@ export function EmailSettings() {
|
|||||||
<ToggleSwitch checked={showPreview} onChange={(checked) => updateSetting('showPreview', checked)} />
|
<ToggleSwitch checked={showPreview} onChange={(checked) => updateSetting('showPreview', checked)} />
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Quick Hover Actions */}
|
||||||
|
<div className="py-3 border-b border-border space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="text-sm font-medium text-foreground">{t('hover_actions.label')}</label>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">{t('hover_actions.description')}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{ALL_HOVER_ACTIONS.map((action) => {
|
||||||
|
const isEnabled = hoverActions.includes(action.id);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={action.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
const newActions = isEnabled
|
||||||
|
? hoverActions.filter((a: HoverAction) => a !== action.id)
|
||||||
|
: [...hoverActions, action.id];
|
||||||
|
updateSetting('hoverActions', newActions);
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
'px-3 py-1.5 text-xs rounded-md transition-colors duration-150',
|
||||||
|
isEnabled
|
||||||
|
? 'bg-primary text-primary-foreground font-medium'
|
||||||
|
: 'bg-muted hover:bg-accent text-foreground'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t(`hover_actions.${action.labelKey}`)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<SettingItem label={t('attachment_click_action.label')} description={t('attachment_click_action.description')}>
|
<SettingItem label={t('attachment_click_action.label')} description={t('attachment_click_action.description')}>
|
||||||
<Select
|
<Select
|
||||||
value={mailAttachmentAction}
|
value={mailAttachmentAction}
|
||||||
@@ -195,12 +246,24 @@ export function EmailSettings() {
|
|||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem label={t('attachment_position.label')} description={t('attachment_position.description')}>
|
||||||
|
<Select
|
||||||
|
value={attachmentPosition}
|
||||||
|
onChange={(value) => updateSetting('attachmentPosition', value as 'beside-sender' | 'below-header')}
|
||||||
|
options={[
|
||||||
|
{ value: 'beside-sender', label: t('attachment_position.beside-sender') },
|
||||||
|
{ value: 'below-header', label: t('attachment_position.below-header') },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
{/* Emails Per Page */}
|
{/* Emails Per Page */}
|
||||||
<SettingItem label={t('emails_per_page.label')} description={t('emails_per_page.description')}>
|
<SettingItem label={t('emails_per_page.label')} description={t('emails_per_page.description')}>
|
||||||
<Select
|
<Select
|
||||||
value={emailsPerPage.toString()}
|
value={emailsPerPage.toString()}
|
||||||
onChange={(value) => updateSetting('emailsPerPage', parseInt(value))}
|
onChange={(value) => updateSetting('emailsPerPage', parseInt(value))}
|
||||||
options={[
|
options={[
|
||||||
|
{ value: '10', label: t('emails_per_page.10') },
|
||||||
{ value: '25', label: t('emails_per_page.25') },
|
{ value: '25', label: t('emails_per_page.25') },
|
||||||
{ value: '50', label: t('emails_per_page.50') },
|
{ value: '50', label: t('emails_per_page.50') },
|
||||||
{ value: '100', label: t('emails_per_page.100') },
|
{ value: '100', label: t('emails_per_page.100') },
|
||||||
@@ -231,6 +294,25 @@ export function EmailSettings() {
|
|||||||
/>
|
/>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{/* Default Mail Program */}
|
||||||
|
<SettingItem label={t('default_mail_program.label')} description={t('default_mail_program.description', { appName: appName || 'Bulwark' })}>
|
||||||
|
<div className="flex flex-col items-end gap-1">
|
||||||
|
<button
|
||||||
|
onClick={handleSetDefaultMailProgram}
|
||||||
|
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-accent rounded-md transition-colors"
|
||||||
|
>
|
||||||
|
<Mail className="w-4 h-4" />
|
||||||
|
<span className="text-sm text-foreground">{t('default_mail_program.button')}</span>
|
||||||
|
</button>
|
||||||
|
{defaultMailStatus === 'success' && (
|
||||||
|
<p className="text-xs text-green-600 dark:text-green-400">{t('default_mail_program.success')}</p>
|
||||||
|
)}
|
||||||
|
{defaultMailStatus === 'error' && (
|
||||||
|
<p className="text-xs text-destructive">{t('default_mail_program.error')}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
{/* Trusted Senders */}
|
{/* Trusted Senders */}
|
||||||
<SettingItem label={t('trusted_senders.label')} description={t('trusted_senders.description')}>
|
<SettingItem label={t('trusted_senders.label')} description={t('trusted_senders.description')}>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { SieveEditorModal } from "@/components/filters/sieve-editor-modal";
|
|||||||
import { useFilterStore } from "@/stores/filter-store";
|
import { useFilterStore } from "@/stores/filter-store";
|
||||||
import { useAuthStore } from "@/stores/auth-store";
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
import { useEmailStore } from "@/stores/email-store";
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
|
import { useSettingsStore } from "@/stores/settings-store";
|
||||||
import { toast } from "@/stores/toast-store";
|
import { toast } from "@/stores/toast-store";
|
||||||
import type { FilterRule } from "@/lib/jmap/sieve-types";
|
import type { FilterRule } from "@/lib/jmap/sieve-types";
|
||||||
import {
|
import {
|
||||||
@@ -25,31 +26,98 @@ import {
|
|||||||
function RuleSummary({ rule }: { rule: FilterRule }) {
|
function RuleSummary({ rule }: { rule: FilterRule }) {
|
||||||
const t = useTranslations("settings.filters");
|
const t = useTranslations("settings.filters");
|
||||||
|
|
||||||
const conditionSummary = rule.conditions
|
const conditions = rule.conditions.slice(0, 2).map((c) => {
|
||||||
.slice(0, 2)
|
const field = t(`condition_fields.${c.field}`);
|
||||||
.map((c) => {
|
const comparator = t(`comparators.${c.comparator}`);
|
||||||
const field = t(`condition_fields.${c.field}`);
|
return `${field} ${comparator} "${c.value}"`;
|
||||||
const comparator = t(`comparators.${c.comparator}`);
|
});
|
||||||
return `${field} ${comparator} "${c.value}"`;
|
|
||||||
})
|
const joiner = rule.matchType === "all" ? t("and") : t("or");
|
||||||
.join(rule.matchType === "all" ? ` ${t("and")} ` : ` ${t("or")} `);
|
|
||||||
|
|
||||||
const extra = rule.conditions.length > 2
|
const extra = rule.conditions.length > 2
|
||||||
? ` (+${rule.conditions.length - 2})`
|
? ` (+${rule.conditions.length - 2})`
|
||||||
: "";
|
: "";
|
||||||
|
|
||||||
const actionSummary = rule.actions
|
const actions = rule.actions.slice(0, 2).map((a) => {
|
||||||
.slice(0, 2)
|
const action = t(`action_types.${a.type}`);
|
||||||
.map((a) => {
|
return a.value ? `${action} "${a.value}"` : action;
|
||||||
const action = t(`action_types.${a.type}`);
|
});
|
||||||
return a.value ? `${action} "${a.value}"` : action;
|
|
||||||
})
|
|
||||||
.join(", ");
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className="text-xs text-muted-foreground truncate">
|
<div className="text-xs text-muted-foreground break-words">
|
||||||
{conditionSummary}{extra} → {actionSummary}
|
<span className="inline">
|
||||||
</span>
|
{conditions.map((cond, i) => (
|
||||||
|
<span key={i}>
|
||||||
|
{i > 0 && <span className="italic opacity-70"> {joiner} </span>}
|
||||||
|
{cond}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
{extra}
|
||||||
|
</span>
|
||||||
|
<span className="mx-1 opacity-50">→</span>
|
||||||
|
<span className="inline">
|
||||||
|
{actions.map((act, i) => (
|
||||||
|
<span key={i}>
|
||||||
|
{i > 0 && ", "}
|
||||||
|
{act}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function VisualRuleSummary({ rule }: { rule: FilterRule }) {
|
||||||
|
const t = useTranslations("settings.filters");
|
||||||
|
|
||||||
|
const joiner = rule.matchType === "all" ? t("and") : t("or");
|
||||||
|
const matchLabel = rule.matchType === "all" ? t("match_all_conditions") : t("match_any_condition");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-1.5 space-y-1 text-xs">
|
||||||
|
<div className="flex items-baseline gap-1.5 flex-wrap">
|
||||||
|
<span className="text-[10px] font-semibold uppercase tracking-wider text-blue-500 dark:text-blue-400">
|
||||||
|
{t("if")}
|
||||||
|
</span>
|
||||||
|
{rule.conditions.map((c, i) => {
|
||||||
|
const field = t(`condition_fields.${c.field}`);
|
||||||
|
const comparator = t(`comparators.${c.comparator}`);
|
||||||
|
return (
|
||||||
|
<span key={i} className="contents">
|
||||||
|
{i > 0 && (
|
||||||
|
<span className="text-[10px] text-muted-foreground/70 italic">{joiner}</span>
|
||||||
|
)}
|
||||||
|
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
|
||||||
|
<span className="font-medium text-blue-600 dark:text-blue-400">{field}</span>
|
||||||
|
<span className="text-muted-foreground">{comparator}</span>
|
||||||
|
<span className="text-foreground">“{c.value}”</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<span className="text-[10px] text-muted-foreground/60 italic">({matchLabel})</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-baseline gap-1.5 flex-wrap">
|
||||||
|
<span className="text-[10px] font-semibold uppercase tracking-wider text-emerald-500 dark:text-emerald-400">
|
||||||
|
{t("then")}
|
||||||
|
</span>
|
||||||
|
{rule.actions.map((a, i) => {
|
||||||
|
const action = t(`action_types.${a.type}`);
|
||||||
|
return (
|
||||||
|
<span key={i} className="contents">
|
||||||
|
{i > 0 && (
|
||||||
|
<span className="text-muted-foreground/50">›</span>
|
||||||
|
)}
|
||||||
|
<span className="inline-flex items-baseline gap-1 px-1.5 py-px rounded-sm bg-muted/60 text-foreground">
|
||||||
|
<span className="font-medium text-emerald-600 dark:text-emerald-400">{action}</span>
|
||||||
|
{a.value && <span className="text-muted-foreground">“{a.value}”</span>}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +126,8 @@ export function FilterSettings() {
|
|||||||
const tNotifications = useTranslations("notifications");
|
const tNotifications = useTranslations("notifications");
|
||||||
const { client } = useAuthStore();
|
const { client } = useAuthStore();
|
||||||
const mailboxes = useEmailStore((s) => s.mailboxes);
|
const mailboxes = useEmailStore((s) => s.mailboxes);
|
||||||
|
const expandedFilterView = useSettingsStore((s) => s.expandedFilterView);
|
||||||
|
const updateSetting = useSettingsStore((s) => s.updateSetting);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
rules,
|
rules,
|
||||||
@@ -337,23 +407,25 @@ export function FilterSettings() {
|
|||||||
onDragOver={(e) => handleDragOver(e, index)}
|
onDragOver={(e) => handleDragOver(e, index)}
|
||||||
onDrop={(e) => handleDrop(e, index)}
|
onDrop={(e) => handleDrop(e, index)}
|
||||||
onDragEnd={handleDragEnd}
|
onDragEnd={handleDragEnd}
|
||||||
className={`flex items-center gap-3 p-3 rounded-md border transition-colors ${
|
className={`flex items-start gap-3 p-3 rounded-md border transition-colors ${
|
||||||
dragOverIndex === index
|
dragOverIndex === index
|
||||||
? "border-primary bg-primary/5"
|
? "border-primary bg-primary/5"
|
||||||
: "border-border hover:bg-muted/50"
|
: "border-border hover:bg-muted/50"
|
||||||
} ${!rule.enabled ? "opacity-60" : ""}`}
|
} ${!rule.enabled ? "opacity-60" : ""}`}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground"
|
className="cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground pt-0.5"
|
||||||
aria-label={t("drag_to_reorder")}
|
aria-label={t("drag_to_reorder")}
|
||||||
>
|
>
|
||||||
<GripVertical className="w-4 h-4" />
|
<GripVertical className="w-4 h-4" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ToggleSwitch
|
<div className="pt-0.5">
|
||||||
checked={rule.enabled}
|
<ToggleSwitch
|
||||||
onChange={() => handleToggle(rule.id)}
|
checked={rule.enabled}
|
||||||
/>
|
onChange={() => handleToggle(rule.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="flex-1 min-w-0 cursor-pointer"
|
className="flex-1 min-w-0 cursor-pointer"
|
||||||
@@ -374,7 +446,11 @@ export function FilterSettings() {
|
|||||||
<p className="text-sm font-medium text-foreground truncate">
|
<p className="text-sm font-medium text-foreground truncate">
|
||||||
{rule.name}
|
{rule.name}
|
||||||
</p>
|
</p>
|
||||||
<RuleSummary rule={rule} />
|
{expandedFilterView ? (
|
||||||
|
<VisualRuleSummary rule={rule} />
|
||||||
|
) : (
|
||||||
|
<RuleSummary rule={rule} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{deleteConfirmId === rule.id ? (
|
{deleteConfirmId === rule.id ? (
|
||||||
@@ -435,12 +511,23 @@ export function FilterSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isSaving && (
|
<div className="flex items-center gap-3">
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
{isSaving && (
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
{t("saving")}
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
</div>
|
{t("saving")}
|
||||||
)}
|
</div>
|
||||||
|
)}
|
||||||
|
{!isOpaque && rules.length > 0 && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-muted-foreground">{t("expanded_view")}</span>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={expandedFilterView}
|
||||||
|
onChange={(v) => updateSetting("expandedFilterView", v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showRuleModal && (
|
{showRuleModal && (
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useSettingsStore, KEYWORD_PALETTE, DEFAULT_KEYWORDS, type KeywordDefinition } from "@/stores/settings-store";
|
import { useSettingsStore, KEYWORD_PALETTE, DEFAULT_KEYWORDS, type KeywordDefinition } from "@/stores/settings-store";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { useEmailStore } from "@/stores/email-store";
|
||||||
import { SettingsSection } from "./settings-section";
|
import { SettingsSection } from "./settings-section";
|
||||||
import { Plus, Pencil, Trash2, GripVertical, Check, X, RotateCcw } from "lucide-react";
|
import { Plus, Pencil, Trash2, GripVertical, Check, X, RotateCcw, Loader2 } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const PALETTE_KEYS = Object.keys(KEYWORD_PALETTE);
|
const PALETTE_KEYS = Object.keys(KEYWORD_PALETTE);
|
||||||
@@ -91,16 +93,14 @@ function KeywordEditForm({
|
|||||||
const [color, setColor] = useState(initial?.color || "blue");
|
const [color, setColor] = useState(initial?.color || "blue");
|
||||||
const isEditing = !!initial;
|
const isEditing = !!initial;
|
||||||
|
|
||||||
const normalizedId = isEditing
|
const normalizedId = label
|
||||||
? initial.id
|
.trim()
|
||||||
: label
|
.toLowerCase()
|
||||||
.trim()
|
.replace(/[^a-z0-9_-]/g, "-")
|
||||||
.toLowerCase()
|
.replace(/-+/g, "-")
|
||||||
.replace(/[^a-z0-9_-]/g, "-")
|
.replace(/^-|-$/g, "");
|
||||||
.replace(/-+/g, "-")
|
|
||||||
.replace(/^-|-$/g, "");
|
|
||||||
|
|
||||||
const isDuplicate = !isEditing && normalizedId.length > 0 && existingIds.includes(normalizedId);
|
const isDuplicate = normalizedId.length > 0 && existingIds.includes(normalizedId);
|
||||||
const isValid = normalizedId.length > 0 && label.trim().length > 0 && !isDuplicate;
|
const isValid = normalizedId.length > 0 && label.trim().length > 0 && !isDuplicate;
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
@@ -159,10 +159,13 @@ function KeywordEditForm({
|
|||||||
|
|
||||||
export function KeywordSettings() {
|
export function KeywordSettings() {
|
||||||
const t = useTranslations("settings.keywords");
|
const t = useTranslations("settings.keywords");
|
||||||
const { emailKeywords, addKeyword, updateKeyword, removeKeyword, reorderKeywords } =
|
const { emailKeywords, addKeyword, updateKeyword, renameKeyword, removeKeyword, reorderKeywords } =
|
||||||
useSettingsStore();
|
useSettingsStore();
|
||||||
|
const { client } = useAuthStore();
|
||||||
|
const { fetchTagCounts } = useEmailStore();
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
const [isAdding, setIsAdding] = useState(false);
|
const [isAdding, setIsAdding] = useState(false);
|
||||||
|
const [isMigrating, setIsMigrating] = useState(false);
|
||||||
|
|
||||||
const existingIds = emailKeywords.map((k) => k.id);
|
const existingIds = emailKeywords.map((k) => k.id);
|
||||||
|
|
||||||
@@ -171,8 +174,32 @@ export function KeywordSettings() {
|
|||||||
setIsAdding(false);
|
setIsAdding(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEdit = (keyword: KeywordDefinition) => {
|
const handleEdit = async (keyword: KeywordDefinition) => {
|
||||||
updateKeyword(keyword.id, { label: keyword.label, color: keyword.color });
|
const oldId = editingId;
|
||||||
|
if (!oldId) return;
|
||||||
|
|
||||||
|
const idChanged = oldId !== keyword.id;
|
||||||
|
|
||||||
|
if (idChanged && client) {
|
||||||
|
setIsMigrating(true);
|
||||||
|
try {
|
||||||
|
const oldJmapKeyword = `$label:${oldId}`;
|
||||||
|
const newJmapKeyword = `$label:${keyword.id}`;
|
||||||
|
await client.migrateKeyword(oldJmapKeyword, newJmapKeyword);
|
||||||
|
renameKeyword(oldId, keyword);
|
||||||
|
fetchTagCounts(client);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to migrate keyword:", error);
|
||||||
|
const toastModule = await import('sonner');
|
||||||
|
toastModule.toast.error(t("migration_error"));
|
||||||
|
setIsMigrating(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsMigrating(false);
|
||||||
|
} else {
|
||||||
|
updateKeyword(oldId, { label: keyword.label, color: keyword.color });
|
||||||
|
}
|
||||||
|
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -187,6 +214,12 @@ export function KeywordSettings() {
|
|||||||
return (
|
return (
|
||||||
<SettingsSection title={t("title")} description={t("description")}>
|
<SettingsSection title={t("title")} description={t("description")}>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
|
{isMigrating && (
|
||||||
|
<div className="flex items-center gap-2 p-2 text-xs text-muted-foreground bg-accent/50 rounded-md">
|
||||||
|
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||||
|
{t("migrating")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{emailKeywords.map((keyword) =>
|
{emailKeywords.map((keyword) =>
|
||||||
editingId === keyword.id ? (
|
editingId === keyword.id ? (
|
||||||
<KeywordEditForm
|
<KeywordEditForm
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { SettingsSection, SettingItem, ToggleSwitch, Select } from './settings-section';
|
||||||
|
import { playNotificationSound, NOTIFICATION_SOUNDS } from '@/lib/notification-sound';
|
||||||
|
import type { NotificationSoundChoice } from '@/lib/notification-sound';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Volume2 } from 'lucide-react';
|
||||||
|
|
||||||
|
export function NotificationSettings() {
|
||||||
|
const t = useTranslations('settings.notifications');
|
||||||
|
const {
|
||||||
|
emailNotificationsEnabled,
|
||||||
|
emailNotificationSound,
|
||||||
|
notificationSoundChoice,
|
||||||
|
calendarNotificationsEnabled,
|
||||||
|
calendarNotificationSound,
|
||||||
|
calendarInvitationParsingEnabled,
|
||||||
|
updateSetting,
|
||||||
|
} = useSettingsStore();
|
||||||
|
|
||||||
|
const soundOptions = NOTIFICATION_SOUNDS.map((s) => ({
|
||||||
|
value: s.id,
|
||||||
|
label: t(`sounds.${s.id}`),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<SettingsSection title={t('sound_selection.title')} description={t('sound_selection.description')}>
|
||||||
|
<SettingItem
|
||||||
|
label={t('sound_selection.choose')}
|
||||||
|
description={t('sound_selection.choose_desc')}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => playNotificationSound(notificationSoundChoice)}
|
||||||
|
title={t('test_sound')}
|
||||||
|
>
|
||||||
|
<Volume2 className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Select
|
||||||
|
value={notificationSoundChoice}
|
||||||
|
onChange={(value) => {
|
||||||
|
const choice = value as NotificationSoundChoice;
|
||||||
|
updateSetting('notificationSoundChoice', choice);
|
||||||
|
playNotificationSound(choice);
|
||||||
|
}}
|
||||||
|
options={soundOptions}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</SettingItem>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
<SettingsSection title={t('email.title')} description={t('email.description')}>
|
||||||
|
<SettingItem
|
||||||
|
label={t('email.enabled')}
|
||||||
|
description={t('email.enabled_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={emailNotificationsEnabled}
|
||||||
|
onChange={(checked) => updateSetting('emailNotificationsEnabled', checked)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem
|
||||||
|
label={t('email.sound')}
|
||||||
|
description={t('email.sound_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={emailNotificationSound}
|
||||||
|
onChange={(checked) => updateSetting('emailNotificationSound', checked)}
|
||||||
|
disabled={!emailNotificationsEnabled}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
<SettingsSection title={t('calendar.title')} description={t('calendar.description')}>
|
||||||
|
<SettingItem
|
||||||
|
label={t('calendar.enabled')}
|
||||||
|
description={t('calendar.enabled_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={calendarNotificationsEnabled}
|
||||||
|
onChange={(checked) => updateSetting('calendarNotificationsEnabled', checked)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem
|
||||||
|
label={t('calendar.sound')}
|
||||||
|
description={t('calendar.sound_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={calendarNotificationSound}
|
||||||
|
onChange={(checked) => updateSetting('calendarNotificationSound', checked)}
|
||||||
|
disabled={!calendarNotificationsEnabled}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem
|
||||||
|
label={t('calendar.invitation_parsing')}
|
||||||
|
description={t('calendar.invitation_parsing_desc')}
|
||||||
|
>
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={calendarInvitationParsingEnabled}
|
||||||
|
onChange={(checked) => updateSetting('calendarInvitationParsingEnabled', checked)}
|
||||||
|
/>
|
||||||
|
</SettingItem>
|
||||||
|
</SettingsSection>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ interface SidebarAppFormData {
|
|||||||
url: string;
|
url: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
openMode: "tab" | "inline";
|
openMode: "tab" | "inline";
|
||||||
|
showOnMobile: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function AppForm({
|
function AppForm({
|
||||||
@@ -37,6 +38,7 @@ function AppForm({
|
|||||||
url: app?.url || "",
|
url: app?.url || "",
|
||||||
icon: app?.icon || "Globe",
|
icon: app?.icon || "Globe",
|
||||||
openMode: app?.openMode || "tab",
|
openMode: app?.openMode || "tab",
|
||||||
|
showOnMobile: app?.showOnMobile ?? false,
|
||||||
});
|
});
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
@@ -144,6 +146,25 @@ function AppForm({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<label className="text-sm font-medium">{t("show_on_mobile")}</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData({ ...formData, showOnMobile: !formData.showOnMobile })}
|
||||||
|
className={cn(
|
||||||
|
"relative inline-flex h-5 w-9 items-center rounded-full transition-colors",
|
||||||
|
formData.showOnMobile ? "bg-primary" : "bg-muted-foreground/30"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform",
|
||||||
|
formData.showOnMobile ? "translate-x-4.5" : "translate-x-0.5"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2 justify-end">
|
<div className="flex gap-2 justify-end">
|
||||||
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
|
<Button type="button" variant="ghost" size="sm" onClick={onCancel}>
|
||||||
{t("cancel")}
|
{t("cancel")}
|
||||||
|
|||||||
@@ -0,0 +1,413 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useRef, useCallback } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useTour } from "./tour-provider";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useFocusTrap } from "@/hooks/use-focus-trap";
|
||||||
|
|
||||||
|
interface Rect {
|
||||||
|
top: number;
|
||||||
|
left: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PADDING = 8;
|
||||||
|
const TOOLTIP_GAP = 12;
|
||||||
|
const TOOLTIP_MAX_W = 360;
|
||||||
|
|
||||||
|
function getTargetRect(selector: string): Rect | null {
|
||||||
|
const el = document.querySelector(selector);
|
||||||
|
if (!el) return null;
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
// Element might exist but be hidden (zero dimensions)
|
||||||
|
if (r.width === 0 && r.height === 0) return null;
|
||||||
|
return { top: r.top, left: r.left, width: r.width, height: r.height };
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeTooltipPosition(
|
||||||
|
target: Rect,
|
||||||
|
placement: "top" | "bottom" | "left" | "right",
|
||||||
|
tooltipSize: { width: number; height: number }
|
||||||
|
): { top: number; left: number; actualPlacement: string } {
|
||||||
|
const vw = window.innerWidth;
|
||||||
|
const vh = window.innerHeight;
|
||||||
|
const tw = Math.max(tooltipSize.width, 200); // minimum fallback width
|
||||||
|
const th = Math.max(tooltipSize.height, 100); // minimum fallback height
|
||||||
|
|
||||||
|
const positions = {
|
||||||
|
bottom: {
|
||||||
|
top: target.top + target.height + PADDING + TOOLTIP_GAP,
|
||||||
|
left: target.left + target.width / 2 - tw / 2,
|
||||||
|
},
|
||||||
|
top: {
|
||||||
|
top: target.top - PADDING - TOOLTIP_GAP - th,
|
||||||
|
left: target.left + target.width / 2 - tw / 2,
|
||||||
|
},
|
||||||
|
right: {
|
||||||
|
top: target.top + target.height / 2 - th / 2,
|
||||||
|
left: target.left + target.width + PADDING + TOOLTIP_GAP,
|
||||||
|
},
|
||||||
|
left: {
|
||||||
|
top: target.top + target.height / 2 - th / 2,
|
||||||
|
left: target.left - PADDING - TOOLTIP_GAP - tw,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const fits = (p: { top: number; left: number }) =>
|
||||||
|
p.top >= 8 && p.left >= 8 && p.top + th <= vh - 8 && p.left + tw <= vw - 8;
|
||||||
|
|
||||||
|
// Try preferred placement first, then fallback order
|
||||||
|
const order: Array<"top" | "bottom" | "left" | "right"> = [placement, "bottom", "right", "left", "top"];
|
||||||
|
for (const dir of order) {
|
||||||
|
const pos = positions[dir];
|
||||||
|
if (fits(pos)) return { ...pos, actualPlacement: dir };
|
||||||
|
}
|
||||||
|
|
||||||
|
// If nothing fits perfectly, use preferred but clamped
|
||||||
|
const pos = positions[placement];
|
||||||
|
return {
|
||||||
|
top: Math.max(8, Math.min(pos.top, vh - th - 8)),
|
||||||
|
left: Math.max(8, Math.min(pos.left, vw - tw - 8)),
|
||||||
|
actualPlacement: placement,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TourOverlay() {
|
||||||
|
const t = useTranslations();
|
||||||
|
const { currentStep, totalSteps, steps, nextStep, prevStep, stopTour } = useTour();
|
||||||
|
const step = steps[currentStep];
|
||||||
|
|
||||||
|
const [targetRect, setTargetRect] = useState<Rect | null>(null);
|
||||||
|
const [tooltipPos, setTooltipPos] = useState<{ top: number; left: number } | null>(null);
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
const tooltipRef = useRef<HTMLDivElement>(null);
|
||||||
|
const pendingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
// Use refs for callbacks to avoid stale closures in timers/intervals
|
||||||
|
const updatePositionRef = useRef<() => void>(() => {});
|
||||||
|
const nextStepRef = useRef<() => void>(() => {});
|
||||||
|
nextStepRef.current = nextStep;
|
||||||
|
|
||||||
|
const focusTrapRef = useFocusTrap({
|
||||||
|
isActive: visible,
|
||||||
|
onEscape: stopTour,
|
||||||
|
restoreFocus: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set mounted for portal
|
||||||
|
useEffect(() => { setMounted(true); }, []);
|
||||||
|
|
||||||
|
const updatePosition = useCallback(() => {
|
||||||
|
if (!step) return;
|
||||||
|
const rect = getTargetRect(step.target);
|
||||||
|
|
||||||
|
if (rect) {
|
||||||
|
setTargetRect(rect);
|
||||||
|
if (tooltipRef.current) {
|
||||||
|
const { width, height } = tooltipRef.current.getBoundingClientRect();
|
||||||
|
const pos = computeTooltipPosition(rect, step.placement, { width, height });
|
||||||
|
setTooltipPos({ top: pos.top, left: pos.left });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If rect is null, keep previous targetRect (element temporarily hidden during scroll/resize)
|
||||||
|
// Only the step-change effect should null out targetRect
|
||||||
|
}, [step]);
|
||||||
|
|
||||||
|
// Keep ref in sync
|
||||||
|
updatePositionRef.current = updatePosition;
|
||||||
|
|
||||||
|
// Wait for target element to appear, then show
|
||||||
|
useEffect(() => {
|
||||||
|
if (!step) return;
|
||||||
|
console.log(`[Tour] Step ${currentStep + 1}/${totalSteps}: "${step.id}" — target: ${step.target}, placement: ${step.placement}, interactive: ${!!step.interactive}`);
|
||||||
|
setVisible(false);
|
||||||
|
// Keep old targetRect and tooltipPos so the cutout/tooltip animate to the new position
|
||||||
|
// instead of disappearing and reappearing
|
||||||
|
|
||||||
|
// Clear any pending timer from a previous step
|
||||||
|
if (pendingTimerRef.current) {
|
||||||
|
clearTimeout(pendingTimerRef.current);
|
||||||
|
pendingTimerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run beforeAction if defined (e.g. click an email to open the viewer)
|
||||||
|
if (step.beforeAction) {
|
||||||
|
step.beforeAction();
|
||||||
|
}
|
||||||
|
|
||||||
|
let attempts = 0;
|
||||||
|
const maxAttempts = 50; // 5 seconds
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
const tryFind = () => {
|
||||||
|
if (cancelled) return true;
|
||||||
|
const el = document.querySelector(step.target);
|
||||||
|
if (el) {
|
||||||
|
const rect = el.getBoundingClientRect();
|
||||||
|
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": element FOUND (${rect.width}x${rect.height} at ${Math.round(rect.left)},${Math.round(rect.top)})`);
|
||||||
|
el.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||||
|
// Delay after scroll for layout to settle
|
||||||
|
pendingTimerRef.current = setTimeout(() => {
|
||||||
|
if (cancelled) return;
|
||||||
|
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": showing tooltip`);
|
||||||
|
updatePositionRef.current();
|
||||||
|
setVisible(true);
|
||||||
|
// Second position update after tooltip renders with final dimensions
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (!cancelled) updatePositionRef.current();
|
||||||
|
});
|
||||||
|
}, 200);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (attempts % 10 === 0) {
|
||||||
|
console.log(`[Tour] Step ${currentStep + 1} "${step.id}": element NOT found (attempt ${attempts + 1}/${maxAttempts})`);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (tryFind()) return () => { cancelled = true; };
|
||||||
|
|
||||||
|
// Poll for element appearance (for page navigation)
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
attempts++;
|
||||||
|
if (tryFind() || attempts >= maxAttempts) {
|
||||||
|
clearInterval(interval);
|
||||||
|
if (attempts >= maxAttempts && !cancelled) {
|
||||||
|
// Skip this step if element never appears
|
||||||
|
console.warn(`[Tour] Step ${currentStep + 1} "${step.id}": SKIPPED — element never appeared after ${maxAttempts} attempts`);
|
||||||
|
nextStepRef.current();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
clearInterval(interval);
|
||||||
|
if (pendingTimerRef.current) {
|
||||||
|
clearTimeout(pendingTimerRef.current);
|
||||||
|
pendingTimerRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [step, currentStep]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
// Recalculate on resize/scroll (debounced)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible) return;
|
||||||
|
let rafId: number | null = null;
|
||||||
|
const handler = () => {
|
||||||
|
if (rafId) cancelAnimationFrame(rafId);
|
||||||
|
rafId = requestAnimationFrame(() => {
|
||||||
|
updatePosition();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
window.addEventListener("resize", handler);
|
||||||
|
window.addEventListener("scroll", handler, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("resize", handler);
|
||||||
|
window.removeEventListener("scroll", handler, true);
|
||||||
|
if (rafId) cancelAnimationFrame(rafId);
|
||||||
|
};
|
||||||
|
}, [visible, updatePosition]);
|
||||||
|
|
||||||
|
// Keyboard navigation
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "ArrowRight" || e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
nextStep();
|
||||||
|
} else if (e.key === "ArrowLeft") {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
prevStep();
|
||||||
|
} else if (e.key === "Escape") {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
stopTour();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", handler, true);
|
||||||
|
return () => window.removeEventListener("keydown", handler, true);
|
||||||
|
}, [nextStep, prevStep, stopTour]);
|
||||||
|
|
||||||
|
// Re-position after tooltip content renders with new dimensions
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible || !tooltipRef.current) return;
|
||||||
|
// Use rAF to wait for the browser to lay out the tooltip content
|
||||||
|
const id = requestAnimationFrame(() => {
|
||||||
|
updatePosition();
|
||||||
|
});
|
||||||
|
return () => cancelAnimationFrame(id);
|
||||||
|
}, [visible, updatePosition, currentStep]);
|
||||||
|
|
||||||
|
if (!mounted || !step) return null;
|
||||||
|
|
||||||
|
const cutout = targetRect
|
||||||
|
? {
|
||||||
|
x: targetRect.left - PADDING,
|
||||||
|
y: targetRect.top - PADDING,
|
||||||
|
w: targetRect.width + PADDING * 2,
|
||||||
|
h: targetRect.height + PADDING * 2,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const isLast = currentStep >= totalSteps - 1;
|
||||||
|
const isFirst = currentStep === 0;
|
||||||
|
const isInteractive = step.interactive;
|
||||||
|
|
||||||
|
const reducedMotion =
|
||||||
|
typeof window !== "undefined" &&
|
||||||
|
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||||
|
|
||||||
|
const transitionStyle = reducedMotion ? "none" : "all 300ms ease";
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<>
|
||||||
|
{/* SVG overlay with cutout */}
|
||||||
|
<svg
|
||||||
|
className="fixed inset-0 z-[9998]"
|
||||||
|
width="100%"
|
||||||
|
height="100%"
|
||||||
|
style={{ pointerEvents: isInteractive ? "none" : "auto" }}
|
||||||
|
onClick={stopTour}
|
||||||
|
>
|
||||||
|
<defs>
|
||||||
|
<mask id="tour-mask">
|
||||||
|
<rect fill="white" width="100%" height="100%" />
|
||||||
|
{cutout && (
|
||||||
|
<rect
|
||||||
|
fill="black"
|
||||||
|
x={cutout.x}
|
||||||
|
y={cutout.y}
|
||||||
|
width={cutout.w}
|
||||||
|
height={cutout.h}
|
||||||
|
rx="8"
|
||||||
|
style={{ transition: transitionStyle }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</mask>
|
||||||
|
</defs>
|
||||||
|
<rect
|
||||||
|
fill="black"
|
||||||
|
opacity="0.5"
|
||||||
|
mask="url(#tour-mask)"
|
||||||
|
width="100%"
|
||||||
|
height="100%"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
{/* Click-through cutout zone for interactive steps */}
|
||||||
|
{isInteractive && cutout && (
|
||||||
|
<div
|
||||||
|
className="fixed z-[9998]"
|
||||||
|
style={{
|
||||||
|
top: cutout.y,
|
||||||
|
left: cutout.x,
|
||||||
|
width: cutout.w,
|
||||||
|
height: cutout.h,
|
||||||
|
pointerEvents: "none",
|
||||||
|
transition: transitionStyle,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Non-interactive overlay click blocker around cutout */}
|
||||||
|
{!isInteractive && cutout && (
|
||||||
|
<div
|
||||||
|
className="fixed z-[9998]"
|
||||||
|
style={{
|
||||||
|
top: cutout.y,
|
||||||
|
left: cutout.x,
|
||||||
|
width: cutout.w,
|
||||||
|
height: cutout.h,
|
||||||
|
pointerEvents: "none",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tooltip */}
|
||||||
|
<div
|
||||||
|
ref={(node) => {
|
||||||
|
(tooltipRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
|
||||||
|
(focusTrapRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
|
||||||
|
}}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label={t(step.titleKey)}
|
||||||
|
className={cn(
|
||||||
|
"fixed z-[9999] transition-all",
|
||||||
|
visible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-2"
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
top: tooltipPos?.top ?? -9999,
|
||||||
|
left: tooltipPos?.left ?? -9999,
|
||||||
|
maxWidth: TOOLTIP_MAX_W,
|
||||||
|
transition: reducedMotion ? "none" : "opacity 200ms ease, transform 200ms ease, top 300ms ease, left 300ms ease",
|
||||||
|
pointerEvents: "auto",
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="bg-background border border-border rounded-xl shadow-2xl p-4">
|
||||||
|
{/* Step counter */}
|
||||||
|
<p className="text-xs text-muted-foreground mb-1" aria-live="polite">
|
||||||
|
{t("tour.step_counter", { current: currentStep + 1, total: totalSteps })}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Title */}
|
||||||
|
<h3 className="font-semibold text-sm text-foreground">{t(step.titleKey)}</h3>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">{t(step.descriptionKey)}</p>
|
||||||
|
|
||||||
|
{/* Navigation buttons */}
|
||||||
|
<div className="flex items-center justify-between mt-3">
|
||||||
|
<button
|
||||||
|
onClick={stopTour}
|
||||||
|
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1 rounded hover:bg-muted"
|
||||||
|
>
|
||||||
|
{t("tour.skip")}
|
||||||
|
</button>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={prevStep}
|
||||||
|
disabled={isFirst}
|
||||||
|
className={cn(
|
||||||
|
"text-xs px-3 py-1.5 rounded-md border border-border transition-colors",
|
||||||
|
isFirst
|
||||||
|
? "opacity-40 cursor-not-allowed"
|
||||||
|
: "hover:bg-muted"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t("tour.back")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={nextStep}
|
||||||
|
className="text-xs px-3 py-1.5 rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
|
||||||
|
>
|
||||||
|
{isLast ? t("tour.finish") : t("tour.next")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Progress dots */}
|
||||||
|
<div className="flex justify-center gap-1 mt-2">
|
||||||
|
{steps.map((_, i) => (
|
||||||
|
<span
|
||||||
|
key={i}
|
||||||
|
className={cn(
|
||||||
|
"w-1.5 h-1.5 rounded-full transition-colors",
|
||||||
|
i === currentStep ? "bg-primary" : "bg-muted-foreground/30"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>,
|
||||||
|
document.body
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react";
|
||||||
|
import { useRouter } from "@/i18n/navigation";
|
||||||
|
import { useAuthStore } from "@/stores/auth-store";
|
||||||
|
import { useCalendarStore } from "@/stores/calendar-store";
|
||||||
|
import { useWebDAVStore } from "@/stores/webdav-store";
|
||||||
|
import { getTourSteps, type TourStep } from "./tour-steps";
|
||||||
|
import { TourOverlay } from "./tour-overlay";
|
||||||
|
|
||||||
|
const TOUR_COMPLETED_KEY = "tour_completed";
|
||||||
|
const TOUR_CURRENT_STEP_KEY = "tour_current_step";
|
||||||
|
|
||||||
|
interface TourContextValue {
|
||||||
|
isActive: boolean;
|
||||||
|
currentStep: number;
|
||||||
|
totalSteps: number;
|
||||||
|
steps: TourStep[];
|
||||||
|
startTour: () => void;
|
||||||
|
stopTour: () => void;
|
||||||
|
nextStep: () => void;
|
||||||
|
prevStep: () => void;
|
||||||
|
hasCompletedTour: boolean;
|
||||||
|
resetTourCompletion: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TourContext = createContext<TourContextValue | null>(null);
|
||||||
|
|
||||||
|
export function useTour() {
|
||||||
|
const ctx = useContext(TourContext);
|
||||||
|
if (!ctx) throw new Error("useTour must be used within TourProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TourProvider({ children }: { children: ReactNode }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { isDemoMode } = useAuthStore();
|
||||||
|
const { supportsCalendar } = useCalendarStore();
|
||||||
|
const { supportsWebDAV } = useWebDAVStore();
|
||||||
|
|
||||||
|
const [isActive, setIsActive] = useState(false);
|
||||||
|
const [currentStep, setCurrentStep] = useState(0);
|
||||||
|
const [hasCompletedTour, setHasCompletedTour] = useState(false);
|
||||||
|
|
||||||
|
const steps = getTourSteps({ isDemoMode, supportsCalendar, supportsWebDAV: supportsWebDAV !== false });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
setHasCompletedTour(localStorage.getItem(TOUR_COMPLETED_KEY) === "true");
|
||||||
|
} catch { /* */ }
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const startTour = useCallback(() => {
|
||||||
|
let resumeStep = 0;
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem(TOUR_CURRENT_STEP_KEY);
|
||||||
|
if (stored) {
|
||||||
|
const parsed = parseInt(stored, 10);
|
||||||
|
if (!isNaN(parsed) && parsed >= 0) resumeStep = parsed;
|
||||||
|
}
|
||||||
|
} catch { /* */ }
|
||||||
|
|
||||||
|
// If the resume step is beyond the current steps, start from 0
|
||||||
|
if (resumeStep >= steps.length) resumeStep = 0;
|
||||||
|
|
||||||
|
setCurrentStep(resumeStep);
|
||||||
|
setIsActive(true);
|
||||||
|
}, [steps.length]);
|
||||||
|
|
||||||
|
const stopTour = useCallback(() => {
|
||||||
|
setIsActive(false);
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
|
||||||
|
} catch { /* */ }
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const completeTour = useCallback(() => {
|
||||||
|
setIsActive(false);
|
||||||
|
setHasCompletedTour(true);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(TOUR_COMPLETED_KEY, "true");
|
||||||
|
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
|
||||||
|
} catch { /* */ }
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const nextStep = useCallback(() => {
|
||||||
|
if (currentStep >= steps.length - 1) {
|
||||||
|
completeTour();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = currentStep + 1;
|
||||||
|
const nextStepDef = steps[next];
|
||||||
|
setCurrentStep(next);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(TOUR_CURRENT_STEP_KEY, String(next));
|
||||||
|
} catch { /* */ }
|
||||||
|
|
||||||
|
// Navigate if the next step requires a different page
|
||||||
|
if (nextStepDef?.page) {
|
||||||
|
router.push(nextStepDef.page);
|
||||||
|
}
|
||||||
|
}, [currentStep, steps, completeTour, router]);
|
||||||
|
|
||||||
|
const prevStep = useCallback(() => {
|
||||||
|
if (currentStep <= 0) return;
|
||||||
|
const prev = currentStep - 1;
|
||||||
|
const prevStepDef = steps[prev];
|
||||||
|
setCurrentStep(prev);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(TOUR_CURRENT_STEP_KEY, String(prev));
|
||||||
|
} catch { /* */ }
|
||||||
|
|
||||||
|
if (prevStepDef?.page) {
|
||||||
|
router.push(prevStepDef.page);
|
||||||
|
} else if (steps[currentStep]?.page) {
|
||||||
|
// Going back from a page-specific step to a non-page step => go to mail
|
||||||
|
router.push("/");
|
||||||
|
}
|
||||||
|
}, [currentStep, steps, router]);
|
||||||
|
|
||||||
|
const resetTourCompletion = useCallback(() => {
|
||||||
|
setHasCompletedTour(false);
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(TOUR_COMPLETED_KEY);
|
||||||
|
localStorage.removeItem(TOUR_CURRENT_STEP_KEY);
|
||||||
|
} catch { /* */ }
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const value: TourContextValue = {
|
||||||
|
isActive,
|
||||||
|
currentStep,
|
||||||
|
totalSteps: steps.length,
|
||||||
|
steps,
|
||||||
|
startTour,
|
||||||
|
stopTour,
|
||||||
|
nextStep,
|
||||||
|
prevStep,
|
||||||
|
hasCompletedTour,
|
||||||
|
resetTourCompletion,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TourContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
{isActive && <TourOverlay />}
|
||||||
|
</TourContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
export interface TourStep {
|
||||||
|
id: string;
|
||||||
|
target: string;
|
||||||
|
titleKey: string;
|
||||||
|
descriptionKey: string;
|
||||||
|
placement: "top" | "bottom" | "left" | "right";
|
||||||
|
interactive?: boolean;
|
||||||
|
spotlight?: "rect" | "circle";
|
||||||
|
page?: string;
|
||||||
|
demoOnly?: boolean;
|
||||||
|
beforeAction?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BASE_TOUR_STEPS: TourStep[] = [
|
||||||
|
{
|
||||||
|
id: "sidebar",
|
||||||
|
target: '[data-tour="sidebar"]',
|
||||||
|
titleKey: "tour.sidebar_title",
|
||||||
|
descriptionKey: "tour.sidebar_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "compose",
|
||||||
|
target: '[data-tour="compose-button"]',
|
||||||
|
titleKey: "tour.compose_title",
|
||||||
|
descriptionKey: "tour.compose_desc",
|
||||||
|
placement: "right",
|
||||||
|
interactive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "search",
|
||||||
|
target: '[data-tour="search-input"]',
|
||||||
|
titleKey: "tour.search_title",
|
||||||
|
descriptionKey: "tour.search_desc",
|
||||||
|
placement: "bottom",
|
||||||
|
interactive: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "email-list",
|
||||||
|
target: '[data-tour="email-list"]',
|
||||||
|
titleKey: "tour.email_list_title",
|
||||||
|
descriptionKey: "tour.email_list_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "email-viewer",
|
||||||
|
target: '[data-tour="email-viewer"]',
|
||||||
|
titleKey: "tour.email_viewer_title",
|
||||||
|
descriptionKey: "tour.email_viewer_desc",
|
||||||
|
placement: "left",
|
||||||
|
beforeAction: () => {
|
||||||
|
// Click the "Welcome to Bulwark Mail!" email (or the first email) to open the viewer
|
||||||
|
const emailList = document.querySelector('[data-tour="email-list"]');
|
||||||
|
if (!emailList) return;
|
||||||
|
// Try to find the welcome email by subject text
|
||||||
|
const items = emailList.querySelectorAll('.cursor-pointer');
|
||||||
|
let target: HTMLElement | null = null;
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.textContent?.includes("Welcome to Bulwark Mail")) {
|
||||||
|
target = item as HTMLElement;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fallback to first email if welcome email not found
|
||||||
|
if (!target) target = emailList.querySelector('.cursor-pointer') as HTMLElement | null;
|
||||||
|
if (target) target.click();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "keywords",
|
||||||
|
target: '[data-tour="keyword-tags"]',
|
||||||
|
titleKey: "tour.keywords_title",
|
||||||
|
descriptionKey: "tour.keywords_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "nav-calendar",
|
||||||
|
target: '[data-tour="nav-calendar"]',
|
||||||
|
titleKey: "tour.calendar_title",
|
||||||
|
descriptionKey: "tour.calendar_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "nav-contacts",
|
||||||
|
target: '[data-tour="nav-contacts"]',
|
||||||
|
titleKey: "tour.contacts_title",
|
||||||
|
descriptionKey: "tour.contacts_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "nav-settings",
|
||||||
|
target: '[data-tour="nav-settings"]',
|
||||||
|
titleKey: "tour.settings_title",
|
||||||
|
descriptionKey: "tour.settings_desc",
|
||||||
|
placement: "right",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "shortcuts",
|
||||||
|
target: '[data-tour="nav-shortcuts"]',
|
||||||
|
titleKey: "tour.shortcuts_title",
|
||||||
|
descriptionKey: "tour.shortcuts_desc",
|
||||||
|
placement: "right",
|
||||||
|
interactive: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const DEMO_TOUR_STEPS: TourStep[] = [
|
||||||
|
{
|
||||||
|
id: "compose-open",
|
||||||
|
target: '[data-tour="composer"]',
|
||||||
|
titleKey: "tour.compose_open_title",
|
||||||
|
descriptionKey: "tour.compose_open_desc",
|
||||||
|
placement: "left",
|
||||||
|
demoOnly: true,
|
||||||
|
beforeAction: () => {
|
||||||
|
// Click the compose button to open the composer
|
||||||
|
const btn = document.querySelector('[data-tour="compose-button"]') as HTMLElement | null;
|
||||||
|
if (btn) btn.click();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "calendar-view",
|
||||||
|
target: '[data-tour="calendar-view"]',
|
||||||
|
titleKey: "tour.calendar_view_title",
|
||||||
|
descriptionKey: "tour.calendar_view_desc",
|
||||||
|
placement: "bottom",
|
||||||
|
page: "/calendar",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "create-event",
|
||||||
|
target: '[data-tour="create-event-button"]',
|
||||||
|
titleKey: "tour.create_event_title",
|
||||||
|
descriptionKey: "tour.create_event_desc",
|
||||||
|
placement: "bottom",
|
||||||
|
page: "/calendar",
|
||||||
|
interactive: true,
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "event-modal",
|
||||||
|
target: '[data-tour="event-modal"]',
|
||||||
|
titleKey: "tour.event_modal_title",
|
||||||
|
descriptionKey: "tour.event_modal_desc",
|
||||||
|
placement: "left",
|
||||||
|
page: "/calendar",
|
||||||
|
interactive: true,
|
||||||
|
demoOnly: true,
|
||||||
|
beforeAction: () => {
|
||||||
|
// Click the create event button to open the modal
|
||||||
|
const btn = document.querySelector('[data-tour="create-event-button"]') as HTMLElement | null;
|
||||||
|
if (btn) btn.click();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "contacts-list",
|
||||||
|
target: '[data-tour="contacts-list"]',
|
||||||
|
titleKey: "tour.contacts_list_title",
|
||||||
|
descriptionKey: "tour.contacts_list_desc",
|
||||||
|
placement: "right",
|
||||||
|
page: "/contacts",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "settings-tabs",
|
||||||
|
target: '[data-tour="settings-tabs"]',
|
||||||
|
titleKey: "tour.settings_tabs_title",
|
||||||
|
descriptionKey: "tour.settings_tabs_desc",
|
||||||
|
placement: "right",
|
||||||
|
page: "/settings",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "nav-files",
|
||||||
|
target: '[data-tour="nav-files"]',
|
||||||
|
titleKey: "tour.files_title",
|
||||||
|
descriptionKey: "tour.files_desc",
|
||||||
|
placement: "right",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "demo-banner",
|
||||||
|
target: '[data-tour="demo-banner"]',
|
||||||
|
titleKey: "tour.demo_banner_title",
|
||||||
|
descriptionKey: "tour.demo_banner_desc",
|
||||||
|
placement: "bottom",
|
||||||
|
page: "/",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "quota",
|
||||||
|
target: '[data-tour="storage-quota"]',
|
||||||
|
titleKey: "tour.quota_title",
|
||||||
|
descriptionKey: "tour.quota_desc",
|
||||||
|
placement: "right",
|
||||||
|
demoOnly: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export function getTourSteps(options: {
|
||||||
|
isDemoMode: boolean;
|
||||||
|
supportsCalendar: boolean;
|
||||||
|
supportsWebDAV: boolean;
|
||||||
|
}): TourStep[] {
|
||||||
|
let steps = [...BASE_TOUR_STEPS];
|
||||||
|
|
||||||
|
if (!options.supportsCalendar) {
|
||||||
|
steps = steps.filter((s) => s.id !== "nav-calendar");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.isDemoMode) {
|
||||||
|
const demoSteps = DEMO_TOUR_STEPS.filter((s) => {
|
||||||
|
if (s.id === "nav-files" && !options.supportsWebDAV) return false;
|
||||||
|
if ((s.id === "calendar-view" || s.id === "create-event" || s.id === "event-modal") && !options.supportsCalendar) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
steps = [...steps, ...demoSteps];
|
||||||
|
}
|
||||||
|
|
||||||
|
return steps;
|
||||||
|
}
|
||||||
@@ -2,15 +2,17 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { X, Lightbulb, Settings } from "lucide-react";
|
import { X, Lightbulb, Settings, PlayCircle } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useRouter } from "@/i18n/navigation";
|
import { useRouter } from "@/i18n/navigation";
|
||||||
|
import { useTour } from "@/components/tour/tour-provider";
|
||||||
|
|
||||||
const ONBOARDING_KEY = "onboarding_completed";
|
const ONBOARDING_KEY = "onboarding_completed";
|
||||||
|
|
||||||
export function WelcomeBanner() {
|
export function WelcomeBanner() {
|
||||||
const t = useTranslations("welcome");
|
const t = useTranslations("welcome");
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { startTour } = useTour();
|
||||||
const [visible, setVisible] = useState(false);
|
const [visible, setVisible] = useState(false);
|
||||||
const [dismissed, setDismissed] = useState(false);
|
const [dismissed, setDismissed] = useState(false);
|
||||||
|
|
||||||
@@ -78,6 +80,15 @@ export function WelcomeBanner() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-2.5 flex justify-end gap-2">
|
<div className="mt-2.5 flex justify-end gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => { dismiss(); startTour(); }}
|
||||||
|
className="text-xs h-7"
|
||||||
|
>
|
||||||
|
<PlayCircle className="w-3.5 h-3.5 mr-1" />
|
||||||
|
{t("start_tour")}
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
+8
-5
@@ -28,15 +28,18 @@ export default [
|
|||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
"@typescript-eslint": tseslint,
|
"@typescript-eslint": tseslint,
|
||||||
"react": reactPlugin,
|
react: reactPlugin,
|
||||||
"react-hooks": reactHooksPlugin,
|
"react-hooks": reactHooksPlugin,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
...tseslint.configs.recommended.rules,
|
...tseslint.configs.recommended.rules,
|
||||||
"@typescript-eslint/no-unused-vars": ["warn", {
|
"@typescript-eslint/no-unused-vars": [
|
||||||
argsIgnorePattern: "^_",
|
"warn",
|
||||||
varsIgnorePattern: "^_"
|
{
|
||||||
}],
|
argsIgnorePattern: "^_",
|
||||||
|
varsIgnorePattern: "^_",
|
||||||
|
},
|
||||||
|
],
|
||||||
"@typescript-eslint/no-explicit-any": "warn",
|
"@typescript-eslint/no-explicit-any": "warn",
|
||||||
"@typescript-eslint/no-empty-object-type": "off",
|
"@typescript-eslint/no-empty-object-type": "off",
|
||||||
"react-hooks/rules-of-hooks": "error",
|
"react-hooks/rules-of-hooks": "error",
|
||||||
|
|||||||
@@ -5,9 +5,10 @@ import { useTranslations, useLocale } from 'next-intl';
|
|||||||
import { useAuthStore } from '@/stores/auth-store';
|
import { useAuthStore } from '@/stores/auth-store';
|
||||||
import { useCalendarStore } from '@/stores/calendar-store';
|
import { useCalendarStore } from '@/stores/calendar-store';
|
||||||
import { useSettingsStore } from '@/stores/settings-store';
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { useTaskStore } from '@/stores/task-store';
|
||||||
import { useCalendarNotificationStore } from '@/stores/calendar-notification-store';
|
import { useCalendarNotificationStore } from '@/stores/calendar-notification-store';
|
||||||
import { useToastStore } from '@/stores/toast-store';
|
import { useToastStore } from '@/stores/toast-store';
|
||||||
import { getPendingAlerts, buildAlertKey } from '@/lib/calendar-alerts';
|
import { getPendingAlerts, getPendingTaskAlerts, buildAlertKey } from '@/lib/calendar-alerts';
|
||||||
import { playNotificationSound } from '@/lib/notification-sound';
|
import { playNotificationSound } from '@/lib/notification-sound';
|
||||||
import type { CalendarEvent } from '@/lib/jmap/types';
|
import type { CalendarEvent } from '@/lib/jmap/types';
|
||||||
|
|
||||||
@@ -18,7 +19,8 @@ const PROACTIVE_THROTTLE_MS = CHECK_INTERVAL_MS * 5;
|
|||||||
export function useCalendarAlerts() {
|
export function useCalendarAlerts() {
|
||||||
const { isAuthenticated, client } = useAuthStore();
|
const { isAuthenticated, client } = useAuthStore();
|
||||||
const { events, calendars, supportsCalendar } = useCalendarStore();
|
const { events, calendars, supportsCalendar } = useCalendarStore();
|
||||||
const { calendarNotificationsEnabled, calendarNotificationSound } = useSettingsStore();
|
const { calendarNotificationsEnabled, calendarNotificationSound, enableCalendarTasks, notificationSoundChoice } = useSettingsStore();
|
||||||
|
const { tasks: storeTasks } = useTaskStore();
|
||||||
const { acknowledgedAlerts, acknowledgeAlert, cleanupStaleAlerts } = useCalendarNotificationStore();
|
const { acknowledgedAlerts, acknowledgeAlert, cleanupStaleAlerts } = useCalendarNotificationStore();
|
||||||
const addToast = useToastStore((s) => s.addToast);
|
const addToast = useToastStore((s) => s.addToast);
|
||||||
const t = useTranslations('calendar.notifications');
|
const t = useTranslations('calendar.notifications');
|
||||||
@@ -45,7 +47,7 @@ export function useCalendarAlerts() {
|
|||||||
acknowledgeAlert(key, alert.fireTimeMs);
|
acknowledgeAlert(key, alert.fireTimeMs);
|
||||||
|
|
||||||
if (calendarNotificationSound) {
|
if (calendarNotificationSound) {
|
||||||
playNotificationSound();
|
playNotificationSound(notificationSoundChoice);
|
||||||
}
|
}
|
||||||
|
|
||||||
const diffMs = new Date(alert.event.utcStart || alert.event.start).getTime() - now;
|
const diffMs = new Date(alert.event.utcStart || alert.event.start).getTime() - now;
|
||||||
@@ -69,11 +71,41 @@ export function useCalendarAlerts() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Task alerts
|
||||||
|
if (enableCalendarTasks && storeTasks.length > 0) {
|
||||||
|
const pendingTaskAlerts = getPendingTaskAlerts(storeTasks, calendars, acknowledgedKeys, now);
|
||||||
|
for (const taskAlert of pendingTaskAlerts) {
|
||||||
|
const key = buildAlertKey(taskAlert.taskId, taskAlert.alertId, taskAlert.fireTimeMs);
|
||||||
|
if (shownKeysRef.current.has(key)) continue;
|
||||||
|
|
||||||
|
shownKeysRef.current.add(key);
|
||||||
|
acknowledgeAlert(key, taskAlert.fireTimeMs);
|
||||||
|
|
||||||
|
if (calendarNotificationSound) {
|
||||||
|
playNotificationSound(notificationSoundChoice);
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskMsg = taskAlert.calendarName
|
||||||
|
? `${t('task_due')} · ${taskAlert.calendarName}`
|
||||||
|
: t('task_due');
|
||||||
|
|
||||||
|
addToast({
|
||||||
|
type: 'info',
|
||||||
|
title: taskAlert.task.title || t('alert_title'),
|
||||||
|
message: taskMsg,
|
||||||
|
duration: 15000,
|
||||||
|
onClick: () => {
|
||||||
|
window.location.href = `/${locale}/calendar`;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Silently ignore alert evaluation errors
|
// Silently ignore alert evaluation errors
|
||||||
}
|
}
|
||||||
}, [
|
}, [
|
||||||
calendarNotificationsEnabled, calendarNotificationSound,
|
calendarNotificationsEnabled, calendarNotificationSound, notificationSoundChoice,
|
||||||
isAuthenticated, events, calendars, acknowledgedAlerts,
|
isAuthenticated, events, calendars, acknowledgedAlerts,
|
||||||
acknowledgeAlert, addToast, t, locale,
|
acknowledgeAlert, addToast, t, locale,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ interface ConfigData {
|
|||||||
loginImprintUrl: string;
|
loginImprintUrl: string;
|
||||||
loginPrivacyPolicyUrl: string;
|
loginPrivacyPolicyUrl: string;
|
||||||
loginWebsiteUrl: string;
|
loginWebsiteUrl: string;
|
||||||
|
demoMode: boolean;
|
||||||
|
autoSsoEnabled: boolean;
|
||||||
|
embeddedMode: boolean;
|
||||||
|
parentOrigin: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AppConfig extends ConfigData {
|
interface AppConfig extends ConfigData {
|
||||||
@@ -91,6 +95,10 @@ export function useConfig(): AppConfig {
|
|||||||
loginImprintUrl: configCache?.loginImprintUrl || '',
|
loginImprintUrl: configCache?.loginImprintUrl || '',
|
||||||
loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '',
|
loginPrivacyPolicyUrl: configCache?.loginPrivacyPolicyUrl || '',
|
||||||
loginWebsiteUrl: configCache?.loginWebsiteUrl || '',
|
loginWebsiteUrl: configCache?.loginWebsiteUrl || '',
|
||||||
|
demoMode: configCache?.demoMode || false,
|
||||||
|
autoSsoEnabled: configCache?.autoSsoEnabled || false,
|
||||||
|
embeddedMode: configCache?.embeddedMode || false,
|
||||||
|
parentOrigin: configCache?.parentOrigin || '',
|
||||||
isLoading: !configCache,
|
isLoading: !configCache,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
@@ -118,6 +126,10 @@ export function useConfig(): AppConfig {
|
|||||||
loginImprintUrl: configCache.loginImprintUrl,
|
loginImprintUrl: configCache.loginImprintUrl,
|
||||||
loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl,
|
loginPrivacyPolicyUrl: configCache.loginPrivacyPolicyUrl,
|
||||||
loginWebsiteUrl: configCache.loginWebsiteUrl,
|
loginWebsiteUrl: configCache.loginWebsiteUrl,
|
||||||
|
demoMode: configCache.demoMode,
|
||||||
|
autoSsoEnabled: configCache.autoSsoEnabled,
|
||||||
|
embeddedMode: configCache.embeddedMode,
|
||||||
|
parentOrigin: configCache.parentOrigin,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
@@ -146,6 +158,10 @@ export function useConfig(): AppConfig {
|
|||||||
loginImprintUrl: data.loginImprintUrl,
|
loginImprintUrl: data.loginImprintUrl,
|
||||||
loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl,
|
loginPrivacyPolicyUrl: data.loginPrivacyPolicyUrl,
|
||||||
loginWebsiteUrl: data.loginWebsiteUrl,
|
loginWebsiteUrl: data.loginWebsiteUrl,
|
||||||
|
demoMode: data.demoMode,
|
||||||
|
autoSsoEnabled: data.autoSsoEnabled,
|
||||||
|
embeddedMode: data.embeddedMode,
|
||||||
|
parentOrigin: data.parentOrigin,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
error: null,
|
error: null,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
const loggerError = vi.fn();
|
||||||
|
|
||||||
|
vi.mock('next/server', () => ({
|
||||||
|
NextResponse: {
|
||||||
|
json: (data: unknown, init?: { status?: number; headers?: unknown }) => ({
|
||||||
|
status: init?.status ?? 200,
|
||||||
|
headers: init?.headers,
|
||||||
|
json: async () => data,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/lib/logger', () => ({
|
||||||
|
logger: {
|
||||||
|
error: loggerError,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('health route', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
loggerError.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns healthy for the basic liveness probe even when heap usage is high', async () => {
|
||||||
|
vi.spyOn(process, 'memoryUsage').mockReturnValue({
|
||||||
|
rss: 120_000_000,
|
||||||
|
heapTotal: 45_000_000,
|
||||||
|
heapUsed: 43_000_000,
|
||||||
|
external: 8_000_000,
|
||||||
|
arrayBuffers: 1_000_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { GET } = await import('@/app/api/health/route');
|
||||||
|
const response = await GET({ nextUrl: new URL('http://localhost/api/health') } as never);
|
||||||
|
const payload = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(payload).toMatchObject({
|
||||||
|
status: 'healthy',
|
||||||
|
});
|
||||||
|
expect(payload.warnings).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns degraded diagnostics in detailed mode without failing the probe', async () => {
|
||||||
|
vi.spyOn(process, 'memoryUsage').mockReturnValue({
|
||||||
|
rss: 120_000_000,
|
||||||
|
heapTotal: 4_100_000_000,
|
||||||
|
heapUsed: 4_000_000_000,
|
||||||
|
external: 8_000_000,
|
||||||
|
arrayBuffers: 1_000_000,
|
||||||
|
});
|
||||||
|
vi.spyOn(process, 'uptime').mockReturnValue(123.45);
|
||||||
|
|
||||||
|
const { GET } = await import('@/app/api/health/route');
|
||||||
|
const response = await GET({ nextUrl: new URL('http://localhost/api/health?detailed=true') } as never);
|
||||||
|
const payload = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(payload.status).toBe('degraded');
|
||||||
|
expect(payload.memory).toMatchObject({
|
||||||
|
heapUsed: 4_000_000_000,
|
||||||
|
heapTotal: 4_100_000_000,
|
||||||
|
rss: 120_000_000,
|
||||||
|
external: 8_000_000,
|
||||||
|
});
|
||||||
|
expect(payload.memory.heapSizeLimit).toBeGreaterThan(0);
|
||||||
|
expect(payload.warnings).toEqual([
|
||||||
|
expect.stringContaining('V8 heap usage is high'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps HEAD as a stable liveness probe', async () => {
|
||||||
|
const { HEAD } = await import('@/app/api/health/route');
|
||||||
|
const response = await HEAD();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 503 when collecting health diagnostics throws', async () => {
|
||||||
|
vi.spyOn(process, 'memoryUsage').mockImplementation(() => {
|
||||||
|
throw new Error('boom');
|
||||||
|
});
|
||||||
|
|
||||||
|
const { GET } = await import('@/app/api/health/route');
|
||||||
|
const response = await GET({ nextUrl: new URL('http://localhost/api/health') } as never);
|
||||||
|
const payload = await response.json();
|
||||||
|
|
||||||
|
expect(response.status).toBe(503);
|
||||||
|
expect(payload).toMatchObject({
|
||||||
|
status: 'unhealthy',
|
||||||
|
reason: 'boom',
|
||||||
|
});
|
||||||
|
expect(loggerError).toHaveBeenCalledWith('Health check failed', { error: 'boom' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -122,10 +122,15 @@ describe('JMAPClient contact methods', () => {
|
|||||||
describe('getContacts', () => {
|
describe('getContacts', () => {
|
||||||
it('should return contacts from server', async () => {
|
it('should return contacts from server', async () => {
|
||||||
const client = createClient();
|
const client = createClient();
|
||||||
mockFetch({
|
const spy = vi.spyOn(globalThis, 'fetch');
|
||||||
|
mockFetchOnce(spy, {
|
||||||
methodResponses: [
|
methodResponses: [
|
||||||
['ContactCard/query', { ids: ['contact-1'] }, '0'],
|
['ContactCard/query', { ids: ['contact-1'] }, 'q'],
|
||||||
['ContactCard/get', { list: [mockContact] }, '1'],
|
],
|
||||||
|
});
|
||||||
|
mockFetchOnce(spy, {
|
||||||
|
methodResponses: [
|
||||||
|
['ContactCard/get', { list: [mockContact] }, 'g'],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -89,6 +89,22 @@ describe('groupEmailsByThread', () => {
|
|||||||
expect(groupEmailsByThread(emails)[0].hasAttachment).toBe(true);
|
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', () => {
|
it('returns empty array for empty input', () => {
|
||||||
expect(groupEmailsByThread([])).toEqual([]);
|
expect(groupEmailsByThread([])).toEqual([]);
|
||||||
});
|
});
|
||||||
@@ -110,6 +126,8 @@ describe('sortThreadGroups', () => {
|
|||||||
hasUnread: false,
|
hasUnread: false,
|
||||||
hasStarred: false,
|
hasStarred: false,
|
||||||
hasAttachment: false,
|
hasAttachment: false,
|
||||||
|
hasAnswered: false,
|
||||||
|
hasForwarded: false,
|
||||||
emailCount: 1,
|
emailCount: 1,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -120,6 +138,8 @@ describe('sortThreadGroups', () => {
|
|||||||
hasUnread: false,
|
hasUnread: false,
|
||||||
hasStarred: false,
|
hasStarred: false,
|
||||||
hasAttachment: false,
|
hasAttachment: false,
|
||||||
|
hasAnswered: false,
|
||||||
|
hasForwarded: false,
|
||||||
emailCount: 1,
|
emailCount: 1,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -169,6 +189,8 @@ describe('mergeThreadEmails', () => {
|
|||||||
hasUnread: false,
|
hasUnread: false,
|
||||||
hasStarred: false,
|
hasStarred: false,
|
||||||
hasAttachment: false,
|
hasAttachment: false,
|
||||||
|
hasAnswered: false,
|
||||||
|
hasForwarded: false,
|
||||||
emailCount: 2,
|
emailCount: 2,
|
||||||
};
|
};
|
||||||
const fetched = [
|
const fetched = [
|
||||||
@@ -189,6 +211,8 @@ describe('mergeThreadEmails', () => {
|
|||||||
hasUnread: false,
|
hasUnread: false,
|
||||||
hasStarred: false,
|
hasStarred: false,
|
||||||
hasAttachment: false,
|
hasAttachment: false,
|
||||||
|
hasAnswered: false,
|
||||||
|
hasForwarded: false,
|
||||||
emailCount: 1,
|
emailCount: 1,
|
||||||
};
|
};
|
||||||
const fetched = [
|
const fetched = [
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { useEmailStore } from '@/stores/email-store';
|
|||||||
import { useContactStore } from '@/stores/contact-store';
|
import { useContactStore } from '@/stores/contact-store';
|
||||||
import { useCalendarStore } from '@/stores/calendar-store';
|
import { useCalendarStore } from '@/stores/calendar-store';
|
||||||
import { useFilterStore } from '@/stores/filter-store';
|
import { useFilterStore } from '@/stores/filter-store';
|
||||||
|
import { DEFAULT_SEARCH_FILTERS } from '@/lib/jmap/search-utils';
|
||||||
import { useIdentityStore } from '@/stores/identity-store';
|
import { useIdentityStore } from '@/stores/identity-store';
|
||||||
import { useVacationStore } from '@/stores/vacation-store';
|
import { useVacationStore } from '@/stores/vacation-store';
|
||||||
|
|
||||||
@@ -97,6 +98,19 @@ export function clearAllStores(): void {
|
|||||||
error: null,
|
error: null,
|
||||||
searchQuery: '',
|
searchQuery: '',
|
||||||
quota: null,
|
quota: null,
|
||||||
|
isPushConnected: false,
|
||||||
|
lastPushUpdate: null,
|
||||||
|
newEmailNotification: null,
|
||||||
|
selectedEmailIds: new Set<string>(),
|
||||||
|
hasMoreEmails: false,
|
||||||
|
totalEmails: 0,
|
||||||
|
expandedThreadIds: new Set<string>(),
|
||||||
|
threadEmailsCache: new Map(),
|
||||||
|
isLoadingThread: null,
|
||||||
|
selectedKeyword: null,
|
||||||
|
tagCounts: {},
|
||||||
|
searchFilters: { ...DEFAULT_SEARCH_FILTERS },
|
||||||
|
isAdvancedSearchOpen: false,
|
||||||
});
|
});
|
||||||
useIdentityStore.getState().clearIdentities();
|
useIdentityStore.getState().clearIdentities();
|
||||||
useContactStore.getState().clearContacts();
|
useContactStore.getState().clearContacts();
|
||||||
|
|||||||
@@ -48,3 +48,38 @@ export function decryptSession(token: string): { serverUrl: string; username: st
|
|||||||
return null;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,51 @@
|
|||||||
|
import { locales } from '@/i18n/routing';
|
||||||
|
|
||||||
export function replaceWindowLocation(url: string): void {
|
export function replaceWindowLocation(url: string): void {
|
||||||
if (typeof window === 'undefined') {
|
if (typeof window === 'undefined') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.location.replace(url);
|
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
@@ -4,7 +4,9 @@ import type {
|
|||||||
CalendarOffsetTrigger,
|
CalendarOffsetTrigger,
|
||||||
CalendarAbsoluteTrigger,
|
CalendarAbsoluteTrigger,
|
||||||
Calendar,
|
Calendar,
|
||||||
|
CalendarTask,
|
||||||
} from '@/lib/jmap/types';
|
} from '@/lib/jmap/types';
|
||||||
|
import { parseDuration } from '@/components/calendar/event-card';
|
||||||
|
|
||||||
export interface PendingAlert {
|
export interface PendingAlert {
|
||||||
eventId: string;
|
eventId: string;
|
||||||
@@ -16,19 +18,20 @@ export interface PendingAlert {
|
|||||||
|
|
||||||
const STALE_THRESHOLD_MS = 10 * 60 * 1000; // 10 minutes
|
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 {
|
export function parseAlertOffset(offset: string): number | null {
|
||||||
const match = DURATION_RE.exec(offset);
|
const match = DURATION_RE.exec(offset);
|
||||||
if (!match) return null;
|
if (!match) return null;
|
||||||
|
|
||||||
const negative = match[1] === '-';
|
const negative = match[1] === '-';
|
||||||
const days = parseInt(match[2] || '0', 10);
|
const weeks = parseInt(match[2] || '0', 10);
|
||||||
const hours = parseInt(match[3] || '0', 10);
|
const days = parseInt(match[3] || '0', 10);
|
||||||
const minutes = parseInt(match[4] || '0', 10);
|
const hours = parseInt(match[4] || '0', 10);
|
||||||
const seconds = parseInt(match[5] || '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;
|
return negative ? -ms : ms;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,9 +49,15 @@ export function computeFireTime(
|
|||||||
|
|
||||||
let baseTime: number;
|
let baseTime: number;
|
||||||
if (trigger.relativeTo === 'end') {
|
if (trigger.relativeTo === 'end') {
|
||||||
baseTime = event.utcEnd
|
if (event.utcEnd) {
|
||||||
? new Date(event.utcEnd).getTime()
|
baseTime = new Date(event.utcEnd).getTime();
|
||||||
: new Date(event.start).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 {
|
} else {
|
||||||
baseTime = event.utcStart
|
baseTime = event.utcStart
|
||||||
? new Date(event.utcStart).getTime()
|
? new Date(event.utcStart).getTime()
|
||||||
@@ -67,6 +76,7 @@ export function getEffectiveAlerts(
|
|||||||
return event.alerts;
|
return event.alerts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!event.calendarIds) return null;
|
||||||
const calendarId = Object.keys(event.calendarIds)[0];
|
const calendarId = Object.keys(event.calendarIds)[0];
|
||||||
if (!calendarId) return null;
|
if (!calendarId) return null;
|
||||||
|
|
||||||
@@ -121,3 +131,68 @@ export function getPendingAlerts(
|
|||||||
|
|
||||||
return pending;
|
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
@@ -251,10 +251,11 @@ function looksLikeReply(event: Partial<CalendarEvent>): boolean {
|
|||||||
|
|
||||||
const participants = Object.values(event.participants);
|
const participants = Object.values(event.participants);
|
||||||
const hasOrganizer = participants.some((participant) => isOrganizerParticipant(participant));
|
const hasOrganizer = participants.some((participant) => isOrganizerParticipant(participant));
|
||||||
if (hasOrganizer) return false;
|
if (!hasOrganizer) return false;
|
||||||
|
|
||||||
return participants.some((participant) =>
|
return participants.some((participant) =>
|
||||||
participant.roles?.attendee
|
participant.roles?.attendee
|
||||||
|
&& !isOrganizerParticipant(participant)
|
||||||
&& (
|
&& (
|
||||||
participant.participationStatus !== 'needs-action'
|
participant.participationStatus !== 'needs-action'
|
||||||
|| !!participant.participationComment
|
|| !!participant.participationComment
|
||||||
@@ -373,6 +374,10 @@ export function getInvitationMethod(
|
|||||||
return 'cancel';
|
return 'cancel';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (looksLikeReply(event)) {
|
||||||
|
return 'reply';
|
||||||
|
}
|
||||||
|
|
||||||
if (event.participants && Object.keys(event.participants).length > 0) {
|
if (event.participants && Object.keys(event.participants).length > 0) {
|
||||||
const hasOrganizer = Object.values(event.participants).some(
|
const hasOrganizer = Object.values(event.participants).some(
|
||||||
(p: CalendarParticipant) => isOrganizerParticipant(p)
|
(p: CalendarParticipant) => isOrganizerParticipant(p)
|
||||||
@@ -382,10 +387,6 @@ export function getInvitationMethod(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (looksLikeReply(event)) {
|
|
||||||
return 'reply';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'unknown';
|
return 'unknown';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -524,36 +525,40 @@ export function formatEventSummary(event: Partial<CalendarEvent>): EventSummary
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addDurationToDate(start: string, duration: string, _timeZone?: string | null): string | null {
|
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;
|
if (!match) return null;
|
||||||
|
|
||||||
const days = parseInt(match[1] || '0');
|
const weeks = parseInt(match[1] || '0');
|
||||||
const hours = parseInt(match[2] || '0');
|
const days = parseInt(match[2] || '0') + weeks * 7;
|
||||||
const minutes = parseInt(match[3] || '0');
|
const hours = parseInt(match[3] || '0');
|
||||||
const seconds = parseInt(match[4] || '0');
|
const minutes = parseInt(match[4] || '0');
|
||||||
|
const seconds = parseInt(match[5] || '0');
|
||||||
|
|
||||||
const date = new Date(start);
|
const date = new Date(start);
|
||||||
if (isNaN(date.getTime())) return null;
|
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.setDate(date.getDate() + days);
|
||||||
date.setHours(date.getHours() + hours);
|
date.setHours(date.getHours() + hours);
|
||||||
date.setMinutes(date.getMinutes() + minutes);
|
date.setMinutes(date.getMinutes() + minutes);
|
||||||
date.setSeconds(date.getSeconds() + seconds);
|
date.setSeconds(date.getSeconds() + seconds);
|
||||||
|
|
||||||
// If the input is a local datetime (no UTC 'Z' suffix), return a local
|
const y = date.getFullYear();
|
||||||
// format string so that all-day date arithmetic isn't shifted by the
|
const m = String(date.getMonth() + 1).padStart(2, '0');
|
||||||
// browser's UTC offset (toISOString converts to UTC).
|
const d = String(date.getDate()).padStart(2, '0');
|
||||||
if (!start.endsWith('Z') && !start.includes('+')) {
|
const h = String(date.getHours()).padStart(2, '0');
|
||||||
const y = date.getFullYear();
|
const min = String(date.getMinutes()).padStart(2, '0');
|
||||||
const m = String(date.getMonth() + 1).padStart(2, '0');
|
const s = String(date.getSeconds()).padStart(2, '0');
|
||||||
const d = String(date.getDate()).padStart(2, '0');
|
return `${y}-${m}-${d}T${h}:${min}:${s}`;
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function findParticipantByEmail(
|
export function findParticipantByEmail(
|
||||||
|
|||||||
@@ -15,11 +15,30 @@ export interface StatusCounts {
|
|||||||
'needs-action': number;
|
'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 {
|
export function isOrganizer(event: CalendarEvent, userEmails: string[]): boolean {
|
||||||
if (!event.participants) return false;
|
if (!event.participants) return false;
|
||||||
const lower = userEmails.map(e => e.toLowerCase());
|
const lower = userEmails.map(e => e.toLowerCase());
|
||||||
return Object.values(event.participants).some(p =>
|
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;
|
if (!event.participants) return null;
|
||||||
const lower = userEmails.map(e => e.toLowerCase());
|
const lower = userEmails.map(e => e.toLowerCase());
|
||||||
for (const [id, p] of Object.entries(event.participants)) {
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -39,20 +58,29 @@ export function getUserStatus(
|
|||||||
if (!event.participants) return null;
|
if (!event.participants) return null;
|
||||||
const lower = userEmails.map(e => e.toLowerCase());
|
const lower = userEmails.map(e => e.toLowerCase());
|
||||||
for (const p of Object.values(event.participants)) {
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getParticipantList(event: CalendarEvent): ParticipantInfo[] {
|
export function getParticipantList(event: CalendarEvent): ParticipantInfo[] {
|
||||||
if (!event.participants) return [];
|
if (!event.participants) return [];
|
||||||
return Object.entries(event.participants).map(([id, p]) => ({
|
return Object.entries(event.participants).map(([id, p]) => {
|
||||||
id,
|
let email = p.email || '';
|
||||||
name: p.name || '',
|
if (!email && p.calendarAddress) {
|
||||||
email: p.email || '',
|
email = p.calendarAddress.replace(/^mailto:/i, '');
|
||||||
status: p.participationStatus || 'needs-action',
|
}
|
||||||
isOrganizer: !!p.roles?.owner,
|
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 {
|
export function getStatusCounts(event: CalendarEvent): StatusCounts {
|
||||||
@@ -76,7 +104,11 @@ export function buildParticipantMap(
|
|||||||
): Record<string, Partial<CalendarParticipant>> {
|
): Record<string, Partial<CalendarParticipant>> {
|
||||||
const participants: 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',
|
'@type': 'Participant',
|
||||||
name: organizer.name,
|
name: organizer.name,
|
||||||
email: organizer.email,
|
email: organizer.email,
|
||||||
@@ -88,8 +120,8 @@ export function buildParticipantMap(
|
|||||||
kind: 'individual',
|
kind: 'individual',
|
||||||
};
|
};
|
||||||
|
|
||||||
attendees.forEach((a, i) => {
|
attendees.forEach((a) => {
|
||||||
participants[`attendee-${i}`] = {
|
participants[generateId()] = {
|
||||||
'@type': 'Participant',
|
'@type': 'Participant',
|
||||||
name: a.name,
|
name: a.name,
|
||||||
email: a.email,
|
email: a.email,
|
||||||
|
|||||||
@@ -40,9 +40,7 @@ export function normalizeAllDayDuration(duration: string | undefined): string |
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function buildAllDayDuration(start: Date, inclusiveEnd: Date): string {
|
export function buildAllDayDuration(start: Date, inclusiveEnd: Date): string {
|
||||||
const startDay = startOfDay(start);
|
const dayCount = Math.max(1, differenceInCalendarDays(startOfDay(inclusiveEnd), startOfDay(start)) + 1);
|
||||||
const endDay = startOfDay(inclusiveEnd);
|
|
||||||
const dayCount = Math.max(1, Math.round((endDay.getTime() - startDay.getTime()) / 86400000) + 1);
|
|
||||||
return `P${dayCount}D`;
|
return `P${dayCount}D`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +111,7 @@ export function layoutOverlappingEvents(
|
|||||||
for (const event of sorted) {
|
for (const event of sorted) {
|
||||||
const start = parseISO(event.start);
|
const start = parseISO(event.start);
|
||||||
const startMin = start.getHours() * 60 + start.getMinutes();
|
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;
|
let placed = false;
|
||||||
for (let col = 0; col < columns.length; col++) {
|
for (let col = 0; col < columns.length; col++) {
|
||||||
if (columns[col].every(e => e.end <= startMin)) {
|
if (columns[col].every(e => e.end <= startMin)) {
|
||||||
@@ -135,8 +133,9 @@ export function layoutOverlappingEvents(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function formatSnapTime(minutes: number, timeFormat: "12h" | "24h"): string {
|
export function formatSnapTime(minutes: number, timeFormat: "12h" | "24h"): string {
|
||||||
const h = Math.floor(minutes / 60);
|
const clamped = Math.max(0, Math.min(1440, minutes));
|
||||||
const m = minutes % 60;
|
const h = Math.floor(clamped / 60) % 24;
|
||||||
|
const m = clamped % 60;
|
||||||
if (timeFormat === "12h") {
|
if (timeFormat === "12h") {
|
||||||
return `${h % 12 || 12}:${String(m).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
|
return `${h % 12 || 12}:${String(m).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,866 @@
|
|||||||
|
import type { IJMAPClient } from '@/lib/jmap/client-interface';
|
||||||
|
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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-memory JMAP client for demo mode.
|
||||||
|
* All data lives in memory — no network calls, no cookies.
|
||||||
|
*/
|
||||||
|
export class DemoJMAPClient implements IJMAPClient {
|
||||||
|
private data: DemoData;
|
||||||
|
private blobStore = new Map<string, Blob>();
|
||||||
|
private connectionCallback: ((connected: boolean) => void) | null = null;
|
||||||
|
private stateChangeCallback: ((change: StateChange) => void) | null = null;
|
||||||
|
private lastStates: AccountStates = {};
|
||||||
|
private incomingTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.data = getDemoData();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Connection lifecycle ──────────────────────────────────────
|
||||||
|
|
||||||
|
async connect(): Promise<void> {
|
||||||
|
// Start simulated incoming email timer
|
||||||
|
this.startIncomingEmailTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect(): void {
|
||||||
|
this.stopIncomingEmailTimer();
|
||||||
|
this.connectionCallback = null;
|
||||||
|
this.stateChangeCallback = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async reconnect(): Promise<void> { /* no-op */ }
|
||||||
|
async ping(): Promise<void> { /* no-op */ }
|
||||||
|
|
||||||
|
// ── Session / auth accessors ──────────────────────────────────
|
||||||
|
|
||||||
|
getServerUrl(): string { return 'https://demo.example.com'; }
|
||||||
|
getAuthHeader(): string { return 'Bearer demo-token'; }
|
||||||
|
updateAccessToken(): void { /* no-op */ }
|
||||||
|
getAccountId(): string { return 'demo-account'; }
|
||||||
|
getUsername(): string { return 'demo@example.com'; }
|
||||||
|
|
||||||
|
// ── Capabilities ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
getCapabilities(): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
'urn:ietf:params:jmap:core': { maxSizeUpload: 50_000_000, maxCallsInRequest: 16, maxObjectsInGet: 500 },
|
||||||
|
'urn:ietf:params:jmap:mail': {},
|
||||||
|
'urn:ietf:params:jmap:submission': {},
|
||||||
|
'urn:ietf:params:jmap:vacationresponse': {},
|
||||||
|
'urn:ietf:params:jmap:contacts': {},
|
||||||
|
'urn:ietf:params:jmap:calendars': {},
|
||||||
|
'urn:ietf:params:jmap:sieve': {},
|
||||||
|
'urn:ietf:params:jmap:quota': {},
|
||||||
|
'urn:ietf:params:jmap:files': {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
getMaxSizeUpload(): number { return 50_000_000; }
|
||||||
|
getMaxCallsInRequest(): number { return 16; }
|
||||||
|
getMaxObjectsInGet(): number { return 500; }
|
||||||
|
getEventSourceUrl(): string | null { return null; }
|
||||||
|
supportsEmailSubmission(): boolean { return true; }
|
||||||
|
supportsQuota(): boolean { return true; }
|
||||||
|
supportsVacationResponse(): boolean { return true; }
|
||||||
|
supportsContacts(): boolean { return true; }
|
||||||
|
supportsCalendars(): boolean { return true; }
|
||||||
|
supportsSieve(): boolean { return true; }
|
||||||
|
supportsFiles(): boolean { return true; }
|
||||||
|
|
||||||
|
// ── Push / state ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
setupPushNotifications(): boolean { return true; }
|
||||||
|
closePushNotifications(): void { /* no-op in demo */ }
|
||||||
|
onConnectionChange(callback: (connected: boolean) => void): void { this.connectionCallback = callback; }
|
||||||
|
onStateChange(callback: (change: StateChange) => void): void { this.stateChangeCallback = callback; }
|
||||||
|
getLastStates(): AccountStates { return { ...this.lastStates }; }
|
||||||
|
setLastStates(states: AccountStates): void { this.lastStates = { ...states }; }
|
||||||
|
|
||||||
|
// ── Quota ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getQuota(): Promise<{ used: number; total: number } | null> {
|
||||||
|
return { used: 245_366_784, total: 1_073_741_824 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mailboxes ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getMailboxes(): Promise<Mailbox[]> { return [...this.data.mailboxes]; }
|
||||||
|
async getAllMailboxes(): Promise<Mailbox[]> { return [...this.data.mailboxes]; }
|
||||||
|
|
||||||
|
async createMailbox(name: string, parentId?: string): Promise<Mailbox> {
|
||||||
|
const mb: Mailbox = {
|
||||||
|
id: generateDemoId('mailbox'),
|
||||||
|
name,
|
||||||
|
sortOrder: 100,
|
||||||
|
totalEmails: 0,
|
||||||
|
unreadEmails: 0,
|
||||||
|
totalThreads: 0,
|
||||||
|
unreadThreads: 0,
|
||||||
|
parentId,
|
||||||
|
isSubscribed: true,
|
||||||
|
myRights: { mayReadItems: true, mayAddItems: true, mayRemoveItems: true, maySetSeen: true, maySetKeywords: true, mayCreateChild: true, mayRename: true, mayDelete: true, maySubmit: true },
|
||||||
|
};
|
||||||
|
this.data.mailboxes.push(mb);
|
||||||
|
return mb;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateMailbox(mailboxId: string, changes: { name?: string; parentId?: string | null; role?: string | null; sortOrder?: number }): Promise<void> {
|
||||||
|
const mb = this.data.mailboxes.find(m => m.id === mailboxId);
|
||||||
|
if (mb) Object.assign(mb, changes);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteMailbox(mailboxId: string): Promise<void> {
|
||||||
|
this.data.mailboxes = this.data.mailboxes.filter(m => m.id !== mailboxId);
|
||||||
|
// Also remove emails in this mailbox
|
||||||
|
this.data.emails = this.data.emails.filter(e => !e.mailboxIds[mailboxId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Emails ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getEmails(mailboxId?: string, _accountId?: string, limit: number = 50, position: number = 0): Promise<{ emails: Email[]; hasMore: boolean; total: number }> {
|
||||||
|
let filtered = this.data.emails;
|
||||||
|
if (mailboxId) {
|
||||||
|
filtered = filtered.filter(e => e.mailboxIds[mailboxId]);
|
||||||
|
}
|
||||||
|
filtered.sort((a, b) => new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime());
|
||||||
|
const total = filtered.length;
|
||||||
|
const emails = filtered.slice(position, position + limit);
|
||||||
|
return { emails, hasMore: position + limit < total, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEmailsInMailbox(mailboxId: string): Promise<Email[]> {
|
||||||
|
return this.data.emails.filter(e => e.mailboxIds[mailboxId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEmail(emailId: string): Promise<Email | null> {
|
||||||
|
return this.data.emails.find(e => e.id === emailId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTagCounts(tagIds: string[]): Promise<Record<string, { total: number; unread: number }>> {
|
||||||
|
const result: Record<string, { total: number; unread: number }> = {};
|
||||||
|
for (const tagId of tagIds) {
|
||||||
|
const tagged = this.data.emails.filter(e => e.keywords[tagId]);
|
||||||
|
result[tagId] = {
|
||||||
|
total: tagged.length,
|
||||||
|
unread: tagged.filter(e => !e.keywords.$seen).length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async searchEmails(query: string, mailboxId?: string, _accountId?: string, limit: number = 50, position: number = 0): Promise<{ emails: Email[]; hasMore: boolean; total: number }> {
|
||||||
|
const q = query.toLowerCase();
|
||||||
|
let filtered = this.data.emails.filter(e => {
|
||||||
|
const text = [e.subject, e.preview, e.from?.[0]?.name, e.from?.[0]?.email].filter(Boolean).join(' ').toLowerCase();
|
||||||
|
return text.includes(q);
|
||||||
|
});
|
||||||
|
if (mailboxId) filtered = filtered.filter(e => e.mailboxIds[mailboxId]);
|
||||||
|
filtered.sort((a, b) => new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime());
|
||||||
|
const total = filtered.length;
|
||||||
|
const emails = filtered.slice(position, position + limit);
|
||||||
|
return { emails, hasMore: position + limit < total, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
async advancedSearchEmails(filter: Record<string, unknown>, _accountId?: string, limit: number = 50, position: number = 0): Promise<{ emails: Email[]; hasMore: boolean; total: number }> {
|
||||||
|
// Simplified: just return all emails for any advanced filter
|
||||||
|
let filtered = [...this.data.emails];
|
||||||
|
if (filter.inMailbox) filtered = filtered.filter(e => e.mailboxIds[filter.inMailbox as string]);
|
||||||
|
if (filter.text) {
|
||||||
|
const q = (filter.text as string).toLowerCase();
|
||||||
|
filtered = filtered.filter(e => [e.subject, e.preview].filter(Boolean).join(' ').toLowerCase().includes(q));
|
||||||
|
}
|
||||||
|
filtered.sort((a, b) => new Date(b.receivedAt).getTime() - new Date(a.receivedAt).getTime());
|
||||||
|
const total = filtered.length;
|
||||||
|
const emails = filtered.slice(position, position + limit);
|
||||||
|
return { emails, hasMore: position + limit < total, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Email mutations ───────────────────────────────────────────
|
||||||
|
|
||||||
|
async markAsRead(emailId: string, read: boolean = true): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
if (!email) return;
|
||||||
|
if (read) {
|
||||||
|
email.keywords.$seen = true;
|
||||||
|
} else {
|
||||||
|
delete email.keywords.$seen;
|
||||||
|
}
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async batchMarkAsRead(emailIds: string[], read: boolean = true): Promise<void> {
|
||||||
|
for (const id of emailIds) {
|
||||||
|
const email = this.data.emails.find(e => e.id === id);
|
||||||
|
if (email) {
|
||||||
|
if (read) email.keywords.$seen = true;
|
||||||
|
else delete email.keywords.$seen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async toggleStar(emailId: string, starred: boolean): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
if (!email) return;
|
||||||
|
if (starred) email.keywords.$flagged = true;
|
||||||
|
else delete email.keywords.$flagged;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateEmailKeywords(emailId: string, keywords: Record<string, boolean>): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
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) {
|
||||||
|
if (email.keywords[oldKeyword]) {
|
||||||
|
delete email.keywords[oldKeyword];
|
||||||
|
email.keywords[newKeyword] = true;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEmail(emailId: string): Promise<void> {
|
||||||
|
this.data.emails = this.data.emails.filter(e => e.id !== emailId);
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async moveToTrash(emailId: string, trashMailboxId: string): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
if (!email) return;
|
||||||
|
email.mailboxIds = { [trashMailboxId]: true };
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async batchDeleteEmails(emailIds: string[]): Promise<void> {
|
||||||
|
const idSet = new Set(emailIds);
|
||||||
|
this.data.emails = this.data.emails.filter(e => !idSet.has(e.id));
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async batchMoveEmails(emailIds: string[], toMailboxId: string): Promise<void> {
|
||||||
|
for (const id of emailIds) {
|
||||||
|
const email = this.data.emails.find(e => e.id === id);
|
||||||
|
if (email) email.mailboxIds = { [toMailboxId]: true };
|
||||||
|
}
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async moveEmail(emailId: string, toMailboxId: string): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
if (email) email.mailboxIds = { [toMailboxId]: true };
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async emptyMailbox(mailboxId: string): Promise<number> {
|
||||||
|
const before = this.data.emails.length;
|
||||||
|
this.data.emails = this.data.emails.filter(e => !e.mailboxIds[mailboxId]);
|
||||||
|
const removed = before - this.data.emails.length;
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
|
async markAsSpam(emailId: string): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
const junkMb = this.data.mailboxes.find(m => m.role === 'junk');
|
||||||
|
if (email && junkMb) email.mailboxIds = { [junkMb.id]: true };
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async undoSpam(emailId: string, originalMailboxId: string): Promise<void> {
|
||||||
|
const email = this.data.emails.find(e => e.id === emailId);
|
||||||
|
if (email) email.mailboxIds = { [originalMailboxId]: true };
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Threads ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getThread(threadId: string): Promise<Thread | null> {
|
||||||
|
const emails = this.data.emails.filter(e => e.threadId === threadId);
|
||||||
|
if (emails.length === 0) return null;
|
||||||
|
return { id: threadId, emailIds: emails.map(e => e.id) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getThreadEmails(threadId: string): Promise<Email[]> {
|
||||||
|
return this.data.emails
|
||||||
|
.filter(e => e.threadId === threadId)
|
||||||
|
.sort((a, b) => new Date(a.receivedAt).getTime() - new Date(b.receivedAt).getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Compose / Send ────────────────────────────────────────────
|
||||||
|
|
||||||
|
async createDraft(
|
||||||
|
to: string[],
|
||||||
|
subject: string,
|
||||||
|
body: string,
|
||||||
|
cc?: string[],
|
||||||
|
bcc?: string[],
|
||||||
|
_identityId?: string,
|
||||||
|
_fromEmail?: string,
|
||||||
|
draftId?: string,
|
||||||
|
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>,
|
||||||
|
_fromName?: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const draftsMb = this.data.mailboxes.find(m => m.role === 'drafts');
|
||||||
|
const id = draftId || generateDemoId('email');
|
||||||
|
const existing = draftId ? this.data.emails.findIndex(e => e.id === draftId) : -1;
|
||||||
|
|
||||||
|
const email: Email = {
|
||||||
|
id, threadId: generateDemoId('thread'),
|
||||||
|
mailboxIds: { [draftsMb?.id || 'demo-mailbox-drafts']: true },
|
||||||
|
keywords: { $seen: true, $draft: true },
|
||||||
|
size: body.length,
|
||||||
|
receivedAt: new Date().toISOString(),
|
||||||
|
from: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
to: to.map(e => ({ email: e })),
|
||||||
|
cc: cc?.map(e => ({ email: e })),
|
||||||
|
bcc: bcc?.map(e => ({ email: e })),
|
||||||
|
subject,
|
||||||
|
sentAt: new Date().toISOString(),
|
||||||
|
preview: body.substring(0, 200),
|
||||||
|
hasAttachment: !!attachments?.length,
|
||||||
|
textBody: [{ partId: '1', blobId: generateDemoId('blob'), size: body.length, type: 'text/plain' }],
|
||||||
|
htmlBody: [],
|
||||||
|
bodyValues: { '1': { value: body } },
|
||||||
|
attachments: attachments?.map(a => ({ ...a, partId: generateDemoId('part') })),
|
||||||
|
messageId: `<${id}@demo.example.com>`,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (existing >= 0) {
|
||||||
|
this.data.emails[existing] = email;
|
||||||
|
} else {
|
||||||
|
this.data.emails.push(email);
|
||||||
|
}
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendEmail(
|
||||||
|
to: string[],
|
||||||
|
subject: string,
|
||||||
|
body: string,
|
||||||
|
cc?: string[],
|
||||||
|
bcc?: string[],
|
||||||
|
_identityId?: string,
|
||||||
|
_fromEmail?: string,
|
||||||
|
draftId?: string,
|
||||||
|
_fromName?: string,
|
||||||
|
htmlBody?: string,
|
||||||
|
attachments?: Array<{ blobId: string; name: string; type: string; size: number }>,
|
||||||
|
): Promise<void> {
|
||||||
|
// Remove draft if updating
|
||||||
|
if (draftId) {
|
||||||
|
this.data.emails = this.data.emails.filter(e => e.id !== draftId);
|
||||||
|
}
|
||||||
|
const sentMb = this.data.mailboxes.find(m => m.role === 'sent');
|
||||||
|
const email: Email = {
|
||||||
|
id: generateDemoId('email'), threadId: generateDemoId('thread'),
|
||||||
|
mailboxIds: { [sentMb?.id || 'demo-mailbox-sent']: true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: body.length + (htmlBody?.length || 0),
|
||||||
|
receivedAt: new Date().toISOString(),
|
||||||
|
from: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
to: to.map(e => ({ email: e })),
|
||||||
|
cc: cc?.map(e => ({ email: e })),
|
||||||
|
bcc: bcc?.map(e => ({ email: e })),
|
||||||
|
subject,
|
||||||
|
sentAt: new Date().toISOString(),
|
||||||
|
preview: body.substring(0, 200),
|
||||||
|
hasAttachment: !!attachments?.length,
|
||||||
|
textBody: [{ partId: '1', blobId: generateDemoId('blob'), size: body.length, type: 'text/plain' }],
|
||||||
|
htmlBody: htmlBody ? [{ partId: '2', blobId: generateDemoId('blob'), size: htmlBody.length, type: 'text/html' }] : [],
|
||||||
|
bodyValues: htmlBody ? { '1': { value: body }, '2': { value: htmlBody } } : { '1': { value: body } },
|
||||||
|
attachments: attachments?.map(a => ({ ...a, partId: generateDemoId('part') })),
|
||||||
|
messageId: `<${generateDemoId('msg')}@demo.example.com>`,
|
||||||
|
};
|
||||||
|
this.data.emails.push(email);
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendImipReply(): Promise<void> { /* no-op in demo */ }
|
||||||
|
async sendImipInvitation(): Promise<void> { /* no-op in demo */ }
|
||||||
|
async sendImipCancellation(): Promise<void> { /* no-op in demo */ }
|
||||||
|
|
||||||
|
// ── Blobs ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async uploadBlob(file: File): Promise<{ blobId: string; size: number; type: string }> {
|
||||||
|
const blobId = generateDemoId('blob');
|
||||||
|
this.blobStore.set(blobId, file);
|
||||||
|
return { blobId, size: file.size, type: file.type };
|
||||||
|
}
|
||||||
|
|
||||||
|
getBlobDownloadUrl(blobId: string): string {
|
||||||
|
return `data:application/octet-stream;demo-blob=${blobId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchBlob(blobId: string): Promise<Blob> {
|
||||||
|
return this.blobStore.get(blobId) ?? new Blob(['[Demo placeholder content]'], { type: 'text/plain' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchBlobAsObjectUrl(blobId: string): Promise<string> {
|
||||||
|
const blob = await this.fetchBlob(blobId);
|
||||||
|
return URL.createObjectURL(blob);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchBlobArrayBuffer(blobId: string): Promise<ArrayBuffer> {
|
||||||
|
const blob = await this.fetchBlob(blobId);
|
||||||
|
return blob.arrayBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
async downloadBlob(blobId: string, name?: string): Promise<void> {
|
||||||
|
const blob = await this.fetchBlob(blobId);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = name || 'download';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Identities ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getIdentities(): Promise<Identity[]> { return [...this.data.identities]; }
|
||||||
|
|
||||||
|
async createIdentity(
|
||||||
|
name: string, email: string,
|
||||||
|
replyTo?: EmailAddress[] | null, bcc?: EmailAddress[] | null,
|
||||||
|
htmlSignature?: string, textSignature?: string,
|
||||||
|
): Promise<Identity> {
|
||||||
|
const identity: Identity = {
|
||||||
|
id: generateDemoId('identity'), name, email,
|
||||||
|
replyTo: replyTo ?? undefined, bcc: bcc ?? undefined,
|
||||||
|
htmlSignature: htmlSignature ?? '', textSignature: textSignature ?? '',
|
||||||
|
mayDelete: true,
|
||||||
|
};
|
||||||
|
this.data.identities.push(identity);
|
||||||
|
return identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateIdentity(identityId: string, updates: { name?: string; replyTo?: EmailAddress[] | null; bcc?: EmailAddress[] | null; htmlSignature?: string; textSignature?: string }): Promise<void> {
|
||||||
|
const identity = this.data.identities.find(i => i.id === identityId);
|
||||||
|
if (identity) Object.assign(identity, updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteIdentity(identityId: string): Promise<void> {
|
||||||
|
this.data.identities = this.data.identities.filter(i => i.id !== identityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Vacation ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getVacationResponse(): Promise<VacationResponse> { return { ...this.data.vacationResponse }; }
|
||||||
|
|
||||||
|
async setVacationResponse(updates: Partial<VacationResponse>): Promise<void> {
|
||||||
|
Object.assign(this.data.vacationResponse, updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Contacts ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
getContactsAccountId(): string { return 'demo-account'; }
|
||||||
|
|
||||||
|
async getAddressBooks(): Promise<AddressBook[]> { return [...this.data.addressBooks]; }
|
||||||
|
async getAllAddressBooks(): Promise<AddressBook[]> { return [...this.data.addressBooks]; }
|
||||||
|
|
||||||
|
async getContacts(addressBookId?: string): Promise<ContactCard[]> {
|
||||||
|
if (addressBookId) return this.data.contacts.filter(c => c.addressBookIds[addressBookId]);
|
||||||
|
return [...this.data.contacts];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllContacts(): Promise<ContactCard[]> { return [...this.data.contacts]; }
|
||||||
|
|
||||||
|
async getContact(contactId: string): Promise<ContactCard | null> {
|
||||||
|
return this.data.contacts.find(c => c.id === contactId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async createContact(contact: Partial<ContactCard>): Promise<ContactCard> {
|
||||||
|
const full: ContactCard = {
|
||||||
|
id: generateDemoId('contact'),
|
||||||
|
addressBookIds: contact.addressBookIds ?? { 'demo-addressbook-personal': true },
|
||||||
|
...contact,
|
||||||
|
} as ContactCard;
|
||||||
|
this.data.contacts.push(full);
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateContact(contactId: string, updates: Partial<ContactCard>): Promise<void> {
|
||||||
|
const contact = this.data.contacts.find(c => c.id === contactId);
|
||||||
|
if (contact) Object.assign(contact, updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteContact(contactId: string): Promise<void> {
|
||||||
|
this.data.contacts = this.data.contacts.filter(c => c.id !== contactId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async searchContacts(query: string): Promise<ContactCard[]> {
|
||||||
|
const q = query.toLowerCase();
|
||||||
|
return this.data.contacts.filter(c => {
|
||||||
|
const nameStr = c.name?.components?.map(nc => nc.value).join(' ').toLowerCase() ?? '';
|
||||||
|
const emailStr = Object.values(c.emails ?? {}).map(e => e.address).join(' ').toLowerCase();
|
||||||
|
return nameStr.includes(q) || emailStr.includes(q);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Calendars ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
getCalendarsAccountId(): string { return 'demo-account'; }
|
||||||
|
|
||||||
|
async getCalendars(): Promise<Calendar[]> { return [...this.data.calendars]; }
|
||||||
|
async getAllCalendars(): Promise<Calendar[]> { return [...this.data.calendars]; }
|
||||||
|
|
||||||
|
async createCalendar(calendar: Partial<Calendar>): Promise<Calendar> {
|
||||||
|
const full: Calendar = {
|
||||||
|
id: generateDemoId('calendar'),
|
||||||
|
name: calendar.name ?? 'New Calendar',
|
||||||
|
description: calendar.description ?? null,
|
||||||
|
color: calendar.color ?? '#6366f1',
|
||||||
|
sortOrder: calendar.sortOrder ?? 99,
|
||||||
|
isSubscribed: true, isVisible: true, isDefault: false,
|
||||||
|
includeInAvailability: 'all',
|
||||||
|
defaultAlertsWithTime: null, defaultAlertsWithoutTime: null,
|
||||||
|
timeZone: null, shareWith: null,
|
||||||
|
myRights: { mayReadFreeBusy: true, mayReadItems: true, mayWriteAll: true, mayWriteOwn: true, mayUpdatePrivate: true, mayRSVP: true, mayAdmin: true, mayDelete: true },
|
||||||
|
...calendar,
|
||||||
|
} as Calendar;
|
||||||
|
this.data.calendars.push(full);
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateCalendar(calendarId: string, updates: Partial<Calendar>): Promise<void> {
|
||||||
|
const cal = this.data.calendars.find(c => c.id === calendarId);
|
||||||
|
if (cal) Object.assign(cal, updates);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteCalendar(calendarId: string): Promise<void> {
|
||||||
|
this.data.calendars = this.data.calendars.filter(c => c.id !== calendarId);
|
||||||
|
this.data.calendarEvents = this.data.calendarEvents.filter(e => !e.calendarIds[calendarId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCalendarEvents(calendarIds?: string[]): Promise<CalendarEvent[]> {
|
||||||
|
let events = [...this.data.calendarEvents];
|
||||||
|
if (calendarIds?.length) {
|
||||||
|
events = events.filter(e => calendarIds.some(cid => e.calendarIds[cid]));
|
||||||
|
}
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCalendarEvent(id: string): Promise<CalendarEvent | null> {
|
||||||
|
return this.data.calendarEvents.find(e => e.id === id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async createCalendarEvent(event: Partial<CalendarEvent>): Promise<CalendarEvent> {
|
||||||
|
const full: CalendarEvent = {
|
||||||
|
id: generateDemoId('event'),
|
||||||
|
calendarIds: event.calendarIds ?? { 'demo-calendar-personal': true },
|
||||||
|
'@type': 'Event',
|
||||||
|
uid: generateDemoId('uid'),
|
||||||
|
title: event.title ?? 'New Event',
|
||||||
|
description: event.description ?? '',
|
||||||
|
descriptionContentType: 'text/plain',
|
||||||
|
isDraft: false, isOrigin: true,
|
||||||
|
created: new Date().toISOString(),
|
||||||
|
updated: new Date().toISOString(),
|
||||||
|
sequence: 0,
|
||||||
|
start: event.start ?? new Date().toISOString(),
|
||||||
|
duration: event.duration ?? 'PT1H',
|
||||||
|
timeZone: event.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
utcStart: event.utcStart ?? null,
|
||||||
|
utcEnd: event.utcEnd ?? null,
|
||||||
|
showWithoutTime: event.showWithoutTime ?? false,
|
||||||
|
status: 'confirmed', freeBusyStatus: 'busy', privacy: 'public',
|
||||||
|
color: null, keywords: null, categories: null, locale: null,
|
||||||
|
replyTo: null, organizerCalendarAddress: null, participants: null,
|
||||||
|
mayInviteSelf: false, mayInviteOthers: false, hideAttendees: false,
|
||||||
|
recurrenceId: null, recurrenceIdTimeZone: null, recurrenceRules: null,
|
||||||
|
recurrenceOverrides: null, excludedRecurrenceRules: null,
|
||||||
|
useDefaultAlerts: true, alerts: null, locations: null,
|
||||||
|
virtualLocations: null, links: null, relatedTo: null,
|
||||||
|
...event,
|
||||||
|
} as CalendarEvent;
|
||||||
|
this.data.calendarEvents.push(full);
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateCalendarEvent(eventId: string, updates: Partial<CalendarEvent>): Promise<void> {
|
||||||
|
const event = this.data.calendarEvents.find(e => e.id === eventId);
|
||||||
|
if (!event) throw new Error('Event not found');
|
||||||
|
Object.assign(event, updates, { updated: new Date().toISOString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteCalendarEvent(eventId: string): Promise<void> {
|
||||||
|
this.data.calendarEvents = this.data.calendarEvents.filter(e => e.id !== eventId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async batchDeleteCalendarEvents(eventIds: string[]): Promise<{ destroyed: string[]; notDestroyed: string[] }> {
|
||||||
|
const idSet = new Set(eventIds);
|
||||||
|
this.data.calendarEvents = this.data.calendarEvents.filter(e => !idSet.has(e.id));
|
||||||
|
return { destroyed: eventIds, notDestroyed: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
async queryCalendarEvents(filter: CalendarEventFilter): Promise<CalendarEvent[]> {
|
||||||
|
return this.data.calendarEvents.filter(e => {
|
||||||
|
if (filter.after && e.start < filter.after) return false;
|
||||||
|
if (filter.before && e.start > filter.before) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async queryAllCalendarEvents(filter: CalendarEventFilter): Promise<CalendarEvent[]> {
|
||||||
|
return this.queryCalendarEvents(filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
async parseCalendarEvents(): Promise<Partial<CalendarEvent>[]> {
|
||||||
|
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'; }
|
||||||
|
|
||||||
|
getSieveCapabilities(): SieveCapabilities | null {
|
||||||
|
return { ...this.data.sieveCapabilities };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSieveScripts(): Promise<SieveScript[]> { return [...this.data.sieveScripts]; }
|
||||||
|
|
||||||
|
async getSieveScriptContent(blobId: string): Promise<string> {
|
||||||
|
return this.data.sieveContent[blobId] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async createSieveScript(name: string, content: string, activate?: boolean): Promise<SieveScript> {
|
||||||
|
const blobId = generateDemoId('sieve-blob');
|
||||||
|
const script: SieveScript = { id: generateDemoId('sieve'), name, blobId, isActive: activate ?? false };
|
||||||
|
this.data.sieveScripts.push(script);
|
||||||
|
this.data.sieveContent[blobId] = content;
|
||||||
|
if (activate) {
|
||||||
|
for (const s of this.data.sieveScripts) {
|
||||||
|
if (s.id !== script.id) s.isActive = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return script;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateSieveScript(scriptId: string, content: string, activate?: boolean): Promise<void> {
|
||||||
|
const script = this.data.sieveScripts.find(s => s.id === scriptId);
|
||||||
|
if (!script) return;
|
||||||
|
const blobId = generateDemoId('sieve-blob');
|
||||||
|
this.data.sieveContent[blobId] = content;
|
||||||
|
script.blobId = blobId;
|
||||||
|
if (activate !== undefined) {
|
||||||
|
script.isActive = activate;
|
||||||
|
if (activate) {
|
||||||
|
for (const s of this.data.sieveScripts) {
|
||||||
|
if (s.id !== scriptId) s.isActive = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteSieveScript(scriptId: string): Promise<void> {
|
||||||
|
this.data.sieveScripts = this.data.sieveScripts.filter(s => s.id !== scriptId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async validateSieveScript(): Promise<{ isValid: boolean; errors?: string[] }> {
|
||||||
|
return { isValid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Files (FileNode) ─────────────────────────────────────────
|
||||||
|
|
||||||
|
getFilesAccountId(): string { return 'demo-account'; }
|
||||||
|
|
||||||
|
async probeFileNodeSupport(): Promise<boolean> { return true; }
|
||||||
|
|
||||||
|
async listFileNodes(parentId: string | null): Promise<FileNode[]> {
|
||||||
|
return this.data.fileNodes.filter(n => n.parentId === parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFileNodes(ids: string[] | null): Promise<FileNode[]> {
|
||||||
|
if (ids === null) return [...this.data.fileNodes];
|
||||||
|
return this.data.fileNodes.filter(n => ids.includes(n.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async createFileDirectory(name: string, parentId: string | null): Promise<FileNode> {
|
||||||
|
const node: FileNode = {
|
||||||
|
id: generateDemoId('file'),
|
||||||
|
parentId, name, type: 'd', blobId: null, size: 0,
|
||||||
|
created: new Date().toISOString(), updated: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
this.data.fileNodes.push(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
async createFileNode(name: string, blobId: string, type: string, size: number, parentId: string | null): Promise<FileNode> {
|
||||||
|
const node: FileNode = {
|
||||||
|
id: generateDemoId('file'),
|
||||||
|
parentId, name, type, blobId, size,
|
||||||
|
created: new Date().toISOString(), updated: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
this.data.fileNodes.push(node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateFileNode(id: string, updates: Partial<Pick<FileNode, 'name' | 'parentId'>>): Promise<void> {
|
||||||
|
const node = this.data.fileNodes.find(n => n.id === id);
|
||||||
|
if (node) Object.assign(node, updates, { updated: new Date().toISOString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
async destroyFileNodes(ids: string[]): Promise<{ destroyed: string[]; notDestroyed: string[] }> {
|
||||||
|
const idSet = new Set(ids);
|
||||||
|
this.data.fileNodes = this.data.fileNodes.filter(n => !idSet.has(n.id));
|
||||||
|
return { destroyed: ids, notDestroyed: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
async copyFileNode(id: string, newName: string, parentId: string | null): Promise<FileNode> {
|
||||||
|
const original = this.data.fileNodes.find(n => n.id === id);
|
||||||
|
if (!original) throw new Error('File node not found');
|
||||||
|
return this.createFileNode(newName, original.blobId ?? '', original.type, original.size, parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── S/MIME raw-email helpers ──────────────────────────────────
|
||||||
|
|
||||||
|
async importRawEmail(): Promise<string> { return generateDemoId('email'); }
|
||||||
|
async submitEmail(): Promise<void> { /* no-op */ }
|
||||||
|
async sendRawEmail(): Promise<void> { /* no-op */ }
|
||||||
|
|
||||||
|
// ── Internal helpers ──────────────────────────────────────────
|
||||||
|
|
||||||
|
private recalcMailboxCounts(): void {
|
||||||
|
for (const mb of this.data.mailboxes) {
|
||||||
|
const inMb = this.data.emails.filter(e => e.mailboxIds[mb.id]);
|
||||||
|
mb.totalEmails = inMb.length;
|
||||||
|
mb.unreadEmails = inMb.filter(e => !e.keywords.$seen).length;
|
||||||
|
mb.totalThreads = new Set(inMb.map(e => e.threadId)).size;
|
||||||
|
mb.unreadThreads = new Set(inMb.filter(e => !e.keywords.$seen).map(e => e.threadId)).size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startIncomingEmailTimer(): void {
|
||||||
|
this.stopIncomingEmailTimer();
|
||||||
|
|
||||||
|
const scheduleNext = () => {
|
||||||
|
const delay = 60_000 + Math.random() * 60_000; // 60-120 seconds
|
||||||
|
this.incomingTimer = setTimeout(() => {
|
||||||
|
this.simulateIncomingEmail();
|
||||||
|
scheduleNext();
|
||||||
|
}, delay);
|
||||||
|
};
|
||||||
|
scheduleNext();
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopIncomingEmailTimer(): void {
|
||||||
|
if (this.incomingTimer) {
|
||||||
|
clearTimeout(this.incomingTimer);
|
||||||
|
this.incomingTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private simulateIncomingEmail(): void {
|
||||||
|
const senders = [
|
||||||
|
{ name: 'Alice Johnson', email: 'alice.johnson@example.com' },
|
||||||
|
{ name: 'Bob Chen', email: 'bob.chen@example.com' },
|
||||||
|
{ name: 'Sarah Kim', email: 'sarah.kim@example.com' },
|
||||||
|
{ name: 'Carlos Rivera', email: 'carlos.rivera@example.com' },
|
||||||
|
];
|
||||||
|
const subjects = [
|
||||||
|
'Quick question about the project',
|
||||||
|
'Meeting rescheduled to tomorrow',
|
||||||
|
'FYI: Updated documentation',
|
||||||
|
'Can you review this PR?',
|
||||||
|
'Lunch today?',
|
||||||
|
'Important: deadline reminder',
|
||||||
|
];
|
||||||
|
|
||||||
|
const sender = senders[Math.floor(Math.random() * senders.length)];
|
||||||
|
const subject = subjects[Math.floor(Math.random() * subjects.length)];
|
||||||
|
const id = generateDemoId('email');
|
||||||
|
|
||||||
|
const email: Email = {
|
||||||
|
id, threadId: generateDemoId('thread'),
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 1800,
|
||||||
|
receivedAt: new Date().toISOString(),
|
||||||
|
from: [sender],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject, sentAt: new Date().toISOString(),
|
||||||
|
preview: `Hi, ${subject.toLowerCase()}. Let me know what you think.`,
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: generateDemoId('blob'), size: 120, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: `Hi,\n\n${subject}. Let me know what you think.\n\nBest,\n${sender.name}` },
|
||||||
|
},
|
||||||
|
messageId: `<${id}@demo.example.com>`,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.data.emails.unshift(email);
|
||||||
|
this.recalcMailboxCounts();
|
||||||
|
|
||||||
|
// Notify state change to trigger UI refresh
|
||||||
|
this.stateChangeCallback?.({
|
||||||
|
'@type': 'StateChange',
|
||||||
|
changed: { 'demo-account': { Email: generateDemoId('state'), Mailbox: generateDemoId('state') } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { cloneFixtures } from './demo-utils';
|
||||||
|
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, CalendarTask, Identity, VacationResponse, FileNode } from '@/lib/jmap/types';
|
||||||
|
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
|
||||||
|
|
||||||
|
export interface DemoData {
|
||||||
|
mailboxes: Mailbox[];
|
||||||
|
emails: Email[];
|
||||||
|
contacts: ContactCard[];
|
||||||
|
addressBooks: AddressBook[];
|
||||||
|
calendars: Calendar[];
|
||||||
|
calendarEvents: CalendarEvent[];
|
||||||
|
calendarTasks: CalendarTask[];
|
||||||
|
identities: Identity[];
|
||||||
|
sieveScripts: SieveScript[];
|
||||||
|
sieveCapabilities: SieveCapabilities;
|
||||||
|
sieveContent: Record<string, string>;
|
||||||
|
fileNodes: FileNode[];
|
||||||
|
vacationResponse: VacationResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Return a fresh deep-cloned copy of all demo data. */
|
||||||
|
export function getDemoData(): DemoData {
|
||||||
|
return cloneFixtures({
|
||||||
|
mailboxes: createDemoMailboxes(),
|
||||||
|
emails: createDemoEmails(),
|
||||||
|
contacts: createDemoContacts(),
|
||||||
|
addressBooks: createDemoAddressBooks(),
|
||||||
|
calendars: createDemoCalendars(),
|
||||||
|
calendarEvents: createDemoCalendarEvents(),
|
||||||
|
calendarTasks: createDemoCalendarTasks(),
|
||||||
|
identities: createDemoIdentities(),
|
||||||
|
sieveScripts: createDemoSieveScripts(),
|
||||||
|
sieveCapabilities: createDemoSieveCapabilities(),
|
||||||
|
sieveContent: createDemoSieveContent(),
|
||||||
|
fileNodes: createDemoFileNodes(),
|
||||||
|
vacationResponse: createDemoVacationResponse(),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
let demoIdCounter = 0;
|
||||||
|
|
||||||
|
/** Generate a unique demo ID with the given prefix. */
|
||||||
|
export function generateDemoId(prefix: string = 'demo'): string {
|
||||||
|
return `${prefix}-${Date.now()}-${++demoIdCounter}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate an ISO date string relative to "now".
|
||||||
|
* @param daysOffset — whole days from today
|
||||||
|
* @param hoursOffset — additional hours offset (default 0)
|
||||||
|
* @param minutesOffset — additional minutes offset (default 0)
|
||||||
|
*/
|
||||||
|
export function demoDate(daysOffset: number, hoursOffset: number = 0, minutesOffset: number = 0): string {
|
||||||
|
const d = new Date();
|
||||||
|
d.setDate(d.getDate() + daysOffset);
|
||||||
|
d.setHours(d.getHours() + hoursOffset, d.getMinutes() + minutesOffset, 0, 0);
|
||||||
|
return d.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a local date-time string (YYYY-MM-DDTHH:mm:ss) for JSCalendar "start" fields.
|
||||||
|
*/
|
||||||
|
export function demoISODate(daysOffset: number, hours: number = 0, minutes: number = 0): string {
|
||||||
|
const d = new Date();
|
||||||
|
d.setDate(d.getDate() + daysOffset);
|
||||||
|
d.setHours(hours, minutes, 0, 0);
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:00`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deep clone fixture data so in-memory mutations don't corrupt originals. */
|
||||||
|
export function cloneFixtures<T>(data: T): T {
|
||||||
|
return JSON.parse(JSON.stringify(data));
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
import type { Calendar, CalendarEvent } from '@/lib/jmap/types';
|
||||||
|
import { demoDate, demoISODate } from '../demo-utils';
|
||||||
|
|
||||||
|
export function createDemoCalendars(): Calendar[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'demo-calendar-personal',
|
||||||
|
name: 'Personal',
|
||||||
|
description: null,
|
||||||
|
color: '#3b82f6',
|
||||||
|
sortOrder: 1,
|
||||||
|
isSubscribed: true,
|
||||||
|
isVisible: true,
|
||||||
|
isDefault: true,
|
||||||
|
includeInAvailability: 'all',
|
||||||
|
defaultAlertsWithTime: null,
|
||||||
|
defaultAlertsWithoutTime: null,
|
||||||
|
timeZone: null,
|
||||||
|
shareWith: null,
|
||||||
|
myRights: { mayReadFreeBusy: true, mayReadItems: true, mayWriteAll: true, mayWriteOwn: true, mayUpdatePrivate: true, mayRSVP: true, mayAdmin: true, mayDelete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-calendar-work',
|
||||||
|
name: 'Work',
|
||||||
|
description: null,
|
||||||
|
color: '#22c55e',
|
||||||
|
sortOrder: 2,
|
||||||
|
isSubscribed: true,
|
||||||
|
isVisible: true,
|
||||||
|
isDefault: false,
|
||||||
|
includeInAvailability: 'all',
|
||||||
|
defaultAlertsWithTime: null,
|
||||||
|
defaultAlertsWithoutTime: null,
|
||||||
|
timeZone: null,
|
||||||
|
shareWith: null,
|
||||||
|
myRights: { mayReadFreeBusy: true, mayReadItems: true, mayWriteAll: true, mayWriteOwn: true, mayUpdatePrivate: true, mayRSVP: true, mayAdmin: true, mayDelete: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-calendar-birthdays',
|
||||||
|
name: 'Birthdays',
|
||||||
|
description: null,
|
||||||
|
color: '#eab308',
|
||||||
|
sortOrder: 3,
|
||||||
|
isSubscribed: true,
|
||||||
|
isVisible: true,
|
||||||
|
isDefault: false,
|
||||||
|
includeInAvailability: 'none',
|
||||||
|
defaultAlertsWithTime: null,
|
||||||
|
defaultAlertsWithoutTime: null,
|
||||||
|
timeZone: null,
|
||||||
|
shareWith: null,
|
||||||
|
myRights: { mayReadFreeBusy: true, mayReadItems: true, mayWriteAll: true, mayWriteOwn: true, mayUpdatePrivate: true, mayRSVP: true, mayAdmin: true, mayDelete: true },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDemoCalendarEvents(): CalendarEvent[] {
|
||||||
|
const baseEvent = {
|
||||||
|
'@type': 'Event' as const,
|
||||||
|
descriptionContentType: 'text/plain',
|
||||||
|
isDraft: false,
|
||||||
|
isOrigin: true,
|
||||||
|
sequence: 0,
|
||||||
|
status: 'confirmed' as const,
|
||||||
|
freeBusyStatus: 'busy' as const,
|
||||||
|
privacy: 'public' as const,
|
||||||
|
color: null,
|
||||||
|
keywords: null,
|
||||||
|
categories: null,
|
||||||
|
locale: null,
|
||||||
|
replyTo: null,
|
||||||
|
organizerCalendarAddress: null,
|
||||||
|
participants: null,
|
||||||
|
mayInviteSelf: false,
|
||||||
|
mayInviteOthers: false,
|
||||||
|
hideAttendees: false,
|
||||||
|
recurrenceId: null,
|
||||||
|
recurrenceIdTimeZone: null,
|
||||||
|
recurrenceRules: null,
|
||||||
|
recurrenceOverrides: null,
|
||||||
|
excludedRecurrenceRules: null,
|
||||||
|
useDefaultAlerts: true,
|
||||||
|
alerts: null,
|
||||||
|
locations: null,
|
||||||
|
virtualLocations: null,
|
||||||
|
links: null,
|
||||||
|
relatedTo: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return [
|
||||||
|
// ── Personal calendar ──────────────────────────────────────
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-1',
|
||||||
|
calendarIds: { 'demo-calendar-personal': true },
|
||||||
|
uid: 'demo-event-1@example.com',
|
||||||
|
title: 'Dentist Appointment',
|
||||||
|
description: 'Regular checkup at Dr. Smith\'s office',
|
||||||
|
created: demoDate(-7),
|
||||||
|
updated: demoDate(-7),
|
||||||
|
start: demoISODate(2, 10, 0),
|
||||||
|
utcStart: demoDate(2, 10),
|
||||||
|
utcEnd: demoDate(2, 11),
|
||||||
|
duration: 'PT1H',
|
||||||
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
showWithoutTime: false,
|
||||||
|
locations: { loc1: { '@type': 'Location', name: 'Dr. Smith Dental Clinic', description: '123 Medical Plaza', locationTypes: null, coordinates: null, timeZone: null, links: null, relativeTo: null } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-2',
|
||||||
|
calendarIds: { 'demo-calendar-personal': true },
|
||||||
|
uid: 'demo-event-2@example.com',
|
||||||
|
title: 'Birthday Party',
|
||||||
|
description: 'Emma\'s birthday celebration',
|
||||||
|
created: demoDate(-10),
|
||||||
|
updated: demoDate(-10),
|
||||||
|
start: demoISODate(5),
|
||||||
|
utcStart: demoDate(5),
|
||||||
|
utcEnd: demoDate(6),
|
||||||
|
duration: 'P1D',
|
||||||
|
timeZone: null,
|
||||||
|
showWithoutTime: true,
|
||||||
|
freeBusyStatus: 'free' as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-3',
|
||||||
|
calendarIds: { 'demo-calendar-personal': true },
|
||||||
|
uid: 'demo-event-3@example.com',
|
||||||
|
title: 'Weekend Trip',
|
||||||
|
description: 'Road trip to the mountains',
|
||||||
|
created: demoDate(-5),
|
||||||
|
updated: demoDate(-5),
|
||||||
|
start: demoISODate(8),
|
||||||
|
utcStart: demoDate(8),
|
||||||
|
utcEnd: demoDate(10),
|
||||||
|
duration: 'P2D',
|
||||||
|
timeZone: null,
|
||||||
|
showWithoutTime: true,
|
||||||
|
freeBusyStatus: 'busy' as const,
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Work calendar ──────────────────────────────────────────
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-4',
|
||||||
|
calendarIds: { 'demo-calendar-work': true },
|
||||||
|
uid: 'demo-event-4@example.com',
|
||||||
|
title: 'Weekly Standup',
|
||||||
|
description: 'Team sync-up meeting',
|
||||||
|
created: demoDate(-30),
|
||||||
|
updated: demoDate(-1),
|
||||||
|
start: demoISODate(1, 9, 30),
|
||||||
|
utcStart: demoDate(1, 9, 30),
|
||||||
|
utcEnd: demoDate(1, 10, 0),
|
||||||
|
duration: 'PT30M',
|
||||||
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
showWithoutTime: false,
|
||||||
|
recurrenceRules: [{
|
||||||
|
'@type': 'RecurrenceRule',
|
||||||
|
frequency: 'weekly',
|
||||||
|
interval: 1,
|
||||||
|
rscale: 'gregorian',
|
||||||
|
skip: 'omit',
|
||||||
|
firstDayOfWeek: 'mo',
|
||||||
|
byDay: [{ day: 'mo' }],
|
||||||
|
byMonthDay: null,
|
||||||
|
byMonth: null,
|
||||||
|
byYearDay: null,
|
||||||
|
byWeekNo: null,
|
||||||
|
byHour: null,
|
||||||
|
byMinute: null,
|
||||||
|
bySecond: null,
|
||||||
|
bySetPosition: null,
|
||||||
|
count: null,
|
||||||
|
until: null,
|
||||||
|
}],
|
||||||
|
virtualLocations: { vl1: { '@type': 'VirtualLocation', name: 'Zoom', uri: 'https://zoom.example/123456', description: 'Weekly standup room', features: null } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-5',
|
||||||
|
calendarIds: { 'demo-calendar-work': true },
|
||||||
|
uid: 'demo-event-5@example.com',
|
||||||
|
title: 'Quarterly Review',
|
||||||
|
description: 'Q4 performance review and planning session',
|
||||||
|
created: demoDate(-14),
|
||||||
|
updated: demoDate(-3),
|
||||||
|
start: demoISODate(4, 14, 0),
|
||||||
|
utcStart: demoDate(4, 14),
|
||||||
|
utcEnd: demoDate(4, 16),
|
||||||
|
duration: 'PT2H',
|
||||||
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
showWithoutTime: false,
|
||||||
|
participants: {
|
||||||
|
p1: {
|
||||||
|
'@type': 'Participant', name: 'Demo User', email: 'demo@example.com', calendarAddress: null, description: null, sendTo: null,
|
||||||
|
kind: 'individual', roles: { attendee: true }, participationStatus: 'accepted', participationComment: null,
|
||||||
|
expectReply: false, scheduleAgent: 'server', scheduleForceSend: false, scheduleId: null, scheduleSequence: 0,
|
||||||
|
scheduleStatus: null, scheduleUpdated: null, invitedBy: null, delegatedTo: null, delegatedFrom: null, memberOf: null,
|
||||||
|
locationId: null, language: null, links: null,
|
||||||
|
},
|
||||||
|
p2: {
|
||||||
|
'@type': 'Participant', name: 'Alice Johnson', email: 'alice.johnson@example.com', calendarAddress: null, description: null, sendTo: null,
|
||||||
|
kind: 'individual', roles: { owner: true }, participationStatus: 'accepted', participationComment: null,
|
||||||
|
expectReply: false, scheduleAgent: 'server', scheduleForceSend: false, scheduleId: null, scheduleSequence: 0,
|
||||||
|
scheduleStatus: null, scheduleUpdated: null, invitedBy: null, delegatedTo: null, delegatedFrom: null, memberOf: null,
|
||||||
|
locationId: null, language: null, links: null,
|
||||||
|
},
|
||||||
|
p3: {
|
||||||
|
'@type': 'Participant', name: 'Bob Chen', email: 'bob.chen@example.com', calendarAddress: null, description: null, sendTo: null,
|
||||||
|
kind: 'individual', roles: { attendee: true }, participationStatus: 'tentative', participationComment: null,
|
||||||
|
expectReply: true, scheduleAgent: 'server', scheduleForceSend: false, scheduleId: null, scheduleSequence: 0,
|
||||||
|
scheduleStatus: null, scheduleUpdated: null, invitedBy: null, delegatedTo: null, delegatedFrom: null, memberOf: null,
|
||||||
|
locationId: null, language: null, links: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-6',
|
||||||
|
calendarIds: { 'demo-calendar-work': true },
|
||||||
|
uid: 'demo-event-6@example.com',
|
||||||
|
title: 'Lunch Meeting with Sarah',
|
||||||
|
description: 'Design review over lunch',
|
||||||
|
created: demoDate(-3),
|
||||||
|
updated: demoDate(-3),
|
||||||
|
start: demoISODate(3, 12, 0),
|
||||||
|
utcStart: demoDate(3, 12),
|
||||||
|
utcEnd: demoDate(3, 13),
|
||||||
|
duration: 'PT1H',
|
||||||
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
showWithoutTime: false,
|
||||||
|
locations: { loc1: { '@type': 'Location', name: 'The Garden Bistro', description: '123 Oak Street', locationTypes: null, coordinates: null, timeZone: null, links: null, relativeTo: null } },
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Birthdays calendar ─────────────────────────────────────
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-7',
|
||||||
|
calendarIds: { 'demo-calendar-birthdays': true },
|
||||||
|
uid: 'demo-event-7@example.com',
|
||||||
|
title: 'Alice Johnson\'s Birthday',
|
||||||
|
description: '',
|
||||||
|
created: demoDate(-30),
|
||||||
|
updated: demoDate(-30),
|
||||||
|
start: demoISODate(12),
|
||||||
|
utcStart: demoDate(12),
|
||||||
|
utcEnd: demoDate(13),
|
||||||
|
duration: 'P1D',
|
||||||
|
timeZone: null,
|
||||||
|
showWithoutTime: true,
|
||||||
|
freeBusyStatus: 'free' as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...baseEvent,
|
||||||
|
id: 'demo-event-8',
|
||||||
|
calendarIds: { 'demo-calendar-birthdays': true },
|
||||||
|
uid: 'demo-event-8@example.com',
|
||||||
|
title: 'Carlos Rivera\'s Birthday',
|
||||||
|
description: '',
|
||||||
|
created: demoDate(-30),
|
||||||
|
updated: demoDate(-30),
|
||||||
|
start: demoISODate(-3),
|
||||||
|
utcStart: demoDate(-3),
|
||||||
|
utcEnd: demoDate(-2),
|
||||||
|
duration: 'P1D',
|
||||||
|
timeZone: null,
|
||||||
|
showWithoutTime: true,
|
||||||
|
freeBusyStatus: 'free' as const,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import type { ContactCard, AddressBook } from '@/lib/jmap/types';
|
||||||
|
|
||||||
|
export function createDemoAddressBooks(): AddressBook[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'demo-addressbook-personal',
|
||||||
|
name: 'Personal',
|
||||||
|
isDefault: true,
|
||||||
|
isSubscribed: true,
|
||||||
|
sortOrder: 1,
|
||||||
|
myRights: { mayRead: true, mayWrite: true, mayShare: true, mayDelete: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-addressbook-work',
|
||||||
|
name: 'Work',
|
||||||
|
isDefault: false,
|
||||||
|
isSubscribed: true,
|
||||||
|
sortOrder: 2,
|
||||||
|
myRights: { mayRead: true, mayWrite: true, mayShare: true, mayDelete: true },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDemoContacts(): ContactCard[] {
|
||||||
|
return [
|
||||||
|
// ── Personal address book ──────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-contact-1',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Alice' }, { kind: 'surname', value: 'Johnson' }] },
|
||||||
|
emails: { e1: { address: 'alice.johnson@example.com', contexts: { work: true }, pref: 1 } },
|
||||||
|
phones: { p1: { number: '+1-555-0101', features: { voice: true }, contexts: { work: true } } },
|
||||||
|
organizations: { o1: { name: 'Acme Corp', units: [{ name: 'Engineering' }] } },
|
||||||
|
titles: { t1: { name: 'Senior Engineer', kind: 'title' } },
|
||||||
|
anniversaries: { a1: { kind: 'birth', date: { year: 1990, month: 3, day: 15 } } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-2',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Bob' }, { kind: 'surname', value: 'Chen' }] },
|
||||||
|
emails: {
|
||||||
|
e1: { address: 'bob.chen@example.com', contexts: { work: true }, pref: 1 },
|
||||||
|
e2: { address: 'bob.personal@email.example', contexts: { private: true } },
|
||||||
|
},
|
||||||
|
phones: {
|
||||||
|
p1: { number: '+1-555-0102', features: { voice: true }, contexts: { work: true } },
|
||||||
|
p2: { number: '+1-555-0103', features: { cell: true }, contexts: { private: true } },
|
||||||
|
},
|
||||||
|
organizations: { o1: { name: 'Acme Corp', units: [{ name: 'Backend Team' }] } },
|
||||||
|
titles: { t1: { name: 'Staff Engineer', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-3',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Sarah' }, { kind: 'surname', value: 'Kim' }] },
|
||||||
|
emails: { e1: { address: 'sarah.kim@example.com', pref: 1 } },
|
||||||
|
phones: { p1: { number: '+1-555-0104', features: { voice: true } } },
|
||||||
|
organizations: { o1: { name: 'DesignCo' } },
|
||||||
|
titles: { t1: { name: 'UX Designer', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-4',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Carlos' }, { kind: 'surname', value: 'Rivera' }] },
|
||||||
|
emails: { e1: { address: 'carlos.rivera@example.com', pref: 1 } },
|
||||||
|
phones: { p1: { number: '+1-555-0105', features: { cell: true } } },
|
||||||
|
notes: { n1: { note: 'Met at the DevConf 2024 conference' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-5',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Emma' }, { kind: 'surname', value: 'Wilson' }] },
|
||||||
|
emails: { e1: { address: 'emma.wilson@example.com', pref: 1 } },
|
||||||
|
addresses: {
|
||||||
|
a1: {
|
||||||
|
components: [
|
||||||
|
{ kind: 'number', value: '456' },
|
||||||
|
{ kind: 'name', value: 'Elm Street' },
|
||||||
|
{ kind: 'locality', value: 'Springfield' },
|
||||||
|
{ kind: 'region', value: 'IL' },
|
||||||
|
{ kind: 'postcode', value: '62701' },
|
||||||
|
],
|
||||||
|
contexts: { private: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
anniversaries: { a1: { kind: 'birth', date: { month: 7, day: 22 } } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-6',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'David' }, { kind: 'surname', value: 'Park' }] },
|
||||||
|
emails: { e1: { address: 'david.park@example.com', pref: 1 } },
|
||||||
|
phones: { p1: { number: '+82-10-1234-5678', features: { cell: true } } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-7',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'org',
|
||||||
|
name: { components: [{ kind: 'surname', value: 'Local Coffee Shop' }] },
|
||||||
|
emails: { e1: { address: 'hello@localcoffee.example', pref: 1 } },
|
||||||
|
phones: { p1: { number: '+1-555-0200', features: { voice: true } } },
|
||||||
|
addresses: {
|
||||||
|
a1: {
|
||||||
|
components: [
|
||||||
|
{ kind: 'number', value: '789' },
|
||||||
|
{ kind: 'name', value: 'Main Street' },
|
||||||
|
{ kind: 'locality', value: 'Anytown' },
|
||||||
|
{ kind: 'region', value: 'CA' },
|
||||||
|
{ kind: 'postcode', value: '90210' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-8',
|
||||||
|
addressBookIds: { 'demo-addressbook-personal': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Lisa' }, { kind: 'surname', value: 'Tanaka' }] },
|
||||||
|
emails: { e1: { address: 'lisa.tanaka@example.com', pref: 1 } },
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Work address book ──────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-contact-9',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Michael' }, { kind: 'surname', value: 'Torres' }] },
|
||||||
|
emails: { e1: { address: 'michael.torres@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
phones: { p1: { number: '+1-555-0301', features: { voice: true }, contexts: { work: true } } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Product' }] } },
|
||||||
|
titles: { t1: { name: 'Product Manager', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-10',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Rachel' }, { kind: 'surname', value: 'Green' }] },
|
||||||
|
emails: { e1: { address: 'rachel.green@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Marketing' }] } },
|
||||||
|
titles: { t1: { name: 'Marketing Lead', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-11',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'James' }, { kind: 'surname', value: 'Miller' }] },
|
||||||
|
emails: { e1: { address: 'james.miller@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Engineering' }] } },
|
||||||
|
titles: { t1: { name: 'CTO', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-12',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Priya' }, { kind: 'surname', value: 'Sharma' }] },
|
||||||
|
emails: { e1: { address: 'priya.sharma@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'QA' }] } },
|
||||||
|
titles: { t1: { name: 'QA Engineer', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-13',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Ahmed' }, { kind: 'surname', value: 'Hassan' }] },
|
||||||
|
emails: { e1: { address: 'ahmed.hassan@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'DevOps' }] } },
|
||||||
|
titles: { t1: { name: 'DevOps Engineer', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-14',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Maria' }, { kind: 'surname', value: 'Lopez' }] },
|
||||||
|
emails: { e1: { address: 'maria.lopez@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'HR' }] } },
|
||||||
|
titles: { t1: { name: 'HR Business Partner', kind: 'title' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-contact-15',
|
||||||
|
addressBookIds: { 'demo-addressbook-work': true },
|
||||||
|
kind: 'individual',
|
||||||
|
name: { components: [{ kind: 'given', value: 'Wei' }, { kind: 'surname', value: 'Zhang' }] },
|
||||||
|
emails: { e1: { address: 'wei.zhang@company.example', contexts: { work: true }, pref: 1 } },
|
||||||
|
organizations: { o1: { name: 'Company Inc', units: [{ name: 'Data Science' }] } },
|
||||||
|
titles: { t1: { name: 'Data Scientist', kind: 'title' } },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
import type { Email } from '@/lib/jmap/types';
|
||||||
|
import { demoDate } from '../demo-utils';
|
||||||
|
|
||||||
|
export function createDemoEmails(): Email[] {
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
return [
|
||||||
|
// ── Inbox ───────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-1',
|
||||||
|
threadId: 'demo-thread-1',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 4200,
|
||||||
|
receivedAt: demoDate(0, -2),
|
||||||
|
from: [{ name: 'Bulwark Team', email: 'welcome@bulwark.email' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Welcome to Bulwark Mail!',
|
||||||
|
sentAt: demoDate(0, -2),
|
||||||
|
preview: 'Thanks for trying out Bulwark Mail. This is a demo environment where you can explore all features...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-1', size: 350, type: 'text/plain' }],
|
||||||
|
htmlBody: [{ partId: '2', blobId: 'blob-2', size: 800, type: 'text/html' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Thanks for trying out Bulwark Mail!\n\nThis is a demo environment where you can explore all features without connecting to a real server. All data stays on your device.\n\nFeel free to:\n- Read, compose, and organize emails\n- Manage contacts and calendars\n- Configure filters and settings\n- Try keyboard shortcuts (press ? to see them)\n\nEnjoy exploring!' },
|
||||||
|
'2': { value: '<div><h2>Welcome to Bulwark Mail!</h2><p>Thanks for trying out Bulwark Mail!</p><p>This is a demo environment where you can explore all features without connecting to a real server. <strong>All data stays on your device.</strong></p><p>Feel free to:</p><ul><li>Read, compose, and organize emails</li><li>Manage contacts and calendars</li><li>Configure filters and settings</li><li>Try keyboard shortcuts (press <kbd>?</kbd> to see them)</li></ul><p>Enjoy exploring!</p></div>' },
|
||||||
|
},
|
||||||
|
messageId: '<welcome@demo.bulwark.email>',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-2',
|
||||||
|
threadId: 'demo-thread-2',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 18500,
|
||||||
|
receivedAt: demoDate(-1, -5),
|
||||||
|
from: [{ name: 'TechDigest Weekly', email: 'newsletter@techdigest.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'This Week in Tech: AI Developments & Open Source Updates',
|
||||||
|
sentAt: demoDate(-1, -5),
|
||||||
|
preview: 'Your weekly roundup of the most important technology news and open source developments...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-3', size: 2400, type: 'text/plain' }],
|
||||||
|
htmlBody: [{ partId: '2', blobId: 'blob-4', size: 5200, type: 'text/html' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'This Week in Tech\n\n1. AI-Powered Code Review Tools\nNew tools are making code reviews faster and more thorough...\n\n2. Open Source Licensing Update\nThe OSI has published new guidelines for AI-generated code...\n\n3. WebAssembly 2.0 Draft\nThe W3C has released the first draft of WebAssembly 2.0...\n\nRead more at techdigest.example' },
|
||||||
|
'2': { value: '<div style="max-width:600px;margin:0 auto;"><h1>This Week in Tech</h1><h3>1. AI-Powered Code Review Tools</h3><p>New tools are making code reviews faster and more thorough, with several open-source options gaining traction.</p><h3>2. Open Source Licensing Update</h3><p>The OSI has published new guidelines for AI-generated code contributions to open source projects.</p><h3>3. WebAssembly 2.0 Draft</h3><p>The W3C has released the first draft of WebAssembly 2.0, promising improved memory management.</p></div>' },
|
||||||
|
},
|
||||||
|
messageId: '<weekly-42@techdigest.example>',
|
||||||
|
},
|
||||||
|
// Thread: Project discussion (3 emails in same thread)
|
||||||
|
{
|
||||||
|
id: 'demo-email-3a',
|
||||||
|
threadId: 'demo-thread-3',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 3100,
|
||||||
|
receivedAt: demoDate(-3, -10),
|
||||||
|
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }, { name: 'Bob Chen', email: 'bob.chen@example.com' }],
|
||||||
|
subject: 'Q4 Project Timeline',
|
||||||
|
sentAt: demoDate(-3, -10),
|
||||||
|
preview: 'Hi team, I wanted to share the updated timeline for our Q4 deliverables...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-5', size: 450, type: 'text/plain' }],
|
||||||
|
htmlBody: [{ partId: '2', blobId: 'blob-6', size: 650, type: 'text/html' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hi team,\n\nI wanted to share the updated timeline for our Q4 deliverables:\n\n- Phase 1: Design review — Oct 15\n- Phase 2: Development — Nov 1-30\n- Phase 3: Testing — Dec 1-15\n- Phase 4: Launch — Dec 20\n\nPlease review and let me know if you see any conflicts.\n\nBest,\nAlice' },
|
||||||
|
'2': { value: '<p>Hi team,</p><p>I wanted to share the updated timeline for our Q4 deliverables:</p><ul><li>Phase 1: Design review — Oct 15</li><li>Phase 2: Development — Nov 1-30</li><li>Phase 3: Testing — Dec 1-15</li><li>Phase 4: Launch — Dec 20</li></ul><p>Please review and let me know if you see any conflicts.</p><p>Best,<br>Alice</p>' },
|
||||||
|
},
|
||||||
|
messageId: '<q4-timeline-1@example.com>',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-3b',
|
||||||
|
threadId: 'demo-thread-3',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 3500,
|
||||||
|
receivedAt: demoDate(-2, -8),
|
||||||
|
from: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
|
||||||
|
to: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }, { name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Re: Q4 Project Timeline',
|
||||||
|
sentAt: demoDate(-2, -8),
|
||||||
|
preview: 'Looks good to me! One concern: the testing window might be tight given the holidays...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-7', size: 520, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Looks good to me! One concern: the testing window might be tight given the holidays. Could we start testing a few days earlier?\n\nAlso, should we set up a shared doc for tracking blockers?\n\n— Bob' },
|
||||||
|
},
|
||||||
|
messageId: '<q4-timeline-2@example.com>',
|
||||||
|
inReplyTo: ['<q4-timeline-1@example.com>'],
|
||||||
|
references: ['<q4-timeline-1@example.com>'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-3c',
|
||||||
|
threadId: 'demo-thread-3',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 3800,
|
||||||
|
receivedAt: demoDate(-1, -3),
|
||||||
|
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
|
||||||
|
to: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }, { name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Re: Q4 Project Timeline',
|
||||||
|
sentAt: demoDate(-1, -3),
|
||||||
|
preview: 'Great point Bob. Let\'s move testing to Nov 28. I\'ll create the shared doc today...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-8', size: 400, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Great point Bob. Let\'s move testing to Nov 28. I\'ll create the shared doc today and share the link.\n\nUpdated timeline:\n- Design review: Oct 15\n- Development: Nov 1-27\n- Testing: Nov 28 - Dec 15\n- Launch: Dec 20\n\n— Alice' },
|
||||||
|
},
|
||||||
|
messageId: '<q4-timeline-3@example.com>',
|
||||||
|
inReplyTo: ['<q4-timeline-2@example.com>'],
|
||||||
|
references: ['<q4-timeline-1@example.com>', '<q4-timeline-2@example.com>'],
|
||||||
|
},
|
||||||
|
// Email with attachments
|
||||||
|
{
|
||||||
|
id: 'demo-email-4',
|
||||||
|
threadId: 'demo-thread-4',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 245000,
|
||||||
|
receivedAt: demoDate(0, -6),
|
||||||
|
from: [{ name: 'Sarah Kim', email: 'sarah.kim@example.com' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Invoice #2024-089 & Project Screenshot',
|
||||||
|
sentAt: demoDate(0, -6),
|
||||||
|
preview: 'Hi, please find attached the invoice for October and a screenshot of the latest prototype...',
|
||||||
|
hasAttachment: true,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-9', size: 280, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hi,\n\nPlease find attached the invoice for October and a screenshot of the latest prototype.\n\nLet me know if you have any questions.\n\nBest regards,\nSarah' },
|
||||||
|
},
|
||||||
|
attachments: [
|
||||||
|
{ partId: 'att-1', blobId: 'demo-blob-att-1', size: 145000, name: 'Invoice-2024-089.pdf', type: 'application/pdf' },
|
||||||
|
{ partId: 'att-2', blobId: 'demo-blob-att-2', size: 89000, name: 'prototype-v3.png', type: 'image/png' },
|
||||||
|
],
|
||||||
|
messageId: '<invoice-089@example.com>',
|
||||||
|
},
|
||||||
|
// Starred email
|
||||||
|
{
|
||||||
|
id: 'demo-email-5',
|
||||||
|
threadId: 'demo-thread-5',
|
||||||
|
mailboxIds: { 'demo-mailbox-inbox': true },
|
||||||
|
keywords: { $seen: true, $flagged: true },
|
||||||
|
size: 2800,
|
||||||
|
receivedAt: demoDate(-2, -1),
|
||||||
|
from: [{ name: 'Carlos Rivera', email: 'carlos.rivera@example.com' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Reminder: Team Dinner Friday',
|
||||||
|
sentAt: demoDate(-2, -1),
|
||||||
|
preview: 'Hey! Just a reminder about our team dinner this Friday at 7 PM at The Garden Bistro...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-10', size: 320, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hey!\n\nJust a reminder about our team dinner this Friday at 7 PM at The Garden Bistro. I\'ve made a reservation for 8 people.\n\nAddress: 123 Oak Street\n\nLet me know if you can make it!\n\nCheers,\nCarlos' },
|
||||||
|
},
|
||||||
|
messageId: '<dinner-reminder@example.com>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Sent ────────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-6',
|
||||||
|
threadId: 'demo-thread-6',
|
||||||
|
mailboxIds: { 'demo-mailbox-sent': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 2100,
|
||||||
|
receivedAt: demoDate(-1, -4),
|
||||||
|
from: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
to: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
|
||||||
|
subject: 'Updated Requirements Document',
|
||||||
|
sentAt: demoDate(-1, -4),
|
||||||
|
preview: 'Hi Alice, I\'ve updated the requirements document with the changes we discussed...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-11', size: 290, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hi Alice,\n\nI\'ve updated the requirements document with the changes we discussed in yesterday\'s meeting. The main updates are in sections 3 and 5.\n\nLet me know if you have any questions.\n\nBest,\nDemo User' },
|
||||||
|
},
|
||||||
|
messageId: '<sent-1@example.com>',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-7',
|
||||||
|
threadId: 'demo-thread-7',
|
||||||
|
mailboxIds: { 'demo-mailbox-sent': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 1800,
|
||||||
|
receivedAt: demoDate(-4, -2),
|
||||||
|
from: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
to: [{ name: 'Sarah Kim', email: 'sarah.kim@example.com' }],
|
||||||
|
subject: 'Re: Design Feedback',
|
||||||
|
sentAt: demoDate(-4, -2),
|
||||||
|
preview: 'Thanks Sarah! The new color scheme looks great. I especially like the contrast improvements...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-12', size: 250, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Thanks Sarah! The new color scheme looks great. I especially like the contrast improvements for accessibility.\n\nLet\'s go with Option B for the navigation.\n\nBest,\nDemo User' },
|
||||||
|
},
|
||||||
|
messageId: '<sent-2@example.com>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Drafts ──────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-8',
|
||||||
|
threadId: 'demo-thread-8',
|
||||||
|
mailboxIds: { 'demo-mailbox-drafts': true },
|
||||||
|
keywords: { $seen: true, $draft: true },
|
||||||
|
size: 900,
|
||||||
|
receivedAt: demoDate(0, -1),
|
||||||
|
from: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
to: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
|
||||||
|
subject: 'Meeting Notes - Draft',
|
||||||
|
sentAt: demoDate(0, -1),
|
||||||
|
preview: 'Here are the notes from today\'s standup...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-13', size: 180, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Here are the notes from today\'s standup:\n\n- API integration on track\n- Need to resolve the caching issue\n- ' },
|
||||||
|
},
|
||||||
|
messageId: '<draft-1@example.com>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Trash ───────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-9',
|
||||||
|
threadId: 'demo-thread-9',
|
||||||
|
mailboxIds: { 'demo-mailbox-trash': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 15200,
|
||||||
|
receivedAt: demoDate(-5, -3),
|
||||||
|
from: [{ name: 'Promo Store', email: 'deals@promostore.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: '🎉 Flash Sale: 50% Off Everything!',
|
||||||
|
sentAt: demoDate(-5, -3),
|
||||||
|
preview: 'Limited time offer! Get 50% off all items in our store...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-14', size: 400, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Limited time offer! Get 50% off all items in our store. Use code FLASH50 at checkout.' },
|
||||||
|
},
|
||||||
|
messageId: '<promo-1@promostore.example>',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-10',
|
||||||
|
threadId: 'demo-thread-10',
|
||||||
|
mailboxIds: { 'demo-mailbox-trash': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 2300,
|
||||||
|
receivedAt: demoDate(-7, 0),
|
||||||
|
from: [{ name: 'System Notification', email: 'noreply@service.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Your password was changed',
|
||||||
|
sentAt: demoDate(-7, 0),
|
||||||
|
preview: 'Your account password was successfully changed on...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-15', size: 200, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Your account password was successfully changed. If you did not make this change, please contact support immediately.' },
|
||||||
|
},
|
||||||
|
messageId: '<notification-1@service.example>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Projects ────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-11',
|
||||||
|
threadId: 'demo-thread-11',
|
||||||
|
mailboxIds: { 'demo-mailbox-projects': true },
|
||||||
|
keywords: { $seen: true, $flagged: true },
|
||||||
|
size: 4500,
|
||||||
|
receivedAt: demoDate(-2, -7),
|
||||||
|
from: [{ name: 'Alice Johnson', email: 'alice.johnson@example.com' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: '[Project] Sprint Planning Agenda',
|
||||||
|
sentAt: demoDate(-2, -7),
|
||||||
|
preview: 'Here\'s the agenda for next week\'s sprint planning session...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-16', size: 600, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hi team,\n\nHere\'s the agenda for next week\'s sprint planning:\n\n1. Review previous sprint velocity\n2. Discuss tech debt items\n3. Prioritize backlog\n4. Assign story points\n5. Capacity planning\n\nPlease come prepared with your updates.\n\nThanks,\nAlice' },
|
||||||
|
},
|
||||||
|
messageId: '<project-1@example.com>',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-email-12',
|
||||||
|
threadId: 'demo-thread-12',
|
||||||
|
mailboxIds: { 'demo-mailbox-projects': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 3200,
|
||||||
|
receivedAt: demoDate(0, -8),
|
||||||
|
from: [{ name: 'Bob Chen', email: 'bob.chen@example.com' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: '[Project] API Rate Limiting Discussion',
|
||||||
|
sentAt: demoDate(0, -8),
|
||||||
|
preview: 'I\'ve been thinking about our rate limiting approach and wanted to propose a few changes...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-17', size: 480, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Hey,\n\nI\'ve been thinking about our rate limiting approach and wanted to propose:\n\n1. Token bucket algorithm instead of fixed window\n2. Per-endpoint limits rather than global\n3. Graduated response (warn → throttle → block)\n\nThoughts? I can put together a more detailed RFC if we agree on the direction.\n\n— Bob' },
|
||||||
|
},
|
||||||
|
messageId: '<project-2@example.com>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Archive ─────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-13',
|
||||||
|
threadId: 'demo-thread-13',
|
||||||
|
mailboxIds: { 'demo-mailbox-archive': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 2600,
|
||||||
|
receivedAt: demoDate(-14, -6),
|
||||||
|
from: [{ name: 'HR Department', email: 'hr@company.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Updated PTO Policy - Effective January 1',
|
||||||
|
sentAt: demoDate(-14, -6),
|
||||||
|
preview: 'Please review the updated PTO policy that takes effect January 1st...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-18', size: 380, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Dear team,\n\nPlease review the updated PTO policy effective January 1st. Key changes include:\n\n- Increased annual allowance from 20 to 25 days\n- Flexible half-day options\n- Rollover limit increased to 10 days\n\nPlease acknowledge receipt.\n\nBest,\nHR Department' },
|
||||||
|
},
|
||||||
|
messageId: '<hr-policy-1@company.example>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Receipts ────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-14',
|
||||||
|
threadId: 'demo-thread-14',
|
||||||
|
mailboxIds: { 'demo-mailbox-receipts': true },
|
||||||
|
keywords: { $seen: true },
|
||||||
|
size: 5200,
|
||||||
|
receivedAt: demoDate(-3, -12),
|
||||||
|
from: [{ name: 'Cloud Services', email: 'billing@cloudprovider.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Payment Receipt - Invoice #INV-2024-1042',
|
||||||
|
sentAt: demoDate(-3, -12),
|
||||||
|
preview: 'Your payment of $49.99 has been processed successfully...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-19', size: 350, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Payment Confirmation\n\nAmount: $49.99\nDate: Processing date\nInvoice: INV-2024-1042\nService: Cloud Hosting (Standard Plan)\n\nThank you for your payment.' },
|
||||||
|
},
|
||||||
|
messageId: '<receipt-1@cloudprovider.example>',
|
||||||
|
},
|
||||||
|
|
||||||
|
// ── Spam ────────────────────────────────────────────────────
|
||||||
|
{
|
||||||
|
id: 'demo-email-15',
|
||||||
|
threadId: 'demo-thread-15',
|
||||||
|
mailboxIds: { 'demo-mailbox-junk': true },
|
||||||
|
keywords: {},
|
||||||
|
size: 8900,
|
||||||
|
receivedAt: demoDate(-1, -9),
|
||||||
|
from: [{ name: 'Prize Center', email: 'winner@totallylegit.example' }],
|
||||||
|
to: [{ name: 'Demo User', email: 'demo@example.com' }],
|
||||||
|
subject: 'Congratulations! You Won $1,000,000!!!',
|
||||||
|
sentAt: demoDate(-1, -9),
|
||||||
|
preview: 'Dear lucky winner, you have been selected to receive one million dollars...',
|
||||||
|
hasAttachment: false,
|
||||||
|
textBody: [{ partId: '1', blobId: 'blob-20', size: 500, type: 'text/plain' }],
|
||||||
|
bodyValues: {
|
||||||
|
'1': { value: 'Dear lucky winner,\n\nYou have been selected to receive ONE MILLION DOLLARS! Click below to claim your prize immediately.\n\n[This is a demo spam email]' },
|
||||||
|
},
|
||||||
|
messageId: '<spam-1@totallylegit.example>',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import type { FileNode } from '@/lib/jmap/types';
|
||||||
|
import { demoDate } from '../demo-utils';
|
||||||
|
|
||||||
|
export function createDemoFileNodes(): FileNode[] {
|
||||||
|
return [
|
||||||
|
// Root-level directories
|
||||||
|
{
|
||||||
|
id: 'demo-file-documents',
|
||||||
|
parentId: null,
|
||||||
|
name: 'Documents',
|
||||||
|
type: 'd',
|
||||||
|
blobId: null,
|
||||||
|
size: 0,
|
||||||
|
created: demoDate(-30),
|
||||||
|
updated: demoDate(-2),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-file-photos',
|
||||||
|
parentId: null,
|
||||||
|
name: 'Photos',
|
||||||
|
type: 'd',
|
||||||
|
blobId: null,
|
||||||
|
size: 0,
|
||||||
|
created: demoDate(-30),
|
||||||
|
updated: demoDate(-5),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Documents contents
|
||||||
|
{
|
||||||
|
id: 'demo-file-meeting-notes',
|
||||||
|
parentId: 'demo-file-documents',
|
||||||
|
name: 'meeting-notes.md',
|
||||||
|
type: 'text/markdown',
|
||||||
|
blobId: 'demo-blob-file-1',
|
||||||
|
size: 2150,
|
||||||
|
created: demoDate(-7),
|
||||||
|
updated: demoDate(-2),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-file-quarterly-report',
|
||||||
|
parentId: 'demo-file-documents',
|
||||||
|
name: 'quarterly-report.pdf',
|
||||||
|
type: 'application/pdf',
|
||||||
|
blobId: 'demo-blob-file-2',
|
||||||
|
size: 148480,
|
||||||
|
created: demoDate(-14),
|
||||||
|
updated: demoDate(-14),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-file-todo',
|
||||||
|
parentId: 'demo-file-documents',
|
||||||
|
name: 'todo.txt',
|
||||||
|
type: 'text/plain',
|
||||||
|
blobId: 'demo-blob-file-3',
|
||||||
|
size: 410,
|
||||||
|
created: demoDate(-3),
|
||||||
|
updated: demoDate(-1),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Photos contents
|
||||||
|
{
|
||||||
|
id: 'demo-file-vacation',
|
||||||
|
parentId: 'demo-file-photos',
|
||||||
|
name: 'vacation.jpg',
|
||||||
|
type: 'image/jpeg',
|
||||||
|
blobId: 'demo-blob-file-4',
|
||||||
|
size: 1258291,
|
||||||
|
created: demoDate(-10),
|
||||||
|
updated: demoDate(-10),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-file-team-photo',
|
||||||
|
parentId: 'demo-file-photos',
|
||||||
|
name: 'team-photo.png',
|
||||||
|
type: 'image/png',
|
||||||
|
blobId: 'demo-blob-file-5',
|
||||||
|
size: 911360,
|
||||||
|
created: demoDate(-21),
|
||||||
|
updated: demoDate(-21),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Root-level file
|
||||||
|
{
|
||||||
|
id: 'demo-file-budget',
|
||||||
|
parentId: null,
|
||||||
|
name: 'budget.xlsx',
|
||||||
|
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
blobId: 'demo-blob-file-6',
|
||||||
|
size: 68608,
|
||||||
|
created: demoDate(-5),
|
||||||
|
updated: demoDate(-1),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import type { SieveScript, SieveCapabilities } from '@/lib/jmap/sieve-types';
|
||||||
|
|
||||||
|
export function createDemoSieveCapabilities(): SieveCapabilities {
|
||||||
|
return {
|
||||||
|
implementation: 'Demo Sieve Engine',
|
||||||
|
maxSizeScript: 65536,
|
||||||
|
sieveExtensions: ['fileinto', 'reject', 'vacation', 'imap4flags', 'comparator-i;ascii-casemap', 'body', 'envelope'],
|
||||||
|
notificationMethods: [],
|
||||||
|
externalLists: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDemoSieveScripts(): SieveScript[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'demo-sieve-1',
|
||||||
|
name: 'Default Filters',
|
||||||
|
blobId: 'demo-sieve-blob-1',
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sieve script content keyed by blobId
|
||||||
|
export function createDemoSieveContent(): Record<string, string> {
|
||||||
|
return {
|
||||||
|
'demo-sieve-blob-1': [
|
||||||
|
'require ["fileinto", "imap4flags"];',
|
||||||
|
'',
|
||||||
|
'# Newsletters to Receipts',
|
||||||
|
'if address :contains "from" "newsletter@" {',
|
||||||
|
' fileinto "Receipts";',
|
||||||
|
' stop;',
|
||||||
|
'}',
|
||||||
|
'',
|
||||||
|
'# Flag emails from boss',
|
||||||
|
'if address :is "from" "alice.johnson@example.com" {',
|
||||||
|
' addflag "\\\\Flagged";',
|
||||||
|
'}',
|
||||||
|
'',
|
||||||
|
'# Move project updates',
|
||||||
|
'if header :contains "subject" "[Project]" {',
|
||||||
|
' fileinto "Projects";',
|
||||||
|
' stop;',
|
||||||
|
'}',
|
||||||
|
].join('\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { Identity } from '@/lib/jmap/types';
|
||||||
|
|
||||||
|
export function createDemoIdentities(): Identity[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: 'demo-identity-primary',
|
||||||
|
name: 'Demo User',
|
||||||
|
email: 'demo@example.com',
|
||||||
|
textSignature: 'Best regards,\nDemo User\nBulwark Mail Demo',
|
||||||
|
htmlSignature: '<p>Best regards,<br><b>Demo User</b><br>Bulwark Mail Demo</p>',
|
||||||
|
mayDelete: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'demo-identity-alias',
|
||||||
|
name: 'Demo User',
|
||||||
|
email: 'demo+newsletter@example.com',
|
||||||
|
textSignature: '',
|
||||||
|
htmlSignature: '',
|
||||||
|
mayDelete: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { Mailbox } from '@/lib/jmap/types';
|
||||||
|
|
||||||
|
const RIGHTS_SYSTEM = { mayReadItems: true, mayAddItems: true, mayRemoveItems: true, maySetSeen: true, maySetKeywords: true, mayCreateChild: true, mayRename: false, mayDelete: false, maySubmit: true };
|
||||||
|
const RIGHTS_CUSTOM = { ...RIGHTS_SYSTEM, mayRename: true, mayDelete: true };
|
||||||
|
|
||||||
|
export function createDemoMailboxes(): Mailbox[] {
|
||||||
|
return [
|
||||||
|
{ id: 'demo-mailbox-inbox', name: 'Inbox', role: 'inbox', sortOrder: 1, totalEmails: 12, unreadEmails: 5, totalThreads: 10, unreadThreads: 4, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-sent', name: 'Sent', role: 'sent', sortOrder: 2, totalEmails: 8, unreadEmails: 0, totalThreads: 8, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-drafts', name: 'Drafts', role: 'drafts', sortOrder: 3, totalEmails: 1, unreadEmails: 0, totalThreads: 1, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-trash', name: 'Trash', role: 'trash', sortOrder: 5, totalEmails: 2, unreadEmails: 0, totalThreads: 2, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-archive', name: 'Archive', role: 'archive', sortOrder: 4, totalEmails: 4, unreadEmails: 0, totalThreads: 4, unreadThreads: 0, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-junk', name: 'Spam', role: 'junk', sortOrder: 6, totalEmails: 3, unreadEmails: 1, totalThreads: 3, unreadThreads: 1, myRights: RIGHTS_SYSTEM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-projects', name: 'Projects', sortOrder: 10, totalEmails: 5, unreadEmails: 2, totalThreads: 5, unreadThreads: 2, myRights: RIGHTS_CUSTOM, isSubscribed: true },
|
||||||
|
{ id: 'demo-mailbox-receipts', name: 'Receipts', sortOrder: 11, totalEmails: 3, unreadEmails: 0, totalThreads: 3, unreadThreads: 0, myRights: RIGHTS_CUSTOM, isSubscribed: true },
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import type { VacationResponse } from '@/lib/jmap/types';
|
||||||
|
|
||||||
|
export function createDemoVacationResponse(): VacationResponse {
|
||||||
|
return {
|
||||||
|
id: 'singleton',
|
||||||
|
isEnabled: false,
|
||||||
|
fromDate: null,
|
||||||
|
toDate: null,
|
||||||
|
subject: 'Out of Office',
|
||||||
|
textBody: 'Thank you for your email. I am currently out of the office and will return on Monday. For urgent matters, please contact support@example.com.',
|
||||||
|
htmlBody: '<p>Thank you for your email. I am currently out of the office and will return on Monday.</p><p>For urgent matters, please contact <a href="mailto:support@example.com">support@example.com</a>.</p>',
|
||||||
|
};
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user