From 68a46e5debd414ef7435d6342d91c57b000570b5 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 8 Jun 2026 15:11:57 +0000 Subject: [PATCH 1/3] chore: apply repo-wide biome migration and project updates - add CI workflow and repository-level TypeScript project references\n- update package/workspace tooling and lockfile metadata\n- apply formatting and lint-driven updates across web and worker code\n- refresh docs, workflow configs, and supporting project files --- .github/renovate.json | 18 +- .github/workflows/ci.yml | 45 + .github/workflows/deploy.yml | 6 +- .github/workflows/release.yml | 2 +- .github/workflows/tag.yml | 12 +- CLAUDE.md | 5 + README.en.md | 30 +- README.md | 32 +- biome.json | 53 + package.json | 6 +- pnpm-lock.yaml | 95 ++ pnpm-workspace.yaml | 1 + tsconfig.json | 4 + web/index.html | 10 +- web/scripts/generate-icons.cjs | 36 +- web/src/App.tsx | 176 ++- web/src/components/ChannelSelector.tsx | 139 +- web/src/components/ConfirmDialog.tsx | 52 +- .../components/NotificationHoursSelector.tsx | 64 +- web/src/components/Portal.tsx | 4 +- web/src/components/TagCombobox.tsx | 77 +- web/src/components/ThemeProvider.tsx | 97 +- web/src/components/layout/AppLayout.tsx | 313 +++-- web/src/components/ui/button.tsx | 65 +- web/src/components/ui/card.tsx | 117 +- web/src/components/ui/input.tsx | 39 +- web/src/components/ui/label.tsx | 17 +- web/src/components/ui/switch.tsx | 18 +- web/src/components/ui/tabs.tsx | 34 +- web/src/hooks/useAuth.tsx | 121 +- web/src/hooks/useIsMobile.ts | 22 +- web/src/hooks/usePWAUpdate.ts | 27 +- web/src/index.css | 88 +- web/src/lib/api.ts | 107 +- web/src/lib/channels.ts | 20 +- web/src/lib/i18n.ts | 20 +- web/src/lib/lunar.ts | 288 +++-- web/src/lib/utils.ts | 72 +- web/src/main.tsx | 14 +- web/src/pages/about/AboutPage.tsx | 49 +- web/src/pages/admin/AdminAppPage.tsx | 66 +- web/src/pages/admin/AdminEmailPage.tsx | 292 +++-- web/src/pages/admin/AdminPage.tsx | 61 +- web/src/pages/admin/AdminSecurityPage.tsx | 109 +- web/src/pages/admin/AdminSystemPage.tsx | 378 ++++-- web/src/pages/admin/AdminUsersPage.tsx | 477 ++++--- web/src/pages/auth/ForgotPasswordPage.tsx | 176 ++- web/src/pages/auth/LoginPage.tsx | 118 +- web/src/pages/auth/RegisterPage.tsx | 106 +- web/src/pages/auth/TwoFactorPage.tsx | 198 +-- web/src/pages/auth/VerifyEmailPage.tsx | 66 +- web/src/pages/channels/ChannelPage.tsx | 430 +++--- web/src/pages/dashboard/DashboardPage.tsx | 237 ++-- web/src/pages/history/HistoryPage.tsx | 270 ++-- web/src/pages/items/ItemDetailPage.tsx | 1152 +++++++++++------ web/src/pages/items/ItemListPage.tsx | 847 ++++++++---- web/src/pages/items/ItemNewPage.tsx | 735 +++++++---- web/src/pages/me/MePage.tsx | 81 +- web/src/pages/settings/SettingsPage.tsx | 756 ++++++----- web/src/types/index.ts | 172 +-- web/src/vite-env.d.ts | 2 +- web/vite.config.ts | 73 +- worker/src/core/auth.ts | 96 +- worker/src/core/currency.ts | 15 +- worker/src/core/lunar.ts | 122 +- worker/src/core/time.ts | 40 +- worker/src/db/queries/items.ts | 62 +- worker/src/db/queries/notification-history.ts | 58 +- worker/src/db/queries/notifications.ts | 46 +- worker/src/db/queries/payments.ts | 53 +- worker/src/db/queries/settings.ts | 13 +- worker/src/db/queries/twofa.ts | 37 +- worker/src/db/queries/users.ts | 64 +- worker/src/env.d.ts | 2 +- worker/src/index.ts | 119 +- worker/src/middleware/admin.ts | 12 +- worker/src/middleware/auth.ts | 61 +- worker/src/middleware/ratelimit.ts | 50 +- worker/src/routes/admin.ts | 606 +++++---- worker/src/routes/auth.ts | 512 +++++--- worker/src/routes/auth2fa.ts | 637 +++++---- worker/src/routes/dashboard.ts | 185 +-- worker/src/routes/items.ts | 873 ++++++++----- worker/src/routes/me.ts | 560 ++++---- worker/src/routes/notify.ts | 68 +- worker/src/routes/setup.ts | 183 ++- worker/src/services/email.ts | 324 ++--- worker/src/services/notify/bark.ts | 36 +- worker/src/services/notify/email-notify.ts | 32 +- worker/src/services/notify/gotify.ts | 37 +- worker/src/services/notify/index.ts | 132 +- worker/src/services/notify/notifyx.ts | 32 +- worker/src/services/notify/pushplus.ts | 40 +- worker/src/services/notify/serverchan.ts | 41 +- worker/src/services/notify/telegram.ts | 49 +- worker/src/services/notify/webhook.ts | 100 +- worker/src/services/notify/wechatbot.ts | 53 +- worker/src/services/scheduler.ts | 403 +++--- worker/src/services/twofa.ts | 186 +-- worker/src/types.ts | 189 +-- 100 files changed, 9439 insertions(+), 5886 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 biome.json create mode 100644 tsconfig.json diff --git a/.github/renovate.json b/.github/renovate.json index 9bd03a8..ef5870e 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -31,29 +31,19 @@ }, { "groupName": "SimpleWebAuthn packages", - "matchPackageNames": [ - "/^@simplewebauthn//" - ] + "matchPackageNames": ["/^@simplewebauthn//"] }, { "groupName": "Radix UI packages", - "matchPackageNames": [ - "/^@radix-ui//" - ] + "matchPackageNames": ["/^@radix-ui//"] }, { "groupName": "i18next packages", - "matchPackageNames": [ - "/^i18next/", - "/^react-i18next/" - ] + "matchPackageNames": ["/^i18next/", "/^react-i18next/"] }, { "groupName": "Tailwind CSS packages", - "matchPackageNames": [ - "/^tailwindcss/", - "/^@tailwindcss//" - ] + "matchPackageNames": ["/^tailwindcss/", "/^@tailwindcss//"] }, { "groupName": "React packages", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..cd05ad4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,45 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + name: Validate + runs-on: ubuntu-latest + env: + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm lint + + - name: Format check + run: pnpm format:check + + - name: Type check + run: pnpm typecheck + + - name: Build + run: pnpm build diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6fb48d0..10ca95d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,12 +1,14 @@ name: Deploy on: - push: - branches: [main] workflow_dispatch: + workflow_run: + workflows: ["CI"] + types: [completed] jobs: deploy: + if: ${{ github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_branch == 'main') }} runs-on: ubuntu-latest env: WRANGLER_SEND_METRICS: "false" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d62e628..51e11fd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,7 @@ name: Release on: push: tags: - - 'v*' + - "v*" jobs: release: diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index d6780c0..60086c6 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -4,14 +4,14 @@ on: workflow_dispatch: inputs: tag: - description: 'Tag name (e.g., v1.0.0)' + description: "Tag name (e.g., v1.0.0)" required: true type: string jobs: create-tag: runs-on: ubuntu-latest - + steps: - name: Validate tag format run: | @@ -22,14 +22,14 @@ jobs: exit 1 fi echo "✅ Tag format is valid: $TAG" - + - name: Checkout repository uses: actions/checkout@v6 with: ref: main fetch-depth: 0 token: ${{ secrets.PAT_TOKEN }} - + - name: Check if tag already exists run: | TAG="${{ inputs.tag }}" @@ -41,12 +41,12 @@ jobs: exit 1 fi echo "✅ Tag '$TAG' does not exist, proceeding..." - + - name: Configure Git run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - + - name: Create and push tag run: | TAG="${{ inputs.tag }}" diff --git a/CLAUDE.md b/CLAUDE.md index 5cd92aa..0faa91f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,6 +43,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` **Entry point**: `worker/src/index.ts` — registers all Hono routes and the scheduled handler. **Route structure** (`worker/src/routes/`): + - `auth.ts` — registration, login, logout, email verification - `auth2fa.ts` — TOTP, Passkey (WebAuthn), email OTP - `me.ts` — user profile, notification settings @@ -53,11 +54,13 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `setup.ts` — one-time DB initialization via `SETUP_SECRET` **Database** (`worker/src/db/`): + - Cloudflare D1 (SQLite). Schema defined in `worker/src/db/schema.sql`. - All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts`. - Query functions are organized by entity in `worker/src/db/queries/`. Key entities: `items`, `payments`, `users`, `notifications` (channel config), `settings`. **Core utilities** (`worker/src/core/`): + - `auth.ts` — JWT signing/verification, password hashing, ID generation - `time.ts` — timezone-aware date arithmetic, period calculations - `lunar.ts` — Chinese lunar calendar support (1900–2100) @@ -66,11 +69,13 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` **Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter. **Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it: + 1. Checks their allowed notification hours (per-timezone). 2. Auto-renews expired items (with KV deduplication). 3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise all enabled channels receive the notification. **Cloudflare bindings**: + - `DB` — D1 database - `KV` — KV namespace (used for scheduler deduplication and status) - `ASSETS` — static file serving diff --git a/README.en.md b/README.en.md index 16ec0e0..ebae971 100644 --- a/README.en.md +++ b/README.en.md @@ -55,20 +55,20 @@ npx wrangler kv namespace create ENOTIFY_KV In your repository Settings → Secrets and variables → Actions, add: -| Secret | Description | -|--------|-------------| +| Secret | Description | +| ---------------------- | ------------------------------------------------------- | | `CLOUDFLARE_API_TOKEN` | Cloudflare API Token (needs Workers and D1 permissions) | -| `JWT_SECRET` | Any random 64-char string — e.g. `openssl rand -hex 32` | -| `SETUP_SECRET` | Any random string — e.g. `openssl rand -hex 16` | +| `JWT_SECRET` | Any random 64-char string — e.g. `openssl rand -hex 32` | +| `SETUP_SECRET` | Any random string — e.g. `openssl rand -hex 16` | In Settings → Secrets and variables → Actions → Variables, add: -| Variable | Description | -|----------|-------------| -| `D1_DATABASE_NAME` | D1 database name | -| `D1_DATABASE_ID` | D1 database ID | -| `KV_NAMESPACE_ID` | KV namespace ID | -| `TABLE_PREFIX` | Optional prefix for all DB table names(e.g. `myapp_`) | +| Variable | Description | +| ------------------ | ----------------------------------------------------- | +| `D1_DATABASE_NAME` | D1 database name | +| `D1_DATABASE_ID` | D1 database ID | +| `KV_NAMESPACE_ID` | KV namespace ID | +| `TABLE_PREFIX` | Optional prefix for all DB table names(e.g. `myapp_`) | ### 3. Deploy @@ -106,12 +106,12 @@ pnpm dev:worker ### Worker Environment Variables (wrangler.toml, injected by GitHub Actions during deployment) -| Variable | Description | -|----------|-------------| -| `JWT_SECRET` | JWT signing secret, any random 64-char string | +| Variable | Description | +| -------------- | ------------------------------------------------------- | +| `JWT_SECRET` | JWT signing secret, any random 64-char string | | `SETUP_SECRET` | Database initialization route secret, any random string | -| `TABLE_PREFIX` | Database table prefix (e.g., `hk_`), default is empty | +| `TABLE_PREFIX` | Database table prefix (e.g., `hk_`), default is empty | ## License -[MIT](LICENSE) \ No newline at end of file +[MIT](LICENSE) diff --git a/README.md b/README.md index 9b79e59..568f076 100644 --- a/README.md +++ b/README.md @@ -55,20 +55,20 @@ npx wrangler kv namespace create ENOTIFY_KV 在仓库的 Settings → Secrets and variables → Actions 中添加: -| Secret | 说明 | -|--------|------| -| `CLOUDFLARE_API_TOKEN` | Cloudflare API Token(需 Workers 和 D1 权限) | -| `JWT_SECRET` | 任意 64 位随机字符串,例如 `openssl rand -hex 32` | -| `SETUP_SECRET` | 任意随机字符串,例如 `openssl rand -hex 16` | +| Secret | 说明 | +| ---------------------- | ------------------------------------------------- | +| `CLOUDFLARE_API_TOKEN` | Cloudflare API Token(需 Workers 和 D1 权限) | +| `JWT_SECRET` | 任意 64 位随机字符串,例如 `openssl rand -hex 32` | +| `SETUP_SECRET` | 任意随机字符串,例如 `openssl rand -hex 16` | 在 Settings → Secrets and variables → Actions → Variables 中添加: -| Variable | 说明 | -|----------|------| -| `D1_DATABASE_NAME` | D1 数据库名称 | -| `D1_DATABASE_ID` | D1 数据库 ID | -| `KV_NAMESPACE_ID` | KV 命名空间 ID | -| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | +| Variable | 说明 | +| ------------------ | ---------------------------------- | +| `D1_DATABASE_NAME` | D1 数据库名称 | +| `D1_DATABASE_ID` | D1 数据库 ID | +| `KV_NAMESPACE_ID` | KV 命名空间 ID | +| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | ### 3. 部署 @@ -106,12 +106,12 @@ pnpm dev:worker ### Worker 环境变量(wrangler.toml,部署时由 GitHub Actions 注入) -| 变量 | 说明 | -|------|------| -| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 | +| 变量 | 说明 | +| -------------- | ------------------------------------ | +| `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 | | `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 | -| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | +| `TABLE_PREFIX` | 数据库表前缀(如 `hk_`),默认为空 | ## 许可证 -[MIT](LICENSE) \ No newline at end of file +[MIT](LICENSE) diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..08258b8 --- /dev/null +++ b/biome.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", + "files": { + "ignore": [ + "**/node_modules/**", + "**/dist/**", + "**/.wrangler/**", + "web/public/**", + "web/dist/**", + "worker/.wrangler/**" + ] + }, + "formatter": { + "enabled": true, + "indentStyle": "space" + }, + "organizeImports": { + "enabled": true + }, + "linter": { + "enabled": true, + "rules": { + "a11y": { + "noLabelWithoutControl": "off", + "useKeyWithClickEvents": "off", + "useButtonType": "warn", + "noAutofocus": "off" + }, + "suspicious": { + "noExplicitAny": "off", + "noGlobalIsNan": "error", + "noArrayIndexKey": "warn", + "noAssignInExpressions": "error" + }, + "style": { + "useTemplate": "off", + "noUnusedTemplateLiteral": "off", + "noNonNullAssertion": "off" + }, + "performance": { + "noDelete": "off" + }, + "correctness": { + "useExhaustiveDependencies": "error", + "noUnusedLabels": "error", + "noUnusedVariables": "error" + }, + "complexity": { + "noUselessFragments": "error" + } + } + } +} diff --git a/package.json b/package.json index 8890588..160fa5f 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,9 @@ "dev": "concurrently \"pnpm dev:worker\" \"pnpm dev:web\"", "dev:web": "pnpm --filter web dev", "dev:worker": "pnpm --filter worker dev", + "lint": "biome lint .", + "format:check": "biome format .", + "format": "biome format --write .", "build": "pnpm --filter web build && pnpm --filter worker build", "build:web": "pnpm --filter web build", "build:worker": "pnpm --filter worker build", @@ -14,11 +17,12 @@ "typecheck": "pnpm --filter web typecheck && pnpm --filter worker typecheck" }, "devDependencies": { + "@biomejs/biome": "^1.9.4", "concurrently": "^9.2.1", "typescript": "^6.0.3" }, "engines": { "node": ">=22.0.0" }, - "packageManager": "pnpm@11.5.1" + "packageManager": "pnpm@11.5.2" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cc97470..630fe32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: devDependencies: + '@biomejs/biome': + specifier: ^1.9.4 + version: 1.9.4 concurrently: specifier: ^9.2.1 version: 9.2.1 @@ -659,6 +662,63 @@ packages: resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==} engines: {node: '>=6.9.0'} + '@biomejs/biome@1.9.4': + resolution: {integrity: sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-darwin-arm64@1.9.4': + resolution: {integrity: sha512-bFBsPWrNvkdKrNCYeAp+xo2HecOGPAy9WyNyB/jKnnedgzl4W4Hb9ZMzYNbf8dMCGmUdSavlYHiR01QaYR58cw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@1.9.4': + resolution: {integrity: sha512-ngYBh/+bEedqkSevPVhLP4QfVPCpb+4BBe2p7Xs32dBgs7rh9nY2AIYUL6BgLw1JVXV8GlpKmb/hNiuIxfPfZg==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@1.9.4': + resolution: {integrity: sha512-v665Ct9WCRjGa8+kTr0CzApU0+XXtRgwmzIf1SeKSGAv+2scAlW6JR5PMFo6FzqqZ64Po79cKODKf3/AAmECqA==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64@1.9.4': + resolution: {integrity: sha512-fJIW0+LYujdjUgJJuwesP4EjIBl/N/TcOX3IvIHJQNsAqvV2CHIogsmA94BPG6jZATS4Hi+xv4SkBBQSt1N4/g==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64-musl@1.9.4': + resolution: {integrity: sha512-gEhi/jSBhZ2m6wjV530Yy8+fNqG8PAinM3oV7CyO+6c3CEh16Eizm21uHVsyVBEB6RIM8JHIl6AGYCv6Q6Q9Tg==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64@1.9.4': + resolution: {integrity: sha512-lRCJv/Vi3Vlwmbd6K+oQ0KhLHMAysN8lXoCI7XeHlxaajk06u7G+UsFSO01NAs5iYuWKmVZjmiOzJ0OJmGsMwg==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-win32-arm64@1.9.4': + resolution: {integrity: sha512-tlbhLk+WXZmgwoIKwHIHEBZUwxml7bRJgk0X2sPyNR3S93cdRq6XulAZRQJ17FYGGzWne0fgrXBKpl7l4M87Hg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@1.9.4': + resolution: {integrity: sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + '@cloudflare/kv-asset-handler@0.5.0': resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==} engines: {node: '>=22.0.0'} @@ -4165,6 +4225,41 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 + '@biomejs/biome@1.9.4': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 1.9.4 + '@biomejs/cli-darwin-x64': 1.9.4 + '@biomejs/cli-linux-arm64': 1.9.4 + '@biomejs/cli-linux-arm64-musl': 1.9.4 + '@biomejs/cli-linux-x64': 1.9.4 + '@biomejs/cli-linux-x64-musl': 1.9.4 + '@biomejs/cli-win32-arm64': 1.9.4 + '@biomejs/cli-win32-x64': 1.9.4 + + '@biomejs/cli-darwin-arm64@1.9.4': + optional: true + + '@biomejs/cli-darwin-x64@1.9.4': + optional: true + + '@biomejs/cli-linux-arm64-musl@1.9.4': + optional: true + + '@biomejs/cli-linux-arm64@1.9.4': + optional: true + + '@biomejs/cli-linux-x64-musl@1.9.4': + optional: true + + '@biomejs/cli-linux-x64@1.9.4': + optional: true + + '@biomejs/cli-win32-arm64@1.9.4': + optional: true + + '@biomejs/cli-win32-x64@1.9.4': + optional: true + '@cloudflare/kv-asset-handler@0.5.0': {} '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260526.1)': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b46a34d..c7c9b64 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,6 +2,7 @@ packages: - web - worker allowBuilds: + '@biomejs/biome': true esbuild: true sharp: true workerd: true diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..460e327 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,4 @@ +{ + "files": [], + "references": [{ "path": "./web" }, { "path": "./worker" }] +} diff --git a/web/index.html b/web/index.html index 41cde76..ac8f4be 100644 --- a/web/index.html +++ b/web/index.html @@ -4,10 +4,16 @@ - + - + eNotify diff --git a/web/scripts/generate-icons.cjs b/web/scripts/generate-icons.cjs index 1026352..698ecca 100644 --- a/web/scripts/generate-icons.cjs +++ b/web/scripts/generate-icons.cjs @@ -1,30 +1,24 @@ -const sharp = require('sharp') -const path = require('path') +const sharp = require("sharp"); +const path = require("node:path"); -const svgPath = path.resolve(__dirname, '../public/favicon.svg') -const publicDir = path.resolve(__dirname, '../public') +const svgPath = path.resolve(__dirname, "../public/favicon.svg"); +const publicDir = path.resolve(__dirname, "../public"); async function generate() { - const sizes = [180, 192, 512] + const sizes = [180, 192, 512]; for (const size of sizes) { - const outputPath = path.join(publicDir, `icon-${size}x${size}.png`) - await sharp(svgPath) - .resize(size, size) - .png() - .toFile(outputPath) - console.log(`Generated ${outputPath}`) + const outputPath = path.join(publicDir, `icon-${size}x${size}.png`); + await sharp(svgPath).resize(size, size).png().toFile(outputPath); + console.log(`Generated ${outputPath}`); } - const appleIconPath = path.join(publicDir, 'apple-touch-icon.png') - await sharp(svgPath) - .resize(180, 180) - .png() - .toFile(appleIconPath) - console.log(`Generated ${appleIconPath}`) + const appleIconPath = path.join(publicDir, "apple-touch-icon.png"); + await sharp(svgPath).resize(180, 180).png().toFile(appleIconPath); + console.log(`Generated ${appleIconPath}`); } -generate().catch(err => { - console.error('Icon generation failed:', err) - process.exit(1) -}) +generate().catch((err) => { + console.error("Icon generation failed:", err); + process.exit(1); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index a6e3263..cb7096a 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,56 +1,106 @@ -import { BrowserRouter, Routes, Route, Navigate } from 'react-router' -import { lazy, Suspense, type ReactNode } from 'react' -import { ThemeProvider } from '@/components/ThemeProvider' -import { AuthProvider, useAuth } from '@/hooks/useAuth' -import { AppLayout } from '@/components/layout/AppLayout' +import { BrowserRouter, Routes, Route, Navigate } from "react-router"; +import { lazy, Suspense, type ReactNode } from "react"; +import { ThemeProvider } from "@/components/ThemeProvider"; +import { AuthProvider, useAuth } from "@/hooks/useAuth"; +import { AppLayout } from "@/components/layout/AppLayout"; // Bottom nav pages — bundled directly for instant tab switching -import { DashboardPage } from '@/pages/dashboard/DashboardPage' -import { ItemListPage } from '@/pages/items/ItemListPage' -import { ChannelPage } from '@/pages/channels/ChannelPage' -import { HistoryPage } from '@/pages/history/HistoryPage' -import { MePage } from '@/pages/me/MePage' +import { DashboardPage } from "@/pages/dashboard/DashboardPage"; +import { ItemListPage } from "@/pages/items/ItemListPage"; +import { ChannelPage } from "@/pages/channels/ChannelPage"; +import { HistoryPage } from "@/pages/history/HistoryPage"; +import { MePage } from "@/pages/me/MePage"; // Lazy-loaded pages for code splitting -const LoginPage = lazy(() => import('@/pages/auth/LoginPage').then(m => ({ default: m.LoginPage }))) -const RegisterPage = lazy(() => import('@/pages/auth/RegisterPage').then(m => ({ default: m.RegisterPage }))) -const TwoFactorPage = lazy(() => import('@/pages/auth/TwoFactorPage').then(m => ({ default: m.TwoFactorPage }))) -const VerifyEmailPage = lazy(() => import('@/pages/auth/VerifyEmailPage').then(m => ({ default: m.VerifyEmailPage }))) -const ForgotPasswordPage = lazy(() => import('@/pages/auth/ForgotPasswordPage').then(m => ({ default: m.ForgotPasswordPage }))) -const ItemNewPage = lazy(() => import('@/pages/items/ItemNewPage').then(m => ({ default: m.ItemNewPage }))) -const ItemDetailPage = lazy(() => import('@/pages/items/ItemDetailPage').then(m => ({ default: m.ItemDetailPage }))) -const SettingsPage = lazy(() => import('@/pages/settings/SettingsPage').then(m => ({ default: m.SettingsPage }))) -const AdminPage = lazy(() => import('@/pages/admin/AdminPage').then(m => ({ default: m.AdminPage }))) -const AdminUsersPage = lazy(() => import('@/pages/admin/AdminUsersPage').then(m => ({ default: m.AdminUsersPage }))) -const AdminAppPage = lazy(() => import('@/pages/admin/AdminAppPage').then(m => ({ default: m.AdminAppPage }))) -const AdminEmailPage = lazy(() => import('@/pages/admin/AdminEmailPage').then(m => ({ default: m.AdminEmailPage }))) -const AdminSecurityPage = lazy(() => import('@/pages/admin/AdminSecurityPage').then(m => ({ default: m.AdminSecurityPage }))) -const AboutPage = lazy(() => import('@/pages/about/AboutPage').then(m => ({ default: m.AboutPage }))) +const LoginPage = lazy(() => + import("@/pages/auth/LoginPage").then((m) => ({ default: m.LoginPage })), +); +const RegisterPage = lazy(() => + import("@/pages/auth/RegisterPage").then((m) => ({ + default: m.RegisterPage, + })), +); +const TwoFactorPage = lazy(() => + import("@/pages/auth/TwoFactorPage").then((m) => ({ + default: m.TwoFactorPage, + })), +); +const VerifyEmailPage = lazy(() => + import("@/pages/auth/VerifyEmailPage").then((m) => ({ + default: m.VerifyEmailPage, + })), +); +const ForgotPasswordPage = lazy(() => + import("@/pages/auth/ForgotPasswordPage").then((m) => ({ + default: m.ForgotPasswordPage, + })), +); +const ItemNewPage = lazy(() => + import("@/pages/items/ItemNewPage").then((m) => ({ default: m.ItemNewPage })), +); +const ItemDetailPage = lazy(() => + import("@/pages/items/ItemDetailPage").then((m) => ({ + default: m.ItemDetailPage, + })), +); +const SettingsPage = lazy(() => + import("@/pages/settings/SettingsPage").then((m) => ({ + default: m.SettingsPage, + })), +); +const AdminPage = lazy(() => + import("@/pages/admin/AdminPage").then((m) => ({ default: m.AdminPage })), +); +const AdminUsersPage = lazy(() => + import("@/pages/admin/AdminUsersPage").then((m) => ({ + default: m.AdminUsersPage, + })), +); +const AdminAppPage = lazy(() => + import("@/pages/admin/AdminAppPage").then((m) => ({ + default: m.AdminAppPage, + })), +); +const AdminEmailPage = lazy(() => + import("@/pages/admin/AdminEmailPage").then((m) => ({ + default: m.AdminEmailPage, + })), +); +const AdminSecurityPage = lazy(() => + import("@/pages/admin/AdminSecurityPage").then((m) => ({ + default: m.AdminSecurityPage, + })), +); +const AboutPage = lazy(() => + import("@/pages/about/AboutPage").then((m) => ({ default: m.AboutPage })), +); function PageLoader() { - return
Loading...
+ return ( +
Loading...
+ ); } function ProtectedRoute({ children }: { children: ReactNode }) { - const { user, loading } = useAuth() - if (loading) return - if (!user) return - return <>{children} + const { user, loading } = useAuth(); + if (loading) return ; + if (!user) return ; + return <>{children}; } function AdminRoute({ children }: { children: ReactNode }) { - const { user, loading } = useAuth() - if (loading) return - if (!user) return - if (user.role !== 'admin') return - return <>{children} + const { user, loading } = useAuth(); + if (loading) return ; + if (!user) return ; + if (user.role !== "admin") return ; + return <>{children}; } function PublicRoute({ children }: { children: ReactNode }) { - const { user, loading } = useAuth() - if (loading) return - if (user) return - return <>{children} + const { user, loading } = useAuth(); + if (loading) return ; + if (user) return ; + return <>{children}; } export function App() { @@ -61,14 +111,41 @@ export function App() { }> {/* Public routes */} - } /> - } /> + + + + } + /> + + + + } + /> } /> } /> - } /> + + + + } + /> {/* Protected routes */} - }> + + + + } + > } /> } /> } /> @@ -80,8 +157,15 @@ export function App() { } /> {/* Admin routes */} - }> - } /> + + + + } + > + } /> } /> } /> @@ -95,5 +179,5 @@ export function App() { - ) -} \ No newline at end of file + ); +} diff --git a/web/src/components/ChannelSelector.tsx b/web/src/components/ChannelSelector.tsx index 7e1a375..28d42c5 100644 --- a/web/src/components/ChannelSelector.tsx +++ b/web/src/components/ChannelSelector.tsx @@ -1,89 +1,98 @@ -import { useState, useEffect, useRef } from 'react' -import { useTranslation } from 'react-i18next' -import { Check, ChevronDown, X, Radio } from 'lucide-react' -import { api } from '@/lib/api' -import { cn } from '@/lib/utils' -import { CHANNELS } from '@/lib/channels' -import type { NotificationConfig } from '@/types' +import { useState, useEffect, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { Check, ChevronDown, X, Radio } from "lucide-react"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { CHANNELS } from "@/lib/channels"; +import type { NotificationConfig } from "@/types"; export function ChannelSelector({ selected, onChange, }: { - selected: string[] - onChange: (channels: string[]) => void + selected: string[]; + onChange: (channels: string[]) => void; }) { - const { t } = useTranslation() - const [open, setOpen] = useState(false) - const [enabledChannels, setEnabledChannels] = useState([]) - const [loading, setLoading] = useState(true) - const ref = useRef(null) + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [enabledChannels, setEnabledChannels] = useState([]); + const [loading, setLoading] = useState(true); + const ref = useRef(null); useEffect(() => { async function fetchConfig() { try { - const config = await api.get('/me/notifications') - setEnabledChannels(config.enabled_channels || []) - } catch (e) { - setEnabledChannels([]) + const config = await api.get("/me/notifications"); + setEnabledChannels(config.enabled_channels || []); + } catch { + setEnabledChannels([]); } finally { - setLoading(false) + setLoading(false); } } - fetchConfig() - }, []) + fetchConfig(); + }, []); // Close dropdown on click outside useEffect(() => { - if (!open) return + if (!open) return; function handleClick(e: MouseEvent) { if (ref.current && !ref.current.contains(e.target as Node)) { - setOpen(false) + setOpen(false); } } - document.addEventListener('mousedown', handleClick) - return () => document.removeEventListener('mousedown', handleClick) - }, [open]) + document.addEventListener("mousedown", handleClick); + return () => document.removeEventListener("mousedown", handleClick); + }, [open]); - const availableChannels = CHANNELS.filter(ch => enabledChannels.includes(ch.id)) + const availableChannels = CHANNELS.filter((ch) => + enabledChannels.includes(ch.id), + ); const toggleChannel = (channelId: string) => { const newSelected = selected.includes(channelId) - ? selected.filter(c => c !== channelId) - : [...selected, channelId] - onChange(newSelected) - } + ? selected.filter((c) => c !== channelId) + : [...selected, channelId]; + onChange(newSelected); + }; const clearSelection = () => { - onChange([]) - } + onChange([]); + }; const toggleAll = () => { if (selected.length === availableChannels.length) { - onChange([]) + onChange([]); } else { - onChange(availableChannels.map(ch => ch.id)) + onChange(availableChannels.map((ch) => ch.id)); } - } + }; return (
- + {open && ( @@ -91,7 +100,7 @@ export function ChannelSelector({
- {availableChannels.length} {t('common.available')} + {availableChannels.length} {t("common.available")}
{selected.length > 0 && ( )}
@@ -117,42 +128,50 @@ export function ChannelSelector({
{loading ? (
- {t('common.loading')} + {t("common.loading")}
) : availableChannels.length === 0 ? (
- {t('channels.noChannelsEnabled')} + {t("channels.noChannelsEnabled")}
) : ( <>
onChange([])} >
{selected.length === 0 && }
- {t('channels.allChannels')} - {selected.length === 0 && } + + {t("channels.allChannels")} + + {selected.length === 0 && ( + + )}
{availableChannels.map((channel) => (
toggleChannel(channel.id)} >
- {selected.includes(channel.id) && } + {selected.includes(channel.id) && ( + + )}
{channel.label} - {selected.includes(channel.id) && } + {selected.includes(channel.id) && ( + + )}
))} @@ -164,8 +183,8 @@ export function ChannelSelector({ {selected.length > 0 && (
{selected.map((channelId) => { - const channel = CHANNELS.find(ch => ch.id === channelId) - if (!channel) return null + const channel = CHANNELS.find((ch) => ch.id === channelId); + if (!channel) return null; return ( - ) + ); })}
)}
- ) + ); } diff --git a/web/src/components/ConfirmDialog.tsx b/web/src/components/ConfirmDialog.tsx index 78d95e3..4104888 100644 --- a/web/src/components/ConfirmDialog.tsx +++ b/web/src/components/ConfirmDialog.tsx @@ -1,14 +1,14 @@ -import { AlertTriangle } from 'lucide-react' +import { AlertTriangle } from "lucide-react"; interface ConfirmDialogProps { - open: boolean - title?: string - message: string - confirmLabel?: string - cancelLabel?: string - variant?: 'danger' | 'primary' - onConfirm: () => void - onCancel: () => void + open: boolean; + title?: string; + message: string; + confirmLabel?: string; + cancelLabel?: string; + variant?: "danger" | "primary"; + onConfirm: () => void; + onCancel: () => void; } export function ConfirmDialog({ @@ -17,20 +17,28 @@ export function ConfirmDialog({ message, confirmLabel, cancelLabel, - variant = 'primary', + variant = "primary", onConfirm, onCancel, }: ConfirmDialogProps) { - if (!open) return null + if (!open) return null; return ( -
+
e.stopPropagation()} >
- +
{title &&

{title}

}

{message}

@@ -38,28 +46,30 @@ export function ConfirmDialog({
- ) + ); } function cn(...classes: (string | undefined | false)[]) { - return classes.filter(Boolean).join(' ') + return classes.filter(Boolean).join(" "); } diff --git a/web/src/components/NotificationHoursSelector.tsx b/web/src/components/NotificationHoursSelector.tsx index 1f0b2fa..b887b27 100644 --- a/web/src/components/NotificationHoursSelector.tsx +++ b/web/src/components/NotificationHoursSelector.tsx @@ -1,12 +1,12 @@ -import { useTranslation } from 'react-i18next' -import { useAuth } from '@/hooks/useAuth' -import { cn } from '@/lib/utils' +import { useTranslation } from "react-i18next"; +import { useAuth } from "@/hooks/useAuth"; +import { cn } from "@/lib/utils"; interface NotificationHoursSelectorProps { - selected: number[] - onChange: (hours: number[]) => void - showTimezone?: boolean - hint?: string + selected: number[]; + onChange: (hours: number[]) => void; + showTimezone?: boolean; + hint?: string; } export function NotificationHoursSelector({ @@ -15,60 +15,72 @@ export function NotificationHoursSelector({ showTimezone = true, hint, }: NotificationHoursSelectorProps) { - const { t } = useTranslation() - const { user } = useAuth() + const { t } = useTranslation(); + const { user } = useAuth(); const toggleHour = (h: number) => { onChange( - selected.includes(h) ? selected.filter((x) => x !== h) : [...selected, h].sort((a, b) => a - b) - ) - } + selected.includes(h) + ? selected.filter((x) => x !== h) + : [...selected, h].sort((a, b) => a - b), + ); + }; - const selectAll = () => onChange(Array.from({ length: 24 }, (_, i) => i)) - const clearAll = () => onChange([]) + const selectAll = () => onChange(Array.from({ length: 24 }, (_, i) => i)); + const clearAll = () => onChange([]); return (
{hint &&

{hint}

} {showTimezone && ( -

({user?.timezone || 'UTC'})

+

+ ({user?.timezone || "UTC"}) +

)}
{Array.from({ length: 24 }, (_, i) => i).map((h) => { - const isSelected = selected.includes(h) + const isSelected = selected.includes(h); return ( - ) + ); })}
- / - {selected.length === 0 && ( - {t('channels.notificationHoursNoLimit')} + {t("channels.notificationHoursNoLimit")} )}
- ) + ); } diff --git a/web/src/components/Portal.tsx b/web/src/components/Portal.tsx index e45596a..6788e61 100644 --- a/web/src/components/Portal.tsx +++ b/web/src/components/Portal.tsx @@ -1,5 +1,5 @@ -import { createPortal } from 'react-dom' +import { createPortal } from "react-dom"; export function Portal({ children }: { children: React.ReactNode }) { - return createPortal(children, document.body) + return createPortal(children, document.body); } diff --git a/web/src/components/TagCombobox.tsx b/web/src/components/TagCombobox.tsx index 97844e3..82237b4 100644 --- a/web/src/components/TagCombobox.tsx +++ b/web/src/components/TagCombobox.tsx @@ -1,36 +1,45 @@ -import { useState, useRef, useEffect } from 'react' -import { useTranslation } from 'react-i18next' -import { cn } from '@/lib/utils' +import { useState, useRef, useEffect } from "react"; +import { useTranslation } from "react-i18next"; +import { cn } from "@/lib/utils"; interface TagComboboxProps { - value: string - onChange: (val: string) => void - options: string[] - placeholder?: string + value: string; + onChange: (val: string) => void; + options: string[]; + placeholder?: string; } const INPUT = - 'w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow' + "w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow"; -export function TagCombobox({ value, onChange, options, placeholder }: TagComboboxProps) { - const { t } = useTranslation() - const [open, setOpen] = useState(false) - const containerRef = useRef(null) +export function TagCombobox({ + value, + onChange, + options, + placeholder, +}: TagComboboxProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const containerRef = useRef(null); - const filtered = options.filter((o) => - value === '' || o.toLowerCase().includes(value.toLowerCase()) - ) - const showCreate = value.trim() !== '' && !options.some((o) => o === value.trim()) + const filtered = options.filter( + (o) => value === "" || o.toLowerCase().includes(value.toLowerCase()), + ); + const showCreate = + value.trim() !== "" && !options.some((o) => o === value.trim()); useEffect(() => { function handleClickOutside(e: MouseEvent) { - if (containerRef.current && !containerRef.current.contains(e.target as Node)) { - setOpen(false) + if ( + containerRef.current && + !containerRef.current.contains(e.target as Node) + ) { + setOpen(false); } } - if (open) document.addEventListener('mousedown', handleClickOutside) - return () => document.removeEventListener('mousedown', handleClickOutside) - }, [open]) + if (open) document.addEventListener("mousedown", handleClickOutside); + return () => document.removeEventListener("mousedown", handleClickOutside); + }, [open]); return (
@@ -41,7 +50,7 @@ export function TagCombobox({ value, onChange, options, placeholder }: TagCombob onFocus={() => setOpen(true)} onChange={(e) => onChange(e.target.value)} onKeyDown={(e) => { - if (e.key === 'Escape') setOpen(false) + if (e.key === "Escape") setOpen(false); }} /> {open && (filtered.length > 0 || showCreate) && ( @@ -52,13 +61,13 @@ export function TagCombobox({ value, onChange, options, placeholder }: TagCombob
  • { - e.preventDefault() - onChange(option) - setOpen(false) + e.preventDefault(); + onChange(option); + setOpen(false); }} > {option} @@ -69,21 +78,21 @@ export function TagCombobox({ value, onChange, options, placeholder }: TagCombob {showCreate && (
    0 && 'border-t', + "px-3 py-2 text-sm cursor-pointer text-primary hover:bg-accent transition-colors flex items-center gap-1.5", + filtered.length > 0 && "border-t", )} onMouseDown={(e) => { - e.preventDefault() - onChange(value.trim()) - setOpen(false) + e.preventDefault(); + onChange(value.trim()); + setOpen(false); }} > + - {t('items.tagCreate', { value: value.trim() })} + {t("items.tagCreate", { value: value.trim() })}
    )}
  • )}
    - ) + ); } diff --git a/web/src/components/ThemeProvider.tsx b/web/src/components/ThemeProvider.tsx index a6568f1..d0eb96e 100644 --- a/web/src/components/ThemeProvider.tsx +++ b/web/src/components/ThemeProvider.tsx @@ -1,72 +1,89 @@ -import { createContext, useContext, useCallback, useEffect, useState, type ReactNode } from 'react' +import { + createContext, + useContext, + useCallback, + useEffect, + useState, + type ReactNode, +} from "react"; -type Theme = 'light' | 'dark' | 'system' +type Theme = "light" | "dark" | "system"; interface ThemeContextType { - theme: Theme - setTheme: (theme: Theme) => void - resolvedTheme: 'light' | 'dark' + theme: Theme; + setTheme: (theme: Theme) => void; + resolvedTheme: "light" | "dark"; } -const ThemeContext = createContext(undefined) +const ThemeContext = createContext(undefined); export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setThemeState] = useState(() => { - return (localStorage.getItem('theme') as Theme) || 'system' - }) + return (localStorage.getItem("theme") as Theme) || "system"; + }); - const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>(() => { - const stored = localStorage.getItem('theme') as Theme | null - if (stored === 'dark') return 'dark' - if (stored === 'light') return 'light' - return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' - }) + const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">(() => { + const stored = localStorage.getItem("theme") as Theme | null; + if (stored === "dark") return "dark"; + if (stored === "light") return "light"; + return window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + }); useEffect(() => { - const root = document.documentElement + const root = document.documentElement; const applyTheme = (t: Theme) => { - if (t === 'system') { - const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches - root.classList.toggle('dark', isDark) - setResolvedTheme(isDark ? 'dark' : 'light') + if (t === "system") { + const isDark = window.matchMedia( + "(prefers-color-scheme: dark)", + ).matches; + root.classList.toggle("dark", isDark); + setResolvedTheme(isDark ? "dark" : "light"); } else { - root.classList.toggle('dark', t === 'dark') - setResolvedTheme(t) + root.classList.toggle("dark", t === "dark"); + setResolvedTheme(t); } - } + }; - applyTheme(theme) + applyTheme(theme); // Update mobile status bar theme-color meta tag - const metaThemeColor = document.querySelector('meta[name="theme-color"]') + const metaThemeColor = document.querySelector('meta[name="theme-color"]'); if (metaThemeColor) { - const isDark = theme === 'system' - ? window.matchMedia('(prefers-color-scheme: dark)').matches - : theme === 'dark' - metaThemeColor.setAttribute('content', isDark ? 'hsl(222.2 84% 4.9%)' : '#ffffff') + const isDark = + theme === "system" + ? window.matchMedia("(prefers-color-scheme: dark)").matches + : theme === "dark"; + metaThemeColor.setAttribute( + "content", + isDark ? "hsl(222.2 84% 4.9%)" : "#ffffff", + ); } - const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)') - const handler = () => { if (theme === 'system') applyTheme('system') } - mediaQuery.addEventListener('change', handler) - return () => mediaQuery.removeEventListener('change', handler) - }, [theme]) + const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); + const handler = () => { + if (theme === "system") applyTheme("system"); + }; + mediaQuery.addEventListener("change", handler); + return () => mediaQuery.removeEventListener("change", handler); + }, [theme]); const setTheme = useCallback((t: Theme) => { - localStorage.setItem('theme', t) - setThemeState(t) - }, []) + localStorage.setItem("theme", t); + setThemeState(t); + }, []); return ( {children} - ) + ); } export function useTheme() { - const ctx = useContext(ThemeContext) - if (!ctx) throw new Error('useTheme must be used within ThemeProvider') - return ctx + const ctx = useContext(ThemeContext); + if (!ctx) throw new Error("useTheme must be used within ThemeProvider"); + return ctx; } diff --git a/web/src/components/layout/AppLayout.tsx b/web/src/components/layout/AppLayout.tsx index 5e9a1de..5c7d39e 100644 --- a/web/src/components/layout/AppLayout.tsx +++ b/web/src/components/layout/AppLayout.tsx @@ -1,43 +1,61 @@ -import { Outlet, NavLink, useNavigate, useLocation } from 'react-router' -import { useTranslation } from 'react-i18next' -import { useAuth } from '@/hooks/useAuth' -import { LayoutDashboard, CreditCard, Shield, LogOut, XCircle, Settings, History, User, ChevronDown, Info, Radio, RefreshCw } from 'lucide-react' -import { useState, useEffect, useRef } from 'react' -import { api } from '@/lib/api' -import { usePWAUpdate } from '@/hooks/usePWAUpdate' -import { DashboardPage } from '@/pages/dashboard/DashboardPage' -import { ItemListPage } from '@/pages/items/ItemListPage' -import { ChannelPage } from '@/pages/channels/ChannelPage' -import { HistoryPage } from '@/pages/history/HistoryPage' -import { MePage } from '@/pages/me/MePage' +import { Outlet, NavLink, useNavigate, useLocation } from "react-router"; +import { useTranslation } from "react-i18next"; +import { useAuth } from "@/hooks/useAuth"; +import { + LayoutDashboard, + CreditCard, + Shield, + LogOut, + XCircle, + Settings, + History, + User, + ChevronDown, + Info, + Radio, + RefreshCw, +} from "lucide-react"; +import { useState, useEffect, useRef } from "react"; +import { api } from "@/lib/api"; +import { usePWAUpdate } from "@/hooks/usePWAUpdate"; +import { DashboardPage } from "@/pages/dashboard/DashboardPage"; +import { ItemListPage } from "@/pages/items/ItemListPage"; +import { ChannelPage } from "@/pages/channels/ChannelPage"; +import { HistoryPage } from "@/pages/history/HistoryPage"; +import { MePage } from "@/pages/me/MePage"; -function AvatarDropdown({ user, onLogout, onNavigate }: { - user: { email: string; role: string } | null - onLogout: () => void - onNavigate: (path: string) => void +function AvatarDropdown({ + user, + onLogout, + onNavigate, +}: { + user: { email: string; role: string } | null; + onLogout: () => void; + onNavigate: (path: string) => void; }) { - const { t } = useTranslation() - const [open, setOpen] = useState(false) - const ref = useRef(null) + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const ref = useRef(null); useEffect(() => { const handler = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) { - setOpen(false) + setOpen(false); } - } - document.addEventListener('mousedown', handler) - return () => document.removeEventListener('mousedown', handler) - }, []) + }; + document.addEventListener("mousedown", handler); + return () => document.removeEventListener("mousedown", handler); + }, []); const handleNavigate = (path: string) => { - setOpen(false) - onNavigate(path) - } + setOpen(false); + onNavigate(path); + }; return (
    - {user?.role === 'admin' && ( - )} -
    )}
    - ) + ); } export function AppLayout() { - const { t } = useTranslation() - const { user, logout, refreshUser } = useAuth() - const navigate = useNavigate() - const location = useLocation() - const { needRefresh, update, dismiss } = usePWAUpdate() - const [impersonating, setImpersonating] = useState(() => !!sessionStorage.getItem('impersonate_user_id')) - const [appName, setAppName] = useState('eNotify') + const { t } = useTranslation(); + const { user, logout, refreshUser } = useAuth(); + const navigate = useNavigate(); + const location = useLocation(); + const { needRefresh, update, dismiss } = usePWAUpdate(); + const [impersonating, setImpersonating] = useState( + () => !!sessionStorage.getItem("impersonate_user_id"), + ); + const [appName, setAppName] = useState("eNotify"); - const TAB_PATHS = ['/', '/items', '/channels', '/history', '/me'] - const isTabPath = TAB_PATHS.includes(location.pathname) - const [visitedTabs, setVisitedTabs] = useState>(() => new Set([location.pathname])) + const TAB_PATHS = ["/", "/items", "/channels", "/history", "/me"]; + const isTabPath = TAB_PATHS.includes(location.pathname); + const [visitedTabs, setVisitedTabs] = useState>( + () => new Set([location.pathname]), + ); useEffect(() => { if (TAB_PATHS.includes(location.pathname)) { setVisitedTabs((prev) => { - if (prev.has(location.pathname)) return prev - return new Set(prev).add(location.pathname) - }) + if (prev.has(location.pathname)) return prev; + return new Set(prev).add(location.pathname); + }); } - }, [location.pathname]) + }, [location.pathname]); useEffect(() => { - api.get<{ app_name: string; version: string }>('/system/info') - .then((info) => { if (info.app_name) setAppName(info.app_name) }) - .catch(() => {}) - }, []) + api + .get<{ app_name: string; version: string }>("/system/info") + .then((info) => { + if (info.app_name) setAppName(info.app_name); + }) + .catch(() => {}); + }, []); useEffect(() => { - const check = () => setImpersonating(!!sessionStorage.getItem('impersonate_user_id')) - window.addEventListener('storage', check) - window.addEventListener('impersonation-change', check) - const id = setInterval(check, 3000) - return () => { window.removeEventListener('storage', check); window.removeEventListener('impersonation-change', check); clearInterval(id) } - }, []) + const check = () => + setImpersonating(!!sessionStorage.getItem("impersonate_user_id")); + window.addEventListener("storage", check); + window.addEventListener("impersonation-change", check); + const id = setInterval(check, 3000); + return () => { + window.removeEventListener("storage", check); + window.removeEventListener("impersonation-change", check); + clearInterval(id); + }; + }, []); useEffect(() => { - if (sessionStorage.getItem('needs_2fa_setup')) { - sessionStorage.removeItem('needs_2fa_setup') - navigate('/settings?tab=security', { replace: true }) + if (sessionStorage.getItem("needs_2fa_setup")) { + sessionStorage.removeItem("needs_2fa_setup"); + navigate("/settings?tab=security", { replace: true }); } - }, [navigate]) + }, [navigate]); const stopImpersonating = async () => { - sessionStorage.removeItem('impersonate_user_id') - window.dispatchEvent(new Event('impersonation-change')) - setImpersonating(false) - await refreshUser() - navigate('/admin/users') - } + sessionStorage.removeItem("impersonate_user_id"); + window.dispatchEvent(new Event("impersonation-change")); + setImpersonating(false); + await refreshUser(); + navigate("/admin/users"); + }; const handleLogout = async () => { - await logout() - navigate('/login') - } + await logout(); + navigate("/login"); + }; const handleMenuNavigate = (path: string) => { - navigate(path) - } + navigate(path); + }; const desktopNavItems = [ - { to: '/', icon: LayoutDashboard, label: t('nav.dashboard') }, - { to: '/items', icon: CreditCard, label: t('nav.items') }, - { to: '/channels', icon: Radio, label: t('nav.channels') }, - { to: '/history', icon: History, label: t('nav.history') }, - ] + { to: "/", icon: LayoutDashboard, label: t("nav.dashboard") }, + { to: "/items", icon: CreditCard, label: t("nav.items") }, + { to: "/channels", icon: Radio, label: t("nav.channels") }, + { to: "/history", icon: History, label: t("nav.history") }, + ]; const mobileNavItems = [ - { to: '/', icon: LayoutDashboard, label: t('nav.dashboard') }, - { to: '/items', icon: CreditCard, label: t('nav.items') }, - { to: '/channels', icon: Radio, label: t('nav.channels') }, - { to: '/history', icon: History, label: t('nav.history') }, - { to: '/me', icon: User, label: t('nav.me') }, - ] + { to: "/", icon: LayoutDashboard, label: t("nav.dashboard") }, + { to: "/items", icon: CreditCard, label: t("nav.items") }, + { to: "/channels", icon: Radio, label: t("nav.channels") }, + { to: "/history", icon: History, label: t("nav.history") }, + { to: "/me", icon: User, label: t("nav.me") }, + ]; return (
    @@ -167,10 +210,12 @@ export function AppLayout() { `flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${ - isActive ? 'bg-primary/10 text-primary font-medium' : 'text-muted-foreground hover:bg-accent' + isActive + ? "bg-primary/10 text-primary font-medium" + : "text-muted-foreground hover:bg-accent" }` } > @@ -185,28 +230,48 @@ export function AppLayout() {
    {/* Desktop top bar */}
    - +
    {impersonating && (
    - {t('admin.impersonating', { defaultValue: 'Impersonating another user' })} -
    )} {needRefresh && (
    - {t('pwa.updateAvailable')} + {t("pwa.updateAvailable")}
    - -
    @@ -222,20 +287,42 @@ export function AppLayout() {
    {isTabPath ? ( <> -
    - {visitedTabs.has('/') && } +
    + {visitedTabs.has("/") && }
    -
    - {visitedTabs.has('/items') && } +
    + {visitedTabs.has("/items") && }
    -
    - {visitedTabs.has('/channels') && } +
    + {visitedTabs.has("/channels") && }
    -
    - {visitedTabs.has('/history') && } +
    + {visitedTabs.has("/history") && }
    -
    - {visitedTabs.has('/me') && } +
    + {visitedTabs.has("/me") && }
    ) : ( @@ -249,8 +336,8 @@ export function AppLayout() {
    {appName} @@ -260,8 +347,8 @@ export function AppLayout() {
    - ) -} \ No newline at end of file + ); +} diff --git a/web/src/components/ui/button.tsx b/web/src/components/ui/button.tsx index 7cef5b7..62b5f54 100644 --- a/web/src/components/ui/button.tsx +++ b/web/src/components/ui/button.tsx @@ -1,44 +1,55 @@ -import * as React from 'react' -import { Slot } from '@radix-ui/react-slot' -import { cva, type VariantProps } from 'class-variance-authority' -import { cn } from '@/lib/utils' +import * as React from "react"; +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "@/lib/utils"; const buttonVariants = cva( - 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50', + "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", { variants: { variant: { - default: 'bg-primary text-primary-foreground hover:bg-primary/90', - destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90', - outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground', - secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', - ghost: 'hover:bg-accent hover:text-accent-foreground', - link: 'text-primary underline-offset-4 hover:underline', + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: + "border border-input bg-background hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", }, size: { - default: 'h-10 px-4 py-2', - sm: 'h-9 rounded-md px-3', - lg: 'h-11 rounded-md px-8', - icon: 'h-10 w-10', + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", }, }, defaultVariants: { - variant: 'default', - size: 'default', + variant: "default", + size: "default", }, - } -) + }, +); -export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { - asChild?: boolean +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { - const Comp = asChild ? Slot : 'button' - return - } -) -Button.displayName = 'Button' + const Comp = asChild ? Slot : "button"; + return ( + + ); + }, +); +Button.displayName = "Button"; -export { Button, buttonVariants } +export { Button, buttonVariants }; diff --git a/web/src/components/ui/card.tsx b/web/src/components/ui/card.tsx index 63d7813..d305169 100644 --- a/web/src/components/ui/card.tsx +++ b/web/src/components/ui/card.tsx @@ -1,46 +1,85 @@ -import * as React from 'react' -import { cn } from '@/lib/utils' +import * as React from "react"; +import { cn } from "@/lib/utils"; -const Card = React.forwardRef>( - ({ className, ...props }, ref) => ( -
    - ) -) -Card.displayName = 'Card' +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
    +)); +Card.displayName = "Card"; -const CardHeader = React.forwardRef>( - ({ className, ...props }, ref) => ( -
    - ) -) -CardHeader.displayName = 'CardHeader' +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
    +)); +CardHeader.displayName = "CardHeader"; -const CardTitle = React.forwardRef>( - ({ className, ...props }, ref) => ( -

    - ) -) -CardTitle.displayName = 'CardTitle' +const CardTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

    +)); +CardTitle.displayName = "CardTitle"; -const CardDescription = React.forwardRef>( - ({ className, ...props }, ref) => ( -

    - ) -) -CardDescription.displayName = 'CardDescription' +const CardDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

    +)); +CardDescription.displayName = "CardDescription"; -const CardContent = React.forwardRef>( - ({ className, ...props }, ref) => ( -

    - ) -) -CardContent.displayName = 'CardContent' +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
    +)); +CardContent.displayName = "CardContent"; -const CardFooter = React.forwardRef>( - ({ className, ...props }, ref) => ( -
    - ) -) -CardFooter.displayName = 'CardFooter' +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
    +)); +CardFooter.displayName = "CardFooter"; -export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } +export { + Card, + CardHeader, + CardFooter, + CardTitle, + CardDescription, + CardContent, +}; diff --git a/web/src/components/ui/input.tsx b/web/src/components/ui/input.tsx index 849d89d..82c077a 100644 --- a/web/src/components/ui/input.tsx +++ b/web/src/components/ui/input.tsx @@ -1,21 +1,22 @@ -import * as React from 'react' -import { cn } from '@/lib/utils' +import * as React from "react"; +import { cn } from "@/lib/utils"; -const Input = React.forwardRef>( - ({ className, type, ...props }, ref) => { - return ( - - ) - } -) -Input.displayName = 'Input' +const Input = React.forwardRef< + HTMLInputElement, + React.InputHTMLAttributes +>(({ className, type, ...props }, ref) => { + return ( + + ); +}); +Input.displayName = "Input"; -export { Input } +export { Input }; diff --git a/web/src/components/ui/label.tsx b/web/src/components/ui/label.tsx index 152b492..e61684d 100644 --- a/web/src/components/ui/label.tsx +++ b/web/src/components/ui/label.tsx @@ -1,6 +1,6 @@ -import * as React from 'react' -import * as LabelPrimitive from '@radix-ui/react-label' -import { cn } from '@/lib/utils' +import * as React from "react"; +import * as LabelPrimitive from "@radix-ui/react-label"; +import { cn } from "@/lib/utils"; const Label = React.forwardRef< React.ComponentRef, @@ -8,10 +8,13 @@ const Label = React.forwardRef< >(({ className, ...props }, ref) => ( -)) -Label.displayName = LabelPrimitive.Root.displayName +)); +Label.displayName = LabelPrimitive.Root.displayName; -export { Label } +export { Label }; diff --git a/web/src/components/ui/switch.tsx b/web/src/components/ui/switch.tsx index c87b499..0147945 100644 --- a/web/src/components/ui/switch.tsx +++ b/web/src/components/ui/switch.tsx @@ -1,6 +1,6 @@ -import * as React from 'react' -import * as SwitchPrimitives from '@radix-ui/react-switch' -import { cn } from '@/lib/utils' +import * as React from "react"; +import * as SwitchPrimitives from "@radix-ui/react-switch"; +import { cn } from "@/lib/utils"; const Switch = React.forwardRef< React.ComponentRef, @@ -8,19 +8,19 @@ const Switch = React.forwardRef< >(({ className, ...props }, ref) => ( -)) -Switch.displayName = SwitchPrimitives.Root.displayName +)); +Switch.displayName = SwitchPrimitives.Root.displayName; -export { Switch } +export { Switch }; diff --git a/web/src/components/ui/tabs.tsx b/web/src/components/ui/tabs.tsx index ad87a47..a9ec550 100644 --- a/web/src/components/ui/tabs.tsx +++ b/web/src/components/ui/tabs.tsx @@ -1,8 +1,8 @@ -import * as React from 'react' -import * as TabsPrimitive from '@radix-ui/react-tabs' -import { cn } from '@/lib/utils' +import * as React from "react"; +import * as TabsPrimitive from "@radix-ui/react-tabs"; +import { cn } from "@/lib/utils"; -const Tabs = TabsPrimitive.Root +const Tabs = TabsPrimitive.Root; const TabsList = React.forwardRef< React.ComponentRef, @@ -11,13 +11,13 @@ const TabsList = React.forwardRef< -)) -TabsList.displayName = TabsPrimitive.List.displayName +)); +TabsList.displayName = TabsPrimitive.List.displayName; const TabsTrigger = React.forwardRef< React.ComponentRef, @@ -26,13 +26,13 @@ const TabsTrigger = React.forwardRef< -)) -TabsTrigger.displayName = TabsPrimitive.Trigger.displayName +)); +TabsTrigger.displayName = TabsPrimitive.Trigger.displayName; const TabsContent = React.forwardRef< React.ComponentRef, @@ -41,12 +41,12 @@ const TabsContent = React.forwardRef< -)) -TabsContent.displayName = TabsPrimitive.Content.displayName +)); +TabsContent.displayName = TabsPrimitive.Content.displayName; -export { Tabs, TabsList, TabsTrigger, TabsContent } +export { Tabs, TabsList, TabsTrigger, TabsContent }; diff --git a/web/src/hooks/useAuth.tsx b/web/src/hooks/useAuth.tsx index afe52f4..fe8a251 100644 --- a/web/src/hooks/useAuth.tsx +++ b/web/src/hooks/useAuth.tsx @@ -1,93 +1,114 @@ -import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react' -import { api } from '@/lib/api' -import i18n from '@/lib/i18n' -import { useTheme } from '@/components/ThemeProvider' -import type { User } from '@/types' +import { + createContext, + useContext, + useState, + useEffect, + useCallback, + type ReactNode, +} from "react"; +import { api } from "@/lib/api"; +import i18n from "@/lib/i18n"; +import { useTheme } from "@/components/ThemeProvider"; +import type { User } from "@/types"; interface LoginResponse { - success?: boolean - user?: User - requires2fa?: boolean - tempToken?: string - availableMethods?: string[] - needs2faSetup?: boolean + success?: boolean; + user?: User; + requires2fa?: boolean; + tempToken?: string; + availableMethods?: string[]; + needs2faSetup?: boolean; } interface RegisterResponse { - success?: boolean - requiresVerification?: boolean + success?: boolean; + requiresVerification?: boolean; } interface AuthContextType { - user: User | null - loading: boolean - login: (email: string, password: string) => Promise - register: (email: string, password: string) => Promise - logout: () => Promise - refreshUser: () => Promise + user: User | null; + loading: boolean; + login: (email: string, password: string) => Promise; + register: (email: string, password: string) => Promise; + logout: () => Promise; + refreshUser: () => Promise; } -const AuthContext = createContext(undefined) +const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { - const [user, setUser] = useState(null) - const [loading, setLoading] = useState(true) - const { setTheme } = useTheme() + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + const { setTheme } = useTheme(); const refreshUser = useCallback(async () => { try { - const data = await api.get('/me', { skipRedirect: true }) - setUser(data) + const data = await api.get("/me", { skipRedirect: true }); + setUser(data); if (data.language && i18n.language !== data.language) { - i18n.changeLanguage(data.language) + i18n.changeLanguage(data.language); } if (data.theme) { - setTheme(data.theme) + setTheme(data.theme); } } catch { - setUser(null) + setUser(null); } finally { - setLoading(false) + setLoading(false); } - }, [setTheme]) + }, [setTheme]); useEffect(() => { - refreshUser() - }, [refreshUser]) + refreshUser(); + }, [refreshUser]); - const login = async (email: string, password: string): Promise => { - const res = await api.post('/auth/login', { email, password }) + const login = async ( + email: string, + password: string, + ): Promise => { + const res = await api.post("/auth/login", { + email, + password, + }); if (res.success && !res.requires2fa) { - await refreshUser() + await refreshUser(); } else if (res.success && res.user) { - setUser(res.user as User) + setUser(res.user as User); } - return res - } + return res; + }; - const register = async (email: string, password: string): Promise => { - return await api.post('/auth/register', { email, password }) - } + const register = async ( + email: string, + password: string, + ): Promise => { + return await api.post("/auth/register", { + email, + password, + }); + }; const logout = async () => { try { - await api.post('/auth/logout') + await api.post("/auth/logout"); } catch { // clear local state even if API fails } - sessionStorage.removeItem('impersonate_user_id') - setUser(null) - } + sessionStorage.removeItem("impersonate_user_id"); + setUser(null); + }; return ( - + {children} - ) + ); } export function useAuth() { - const ctx = useContext(AuthContext) - if (!ctx) throw new Error('useAuth must be used within AuthProvider') - return ctx + const ctx = useContext(AuthContext); + if (!ctx) throw new Error("useAuth must be used within AuthProvider"); + return ctx; } diff --git a/web/src/hooks/useIsMobile.ts b/web/src/hooks/useIsMobile.ts index 6501376..d637599 100644 --- a/web/src/hooks/useIsMobile.ts +++ b/web/src/hooks/useIsMobile.ts @@ -1,19 +1,19 @@ -import { useState, useEffect } from 'react' +import { useState, useEffect } from "react"; -const MOBILE_BREAKPOINT = '(max-width: 767px)' +const MOBILE_BREAKPOINT = "(max-width: 767px)"; export function useIsMobile() { const [isMobile, setIsMobile] = useState(() => { - if (typeof window === 'undefined') return false - return window.matchMedia(MOBILE_BREAKPOINT).matches - }) + if (typeof window === "undefined") return false; + return window.matchMedia(MOBILE_BREAKPOINT).matches; + }); useEffect(() => { - const mq = window.matchMedia(MOBILE_BREAKPOINT) - const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches) - mq.addEventListener('change', handler) - return () => mq.removeEventListener('change', handler) - }, []) + const mq = window.matchMedia(MOBILE_BREAKPOINT); + const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches); + mq.addEventListener("change", handler); + return () => mq.removeEventListener("change", handler); + }, []); - return isMobile + return isMobile; } diff --git a/web/src/hooks/usePWAUpdate.ts b/web/src/hooks/usePWAUpdate.ts index 0b41e11..c2d2a75 100644 --- a/web/src/hooks/usePWAUpdate.ts +++ b/web/src/hooks/usePWAUpdate.ts @@ -1,29 +1,32 @@ -import { useRegisterSW } from 'virtual:pwa-register/react' +import { useRegisterSW } from "virtual:pwa-register/react"; export function usePWAUpdate() { const { needRefresh: [needRefresh, setNeedRefresh], updateServiceWorker, } = useRegisterSW({ - onRegisteredSW(swUrl, r) { + onRegisteredSW(_swUrl, r) { if (r) { - setInterval(() => { - r.update() - }, 30 * 60 * 1000) + setInterval( + () => { + r.update(); + }, + 30 * 60 * 1000, + ); } }, onRegisterError(error) { - console.error('SW registration error:', error) + console.error("SW registration error:", error); }, - }) + }); const update = () => { - updateServiceWorker(true) - } + updateServiceWorker(true); + }; const dismiss = () => { - setNeedRefresh(false) - } + setNeedRefresh(false); + }; - return { needRefresh, update, dismiss } + return { needRefresh, update, dismiss }; } diff --git a/web/src/index.css b/web/src/index.css index 20706e2..be218b4 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -125,37 +125,81 @@ select { /* iOS 15 fallback: color-mix() not supported, provide hsl() with alpha */ @supports not (color: color-mix(in lab, red, red)) { - .bg-destructive\/5 { background-color: hsl(var(--destructive) / 0.05); } + .bg-destructive\/5 { + background-color: hsl(var(--destructive) / 0.05); + } .bg-destructive\/10, - .hover\:bg-destructive\/10:hover { background-color: hsl(var(--destructive) / 0.1); } + .hover\:bg-destructive\/10:hover { + background-color: hsl(var(--destructive) / 0.1); + } .bg-destructive\/20, - .hover\:bg-destructive\/20:hover { background-color: hsl(var(--destructive) / 0.2); } + .hover\:bg-destructive\/20:hover { + background-color: hsl(var(--destructive) / 0.2); + } .bg-destructive\/90, - .hover\:bg-destructive\/90:hover { background-color: hsl(var(--destructive) / 0.9); } - .bg-primary\/10 { background-color: hsl(var(--primary) / 0.1); } - .bg-primary\/20 { background-color: hsl(var(--primary) / 0.2); } + .hover\:bg-destructive\/90:hover { + background-color: hsl(var(--destructive) / 0.9); + } + .bg-primary\/10 { + background-color: hsl(var(--primary) / 0.1); + } + .bg-primary\/20 { + background-color: hsl(var(--primary) / 0.2); + } .bg-primary\/90, - .hover\:bg-primary\/90:hover { background-color: hsl(var(--primary) / 0.9); } + .hover\:bg-primary\/90:hover { + background-color: hsl(var(--primary) / 0.9); + } .bg-muted\/20, - .hover\:bg-muted\/20:hover { background-color: hsl(var(--muted) / 0.2); } + .hover\:bg-muted\/20:hover { + background-color: hsl(var(--muted) / 0.2); + } .bg-muted\/30, - .hover\:bg-muted\/30:hover { background-color: hsl(var(--muted) / 0.3); } - .bg-muted\/50 { background-color: hsl(var(--muted) / 0.5); } + .hover\:bg-muted\/30:hover { + background-color: hsl(var(--muted) / 0.3); + } + .bg-muted\/50 { + background-color: hsl(var(--muted) / 0.5); + } .bg-muted\/80, - .hover\:bg-muted\/80:hover { background-color: hsl(var(--muted) / 0.8); } - .bg-card\/85 { background-color: hsl(var(--card) / 0.85); } - .bg-card\/95 { background-color: hsl(var(--card) / 0.95); } + .hover\:bg-muted\/80:hover { + background-color: hsl(var(--muted) / 0.8); + } + .bg-card\/85 { + background-color: hsl(var(--card) / 0.85); + } + .bg-card\/95 { + background-color: hsl(var(--card) / 0.95); + } .bg-accent\/70, - .hover\:bg-accent\/70:hover { background-color: hsl(var(--accent) / 0.7); } + .hover\:bg-accent\/70:hover { + background-color: hsl(var(--accent) / 0.7); + } .bg-secondary\/80, - .hover\:bg-secondary\/80:hover { background-color: hsl(var(--secondary) / 0.8); } - .border-destructive\/20 { border-color: hsl(var(--destructive) / 0.2); } - .border-destructive\/30 { border-color: hsl(var(--destructive) / 0.3); } - .border-primary\/30 { border-color: hsl(var(--primary) / 0.3); } + .hover\:bg-secondary\/80:hover { + background-color: hsl(var(--secondary) / 0.8); + } + .border-destructive\/20 { + border-color: hsl(var(--destructive) / 0.2); + } + .border-destructive\/30 { + border-color: hsl(var(--destructive) / 0.3); + } + .border-primary\/30 { + border-color: hsl(var(--primary) / 0.3); + } .border-primary\/50, - .hover\:border-primary\/50:hover { border-color: hsl(var(--primary) / 0.5); } - .text-destructive\/50 { color: hsl(var(--destructive) / 0.5); } - .text-muted-foreground\/50 { color: hsl(var(--muted-foreground) / 0.5); } + .hover\:border-primary\/50:hover { + border-color: hsl(var(--primary) / 0.5); + } + .text-destructive\/50 { + color: hsl(var(--destructive) / 0.5); + } + .text-muted-foreground\/50 { + color: hsl(var(--muted-foreground) / 0.5); + } .text-primary\/70, - .hover\:text-primary\/70:hover { color: hsl(var(--primary) / 0.7); } + .hover\:text-primary\/70:hover { + color: hsl(var(--primary) / 0.7); + } } diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 41aabe5..87aee70 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1,83 +1,108 @@ -const BASE_URL = '/api' +const BASE_URL = "/api"; -let refreshPromise: Promise | null = null +let refreshPromise: Promise | null = null; class ApiError extends Error { - constructor(public status: number, message: string) { - super(message) - this.name = 'ApiError' + constructor( + public status: number, + message: string, + ) { + super(message); + this.name = "ApiError"; } } async function doRefresh(): Promise { const res = await fetch(`${BASE_URL}/auth/refresh`, { - method: 'POST', - credentials: 'include', - }) - return res.ok + method: "POST", + credentials: "include", + }); + return res.ok; } -async function request(path: string, options: RequestInit & { skipRedirect?: boolean } = {}): Promise { - const { skipRedirect, ...fetchOptions } = options - const impersonateId = sessionStorage.getItem('impersonate_user_id') +async function request( + path: string, + options: RequestInit & { skipRedirect?: boolean } = {}, +): Promise { + const { skipRedirect, ...fetchOptions } = options; + const impersonateId = sessionStorage.getItem("impersonate_user_id"); const headers: Record = { - ...(fetchOptions.body ? { 'Content-Type': 'application/json' } : {}), - ...(impersonateId ? { 'X-Impersonate-User': impersonateId } : {}), - ...(fetchOptions.headers as Record || {}), - } + ...(fetchOptions.body ? { "Content-Type": "application/json" } : {}), + ...(impersonateId ? { "X-Impersonate-User": impersonateId } : {}), + ...((fetchOptions.headers as Record) || {}), + }; const response = await fetch(`${BASE_URL}${path}`, { ...fetchOptions, - credentials: 'include', + credentials: "include", headers, - }) + }); if (response.status === 401) { if (skipRedirect) { - throw new ApiError(401, 'Unauthorized') + throw new ApiError(401, "Unauthorized"); } if (!refreshPromise) { - refreshPromise = doRefresh().finally(() => { refreshPromise = null }) + refreshPromise = doRefresh().finally(() => { + refreshPromise = null; + }); } - const refreshed = await refreshPromise + const refreshed = await refreshPromise; if (refreshed) { const retryRes = await fetch(`${BASE_URL}${path}`, { ...fetchOptions, - credentials: 'include', + credentials: "include", headers, - }) - if (retryRes.ok) return retryRes.json() + }); + if (retryRes.ok) return retryRes.json(); if (retryRes.status === 401) { - window.location.href = '/login' - throw new ApiError(401, 'Unauthorized') + window.location.href = "/login"; + throw new ApiError(401, "Unauthorized"); } - const retryBody = await retryRes.json().catch(() => ({ error: 'Unknown error' })) - throw new ApiError(retryRes.status, retryBody.error || 'Request failed') + const retryBody = await retryRes + .json() + .catch(() => ({ error: "Unknown error" })); + throw new ApiError(retryRes.status, retryBody.error || "Request failed"); } - window.location.href = '/login' - throw new ApiError(401, 'Unauthorized') + window.location.href = "/login"; + throw new ApiError(401, "Unauthorized"); } if (!response.ok) { - const body = await response.json().catch(() => ({ error: 'Unknown error' })) - throw new ApiError(response.status, body.error || 'Request failed') + const body = await response + .json() + .catch(() => ({ error: "Unknown error" })); + throw new ApiError(response.status, body.error || "Request failed"); } - if (response.status === 204 || response.headers.get('content-length') === '0') { - return undefined as T + if ( + response.status === 204 || + response.headers.get("content-length") === "0" + ) { + return undefined as T; } - return response.json() + return response.json(); } export const api = { - get: (path: string, opts?: { skipRedirect?: boolean }) => request(path, opts), - post: (path: string, data?: unknown, opts?: { skipRedirect?: boolean }) => request(path, { method: 'POST', body: data ? JSON.stringify(data) : undefined, ...opts }), - put: (path: string, data?: unknown) => request(path, { method: 'PUT', body: data ? JSON.stringify(data) : undefined }), - delete: (path: string) => request(path, { method: 'DELETE' }), -} + get: (path: string, opts?: { skipRedirect?: boolean }) => + request(path, opts), + post: (path: string, data?: unknown, opts?: { skipRedirect?: boolean }) => + request(path, { + method: "POST", + body: data ? JSON.stringify(data) : undefined, + ...opts, + }), + put: (path: string, data?: unknown) => + request(path, { + method: "PUT", + body: data ? JSON.stringify(data) : undefined, + }), + delete: (path: string) => request(path, { method: "DELETE" }), +}; -export { ApiError } +export { ApiError }; diff --git a/web/src/lib/channels.ts b/web/src/lib/channels.ts index 0d2e379..d5b901d 100644 --- a/web/src/lib/channels.ts +++ b/web/src/lib/channels.ts @@ -1,11 +1,11 @@ export const CHANNELS = [ - { id: 'telegram', label: 'Telegram' }, - { id: 'webhook', label: 'Webhook' }, - { id: 'wechatbot', label: 'WeCom Bot' }, - { id: 'email', label: 'Email' }, - { id: 'bark', label: 'Bark' }, - { id: 'gotify', label: 'Gotify' }, - { id: 'serverchan', label: 'ServerChan' }, - { id: 'pushplus', label: 'PushPlus' }, - { id: 'notifyx', label: 'NotifyX' }, -] as const + { id: "telegram", label: "Telegram" }, + { id: "webhook", label: "Webhook" }, + { id: "wechatbot", label: "WeCom Bot" }, + { id: "email", label: "Email" }, + { id: "bark", label: "Bark" }, + { id: "gotify", label: "Gotify" }, + { id: "serverchan", label: "ServerChan" }, + { id: "pushplus", label: "PushPlus" }, + { id: "notifyx", label: "NotifyX" }, +] as const; diff --git a/web/src/lib/i18n.ts b/web/src/lib/i18n.ts index 7d87607..90b1ba2 100644 --- a/web/src/lib/i18n.ts +++ b/web/src/lib/i18n.ts @@ -1,8 +1,8 @@ -import i18n from 'i18next' -import { initReactI18next } from 'react-i18next' -import LanguageDetector from 'i18next-browser-languagedetector' -import zh from '../locales/zh.json' -import en from '../locales/en.json' +import i18n from "i18next"; +import { initReactI18next } from "react-i18next"; +import LanguageDetector from "i18next-browser-languagedetector"; +import zh from "../locales/zh.json"; +import en from "../locales/en.json"; i18n .use(LanguageDetector) @@ -12,12 +12,12 @@ i18n zh: { translation: zh }, en: { translation: en }, }, - fallbackLng: 'en', + fallbackLng: "en", interpolation: { escapeValue: false }, detection: { - order: ['localStorage', 'navigator'], - caches: ['localStorage'], + order: ["localStorage", "navigator"], + caches: ["localStorage"], }, - }) + }); -export default i18n +export default i18n; diff --git a/web/src/lib/lunar.ts b/web/src/lib/lunar.ts index e2cd903..4e2ff37 100644 --- a/web/src/lib/lunar.ts +++ b/web/src/lib/lunar.ts @@ -4,98 +4,197 @@ */ const lunarInfo: readonly number[] = [ - 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2, - 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, - 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, - 0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, - 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, - 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, - 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, - 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, - 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, - 0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, - 0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, - 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, - 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, - 0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, - 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, - 0x14b63, 0x09370, 0x14a38, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x1a978, 0x16aa0, 0x0a6c0, - 0x0aa60, 0x16d63, 0x0d260, 0x0d950, 0x0d554, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, - 0x025d0, 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, - 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, - 0x0d260, 0x0ea65, 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x1a4bb, 0x0a4d0, 0x0d0b0, + 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, + 0x09ad0, 0x055d2, 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, + 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, + 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566, 0x0d4a0, + 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, + 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, + 0x0a950, 0x0b557, 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, + 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, + 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, 0x096d0, 0x04dd5, + 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, + 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, + 0x0ab60, 0x09570, 0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, + 0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960, 0x0d954, 0x0d4a0, 0x0da50, + 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, + 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, + 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, + 0x0ea65, 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, + 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, + 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, 0x14b63, 0x09370, + 0x14a38, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x1a978, 0x16aa0, 0x0a6c0, + 0x0aa60, 0x16d63, 0x0d260, 0x0d950, 0x0d554, 0x0d4a0, 0x0da50, 0x07552, + 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, + 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, + 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, + 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x1a4bb, 0x0a4d0, 0x0d0b0, 0x0d250, -] +]; -const HEAVENLY = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'] as const -const EARTHLY = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'] as const +const HEAVENLY = [ + "甲", + "乙", + "丙", + "丁", + "戊", + "己", + "庚", + "辛", + "壬", + "癸", +] as const; +const EARTHLY = [ + "子", + "丑", + "寅", + "卯", + "辰", + "巳", + "午", + "未", + "申", + "酉", + "戌", + "亥", +] as const; function lunarYearName(year: number): string { - const h = (year - 4) % 10 - const e = (year - 4) % 12 - return HEAVENLY[h < 0 ? h + 10 : h] + EARTHLY[e < 0 ? e + 12 : e] + const h = (year - 4) % 10; + const e = (year - 4) % 12; + return HEAVENLY[h < 0 ? h + 10 : h] + EARTHLY[e < 0 ? e + 12 : e]; } -const MONTHS = ['正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'] as const +const MONTHS = [ + "正", + "二", + "三", + "四", + "五", + "六", + "七", + "八", + "九", + "十", + "冬", + "腊", +] as const; const DAYS = [ - '初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', - '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', - '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十', -] as const - -function leapMonth(year: number): number { return lunarInfo[year - 1900] & 0xf } -function leapDays(year: number): number { return leapMonth(year) ? ((lunarInfo[year - 1900] & 0x10000) ? 30 : 29) : 0 } -function monthDays(year: number, month: number): number { return (lunarInfo[year - 1900] & (0x10000 >> month)) ? 30 : 29 } + "初一", + "初二", + "初三", + "初四", + "初五", + "初六", + "初七", + "初八", + "初九", + "初十", + "十一", + "十二", + "十三", + "十四", + "十五", + "十六", + "十七", + "十八", + "十九", + "二十", + "廿一", + "廿二", + "廿三", + "廿四", + "廿五", + "廿六", + "廿七", + "廿八", + "廿九", + "三十", +] as const; + +function leapMonth(year: number): number { + return lunarInfo[year - 1900] & 0xf; +} +function leapDays(year: number): number { + return leapMonth(year) ? (lunarInfo[year - 1900] & 0x10000 ? 30 : 29) : 0; +} +function monthDays(year: number, month: number): number { + return lunarInfo[year - 1900] & (0x10000 >> month) ? 30 : 29; +} function lunarYearDays(year: number): number { - let sum = 348 - for (let i = 0x8000; i > 0x8; i >>= 1) sum += (lunarInfo[year - 1900] & i) ? 1 : 0 - return sum + leapDays(year) + let sum = 348; + for (let i = 0x8000; i > 0x8; i >>= 1) + sum += lunarInfo[year - 1900] & i ? 1 : 0; + return sum + leapDays(year); } export interface LunarDate { - lunarYear: number - month: number - day: number - isLeap: boolean - monthStr: string - dayStr: string + lunarYear: number; + month: number; + day: number; + isLeap: boolean; + monthStr: string; + dayStr: string; } -export function solarToLunar(year: number, month: number, day: number): LunarDate | null { - if (year < 1900 || year > 2100) return null - const baseMs = Date.UTC(1900, 0, 31) - const dateMs = Date.UTC(year, month - 1, day) - let offset = Math.round((dateMs - baseMs) / 86_400_000) +export function solarToLunar( + year: number, + month: number, + day: number, +): LunarDate | null { + if (year < 1900 || year > 2100) return null; + const baseMs = Date.UTC(1900, 0, 31); + const dateMs = Date.UTC(year, month - 1, day); + let offset = Math.round((dateMs - baseMs) / 86_400_000); - let temp = 0 - let lunarYear = 1900 - for (; lunarYear < 2101 && offset > 0; lunarYear++) { temp = lunarYearDays(lunarYear); offset -= temp } - if (offset < 0) { offset += temp; lunarYear-- } + let temp = 0; + let lunarYear = 1900; + for (; lunarYear < 2101 && offset > 0; lunarYear++) { + temp = lunarYearDays(lunarYear); + offset -= temp; + } + if (offset < 0) { + offset += temp; + lunarYear--; + } - let lunarMonth = 1 - const leap = leapMonth(lunarYear) - let isLeap = false + let lunarMonth = 1; + const leap = leapMonth(lunarYear); + let isLeap = false; for (lunarMonth = 1; lunarMonth < 13 && offset > 0; lunarMonth++) { - if (leap > 0 && lunarMonth === leap + 1 && !isLeap) { --lunarMonth; isLeap = true; temp = leapDays(lunarYear) } - else { temp = monthDays(lunarYear, lunarMonth) } - if (isLeap && lunarMonth === leap + 1) isLeap = false - offset -= temp + if (leap > 0 && lunarMonth === leap + 1 && !isLeap) { + --lunarMonth; + isLeap = true; + temp = leapDays(lunarYear); + } else { + temp = monthDays(lunarYear, lunarMonth); + } + if (isLeap && lunarMonth === leap + 1) isLeap = false; + offset -= temp; } if (offset === 0 && leap > 0 && lunarMonth === leap + 1) { - if (isLeap) { isLeap = false } else { isLeap = true; --lunarMonth } + if (isLeap) { + isLeap = false; + } else { + isLeap = true; + --lunarMonth; + } + } + if (offset < 0) { + offset += temp; + --lunarMonth; } - if (offset < 0) { offset += temp; --lunarMonth } - const lunarDay = offset + 1 + const lunarDay = offset + 1; return { lunarYear, month: lunarMonth, day: lunarDay, isLeap, - monthStr: (isLeap ? '闰' : '') + MONTHS[lunarMonth - 1] + '月', + monthStr: (isLeap ? "闰" : "") + MONTHS[lunarMonth - 1] + "月", dayStr: DAYS[lunarDay - 1], - } + }; } /** @@ -111,14 +210,15 @@ export function lunarToSolar( for (let y = year - 1; y <= year + 1; y++) { for (let m = 1; m <= 12; m++) { for (let d = 1; d <= 31; d++) { - const probe = new Date(y, m - 1, d) + const probe = new Date(y, m - 1, d); if ( probe.getFullYear() !== y || probe.getMonth() + 1 !== m || probe.getDate() !== d - ) continue + ) + continue; - const lunar = solarToLunar(y, m, d) + const lunar = solarToLunar(y, m, d); if ( lunar && lunar.lunarYear === year && @@ -126,12 +226,12 @@ export function lunarToSolar( lunar.day === day && lunar.isLeap === isLeap ) { - return { year: y, month: m, day: d } + return { year: y, month: m, day: d }; } } } } - return null + return null; } /** @@ -139,13 +239,13 @@ export function lunarToSolar( * Returns null if the date is invalid or out of range. */ export function formatLunarDate(solarDateStr: string): string | null { - if (!solarDateStr) return null - const parts = solarDateStr.split('-').map(Number) - if (parts.length !== 3) return null - const [y, m, d] = parts - const lunar = solarToLunar(y, m, d) - if (!lunar) return null - return `${lunarYearName(lunar.lunarYear)}年${lunar.monthStr}${lunar.dayStr}` + if (!solarDateStr) return null; + const parts = solarDateStr.split("-").map(Number); + if (parts.length !== 3) return null; + const [y, m, d] = parts; + const lunar = solarToLunar(y, m, d); + if (!lunar) return null; + return `${lunarYearName(lunar.lunarYear)}年${lunar.monthStr}${lunar.dayStr}`; } /** @@ -153,26 +253,36 @@ export function formatLunarDate(solarDateStr: string): string | null { * Returns the solar date as YYYY-MM-DD, or null if out of range. */ export function nextLunarAnniversary(solarDateStr: string): string | null { - const [y, m, d] = solarDateStr.split('-').map(Number) - const lunar = solarToLunar(y, m, d) - if (!lunar) return null + const [y, m, d] = solarDateStr.split("-").map(Number); + const lunar = solarToLunar(y, m, d); + if (!lunar) return null; - const now = new Date() - const currentYear = now.getFullYear() - const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}` + const now = new Date(); + const currentYear = now.getFullYear(); + const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`; // Try this year - const thisYear = lunarToSolar(currentYear, lunar.month, lunar.day, lunar.isLeap) + const thisYear = lunarToSolar( + currentYear, + lunar.month, + lunar.day, + lunar.isLeap, + ); if (thisYear) { - const dateStr = `${thisYear.year.toString().padStart(4, '0')}-${thisYear.month.toString().padStart(2, '0')}-${thisYear.day.toString().padStart(2, '0')}` - if (dateStr > todayStr) return dateStr + const dateStr = `${thisYear.year.toString().padStart(4, "0")}-${thisYear.month.toString().padStart(2, "0")}-${thisYear.day.toString().padStart(2, "0")}`; + if (dateStr > todayStr) return dateStr; } // Try next year - const nextYear = lunarToSolar(currentYear + 1, lunar.month, lunar.day, lunar.isLeap) + const nextYear = lunarToSolar( + currentYear + 1, + lunar.month, + lunar.day, + lunar.isLeap, + ); if (nextYear) { - return `${nextYear.year.toString().padStart(4, '0')}-${nextYear.month.toString().padStart(2, '0')}-${nextYear.day.toString().padStart(2, '0')}` + return `${nextYear.year.toString().padStart(4, "0")}-${nextYear.month.toString().padStart(2, "0")}-${nextYear.day.toString().padStart(2, "0")}`; } - return null + return null; } diff --git a/web/src/lib/utils.ts b/web/src/lib/utils.ts index d914078..ea2f9a1 100644 --- a/web/src/lib/utils.ts +++ b/web/src/lib/utils.ts @@ -1,42 +1,52 @@ -import { type ClassValue, clsx } from 'clsx' -import { twMerge } from 'tailwind-merge' +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)) + return twMerge(clsx(inputs)); } function bufferToBase64url(buffer: ArrayBuffer): string { - const bytes = new Uint8Array(buffer) - let binary = '' - for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]) - return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + const bytes = new Uint8Array(buffer); + let binary = ""; + for (let i = 0; i < bytes.length; i++) + binary += String.fromCharCode(bytes[i]); + return btoa(binary) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); } function base64urlToBuffer(base64url: string): ArrayBuffer { - const padded = base64url.replace(/-/g, '+').replace(/_/g, '/') - const pad = padded.length % 4 - const binary = atob(pad ? padded + '='.repeat(4 - pad) : padded) - const bytes = new Uint8Array(binary.length) - for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i) - return bytes.buffer + const padded = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const pad = padded.length % 4; + const binary = atob(pad ? padded + "=".repeat(4 - pad) : padded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes.buffer; } -export function prepareRegistrationOptions(opts: any): PublicKeyCredentialCreationOptions { +export function prepareRegistrationOptions( + opts: any, +): PublicKeyCredentialCreationOptions { return { ...opts, challenge: base64urlToBuffer(opts.challenge), - user: opts.user ? { - ...opts.user, - id: base64urlToBuffer(opts.user.id), - } : opts.user, + user: opts.user + ? { + ...opts.user, + id: base64urlToBuffer(opts.user.id), + } + : opts.user, excludeCredentials: opts.excludeCredentials?.map((c: any) => ({ ...c, id: base64urlToBuffer(c.id), })), - } + }; } -export function prepareAuthenticationOptions(opts: any): PublicKeyCredentialRequestOptions { +export function prepareAuthenticationOptions( + opts: any, +): PublicKeyCredentialRequestOptions { return { ...opts, challenge: base64urlToBuffer(opts.challenge), @@ -44,11 +54,13 @@ export function prepareAuthenticationOptions(opts: any): PublicKeyCredentialRequ ...c, id: base64urlToBuffer(c.id), })), - } + }; } -export function serializeRegistrationCredential(credential: PublicKeyCredential) { - const response = credential.response as AuthenticatorAttestationResponse +export function serializeRegistrationCredential( + credential: PublicKeyCredential, +) { + const response = credential.response as AuthenticatorAttestationResponse; return { id: credential.id, rawId: bufferToBase64url(credential.rawId), @@ -57,11 +69,13 @@ export function serializeRegistrationCredential(credential: PublicKeyCredential) clientDataJSON: bufferToBase64url(response.clientDataJSON), attestationObject: bufferToBase64url(response.attestationObject), }, - } + }; } -export function serializeAuthenticationCredential(credential: PublicKeyCredential) { - const response = credential.response as AuthenticatorAssertionResponse +export function serializeAuthenticationCredential( + credential: PublicKeyCredential, +) { + const response = credential.response as AuthenticatorAssertionResponse; return { id: credential.id, rawId: bufferToBase64url(credential.rawId), @@ -70,7 +84,9 @@ export function serializeAuthenticationCredential(credential: PublicKeyCredentia clientDataJSON: bufferToBase64url(response.clientDataJSON), authenticatorData: bufferToBase64url(response.authenticatorData), signature: bufferToBase64url(response.signature), - userHandle: response.userHandle ? bufferToBase64url(response.userHandle) : null, + userHandle: response.userHandle + ? bufferToBase64url(response.userHandle) + : null, }, - } + }; } diff --git a/web/src/main.tsx b/web/src/main.tsx index fb54703..514fcdc 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,11 +1,11 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { App } from './App' -import './lib/i18n' -import './index.css' +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; +import "./lib/i18n"; +import "./index.css"; -createRoot(document.getElementById('root')!).render( +createRoot(document.getElementById("root")!).render( , -) +); diff --git a/web/src/pages/about/AboutPage.tsx b/web/src/pages/about/AboutPage.tsx index 765d4cc..038500f 100644 --- a/web/src/pages/about/AboutPage.tsx +++ b/web/src/pages/about/AboutPage.tsx @@ -1,36 +1,45 @@ -import { useTranslation } from 'react-i18next' +import { useTranslation } from "react-i18next"; export function AboutPage() { - const { t } = useTranslation() + const { t } = useTranslation(); const stack = [ - 'Cloudflare Workers', - 'Cloudflare D1 (SQLite)', - 'Hono.js', - 'React 19', - 'Vite', - 'Tailwind CSS v4', - ] + "Cloudflare Workers", + "Cloudflare D1 (SQLite)", + "Hono.js", + "React 19", + "Vite", + "Tailwind CSS v4", + ]; return (
    -

    {t('about.title')}

    +

    {t("about.title")}

    - {t('about.version')} - {__APP_VERSION__} + + {t("about.version")} + + + {__APP_VERSION__} +
    -

    {t('about.description')}

    +

    + {t("about.description")} +

    -

    {t('about.builtWith')}

    +

    {t("about.builtWith")}

    - ) + ); } diff --git a/web/src/pages/admin/AdminAppPage.tsx b/web/src/pages/admin/AdminAppPage.tsx index 77d3001..c3b3e73 100644 --- a/web/src/pages/admin/AdminAppPage.tsx +++ b/web/src/pages/admin/AdminAppPage.tsx @@ -1,11 +1,11 @@ -import { useEffect, useState, type ReactNode } from 'react' -import { useTranslation } from 'react-i18next' -import { AlertCircle } from 'lucide-react' -import { api } from '@/lib/api' -import type { SystemSettings } from '@/types' +import { useEffect, useState, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { AlertCircle } from "lucide-react"; +import { api } from "@/lib/api"; +import type { SystemSettings } from "@/types"; const INPUT = - 'w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow' + "w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow"; function Field({ label, children }: { label: string; children: ReactNode }) { return ( @@ -13,47 +13,49 @@ function Field({ label, children }: { label: string; children: ReactNode }) { {children}
    - ) + ); } export function AdminAppPage() { - const { t } = useTranslation() - const [appName, setAppName] = useState('') - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [error, setError] = useState('') - const [saveMsg, setSaveMsg] = useState('') + const { t } = useTranslation(); + const [appName, setAppName] = useState(""); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saveMsg, setSaveMsg] = useState(""); useEffect(() => { api - .get('/admin/system/settings') - .then((s) => setAppName(s.app_name || 'eNotify')) + .get("/admin/system/settings") + .then((s) => setAppName(s.app_name || "eNotify")) .catch((e) => setError(e.message)) - .finally(() => setLoading(false)) - }, []) + .finally(() => setLoading(false)); + }, []); const handleSave = async (e: { preventDefault(): void }) => { - e.preventDefault() - setSaving(true) - setError('') - setSaveMsg('') + e.preventDefault(); + setSaving(true); + setError(""); + setSaveMsg(""); try { - await api.put('/admin/system/settings', { app_name: appName.trim() || 'eNotify' }) - setSaveMsg(t('common.success')) - setTimeout(() => setSaveMsg(''), 3000) + await api.put("/admin/system/settings", { + app_name: appName.trim() || "eNotify", + }); + setSaveMsg(t("common.success")); + setTimeout(() => setSaveMsg(""), 3000); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setSaving(false) + setSaving(false); } - } + }; if (loading) { return (
    - ) + ); } return ( @@ -67,8 +69,8 @@ export function AdminAppPage() {
    -

    {t('admin.appSettings')}

    - +

    {t("admin.appSettings")}

    + - {saving ? t('common.loading') : t('common.save')} + {saving ? t("common.loading") : t("common.save")} {saveMsg && {saveMsg}}
    - ) + ); } diff --git a/web/src/pages/admin/AdminEmailPage.tsx b/web/src/pages/admin/AdminEmailPage.tsx index d02678a..49f9424 100644 --- a/web/src/pages/admin/AdminEmailPage.tsx +++ b/web/src/pages/admin/AdminEmailPage.tsx @@ -1,29 +1,29 @@ -import { useEffect, useState, type ReactNode } from 'react' -import { useTranslation } from 'react-i18next' -import { AlertCircle } from 'lucide-react' -import { api } from '@/lib/api' -import type { SystemSettings } from '@/types' -import { useAuth } from '@/hooks/useAuth' +import { useEffect, useState, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { AlertCircle } from "lucide-react"; +import { api } from "@/lib/api"; +import type { SystemSettings } from "@/types"; +import { useAuth } from "@/hooks/useAuth"; -type EmailProvider = 'none' | 'smtp' | 'resend' +type EmailProvider = "none" | "smtp" | "resend"; interface SmtpConfig { - host: string - port: string - username: string - password: string - from: string - from_name: string + host: string; + port: string; + username: string; + password: string; + from: string; + from_name: string; } interface ResendConfig { - api_key: string - from: string - from_name: string + api_key: string; + from: string; + from_name: string; } const INPUT = - 'w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow' + "w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow"; function Field({ label, children }: { label: string; children: ReactNode }) { return ( @@ -31,114 +31,134 @@ function Field({ label, children }: { label: string; children: ReactNode }) { {children}
    - ) + ); } -const DEFAULT_SMTP: SmtpConfig = { host: '', port: '587', username: '', password: '', from: '', from_name: '' } -const DEFAULT_RESEND: ResendConfig = { api_key: '', from: '', from_name: '' } +const DEFAULT_SMTP: SmtpConfig = { + host: "", + port: "587", + username: "", + password: "", + from: "", + from_name: "", +}; +const DEFAULT_RESEND: ResendConfig = { api_key: "", from: "", from_name: "" }; export function AdminEmailPage() { - const { t } = useTranslation() - const { user } = useAuth() + const { t } = useTranslation(); + const { user } = useAuth(); - const [emailProvider, setEmailProvider] = useState('none') - const [smtp, setSmtp] = useState(DEFAULT_SMTP) - const [resend, setResend] = useState(DEFAULT_RESEND) + const [emailProvider, setEmailProvider] = useState("none"); + const [smtp, setSmtp] = useState(DEFAULT_SMTP); + const [resend, setResend] = useState(DEFAULT_RESEND); - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [error, setError] = useState('') - const [saveMsg, setSaveMsg] = useState('') + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saveMsg, setSaveMsg] = useState(""); - const [testEmailTo, setTestEmailTo] = useState('') - const [testEmailLoading, setTestEmailLoading] = useState(false) - const [testEmailMsg, setTestEmailMsg] = useState('') - const [testEmailError, setTestEmailError] = useState('') + const [testEmailTo, setTestEmailTo] = useState(""); + const [testEmailLoading, setTestEmailLoading] = useState(false); + const [testEmailMsg, setTestEmailMsg] = useState(""); + const [testEmailError, setTestEmailError] = useState(""); useEffect(() => { - if (user?.email) setTestEmailTo(user.email) - }, [user?.email]) + if (user?.email) setTestEmailTo(user.email); + }, [user?.email]); useEffect(() => { api - .get('/admin/system/settings') + .get("/admin/system/settings") .then((s) => { - setEmailProvider((s.email_provider as EmailProvider) || 'none') + setEmailProvider((s.email_provider as EmailProvider) || "none"); if (s.smtp_config) { try { - const parsed = JSON.parse(s.smtp_config) - const hasPassword = parsed.password && parsed.password !== '' - setSmtp({ ...DEFAULT_SMTP, ...parsed, password: '', _hasExisting: hasPassword } as any) + const parsed = JSON.parse(s.smtp_config); + const hasPassword = parsed.password && parsed.password !== ""; + setSmtp({ + ...DEFAULT_SMTP, + ...parsed, + password: "", + _hasExisting: hasPassword, + } as any); } catch { // ignore } } if (s.resend_config) { try { - const parsed = JSON.parse(s.resend_config) - const hasKey = parsed.api_key && parsed.api_key !== '' - setResend({ ...DEFAULT_RESEND, ...parsed, api_key: '', _hasExisting: hasKey } as any) + const parsed = JSON.parse(s.resend_config); + const hasKey = parsed.api_key && parsed.api_key !== ""; + setResend({ + ...DEFAULT_RESEND, + ...parsed, + api_key: "", + _hasExisting: hasKey, + } as any); } catch { // ignore } } }) .catch((e) => setError(e.message)) - .finally(() => setLoading(false)) - }, []) + .finally(() => setLoading(false)); + }, []); const setSmtpField = (key: keyof SmtpConfig, val: string) => - setSmtp((prev) => ({ ...prev, [key]: val })) + setSmtp((prev) => ({ ...prev, [key]: val })); const setResendField = (key: keyof ResendConfig, val: string) => - setResend((prev) => ({ ...prev, [key]: val })) + setResend((prev) => ({ ...prev, [key]: val })); const handleSave = async (e: { preventDefault(): void }) => { - e.preventDefault() - setSaving(true) - setError('') - setSaveMsg('') + e.preventDefault(); + setSaving(true); + setError(""); + setSaveMsg(""); - const payload: Record = { email_provider: emailProvider } + const payload: Record = { email_provider: emailProvider }; - if (emailProvider === 'smtp') { - const smtpPayload: Record = { ...smtp, port: Number(smtp.port) || 587 } - delete smtpPayload._hasExisting - if (!smtpPayload.password) delete smtpPayload.password - payload.smtp_config = JSON.stringify(smtpPayload) + if (emailProvider === "smtp") { + const smtpPayload: Record = { + ...smtp, + port: Number(smtp.port) || 587, + }; + delete smtpPayload._hasExisting; + if (!smtpPayload.password) delete smtpPayload.password; + payload.smtp_config = JSON.stringify(smtpPayload); } - if (emailProvider === 'resend') { - const resendPayload: Record = { ...resend } - delete resendPayload._hasExisting - if (!resendPayload.api_key) delete resendPayload.api_key - payload.resend_config = JSON.stringify(resendPayload) + if (emailProvider === "resend") { + const resendPayload: Record = { ...resend }; + delete resendPayload._hasExisting; + if (!resendPayload.api_key) delete resendPayload.api_key; + payload.resend_config = JSON.stringify(resendPayload); } try { - await api.put('/admin/system/settings', payload) - setSaveMsg(t('common.success')) - setTimeout(() => setSaveMsg(''), 3000) + await api.put("/admin/system/settings", payload); + setSaveMsg(t("common.success")); + setTimeout(() => setSaveMsg(""), 3000); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setSaving(false) + setSaving(false); } - } + }; const handleTestEmail = async () => { - setTestEmailLoading(true) - setTestEmailMsg('') - setTestEmailError('') + setTestEmailLoading(true); + setTestEmailMsg(""); + setTestEmailError(""); try { - await api.post('/admin/system/settings/test-email', { to: testEmailTo }) - setTestEmailMsg(t('admin.testEmailSent')) - setTimeout(() => setTestEmailMsg(''), 4000) + await api.post("/admin/system/settings/test-email", { to: testEmailTo }); + setTestEmailMsg(t("admin.testEmailSent")); + setTimeout(() => setTestEmailMsg(""), 4000); } catch (e: any) { - setTestEmailError(e.message || t('admin.testEmailFailed')) + setTestEmailError(e.message || t("admin.testEmailFailed")); } finally { - setTestEmailLoading(false) + setTestEmailLoading(false); } - } + }; if (loading) { return ( @@ -146,7 +166,7 @@ export function AdminEmailPage() {
    - ) + ); } return ( @@ -160,10 +180,10 @@ export function AdminEmailPage() {
    -

    {t('admin.emailProvider')}

    +

    {t("admin.emailProvider")}

    - {(['none', 'smtp', 'resend'] as EmailProvider[]).map((p) => ( + {(["none", "smtp", "resend"] as EmailProvider[]).map((p) => ( ))}
    - {emailProvider === 'smtp' && ( + {emailProvider === "smtp" && (
    - - setSmtpField('host', e.target.value)} placeholder="smtp.example.com" /> + + setSmtpField("host", e.target.value)} + placeholder="smtp.example.com" + /> - - setSmtpField('port', e.target.value)} /> + + setSmtpField("port", e.target.value)} + /> - - setSmtpField('username', e.target.value)} /> + + setSmtpField("username", e.target.value)} + /> - - setSmtpField('password', e.target.value)} placeholder="Leave blank to keep existing" /> + + setSmtpField("password", e.target.value)} + placeholder="Leave blank to keep existing" + /> - - setSmtpField('from', e.target.value)} /> + + setSmtpField("from", e.target.value)} + /> - - setSmtpField('from_name', e.target.value)} /> + + setSmtpField("from_name", e.target.value)} + />
    )} - {emailProvider === 'resend' && ( + {emailProvider === "resend" && (
    - - setResendField('api_key', e.target.value)} placeholder="Leave blank to keep existing" /> + + setResendField("api_key", e.target.value)} + placeholder="Leave blank to keep existing" + />
    - - setResendField('from', e.target.value)} /> + + setResendField("from", e.target.value)} + /> - - setResendField('from_name', e.target.value)} /> + + setResendField("from_name", e.target.value)} + />
    )}
    - {emailProvider !== 'none' && ( + {emailProvider !== "none" && (
    -

    {t('admin.testEmail')}

    - +

    {t("admin.testEmail")}

    + - {testEmailLoading ? t('common.loading') : t('admin.testEmail')} + {testEmailLoading ? t("common.loading") : t("admin.testEmail")} - {testEmailMsg && {testEmailMsg}} - {testEmailError && {testEmailError}} + {testEmailMsg && ( + {testEmailMsg} + )} + {testEmailError && ( + + {testEmailError} + + )}
    )} @@ -252,11 +326,11 @@ export function AdminEmailPage() { disabled={saving} className="bg-primary text-primary-foreground px-6 py-2 rounded-lg text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors" > - {saving ? t('common.loading') : t('common.save')} + {saving ? t("common.loading") : t("common.save")} {saveMsg && {saveMsg}}
    - ) + ); } diff --git a/web/src/pages/admin/AdminPage.tsx b/web/src/pages/admin/AdminPage.tsx index e00dbee..8371036 100644 --- a/web/src/pages/admin/AdminPage.tsx +++ b/web/src/pages/admin/AdminPage.tsx @@ -1,58 +1,67 @@ -import { useEffect } from 'react' -import { useTranslation } from 'react-i18next' -import { NavLink, Outlet, useLocation, useNavigate } from 'react-router' -import { Users, Settings, Mail, ShieldCheck, ChevronRight } from 'lucide-react' -import { cn } from '@/lib/utils' -import { useIsMobile } from '@/hooks/useIsMobile' +import { useEffect } from "react"; +import { useTranslation } from "react-i18next"; +import { NavLink, Outlet, useLocation, useNavigate } from "react-router"; +import { Users, Settings, Mail, ShieldCheck, ChevronRight } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { useIsMobile } from "@/hooks/useIsMobile"; export function AdminPage() { - const { t } = useTranslation() - const isMobile = useIsMobile() - const location = useLocation() - const navigate = useNavigate() + const { t } = useTranslation(); + const isMobile = useIsMobile(); + const location = useLocation(); + const navigate = useNavigate(); - const isIndex = location.pathname === '/admin' + const isIndex = location.pathname === "/admin"; const tabs = [ - { to: '/admin/users', label: t('admin.users'), icon: Users }, - { to: '/admin/app', label: t('admin.appSettings'), icon: Settings }, - { to: '/admin/email', label: t('admin.emailProvider'), icon: Mail }, - { to: '/admin/security', label: t('admin.accessSecurity'), icon: ShieldCheck }, - ] + { to: "/admin/users", label: t("admin.users"), icon: Users }, + { to: "/admin/app", label: t("admin.appSettings"), icon: Settings }, + { to: "/admin/email", label: t("admin.emailProvider"), icon: Mail }, + { + to: "/admin/security", + label: t("admin.accessSecurity"), + icon: ShieldCheck, + }, + ]; // Desktop: redirect /admin to /admin/users useEffect(() => { if (isIndex && !isMobile) { - navigate('/admin/users', { replace: true }) + navigate("/admin/users", { replace: true }); } - }, [isIndex, isMobile, navigate]) + }, [isIndex, isMobile, navigate]); // Mobile: show sub-menu at index if (isIndex && isMobile) { return (
    -

    {t('admin.title')}

    +

    + {t("admin.title")} +

    {tabs.map(({ to, label, icon: Icon }) => ( ))}
    - ) + ); } // Desktop or mobile sub-route: show tabs + content return (
    -

    {t('admin.title')}

    +

    {t("admin.title")}

    {tabs.map(({ to, label, icon: Icon }) => ( @@ -61,10 +70,10 @@ export function AdminPage() { to={to} className={({ isActive }) => cn( - 'flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors', + "flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors", isActive - ? 'border-primary text-primary' - : 'border-transparent text-muted-foreground hover:text-foreground', + ? "border-primary text-primary" + : "border-transparent text-muted-foreground hover:text-foreground", ) } > @@ -76,5 +85,5 @@ export function AdminPage() {
    - ) + ); } diff --git a/web/src/pages/admin/AdminSecurityPage.tsx b/web/src/pages/admin/AdminSecurityPage.tsx index 14a74aa..9d43851 100644 --- a/web/src/pages/admin/AdminSecurityPage.tsx +++ b/web/src/pages/admin/AdminSecurityPage.tsx @@ -1,84 +1,99 @@ -import { useEffect, useState } from 'react' -import { useTranslation } from 'react-i18next' -import { AlertCircle } from 'lucide-react' -import { api } from '@/lib/api' -import { cn } from '@/lib/utils' -import type { SystemSettings } from '@/types' +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { AlertCircle } from "lucide-react"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import type { SystemSettings } from "@/types"; -function Toggle({ checked, onChange, label, description }: { checked: boolean; onChange: (v: boolean) => void; label: string; description?: string }) { +function Toggle({ + checked, + onChange, + label, + description, +}: { + checked: boolean; + onChange: (v: boolean) => void; + label: string; + description?: string; +}) { return (

    {label}

    - {description &&

    {description}

    } + {description && ( +

    {description}

    + )}
    - ) + ); } export function AdminSecurityPage() { - const { t } = useTranslation() - const [emailVerification, setEmailVerification] = useState(false) - const [require2fa, setRequire2fa] = useState(false) - const [registration, setRegistration] = useState(true) + const { t } = useTranslation(); + const [emailVerification, setEmailVerification] = useState(false); + const [require2fa, setRequire2fa] = useState(false); + const [registration, setRegistration] = useState(true); - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [error, setError] = useState('') - const [saveMsg, setSaveMsg] = useState('') + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saveMsg, setSaveMsg] = useState(""); useEffect(() => { api - .get('/admin/system/settings') + .get("/admin/system/settings") .then((s) => { - setEmailVerification(s.email_verification_enabled === 'true') - setRequire2fa(s.require_2fa === 'true') - setRegistration(s.registration_enabled !== 'false') + setEmailVerification(s.email_verification_enabled === "true"); + setRequire2fa(s.require_2fa === "true"); + setRegistration(s.registration_enabled !== "false"); }) .catch((e) => setError(e.message)) - .finally(() => setLoading(false)) - }, []) + .finally(() => setLoading(false)); + }, []); const handleSave = async (e: { preventDefault(): void }) => { - e.preventDefault() - setSaving(true) - setError('') - setSaveMsg('') + e.preventDefault(); + setSaving(true); + setError(""); + setSaveMsg(""); try { - await api.put('/admin/system/settings', { + await api.put("/admin/system/settings", { email_verification_enabled: String(emailVerification), require_2fa: String(require2fa), registration_enabled: String(registration), - }) - setSaveMsg(t('common.success')) - setTimeout(() => setSaveMsg(''), 3000) + }); + setSaveMsg(t("common.success")); + setTimeout(() => setSaveMsg(""), 3000); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setSaving(false) + setSaving(false); } - } + }; if (loading) { return (
    - ) + ); } return ( @@ -92,21 +107,21 @@ export function AdminSecurityPage() {
    -

    {t('admin.accessSecurity')}

    +

    {t("admin.accessSecurity")}

    @@ -114,8 +129,8 @@ export function AdminSecurityPage() {
    @@ -126,11 +141,11 @@ export function AdminSecurityPage() { disabled={saving} className="bg-primary text-primary-foreground px-6 py-2 rounded-lg text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors" > - {saving ? t('common.loading') : t('common.save')} + {saving ? t("common.loading") : t("common.save")} {saveMsg && {saveMsg}}

    - ) + ); } diff --git a/web/src/pages/admin/AdminSystemPage.tsx b/web/src/pages/admin/AdminSystemPage.tsx index 923ecb0..c0db2d3 100644 --- a/web/src/pages/admin/AdminSystemPage.tsx +++ b/web/src/pages/admin/AdminSystemPage.tsx @@ -1,31 +1,31 @@ -import { useEffect, useState, type ReactNode } from 'react' -import { useTranslation } from 'react-i18next' -import { useNavigate } from 'react-router' -import { ArrowLeft, AlertCircle } from 'lucide-react' -import { api } from '@/lib/api' -import { cn } from '@/lib/utils' -import type { SystemSettings } from '@/types' -import { useAuth } from '@/hooks/useAuth' +import { useEffect, useState, type ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate } from "react-router"; +import { ArrowLeft, AlertCircle } from "lucide-react"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import type { SystemSettings } from "@/types"; +import { useAuth } from "@/hooks/useAuth"; -type EmailProvider = 'none' | 'smtp' | 'resend' +type EmailProvider = "none" | "smtp" | "resend"; interface SmtpConfig { - host: string - port: string - username: string - password: string - from: string - from_name: string + host: string; + port: string; + username: string; + password: string; + from: string; + from_name: string; } interface ResendConfig { - api_key: string - from: string - from_name: string + api_key: string; + from: string; + from_name: string; } const INPUT = - 'w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow' + "w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow"; function Field({ label, children }: { label: string; children: ReactNode }) { return ( @@ -33,154 +33,190 @@ function Field({ label, children }: { label: string; children: ReactNode }) { {children}
    - ) + ); } -function Toggle({ checked, onChange, label, description }: { checked: boolean; onChange: (v: boolean) => void; label: string; description?: string }) { return ( +function Toggle({ + checked, + onChange, + label, + description, +}: { + checked: boolean; + onChange: (v: boolean) => void; + label: string; + description?: string; +}) { + return (

    {label}

    - {description &&

    {description}

    } + {description && ( +

    {description}

    + )}
    - ) + ); } -const DEFAULT_SMTP: SmtpConfig = { host: '', port: '587', username: '', password: '', from: '', from_name: '' } -const DEFAULT_RESEND: ResendConfig = { api_key: '', from: '', from_name: '' } +const DEFAULT_SMTP: SmtpConfig = { + host: "", + port: "587", + username: "", + password: "", + from: "", + from_name: "", +}; +const DEFAULT_RESEND: ResendConfig = { api_key: "", from: "", from_name: "" }; export function AdminSystemPage() { - const { t } = useTranslation() - const navigate = useNavigate() - const { user } = useAuth() - - const [appName, setAppName] = useState('') - const [emailProvider, setEmailProvider] = useState('none') - const [smtp, setSmtp] = useState(DEFAULT_SMTP) - const [resend, setResend] = useState(DEFAULT_RESEND) - const [emailVerification, setEmailVerification] = useState(false) - const [require2fa, setRequire2fa] = useState(false) - const [registration, setRegistration] = useState(true) - - const [loading, setLoading] = useState(true) - const [saving, setSaving] = useState(false) - const [error, setError] = useState('') - const [saveMsg, setSaveMsg] = useState('') - - const [testEmailTo, setTestEmailTo] = useState('') - const [testEmailLoading, setTestEmailLoading] = useState(false) - const [testEmailMsg, setTestEmailMsg] = useState('') - const [testEmailError, setTestEmailError] = useState('') + const { t } = useTranslation(); + const navigate = useNavigate(); + const { user } = useAuth(); + + const [appName, setAppName] = useState(""); + const [emailProvider, setEmailProvider] = useState("none"); + const [smtp, setSmtp] = useState(DEFAULT_SMTP); + const [resend, setResend] = useState(DEFAULT_RESEND); + const [emailVerification, setEmailVerification] = useState(false); + const [require2fa, setRequire2fa] = useState(false); + const [registration, setRegistration] = useState(true); + + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saveMsg, setSaveMsg] = useState(""); + + const [testEmailTo, setTestEmailTo] = useState(""); + const [testEmailLoading, setTestEmailLoading] = useState(false); + const [testEmailMsg, setTestEmailMsg] = useState(""); + const [testEmailError, setTestEmailError] = useState(""); useEffect(() => { - if (user?.email) setTestEmailTo(user.email) - }, [user?.email]) + if (user?.email) setTestEmailTo(user.email); + }, [user?.email]); useEffect(() => { api - .get('/admin/system/settings') + .get("/admin/system/settings") .then((s) => { - setAppName(s.app_name || 'eNotify') - setEmailProvider((s.email_provider as EmailProvider) || 'none') - setEmailVerification(s.email_verification_enabled === 'true') - setRequire2fa(s.require_2fa === 'true') - setRegistration(s.registration_enabled !== 'false') + setAppName(s.app_name || "eNotify"); + setEmailProvider((s.email_provider as EmailProvider) || "none"); + setEmailVerification(s.email_verification_enabled === "true"); + setRequire2fa(s.require_2fa === "true"); + setRegistration(s.registration_enabled !== "false"); if (s.smtp_config) { try { - const parsed = JSON.parse(s.smtp_config) - const hasPassword = parsed.password && parsed.password !== '' - setSmtp({ ...DEFAULT_SMTP, ...parsed, password: '', _hasExisting: hasPassword } as any) + const parsed = JSON.parse(s.smtp_config); + const hasPassword = parsed.password && parsed.password !== ""; + setSmtp({ + ...DEFAULT_SMTP, + ...parsed, + password: "", + _hasExisting: hasPassword, + } as any); } catch { // ignore } } if (s.resend_config) { try { - const parsed = JSON.parse(s.resend_config) - const hasKey = parsed.api_key && parsed.api_key !== '' - setResend({ ...DEFAULT_RESEND, ...parsed, api_key: '', _hasExisting: hasKey } as any) + const parsed = JSON.parse(s.resend_config); + const hasKey = parsed.api_key && parsed.api_key !== ""; + setResend({ + ...DEFAULT_RESEND, + ...parsed, + api_key: "", + _hasExisting: hasKey, + } as any); } catch { // ignore } } }) .catch((e) => setError(e.message)) - .finally(() => setLoading(false)) - }, []) + .finally(() => setLoading(false)); + }, []); const setSmtpField = (key: keyof SmtpConfig, val: string) => - setSmtp((prev) => ({ ...prev, [key]: val })) + setSmtp((prev) => ({ ...prev, [key]: val })); const setResendField = (key: keyof ResendConfig, val: string) => - setResend((prev) => ({ ...prev, [key]: val })) + setResend((prev) => ({ ...prev, [key]: val })); const handleSave = async (e: React.SyntheticEvent) => { - e.preventDefault() - setSaving(true) - setError('') - setSaveMsg('') + e.preventDefault(); + setSaving(true); + setError(""); + setSaveMsg(""); const payload: Record = { - app_name: appName.trim() || 'eNotify', + app_name: appName.trim() || "eNotify", email_provider: emailProvider, email_verification_enabled: String(emailVerification), require_2fa: String(require2fa), registration_enabled: String(registration), + }; + + if (emailProvider === "smtp") { + const smtpPayload: Record = { + ...smtp, + port: Number(smtp.port) || 587, + }; + delete smtpPayload._hasExisting; + if (!smtpPayload.password) delete smtpPayload.password; + payload.smtp_config = JSON.stringify(smtpPayload); } - - if (emailProvider === 'smtp') { - const smtpPayload: Record = { ...smtp, port: Number(smtp.port) || 587 } - delete smtpPayload._hasExisting - if (!smtpPayload.password) delete smtpPayload.password - payload.smtp_config = JSON.stringify(smtpPayload) - } - if (emailProvider === 'resend') { - const resendPayload: Record = { ...resend } - delete resendPayload._hasExisting - if (!resendPayload.api_key) delete resendPayload.api_key - payload.resend_config = JSON.stringify(resendPayload) + if (emailProvider === "resend") { + const resendPayload: Record = { ...resend }; + delete resendPayload._hasExisting; + if (!resendPayload.api_key) delete resendPayload.api_key; + payload.resend_config = JSON.stringify(resendPayload); } try { - await api.put('/admin/system/settings', payload) - setSaveMsg(t('common.success')) - setTimeout(() => setSaveMsg(''), 3000) + await api.put("/admin/system/settings", payload); + setSaveMsg(t("common.success")); + setTimeout(() => setSaveMsg(""), 3000); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setSaving(false) + setSaving(false); } - } + }; const handleTestEmail = async () => { - setTestEmailLoading(true) - setTestEmailMsg('') - setTestEmailError('') + setTestEmailLoading(true); + setTestEmailMsg(""); + setTestEmailError(""); try { - await api.post('/admin/system/settings/test-email', { to: testEmailTo }) - setTestEmailMsg(t('admin.testEmailSent')) - setTimeout(() => setTestEmailMsg(''), 4000) + await api.post("/admin/system/settings/test-email", { to: testEmailTo }); + setTestEmailMsg(t("admin.testEmailSent")); + setTimeout(() => setTestEmailMsg(""), 4000); } catch (e: any) { - setTestEmailError(e.message || t('admin.testEmailFailed')) + setTestEmailError(e.message || t("admin.testEmailFailed")); } finally { - setTestEmailLoading(false) + setTestEmailLoading(false); } - } + }; if (loading) { return ( @@ -189,16 +225,20 @@ export function AdminSystemPage() {
    - ) + ); } return (
    - -

    {t('admin.system')}

    +

    {t("admin.system")}

    {error && ( @@ -211,8 +251,8 @@ export function AdminSystemPage() {
    {/* App settings */}
    -

    {t('admin.appSettings')}

    - +

    {t("admin.appSettings")}

    + -

    {t('admin.emailProvider')}

    +

    {t("admin.emailProvider")}

    - {(['none', 'smtp', 'resend'] as EmailProvider[]).map((p) => ( + {(["none", "smtp", "resend"] as EmailProvider[]).map((p) => ( ))}
    - {emailProvider === 'smtp' && ( + {emailProvider === "smtp" && (
    - - setSmtpField('host', e.target.value)} placeholder="smtp.example.com" /> + + setSmtpField("host", e.target.value)} + placeholder="smtp.example.com" + /> - - setSmtpField('port', e.target.value)} /> + + setSmtpField("port", e.target.value)} + /> - - setSmtpField('username', e.target.value)} /> + + setSmtpField("username", e.target.value)} + /> - - setSmtpField('password', e.target.value)} placeholder="Leave blank to keep existing" /> + + setSmtpField("password", e.target.value)} + placeholder="Leave blank to keep existing" + /> - - setSmtpField('from', e.target.value)} /> + + setSmtpField("from", e.target.value)} + /> - - setSmtpField('from_name', e.target.value)} /> + + setSmtpField("from_name", e.target.value)} + />
    )} - {emailProvider === 'resend' && ( + {emailProvider === "resend" && (
    - - setResendField('api_key', e.target.value)} placeholder="Leave blank to keep existing" /> + + setResendField("api_key", e.target.value)} + placeholder="Leave blank to keep existing" + />
    - - setResendField('from', e.target.value)} /> + + setResendField("from", e.target.value)} + /> - - setResendField('from_name', e.target.value)} /> + + setResendField("from_name", e.target.value)} + />
    )}
    {/* Test email */} - {emailProvider !== 'none' && ( + {emailProvider !== "none" && (
    -

    {t('admin.testEmail')}

    - +

    {t("admin.testEmail")}

    + - {testEmailLoading ? t('common.loading') : t('admin.testEmail')} + {testEmailLoading ? t("common.loading") : t("admin.testEmail")} - {testEmailMsg && {testEmailMsg}} - {testEmailError && {testEmailError}} + {testEmailMsg && ( + {testEmailMsg} + )} + {testEmailError && ( + + {testEmailError} + + )}
    )} {/* Toggles */}
    -

    {t('admin.accessSecurity')}

    +

    {t("admin.accessSecurity")}

    @@ -336,8 +430,8 @@ export function AdminSystemPage() {
    @@ -348,11 +442,11 @@ export function AdminSystemPage() { disabled={saving} className="bg-primary text-primary-foreground px-6 py-2 rounded-lg text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors" > - {saving ? t('common.loading') : t('common.save')} + {saving ? t("common.loading") : t("common.save")} {saveMsg && {saveMsg}}
    - ) + ); } diff --git a/web/src/pages/admin/AdminUsersPage.tsx b/web/src/pages/admin/AdminUsersPage.tsx index 1dc3b13..e1a53e9 100644 --- a/web/src/pages/admin/AdminUsersPage.tsx +++ b/web/src/pages/admin/AdminUsersPage.tsx @@ -1,143 +1,179 @@ -import { useEffect, useState } from 'react' -import { useTranslation } from 'react-i18next' -import { useNavigate } from 'react-router' -import { AlertCircle, ShieldCheck, UserX, UserCheck, Trash2, LogIn, UserPlus, Pencil, X, Users } from 'lucide-react' -import { api } from '@/lib/api' -import { cn } from '@/lib/utils' -import { useAuth } from '@/hooks/useAuth' +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate } from "react-router"; +import { + AlertCircle, + ShieldCheck, + UserX, + UserCheck, + Trash2, + LogIn, + UserPlus, + Pencil, + X, + Users, +} from "lucide-react"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { useAuth } from "@/hooks/useAuth"; interface AdminUser { - id: string - email: string - role: 'admin' | 'user' - is_active: boolean - email_verified: boolean - created_at: string + id: string; + email: string; + role: "admin" | "user"; + is_active: boolean; + email_verified: boolean; + created_at: string; } const ROLE_STYLE: Record = { - admin: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400', - user: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400', -} + admin: + "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400", + user: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400", +}; -const INPUT = 'w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring' -const SELECT = cn(INPUT, 'cursor-pointer') +const INPUT = + "w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"; +const SELECT = cn(INPUT, "cursor-pointer"); export function AdminUsersPage() { - const { t } = useTranslation() - const navigate = useNavigate() - const { user: currentUser, refreshUser } = useAuth() - const [users, setUsers] = useState([]) - const [loading, setLoading] = useState(true) - const [error, setError] = useState('') + const { t } = useTranslation(); + const navigate = useNavigate(); + const { user: currentUser, refreshUser } = useAuth(); + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); // Add user form - const [showAddForm, setShowAddForm] = useState(false) - const [newEmail, setNewEmail] = useState('') - const [newPassword, setNewPassword] = useState('') - const [newRole, setNewRole] = useState<'user' | 'admin'>('user') - const [adding, setAdding] = useState(false) + const [showAddForm, setShowAddForm] = useState(false); + const [newEmail, setNewEmail] = useState(""); + const [newPassword, setNewPassword] = useState(""); + const [newRole, setNewRole] = useState<"user" | "admin">("user"); + const [adding, setAdding] = useState(false); // Edit user - const [editUser, setEditUser] = useState(null) - const [editEmail, setEditEmail] = useState('') - const [editPassword, setEditPassword] = useState('') - const [editing, setEditing] = useState(false) - - const load = () => { - api - .get('/admin/users') - .then(setUsers) - .catch((e) => setError(e.message)) - .finally(() => setLoading(false)) - } + const [editUser, setEditUser] = useState(null); + const [editEmail, setEditEmail] = useState(""); + const [editPassword, setEditPassword] = useState(""); + const [editing, setEditing] = useState(false); useEffect(() => { - load() - }, []) + const load = () => { + api + .get("/admin/users") + .then(setUsers) + .catch((e) => setError(e.message)) + .finally(() => setLoading(false)); + }; + load(); + }, []); const handleToggleActive = async (u: AdminUser) => { try { - await api.put(`/admin/users/${u.id}`, { is_active: u.is_active ? 0 : 1 }) - setUsers((prev) => prev.map((x) => (x.id === u.id ? { ...x, is_active: !u.is_active } : x))) + await api.put(`/admin/users/${u.id}`, { is_active: u.is_active ? 0 : 1 }); + setUsers((prev) => + prev.map((x) => + x.id === u.id ? { ...x, is_active: !u.is_active } : x, + ), + ); } catch (e: any) { - setError(e.message) + setError(e.message); } - } + }; const handleChangeRole = async (u: AdminUser) => { - const newRole = u.role === 'admin' ? 'user' : 'admin' - if (!window.confirm(t('admin.confirmRoleChange', { email: u.email, role: newRole }))) return + const newRole = u.role === "admin" ? "user" : "admin"; + if ( + !window.confirm( + t("admin.confirmRoleChange", { email: u.email, role: newRole }), + ) + ) + return; try { - await api.put(`/admin/users/${u.id}`, { role: newRole }) - setUsers((prev) => prev.map((x) => (x.id === u.id ? { ...x, role: newRole } : x))) + await api.put(`/admin/users/${u.id}`, { role: newRole }); + setUsers((prev) => + prev.map((x) => (x.id === u.id ? { ...x, role: newRole } : x)), + ); } catch (e: any) { - setError(e.message) + setError(e.message); } - } + }; const handleDelete = async (u: AdminUser) => { - if (!window.confirm(t('admin.confirmDeleteUser', { email: u.email }))) return + if (!window.confirm(t("admin.confirmDeleteUser", { email: u.email }))) + return; try { - await api.delete(`/admin/users/${u.id}`) - setUsers((prev) => prev.filter((x) => x.id !== u.id)) + await api.delete(`/admin/users/${u.id}`); + setUsers((prev) => prev.filter((x) => x.id !== u.id)); } catch (e: any) { - setError(e.message) + setError(e.message); } - } + }; const handleAddUser = async (e: React.SyntheticEvent) => { - e.preventDefault() - setAdding(true) - setError('') + e.preventDefault(); + setAdding(true); + setError(""); try { - const created = await api.post('/admin/users', { email: newEmail, password: newPassword, role: newRole }) - setUsers((prev) => [created, ...prev]) - setNewEmail('') - setNewPassword('') - setNewRole('user') - setShowAddForm(false) + const created = await api.post("/admin/users", { + email: newEmail, + password: newPassword, + role: newRole, + }); + setUsers((prev) => [created, ...prev]); + setNewEmail(""); + setNewPassword(""); + setNewRole("user"); + setShowAddForm(false); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setAdding(false) + setAdding(false); } - } + }; const openEditUser = (u: AdminUser) => { - setEditUser(u) - setEditEmail(u.email) - setEditPassword('') - setError('') - } + setEditUser(u); + setEditEmail(u.email); + setEditPassword(""); + setError(""); + }; const handleEditUser = async (e: React.SyntheticEvent) => { - e.preventDefault() - if (!editUser) return - setEditing(true) - setError('') + e.preventDefault(); + if (!editUser) return; + setEditing(true); + setError(""); try { - const body: Record = {} - if (editEmail !== editUser.email) body.email = editEmail - if (editPassword) body.password = editPassword - if (Object.keys(body).length === 0) { setEditUser(null); return } - await api.put(`/admin/users/${editUser.id}`, body) - setUsers((prev) => prev.map((x) => x.id === editUser.id ? { ...x, email: editEmail || x.email } : x)) - setEditUser(null) + const body: Record = {}; + if (editEmail !== editUser.email) body.email = editEmail; + if (editPassword) body.password = editPassword; + if (Object.keys(body).length === 0) { + setEditUser(null); + return; + } + await api.put(`/admin/users/${editUser.id}`, body); + setUsers((prev) => + prev.map((x) => + x.id === editUser.id ? { ...x, email: editEmail || x.email } : x, + ), + ); + setEditUser(null); } catch (e: any) { - setError(e.message) + setError(e.message); } finally { - setEditing(false) + setEditing(false); } - } + }; const handleImpersonate = async (u: AdminUser) => { - if (!window.confirm(t('admin.confirmImpersonate', { email: u.email }))) return - sessionStorage.setItem('impersonate_user_id', u.id) - window.dispatchEvent(new Event('impersonation-change')) - await refreshUser() - navigate('/') - } + if (!window.confirm(t("admin.confirmImpersonate", { email: u.email }))) + return; + sessionStorage.setItem("impersonate_user_id", u.id); + window.dispatchEvent(new Event("impersonation-change")); + await refreshUser(); + navigate("/"); + }; return (
    @@ -147,7 +183,9 @@ export function AdminUsersPage() {
    -

    {t('admin.userCount')}

    +

    + {t("admin.userCount")} +

    {loading ? (
    ) : ( @@ -156,11 +194,15 @@ export function AdminUsersPage() {
    @@ -174,31 +216,60 @@ export function AdminUsersPage() { {/* Add user form */} {showAddForm && (
    -

    {t('admin.addUser')}

    +

    {t("admin.addUser")}

    - - setNewEmail(e.target.value)} /> + + setNewEmail(e.target.value)} + />
    - - setNewPassword(e.target.value)} /> + + setNewPassword(e.target.value)} + />
    - - + setNewRole(e.target.value as "user" | "admin") + } + > + +
    - -
    @@ -210,26 +281,53 @@ export function AdminUsersPage() {
    -

    {t('admin.editUser')}

    -
    - - setEditEmail(e.target.value)} /> + + setEditEmail(e.target.value)} + />
    - - setEditPassword(e.target.value)} placeholder="••••••••" /> + + setEditPassword(e.target.value)} + placeholder="••••••••" + />
    - -
    @@ -239,9 +337,14 @@ export function AdminUsersPage() { {loading ? (
    - {Array.from({ length: 4 }).map((_, i) => ( -
    - ))} + {Array.from({ length: 4 }, (_, i) => `skeleton-${i + 1}`).map( + (skeletonKey) => ( +
    + ), + )}
    ) : ( <> @@ -250,8 +353,18 @@ export function AdminUsersPage() { - {[t('auth.email'), t('admin.role'), t('common.status'), t('admin.verified'), t('admin.created'), t('common.actions')].map((h) => ( - ))} @@ -259,32 +372,46 @@ export function AdminUsersPage() { {users.map((u) => ( - +
    + {[ + t("auth.email"), + t("admin.role"), + t("common.status"), + t("admin.verified"), + t("admin.created"), + t("common.actions"), + ].map((h) => ( + {h}
    {u.email} {u.id === currentUser?.id && ( - ({t('admin.you')}) + + ({t("admin.you")}) + )} - - {t(`admin.role${u.role.charAt(0).toUpperCase() + u.role.slice(1)}`)} + + {t( + `admin.role${u.role.charAt(0).toUpperCase() + u.role.slice(1)}`, + )} - {u.is_active ? t('common.active') : t('common.inactive')} + {u.is_active + ? t("common.active") + : t("common.inactive")} - {u.email_verified ? '✓' : '✗'} + {u.email_verified ? "✓" : "✗"} {u.created_at.slice(0, 10)} @@ -292,11 +419,20 @@ export function AdminUsersPage() {
    @@ -350,59 +490,78 @@ export function AdminUsersPage() { {/* Mobile cards */}
    {users.map((u) => ( -
    +

    {u.email}

    -

    {u.created_at.slice(0, 10)}

    +

    + {u.created_at.slice(0, 10)} +

    - - {t(`admin.role${u.role.charAt(0).toUpperCase() + u.role.slice(1)}`)} + + {t( + `admin.role${u.role.charAt(0).toUpperCase() + u.role.slice(1)}`, + )} - {u.is_active ? t('common.active') : t('common.inactive')} + {u.is_active ? t("common.active") : t("common.inactive")}
    {u.id !== currentUser?.id && (
    )} @@ -412,5 +571,5 @@ export function AdminUsersPage() { )}
    - ) + ); } diff --git a/web/src/pages/auth/ForgotPasswordPage.tsx b/web/src/pages/auth/ForgotPasswordPage.tsx index cedbf3f..00f64f1 100644 --- a/web/src/pages/auth/ForgotPasswordPage.tsx +++ b/web/src/pages/auth/ForgotPasswordPage.tsx @@ -1,92 +1,114 @@ -import { useState, useEffect, useCallback } from 'react' -import { useTranslation } from 'react-i18next' -import { Link } from 'react-router' -import { api } from '@/lib/api' +import { useState, useEffect, useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router"; +import { api } from "@/lib/api"; export function ForgotPasswordPage() { - const { t } = useTranslation() - - const [step, setStep] = useState<'email' | 'reset'>('email') - const [email, setEmail] = useState('') - const [code, setCode] = useState('') - const [newPassword, setNewPassword] = useState('') - const [confirmPassword, setConfirmPassword] = useState('') - const [loading, setLoading] = useState(false) - const [error, setError] = useState('') - const [done, setDone] = useState(false) - const [countdown, setCountdown] = useState(0) + const { t } = useTranslation(); + + const [step, setStep] = useState<"email" | "reset">("email"); + const [email, setEmail] = useState(""); + const [code, setCode] = useState(""); + const [newPassword, setNewPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [done, setDone] = useState(false); + const [countdown, setCountdown] = useState(0); const startCountdown = useCallback(() => { - setCountdown(60) - }, []) + setCountdown(60); + }, []); useEffect(() => { - if (countdown <= 0) return - const timer = setTimeout(() => setCountdown(countdown - 1), 1000) - return () => clearTimeout(timer) - }, [countdown]) + if (countdown <= 0) return; + const timer = setTimeout(() => setCountdown(countdown - 1), 1000); + return () => clearTimeout(timer); + }, [countdown]); const handleSendCode = async (e?: React.SyntheticEvent) => { - if (e) e.preventDefault() - setError('') - setLoading(true) + if (e) e.preventDefault(); + setError(""); + setLoading(true); try { - await api.post('/auth/password/forgot', { email }, { skipRedirect: true }) - setStep('reset') - startCountdown() + await api.post( + "/auth/password/forgot", + { email }, + { skipRedirect: true }, + ); + setStep("reset"); + startCountdown(); } catch (err: any) { if (err.status === 429) { - setError(t('auth.resetCodeCooldown')) - if (step === 'reset') startCountdown() + setError(t("auth.resetCodeCooldown")); + if (step === "reset") startCountdown(); } else { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } } finally { - setLoading(false) + setLoading(false); } - } + }; const handleReset = async (e: React.SyntheticEvent) => { - e.preventDefault() - setError('') + e.preventDefault(); + setError(""); if (newPassword !== confirmPassword) { - setError(t('auth.passwordMismatch')) - return + setError(t("auth.passwordMismatch")); + return; } - setLoading(true) + setLoading(true); try { - await api.post('/auth/password/reset', { email, code, new_password: newPassword }, { skipRedirect: true }) - setDone(true) + await api.post( + "/auth/password/reset", + { email, code, new_password: newPassword }, + { skipRedirect: true }, + ); + setDone(true); } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; - const INPUT = 'w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring' + const INPUT = + "w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"; return (
    -

    {t('app.name')}

    -

    {t('auth.forgotPassword')}

    +

    + {t("app.name")} +

    +

    + {t("auth.forgotPassword")} +

    {done ? (
    -

    {t('auth.resetPasswordSuccess')}

    - - {t('auth.login')} +

    + {t("auth.resetPasswordSuccess")} +

    + + {t("auth.login")}
    - ) : step === 'email' ? ( + ) : step === "email" ? (
    -

    {t('auth.forgotPasswordDesc')}

    +

    + {t("auth.forgotPasswordDesc")} +

    - + {error && ( -

    {error}

    +

    + {error} +

    )}

    - - {t('auth.backToLogin')} + + {t("auth.backToLogin")}

    ) : (
    -

    {t('auth.resetCodeSent')}

    +

    + {t("auth.resetCodeSent")} +

    - + setCode(e.target.value.replace(/\D/g, ''))} + onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))} className={INPUT} placeholder="123456" />
    - +
    - + {error && ( -

    {error}

    +

    + {error} +

    )}
    @@ -174,12 +211,17 @@ export function ForgotPasswordPage() { type="button" disabled={countdown > 0 || loading} onClick={() => handleSendCode()} - className={`font-medium ${countdown > 0 ? 'text-muted-foreground cursor-not-allowed' : 'text-primary hover:underline'}`} + className={`font-medium ${countdown > 0 ? "text-muted-foreground cursor-not-allowed" : "text-primary hover:underline"}`} > - {countdown > 0 ? t('auth.resendCodeCountdown', { seconds: countdown }) : t('auth.resendCode')} + {countdown > 0 + ? t("auth.resendCodeCountdown", { seconds: countdown }) + : t("auth.resendCode")} - - {t('auth.backToLogin')} + + {t("auth.backToLogin")}
    @@ -187,5 +229,5 @@ export function ForgotPasswordPage() {
    - ) + ); } diff --git a/web/src/pages/auth/LoginPage.tsx b/web/src/pages/auth/LoginPage.tsx index 2249749..b6d099f 100644 --- a/web/src/pages/auth/LoginPage.tsx +++ b/web/src/pages/auth/LoginPage.tsx @@ -1,67 +1,78 @@ -import { useState, useEffect } from 'react' -import { useNavigate, Link } from 'react-router' -import { useTranslation } from 'react-i18next' -import { Globe, Sun, Moon, Monitor } from 'lucide-react' -import { useAuth } from '@/hooks/useAuth' -import { useTheme } from '@/components/ThemeProvider' -import { api } from '@/lib/api' +import { useState, useEffect } from "react"; +import { useNavigate, Link } from "react-router"; +import { useTranslation } from "react-i18next"; +import { Globe, Sun, Moon, Monitor } from "lucide-react"; +import { useAuth } from "@/hooks/useAuth"; +import { useTheme } from "@/components/ThemeProvider"; +import { api } from "@/lib/api"; export function LoginPage() { - const { t, i18n } = useTranslation() - const navigate = useNavigate() - const { login } = useAuth() - const { theme, setTheme } = useTheme() + const { t, i18n } = useTranslation(); + const navigate = useNavigate(); + const { login } = useAuth(); + const { theme, setTheme } = useTheme(); - const [email, setEmail] = useState('') - const [password, setPassword] = useState('') - const [error, setError] = useState('') - const [loading, setLoading] = useState(false) - const [registrationEnabled, setRegistrationEnabled] = useState(false) + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [registrationEnabled, setRegistrationEnabled] = useState(false); useEffect(() => { - api.get<{ registration_enabled: boolean }>('/system/info') + api + .get<{ registration_enabled: boolean }>("/system/info") .then((info) => setRegistrationEnabled(info.registration_enabled)) - .catch(() => {}) - }, []) + .catch(() => {}); + }, []); const handleSubmit = async (e: React.SyntheticEvent) => { - e.preventDefault() - setError('') - setLoading(true) + e.preventDefault(); + setError(""); + setLoading(true); try { - const res = await login(email, password) + const res = await login(email, password); if (res.requires2fa) { - navigate('/2fa', { state: { tempToken: res.tempToken, availableMethods: res.availableMethods } }) + navigate("/2fa", { + state: { + tempToken: res.tempToken, + availableMethods: res.availableMethods, + }, + }); } else if (res.needs2faSetup) { - sessionStorage.setItem('needs_2fa_setup', '1') - navigate('/') + sessionStorage.setItem("needs_2fa_setup", "1"); + navigate("/"); } else { - navigate('/') + navigate("/"); } } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; const toggleLang = () => { - i18n.changeLanguage(i18n.language === 'zh' ? 'en' : 'zh') - } + i18n.changeLanguage(i18n.language === "zh" ? "en" : "zh"); + }; const cycleTheme = () => { - const order: Array<'light' | 'dark' | 'system'> = ['light', 'dark', 'system'] - const idx = order.indexOf(theme) - setTheme(order[(idx + 1) % 3]) - } + const order: Array<"light" | "dark" | "system"> = [ + "light", + "dark", + "system", + ]; + const idx = order.indexOf(theme); + setTheme(order[(idx + 1) % 3]); + }; - const ThemeIcon = theme === 'light' ? Sun : theme === 'dark' ? Moon : Monitor + const ThemeIcon = theme === "light" ? Sun : theme === "dark" ? Moon : Monitor; return (
    {/* Top-right controls */}
    {registrationEnabled && (

    - {t('auth.noAccount')}{' '} - - {t('auth.register')} + {t("auth.noAccount")}{" "} + + {t("auth.register")}

    )}
    - ) + ); } diff --git a/web/src/pages/auth/RegisterPage.tsx b/web/src/pages/auth/RegisterPage.tsx index c34dd17..df81b48 100644 --- a/web/src/pages/auth/RegisterPage.tsx +++ b/web/src/pages/auth/RegisterPage.tsx @@ -1,61 +1,66 @@ -import { useState } from 'react' -import { useNavigate, Link } from 'react-router' -import { useTranslation } from 'react-i18next' -import { Globe, Sun, Moon, Monitor } from 'lucide-react' -import { useAuth } from '@/hooks/useAuth' -import { useTheme } from '@/components/ThemeProvider' +import { useState } from "react"; +import { Link } from "react-router"; +import { useTranslation } from "react-i18next"; +import { Globe, Sun, Moon, Monitor } from "lucide-react"; +import { useAuth } from "@/hooks/useAuth"; +import { useTheme } from "@/components/ThemeProvider"; export function RegisterPage() { - const { t, i18n } = useTranslation() - const { register } = useAuth() - const { theme, setTheme } = useTheme() + const { t, i18n } = useTranslation(); + const { register } = useAuth(); + const { theme, setTheme } = useTheme(); - const [email, setEmail] = useState('') - const [password, setPassword] = useState('') - const [confirmPassword, setConfirmPassword] = useState('') - const [error, setError] = useState('') - const [message, setMessage] = useState('') - const [loading, setLoading] = useState(false) + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [error, setError] = useState(""); + const [message, setMessage] = useState(""); + const [loading, setLoading] = useState(false); const handleSubmit = async (e: React.SyntheticEvent) => { - e.preventDefault() + e.preventDefault(); if (password !== confirmPassword) { - setError(t('auth.passwordMismatch')) - return + setError(t("auth.passwordMismatch")); + return; } - setError('') - setLoading(true) + setError(""); + setLoading(true); try { - const res = await register(email, password) + const res = await register(email, password); if (res.requiresVerification) { - setMessage(t('auth.verifyEmailSent')) + setMessage(t("auth.verifyEmailSent")); } else { - setMessage(t('auth.registerSuccess')) + setMessage(t("auth.registerSuccess")); } } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; const toggleLang = () => { - i18n.changeLanguage(i18n.language === 'zh' ? 'en' : 'zh') - } + i18n.changeLanguage(i18n.language === "zh" ? "en" : "zh"); + }; const cycleTheme = () => { - const order: Array<'light' | 'dark' | 'system'> = ['light', 'dark', 'system'] - const idx = order.indexOf(theme) - setTheme(order[(idx + 1) % 3]) - } + const order: Array<"light" | "dark" | "system"> = [ + "light", + "dark", + "system", + ]; + const idx = order.indexOf(theme); + setTheme(order[(idx + 1) % 3]); + }; - const ThemeIcon = theme === 'light' ? Sun : theme === 'dark' ? Moon : Monitor + const ThemeIcon = theme === "light" ? Sun : theme === "dark" ? Moon : Monitor; return (
    {/* Top-right controls */}
    )} {!message && (

    - {t('auth.hasAccount')}{' '} - - {t('auth.login')} + {t("auth.hasAccount")}{" "} + + {t("auth.login")}

    )}
    - ) + ); } diff --git a/web/src/pages/auth/TwoFactorPage.tsx b/web/src/pages/auth/TwoFactorPage.tsx index 72f624e..50f66be 100644 --- a/web/src/pages/auth/TwoFactorPage.tsx +++ b/web/src/pages/auth/TwoFactorPage.tsx @@ -1,147 +1,161 @@ -import { useState, useEffect } from 'react' -import { useNavigate, useLocation, Link } from 'react-router' -import { useTranslation } from 'react-i18next' -import { KeyRound, Mail, Smartphone } from 'lucide-react' -import { api } from '@/lib/api' -import { useAuth } from '@/hooks/useAuth' -import { cn, serializeAuthenticationCredential, prepareAuthenticationOptions } from '@/lib/utils' - -type Method = 'totp' | 'email_otp' | 'passkey' +import { useState, useEffect } from "react"; +import { useNavigate, useLocation, Link } from "react-router"; +import { useTranslation } from "react-i18next"; +import { KeyRound, Mail, Smartphone } from "lucide-react"; +import { api } from "@/lib/api"; +import { useAuth } from "@/hooks/useAuth"; +import { + cn, + serializeAuthenticationCredential, + prepareAuthenticationOptions, +} from "@/lib/utils"; + +type Method = "totp" | "email_otp" | "passkey"; interface LocationState { - tempToken: string - availableMethods: string[] + tempToken: string; + availableMethods: string[]; } export function TwoFactorPage() { - const { t } = useTranslation() - const navigate = useNavigate() - const location = useLocation() - const { refreshUser } = useAuth() + const { t } = useTranslation(); + const navigate = useNavigate(); + const location = useLocation(); + const { refreshUser } = useAuth(); - const state = location.state as LocationState | null - const availableMethods = (state?.availableMethods ?? ['totp']) as Method[] + const state = location.state as LocationState | null; + const availableMethods = (state?.availableMethods ?? ["totp"]) as Method[]; - const [activeMethod, setActiveMethod] = useState(availableMethods[0]) - const [code, setCode] = useState('') - const [error, setError] = useState('') - const [loading, setLoading] = useState(false) - const [codeSent, setCodeSent] = useState(false) + const [activeMethod, setActiveMethod] = useState(availableMethods[0]); + const [code, setCode] = useState(""); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + const [codeSent, setCodeSent] = useState(false); useEffect(() => { if (!state?.tempToken) { - navigate('/login', { replace: true }) + navigate("/login", { replace: true }); } - }, [state, navigate]) - - if (!state?.tempToken) return null - - const methodConfig: Record = { - totp: { label: t('auth.totp'), icon: }, - email_otp: { label: t('auth.emailOtp'), icon: }, - passkey: { label: t('auth.passkey'), icon: }, - } + }, [state, navigate]); + + if (!state?.tempToken) return null; + + const methodConfig: Record = + { + totp: { label: t("auth.totp"), icon: }, + email_otp: { + label: t("auth.emailOtp"), + icon: , + }, + passkey: { + label: t("auth.passkey"), + icon: , + }, + }; const switchMethod = (m: Method) => { - setActiveMethod(m) - setCode('') - setError('') - setCodeSent(false) - } + setActiveMethod(m); + setCode(""); + setError(""); + setCodeSent(false); + }; const handleVerify = async (e: React.SyntheticEvent) => { - e.preventDefault() - setError('') - setLoading(true) + e.preventDefault(); + setError(""); + setLoading(true); try { - const res = await api.post('/auth/2fa/verify', { + const res = await api.post("/auth/2fa/verify", { tempToken: state.tempToken, method: activeMethod, code, - }) + }); if (res.success) { - await refreshUser().catch(() => {}) - navigate('/', { replace: true }) + await refreshUser().catch(() => {}); + navigate("/", { replace: true }); } } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; const handleSendCode = async () => { - setError('') - setLoading(true) + setError(""); + setLoading(true); try { - await api.post('/auth/2fa/otp/send', { tempToken: state.tempToken }) - setCodeSent(true) + await api.post("/auth/2fa/otp/send", { tempToken: state.tempToken }); + setCodeSent(true); } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; const handlePasskey = async () => { - setError('') - setLoading(true) + setError(""); + setLoading(true); try { const opts = await api.post( - '/auth/2fa/passkey/authenticate/options', - { tempToken: state.tempToken } - ) + "/auth/2fa/passkey/authenticate/options", + { tempToken: state.tempToken }, + ); const credential = await navigator.credentials.get({ publicKey: prepareAuthenticationOptions(opts), - }) - if (!credential) throw new Error('No credential returned') - const serialized = serializeAuthenticationCredential(credential as PublicKeyCredential) - const res = await api.post('/auth/2fa/passkey/authenticate/verify', { + }); + if (!credential) throw new Error("No credential returned"); + const serialized = serializeAuthenticationCredential( + credential as PublicKeyCredential, + ); + const res = await api.post("/auth/2fa/passkey/authenticate/verify", { tempToken: state.tempToken, ...serialized, - }) + }); if (res.success) { - await refreshUser().catch(() => {}) - navigate('/', { replace: true }) + await refreshUser().catch(() => {}); + navigate("/", { replace: true }); } } catch (err: any) { - setError(err.message || t('common.error')) + setError(err.message || t("common.error")); } finally { - setLoading(false) + setLoading(false); } - } + }; return (

    - {t('auth.twoFactor')} + {t("auth.twoFactor")}

    - {t('auth.enterCode')} + {t("auth.enterCode")}

    {/* Method selector */} {availableMethods.length > 1 && (
    {availableMethods.map((m) => { - const cfg = methodConfig[m] + const cfg = methodConfig[m]; return ( - ) + ); })}
    )} @@ -152,45 +166,48 @@ export function TwoFactorPage() {

    )} - {activeMethod === 'passkey' ? ( + {activeMethod === "passkey" ? ( ) : (
    - {activeMethod === 'email_otp' && !codeSent && ( + {activeMethod === "email_otp" && !codeSent && ( )} - {activeMethod === 'email_otp' && codeSent && ( + {activeMethod === "email_otp" && codeSent && (

    - {t('auth.verifyEmailSent')} + {t("auth.verifyEmailSent")}

    )} - {(activeMethod === 'totp' || codeSent) && ( + {(activeMethod === "totp" || codeSent) && ( <>
    setCode(e.target.value.replace(/\D/g, ''))} + onChange={(e) => + setCode(e.target.value.replace(/\D/g, "")) + } className="w-full px-3 py-3 rounded-md border border-input bg-background text-foreground text-center text-2xl tracking-[0.5em] font-mono focus:outline-none focus:ring-2 focus:ring-ring" placeholder="000000" autoFocus @@ -201,7 +218,7 @@ export function TwoFactorPage() { disabled={loading || code.length < 6} className="w-full py-2 px-4 bg-primary hover:bg-primary/90 disabled:opacity-50 text-primary-foreground text-sm font-medium rounded-md transition-colors" > - {loading ? t('common.loading') : t('common.confirm')} + {loading ? t("common.loading") : t("common.confirm")} )} @@ -209,12 +226,15 @@ export function TwoFactorPage() { )}
    - - ← {t('common.back')} + + ← {t("common.back")}
    - ) + ); } diff --git a/web/src/pages/auth/VerifyEmailPage.tsx b/web/src/pages/auth/VerifyEmailPage.tsx index 2a2b938..7cc0ddd 100644 --- a/web/src/pages/auth/VerifyEmailPage.tsx +++ b/web/src/pages/auth/VerifyEmailPage.tsx @@ -1,54 +1,58 @@ -import { useState, useEffect, useRef } from 'react' -import { Link, useSearchParams } from 'react-router' -import { useTranslation } from 'react-i18next' -import { CheckCircle, XCircle, Loader2 } from 'lucide-react' -import { api } from '@/lib/api' +import { useState, useEffect, useRef } from "react"; +import { Link, useSearchParams } from "react-router"; +import { useTranslation } from "react-i18next"; +import { CheckCircle, XCircle, Loader2 } from "lucide-react"; +import { api } from "@/lib/api"; export function VerifyEmailPage() { - const { t } = useTranslation() - const [searchParams] = useSearchParams() - const token = searchParams.get('token') + const { t } = useTranslation(); + const [searchParams] = useSearchParams(); + const token = searchParams.get("token"); - const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading') - const [message, setMessage] = useState('') - const calledRef = useRef(false) + const [status, setStatus] = useState<"loading" | "success" | "error">( + "loading", + ); + const [message, setMessage] = useState(""); + const calledRef = useRef(false); useEffect(() => { - if (calledRef.current) return - calledRef.current = true + if (calledRef.current) return; + calledRef.current = true; if (!token) { - setStatus('error') - setMessage(t('auth.missingToken')) - return + setStatus("error"); + setMessage(t("auth.missingToken")); + return; } api - .post('/auth/email/verify', { token }) + .post("/auth/email/verify", { token }) .then(() => { - setStatus('success') - setMessage(t('auth.verifyEmailSuccess')) + setStatus("success"); + setMessage(t("auth.verifyEmailSuccess")); }) .catch((err: any) => { - setStatus('error') - setMessage(err.message || t('common.error')) - }) - }, [token, t]) + setStatus("error"); + setMessage(err.message || t("common.error")); + }); + }, [token, t]); return (
    -

    {t('auth.verifyEmail')}

    +

    + {t("auth.verifyEmail")} +

    - {status === 'loading' && ( + {status === "loading" && (
    -

    {t('common.loading')}

    +

    {t("common.loading")}

    )} - {status === 'success' && ( + {status === "success" && (

    {message}

    @@ -56,12 +60,12 @@ export function VerifyEmailPage() { to="/login" className="mt-4 inline-block py-2 px-6 bg-primary hover:bg-primary/90 text-primary-foreground text-sm font-medium rounded-md transition-colors" > - {t('auth.login')} + {t("auth.login")}
    )} - {status === 'error' && ( + {status === "error" && (

    {message}

    @@ -69,12 +73,12 @@ export function VerifyEmailPage() { to="/login" className="mt-4 inline-block text-sm text-primary hover:underline font-medium" > - {t('auth.login')} + {t("auth.login")}
    )}
    - ) + ); } diff --git a/web/src/pages/channels/ChannelPage.tsx b/web/src/pages/channels/ChannelPage.tsx index adffcc2..dc64727 100644 --- a/web/src/pages/channels/ChannelPage.tsx +++ b/web/src/pages/channels/ChannelPage.tsx @@ -1,28 +1,27 @@ -import { useState, useEffect, useCallback } from 'react' -import { useTranslation } from 'react-i18next' -import { ChevronDown, ChevronUp, Clock, Radio } from 'lucide-react' -import { api } from '@/lib/api' -import { useAuth } from '@/hooks/useAuth' -import { cn } from '@/lib/utils' -import { NotificationHoursSelector } from '@/components/NotificationHoursSelector' -import type { NotificationConfig } from '@/types' +import { useState, useEffect, useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { ChevronDown, ChevronUp, Clock, Radio } from "lucide-react"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { NotificationHoursSelector } from "@/components/NotificationHoursSelector"; +import type { NotificationConfig } from "@/types"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface ChannelFieldDef { - key: string - label: string - type: 'text' | 'password' | 'textarea' | 'select' - options?: string[] - placeholder?: string + key: string; + label: string; + type: "text" | "password" | "textarea" | "select"; + options?: string[]; + placeholder?: string; } interface ChannelDef { - id: string - label: string - fields: ChannelFieldDef[] + id: string; + label: string; + fields: ChannelFieldDef[]; } // --------------------------------------------------------------------------- @@ -31,73 +30,115 @@ interface ChannelDef { const CHANNELS: ChannelDef[] = [ { - id: 'telegram', - label: 'Telegram', + id: "telegram", + label: "Telegram", fields: [ - { key: 'bot_token', label: 'Bot Token', type: 'password' }, - { key: 'chat_id', label: 'Chat ID', type: 'text' }, + { key: "bot_token", label: "Bot Token", type: "password" }, + { key: "chat_id", label: "Chat ID", type: "text" }, ], }, { - id: 'webhook', - label: 'Webhook', + id: "webhook", + label: "Webhook", fields: [ - { key: 'url', label: 'URL', type: 'text', placeholder: 'https://' }, - { key: 'method', label: 'Method', type: 'select', options: ['POST', 'GET', 'PUT'] }, - { key: 'headers', label: 'Headers (JSON)', type: 'textarea', placeholder: '{"Authorization": "Bearer ..."}' }, - { key: 'template', label: 'Body Template', type: 'textarea' }, + { key: "url", label: "URL", type: "text", placeholder: "https://" }, + { + key: "method", + label: "Method", + type: "select", + options: ["POST", "GET", "PUT"], + }, + { + key: "headers", + label: "Headers (JSON)", + type: "textarea", + placeholder: '{"Authorization": "Bearer ..."}', + }, + { key: "template", label: "Body Template", type: "textarea" }, ], }, { - id: 'wechatbot', - label: 'WeCom Bot', + id: "wechatbot", + label: "WeCom Bot", fields: [ - { key: 'webhook', label: 'Webhook URL', type: 'text', placeholder: 'https://' }, - { key: 'msg_type', label: 'Message Type', type: 'select', options: ['markdown', 'text'] }, - { key: 'at_all', label: 'At All', type: 'select', options: ['false', 'true'] }, + { + key: "webhook", + label: "Webhook URL", + type: "text", + placeholder: "https://", + }, + { + key: "msg_type", + label: "Message Type", + type: "select", + options: ["markdown", "text"], + }, + { + key: "at_all", + label: "At All", + type: "select", + options: ["false", "true"], + }, ], }, { - id: 'email', - label: 'Email', - fields: [{ key: 'to', label: 'To Address', type: 'text', placeholder: '' }], + id: "email", + label: "Email", + fields: [ + { + key: "to", + label: "To Address", + type: "text", + placeholder: "", + }, + ], }, { - id: 'bark', - label: 'Bark', + id: "bark", + label: "Bark", fields: [ - { key: 'device_key', label: 'Device Key', type: 'text' }, - { key: 'server', label: 'Server (optional)', type: 'text', placeholder: 'https://api.day.app' }, + { key: "device_key", label: "Device Key", type: "text" }, + { + key: "server", + label: "Server (optional)", + type: "text", + placeholder: "https://api.day.app", + }, ], }, { - id: 'gotify', - label: 'Gotify', + id: "gotify", + label: "Gotify", fields: [ - { key: 'server_url', label: 'Server URL', type: 'text', placeholder: 'https://' }, - { key: 'app_token', label: 'App Token', type: 'password' }, + { + key: "server_url", + label: "Server URL", + type: "text", + placeholder: "https://", + }, + { key: "app_token", label: "App Token", type: "password" }, ], }, { - id: 'serverchan', - label: 'ServerChan', - fields: [{ key: 'sendkey', label: 'SendKey', type: 'text' }], + id: "serverchan", + label: "ServerChan", + fields: [{ key: "sendkey", label: "SendKey", type: "text" }], }, { - id: 'pushplus', - label: 'PushPlus', + id: "pushplus", + label: "PushPlus", fields: [ - { key: 'token', label: 'Token', type: 'text' }, - { key: 'topic', label: 'Topic (optional)', type: 'text' }, - { key: 'channel', label: 'Channel (optional)', type: 'text' }, + { key: "token", label: "Token", type: "text" }, + { key: "topic", label: "Topic (optional)", type: "text" }, + { key: "channel", label: "Channel (optional)", type: "text" }, ], }, { - id: 'notifyx', - label: 'NotifyX', - fields: [{ key: 'api_key', label: 'API Key', type: 'password' }], + id: "notifyx", + label: "NotifyX", + fields: [{ key: "api_key", label: "API Key", type: "password" }], }, -] +]; // --------------------------------------------------------------------------- // Shared UI primitives @@ -108,44 +149,48 @@ function FormField({ value, onChange, }: { - def: ChannelFieldDef - value: string - onChange: (v: string) => void + def: ChannelFieldDef; + value: string; + onChange: (v: string) => void; }) { const base = - 'w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring' + "w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"; - if (def.type === 'textarea') { + if (def.type === "textarea") { return (