mirror of
https://github.com/luckjiawei/podux.git
synced 2026-11-30 11:36:53 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54e1b343cc | ||
|
|
b2b6f129e6 | ||
|
|
1136797a36 | ||
|
|
8a44a6ed87 | ||
|
|
0736130769 | ||
|
|
1bdd35a234 | ||
|
|
e37661c6e9 | ||
|
|
1578832510 | ||
|
|
cfbbf31543 | ||
|
|
3a1ad7ce65 | ||
|
|
01c3a70d2b |
No files matched your search
@@ -0,0 +1,91 @@
|
||||
# Podux Agent Development Guide
|
||||
|
||||
## Project Scope and Technology Stack
|
||||
|
||||
Podux is a web management platform for centrally managing frpc server configurations, proxies, connection status, network latency, and runtime logs. The current codebase uses Go 1.25.5, PocketBase 0.35.0, and embedded frp 0.68.0. The application frontend is under `site/` and uses React 19, TypeScript 5.9, Vite 7, Radix Themes 3, and Tailwind CSS 4. `docs/` is a VitePress 1 documentation site; its Vue dependency does not mean that the application frontend uses Vue.
|
||||
|
||||
Treat `go.mod`, `site/package.json`, and `docs/package.json` as the sources of truth for versions and dependencies. Do not infer versions from documentation examples.
|
||||
|
||||
## Directory Map
|
||||
|
||||
| Path | Responsibility |
|
||||
| --- | --- |
|
||||
| `main.go` | PocketBase startup and dependency wiring, hooks/custom routes, monitoring scheduler, and static asset serving entry point |
|
||||
| `internal/domain/` | Server/proxy domain models and repository interfaces |
|
||||
| `internal/application/` | Use-case services for dashboard, frpc, importer, monitoring, proxy, server, system, version, and related features |
|
||||
| `internal/infrastructure/persistence/` | Repository implementations based on PocketBase/dbx |
|
||||
| `internal/interfaces/http/` | Custom HTTP handlers and authentication middleware |
|
||||
| `migrations/` | The sole version-controlled source of truth for PocketBase collection schemas |
|
||||
| `pkg/` | Build information, responses, shared types, and utilities |
|
||||
| `site/` | React application frontend; calls both the PocketBase collection API and custom `/api/*` endpoints |
|
||||
| `docs/` | Independent VitePress documentation site |
|
||||
| `development/` | Development design documents for agents and maintainers; not part of the web documentation site |
|
||||
| `pb_public/` | Copy destination for `site/dist`; embedded into the Go binary by `main.go` via `go:embed`; not committed |
|
||||
| `pb_data/` | PocketBase SQLite data, uploads, and `frpc/<server-id>` runtime logs/certificates; not committed |
|
||||
| `build/`, `deploy/` | Multi-platform build scripts and Docker deployment files |
|
||||
|
||||
See the [development design documentation](development/README.md) for the full design index.
|
||||
|
||||
## Local Development and Verification
|
||||
|
||||
Prerequisites: Go 1.25.5 as required by `go.mod`, Node.js 20 (CI baseline), and pnpm 10 (CI baseline).
|
||||
|
||||
```bash
|
||||
# Backend (ensure pb_public/index.html exists first; see the full frontend build below)
|
||||
go run . serve
|
||||
|
||||
# Application frontend; Vite proxies /api to 127.0.0.1:8090
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
pnpm --dir site run dev
|
||||
|
||||
# Documentation site
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:dev
|
||||
```
|
||||
|
||||
Run before submitting:
|
||||
|
||||
```bash
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
pnpm --dir site run lint
|
||||
pnpm --dir site run build
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:build
|
||||
|
||||
# go:embed must be satisfied before Go tooling loads the main package
|
||||
rm -rf pb_public
|
||||
mkdir -p pb_public
|
||||
cp -R site/dist/. pb_public/
|
||||
go vet ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
`build/build.sh` builds the frontend, copies `site/dist` to `pb_public`, runs `go mod tidy`, and builds platform packages. It rewrites generated directories and may modify module files, so it is not the preferred verification command for documentation-only or narrowly scoped changes.
|
||||
|
||||
## Change Conventions
|
||||
|
||||
- Backend: preserve the `interfaces -> application -> domain` dependency direction. Infrastructure implements domain repositories, and `main.go` performs central wiring. Handlers own transport-level validation and responses; business orchestration belongs in application services.
|
||||
- Frontend: keep React + TypeScript and follow the existing split between `index.tsx` (state/orchestration) and `*.view.tsx` (presentation). Prefer components from `site/src/components/` and Radix Themes. Reuse `site/src/lib/api.ts` or `pocketbase.ts` for API requests.
|
||||
- Migrations: schema changes must add a reviewable, reversible `migrations/*.go` migration. Migrations are the source of truth; never replace one by modifying a live SQLite database or production schema through the admin UI.
|
||||
- API: place custom routes in `internal/interfaces/http/` and use `requireAuth` by default. Review PocketBase collection rules as well. When paths, request/response contracts, authentication, or collection fields change, update the relevant design documents.
|
||||
- Styling: follow the [UI specification](development/ui-spec.md). Prefer Radix tokens, component props, and Tailwind utilities; do not introduce another unsupported set of brand tokens.
|
||||
- Internationalization: update both `site/src/locales/zh.json` and `en.json` for user-visible text, and access it through `react-i18next`'s `t()`. Avoid new hard-coded strings.
|
||||
- Documentation: implementation changes must update the [architecture](development/architecture.md), [database design](development/database-design.md), or [UI specification](development/ui-spec.md) when applicable. Documentation claims must link to repository paths or be marked "To be confirmed."
|
||||
|
||||
## Security Boundaries
|
||||
|
||||
- Do not commit secrets, tokens, certificates, user data, `pb_data/`, `pb_public/`, `site/dist/`, `docs/.vitepress/dist/`, or build packages.
|
||||
- `fh_servers.auth`, TLS private keys, user passwords, and token keys are sensitive. Never log their original values. Avoid logging, copying, or exposing tokens used in SSE query parameters.
|
||||
- Do not substitute manual database operations for migrations. Relations currently have no cascading deletes; assess orphaned-data risks before deleting parent records.
|
||||
- Do not perform unrelated repository-wide formatting or overwrite existing worktree changes.
|
||||
- Changes to endpoints, authentication rules, or data structures must update tests, callers, and the design documents in this directory.
|
||||
|
||||
## Pre-Submission Checklist
|
||||
|
||||
- [ ] `git diff` contains only the intended scope, with no runtime data, build artifacts, or unrelated formatting.
|
||||
- [ ] Go vet/test/build, frontend lint/build, and documentation build were run and their results reported accurately.
|
||||
- [ ] New or changed APIs, collections, relations, and rules are reflected in the database/architecture documentation.
|
||||
- [ ] The UI reuses shared components; both themes, the 760px mobile layout, Chinese/English text, and basic keyboard operation were checked.
|
||||
- [ ] Relative Markdown links work, and Mermaid names match the code and render correctly.
|
||||
- [ ] No sensitive values appear in code, logs, screenshots, or commit history.
|
||||
@@ -35,6 +35,8 @@
|
||||
<a href="https://github.com/luckjiawei/podux/issues">🐛 Report Bug</a>
|
||||
·
|
||||
<a href="https://github.com/luckjiawei/podux/issues">✨ Request Feature</a>
|
||||
·
|
||||
<a href="#community"><strong>💬 Community</strong></a>
|
||||
</p>
|
||||
|
||||
<br />
|
||||
@@ -62,6 +64,30 @@
|
||||
- 2026-03-12: Released v0.1.2
|
||||
- 2026-03-16: Released v0.1.3
|
||||
- 2026-03-25: Released v0.1.4
|
||||
- 2026-03-26: Released v0.1.5
|
||||
- 2026-03-31: Released v0.1.6
|
||||
|
||||
## Community
|
||||
|
||||
No advertisements allowed!
|
||||
|
||||
### Telegram
|
||||
|
||||
Join the Telegram group for announcements, tips and general discussion:
|
||||
|
||||
👉 [https://t.me/+Tv7AcgbLn21hMDA1](https://t.me/+Tv7AcgbLn21hMDA1)
|
||||
|
||||
### WeChat Group
|
||||
|
||||
Scan the QR code to join the open source project discussion group.
|
||||
|
||||
If the group is full, scan the official account QR code on the right and follow it to get an invitation.
|
||||
|
||||
<img src="screenshot/wechat-qr.png" alt="WeChat Group QR Code" width="200"> <img src="screenshot/mp-qr.jpg" alt="Official Account QR Code" width="200">
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE)
|
||||
|
||||
## Star History
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@
|
||||
<a href="https://github.com/luckjiawei/podux/issues">🐛 提交 Bug</a>
|
||||
·
|
||||
<a href="https://github.com/luckjiawei/podux/issues">✨ 需求建议</a>
|
||||
·
|
||||
<a href="#社区"><strong>💬 交流群</strong></a>
|
||||
</p>
|
||||
|
||||
<br />
|
||||
@@ -62,6 +64,30 @@
|
||||
- 2026-03-14: 发布 v0.1.2
|
||||
- 2026-03-16: 发布 v0.1.3
|
||||
- 2026-03-25: 发布 v0.1.4
|
||||
- 2026-03-26: 发布 v0.1.5
|
||||
- 2026-03-31: 发布 v0.1.6
|
||||
|
||||
## 社区
|
||||
|
||||
禁止广告!
|
||||
|
||||
### Telegram
|
||||
|
||||
欢迎加入 Telegram 群,获取项目动态、使用技巧并参与交流:
|
||||
|
||||
👉 [https://t.me/+Tv7AcgbLn21hMDA1](https://t.me/+Tv7AcgbLn21hMDA1)
|
||||
|
||||
### 微信群
|
||||
|
||||
扫描微信二维码加入开源项目交流群。
|
||||
|
||||
若群已满,请扫描右侧公众号二维码,关注后获取入群方式。
|
||||
|
||||
<img src="screenshot/wechat-qr.png" alt="微信群二维码" width="200"> <img src="screenshot/mp-qr.jpg" alt="公众号二维码" width="200">
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE)
|
||||
|
||||
## Star 历史
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Podux Development Design Documentation
|
||||
|
||||
This directory documents the verifiable design of the current `main` baseline and serves as the entry point for future development and agent changes:
|
||||
|
||||
- [System architecture](architecture.md): in-process components, layering, request/startup flows, build and deployment, and CI boundaries.
|
||||
- [Database design](database-design.md): all application collections, relations, rules, indexes, lifecycles, and implementation discrepancies.
|
||||
- [UI specification](ui-spec.md): themes, actual tokens, layouts, and component reuse rules for the React application frontend.
|
||||
|
||||
## Sources of Truth and Scope
|
||||
|
||||
These documents are based on repository code and configuration, not speculation about a target architecture. For the database, `migrations/*.go` is the primary source of truth and is cross-checked against domain models, repositories, application services, HTTP handlers, and callers under `site/src/`. For the UI, the sources are `site/src/index.css`, theme contexts, layouts, shared components, and pages. Build and deployment facts come from `go.mod`, package manifests, `main.go`, CI, `build/build.sh`, and Docker files.
|
||||
|
||||
"Verified current state" describes the present implementation. "Current discrepancy / To be confirmed" and "Technical debt" identify gaps that the code cannot resolve or constraints that are not yet unified; they do not authorize schema or behavior changes.
|
||||
|
||||
## Update Triggers
|
||||
|
||||
- Update the architecture document when component boundaries, startup flow, custom routes, background tasks, persistence, or deployment change.
|
||||
- Update the database document when migrations, collection rules/indexes/relations, field mappings, or retention/deletion policies change.
|
||||
- Update the UI document when theme configuration, design tokens, layout breakpoints, shared components, interaction states, internationalization, or accessibility constraints change.
|
||||
- Update the repository-root `AGENT.md` when any of the changes above also affect agent working conventions.
|
||||
@@ -0,0 +1,97 @@
|
||||
# System Architecture
|
||||
|
||||
## Verified Current State
|
||||
|
||||
Podux is a single Go/PocketBase service that hosts the API, SQLite persistence, background monitoring, frpc client services, and the React static site. The code calls running instances `processes`, but `internal/application/frpc/service.go` actually creates in-process `frp/client.Service` instances and runs them in goroutines; it does not launch separate `frpc` OS processes.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B[Browser / React Web<br/>site/src] -->|PocketBase collection API| PB[PocketBase / Go<br/>main.go]
|
||||
B -->|custom /api routes| H[HTTP handlers<br/>internal/interfaces/http]
|
||||
H --> A[Application services<br/>internal/application]
|
||||
PB --> H
|
||||
A --> D[Domain contracts/models<br/>internal/domain]
|
||||
A --> R[Repository implementations<br/>internal/infrastructure/persistence]
|
||||
R --> DB[(SQLite / PocketBase collections<br/>pb_data)]
|
||||
PB --> DB
|
||||
A --> F[frp client.Service instances<br/>in-process goroutines]
|
||||
F --> FRPS[Remote frps servers]
|
||||
A --> M[MonitorService + MetricsScheduler]
|
||||
M --> DB
|
||||
PB --> E[Embedded React assets<br/>pb_public]
|
||||
```
|
||||
|
||||
### Layers and Entry Points
|
||||
|
||||
- `main.go` creates the PocketBase app, registers migration commands, constructs repositories/services/handlers, binds the `fh_proxies` update hook, and initializes state, starts background tasks, registers routes, and configures the static-file fallback in `OnServe`.
|
||||
- `internal/domain` currently defines lightweight models, status values, and repository interfaces only for servers and proxies.
|
||||
- `internal/application` handles statistics, imports, frpc configuration/lifecycle, networking and metrics, system settings, and version queries.
|
||||
- `internal/infrastructure/persistence` implements server and proxy repositories with dbx/PocketBase.
|
||||
- `internal/interfaces/http` exposes `/api/dashboard/*`, `/api/frpc/*`, `/api/import/*`, `/api/servers*`, `/api/system/*`, and `/api/frp/version`. Except for initialization-status and initialization endpoints, registered custom routes use `requireAuth`.
|
||||
- React also uses the PocketBase SDK directly for `fh_users`, `fh_servers`, and `fh_proxies`; collection API rules control that access boundary.
|
||||
|
||||
### Typical Request Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as React Servers page
|
||||
participant H as FrpcHandler
|
||||
participant S as frpc.Service
|
||||
participant R as server/proxy repositories
|
||||
participant DB as PocketBase/SQLite
|
||||
participant C as frp client.Service
|
||||
UI->>H: POST /api/frpc/launch {id}
|
||||
H->>H: requireAuth + 15-char id validation
|
||||
H->>S: LaunchFrpc(id)
|
||||
S->>DB: load fh_servers
|
||||
S->>R: FindEnabledByServerID(id)
|
||||
R->>DB: query fh_proxies
|
||||
S->>C: NewService + Run(ctx)
|
||||
S->>R: bootStatus = running
|
||||
H-->>UI: 200 / error
|
||||
loop every 5 seconds
|
||||
S->>C: StatusExporter
|
||||
S->>R: proxy bootStatus online/offline
|
||||
end
|
||||
```
|
||||
|
||||
Standard server/proxy CRUD primarily uses the PocketBase SDK. Server lists, dashboard data, imports, settings, and runtime controls use custom APIs. After a successful `fh_proxies` update, a hook calls `ReloadFrpc` if the owning server is running.
|
||||
|
||||
### Startup Flow and Background Tasks
|
||||
|
||||
1. Go `init` loads `migrations`; `main` registers the migrate command and wires dependencies.
|
||||
2. PocketBase `serve` triggers `OnServe`, which sets every server to `stopped` and every proxy to `offline`.
|
||||
3. After a 10-second delay, servers with `autoConnection=true` start automatically.
|
||||
4. `MonitorService` immediately runs TCP latency and missing-geolocation checks, then repeats them at intervals from `fh_settings.general`; server-side defaults are 5 seconds and 24 hours.
|
||||
5. PocketBase cron aggregates raw metrics into hourly metrics at minute 5 of every hour. At 01:05 each day it aggregates daily metrics and deletes raw data older than 7 days and hourly data older than 30 days.
|
||||
6. After handlers are registered, `pb_public` is served through `embed.FS` with an SPA fallback; `/_/` remains the PocketBase Admin UI.
|
||||
|
||||
### Frontend Build and Embedding
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
SRC[site/src React + TypeScript] -->|pnpm run build| DIST[site/dist]
|
||||
DIST -->|build/build.sh copy| PUBLIC[pb_public]
|
||||
PUBLIC -->|go:embed all:pb_public| BIN[Podux Go binary]
|
||||
BIN -->|apis.Static fallback| WEB[Browser]
|
||||
```
|
||||
|
||||
The Vite development server listens on `0.0.0.0` and proxies `/api` to `127.0.0.1:8090`. Production builds do not automatically copy files to `pb_public`; CI performs that step through artifact downloads, while `build/build.sh` copies them explicitly. Go compilation still requires the directory to exist when `pb_public/index.html` is missing, and runtime logs a warning.
|
||||
|
||||
## Configuration, Persistence, and Deployment Boundaries
|
||||
|
||||
- PocketBase uses `pb_data/` as its default data root; the Docker volume mounts `/app/pb_data`. The database, uploads, and `pb_data/frpc/<id>/logs|certs` are runtime data.
|
||||
- Server connection/authentication/transport/logging/metadata settings are stored in collection JSON fields. TLS certificate contents are written to a server-specific certificates directory at startup, with private-key permissions set to `0600`. Never commit this content.
|
||||
- The fixed system-settings record ID is `wcstsqmz8hur331`; the initialization transaction creates both the first `fh_users` record and the settings record.
|
||||
- Geolocation and version queries access external services and depend on network availability. frpc instance status exists only in memory; database statuses are reset together on restart.
|
||||
- The Dockerfile builds React and then compiles a static Go binary; deployment files define ports and volumes. This document makes no claims about production reverse proxies, backups, or high availability that are not verified in repository configuration.
|
||||
|
||||
## CI and Quality Boundaries
|
||||
|
||||
`.github/workflows/ci.yml` runs on pushes to main/dev and pull requests to main. It performs a frozen frontend install, permissive type checking (`continue-on-error`), and a production build; it then downloads the frontend artifact and runs `go vet` and a Linux amd64 build. CI currently does not run `go test`, frontend lint, or the documentation build, but this project's pre-submission baseline requires those checks locally. Pushes to dev also build and publish a multi-architecture container.
|
||||
|
||||
## To Be Confirmed
|
||||
|
||||
- `github_handler.go` and its service exist, but their wiring and registration are commented out in `main.go`; they must not be treated as a published API.
|
||||
- No graceful-shutdown hook for `MonitorService` was found; it currently relies on process termination.
|
||||
- No formal repository-level backup/restore, horizontal-scaling, or multi-instance mutual-exclusion design was found.
|
||||
@@ -0,0 +1,121 @@
|
||||
# Database Design
|
||||
|
||||
## Sources of Truth and Migration Constraints
|
||||
|
||||
PocketBase uses SQLite and registers Go migrations through the blank import of `migrations` in `main.go`; `migratecmd` enables `Automigrate: true`. The only current migration is `migrations/1774402980_collections_snapshot.go`, which imports a collection snapshot with `ImportCollectionsByMarshaledJSON(..., false)`; its rollback function is currently empty. The migration, not any running `pb_data/data.db`, is therefore the primary schema source of truth.
|
||||
|
||||
Every structure/rule/index change must add a reviewable migration with an appropriate rollback. Never modify production SQLite directly or make changes only through the PocketBase Admin UI. "Default" below records only snapshot autogeneration behavior; fields without an explicit statement have no verified schema default.
|
||||
|
||||
The snapshot also contains PocketBase system collections such as `_mfas`, `_otps`, `_externalAuths`, `_authOrigins`, and `_superusers`, which are not individually modeled here. There are nine application collections: `fh_users`, `fh_servers`, `fh_proxies`, `fh_version`, `fh_settings`, `fh_metrics_targets`, `fh_metrics_raw`, `fh_metrics_hourly`, and `fh_metrics_daily`.
|
||||
|
||||
Every base collection has a required system text primary key named `id`, automatically generated as 15 lowercase alphanumeric characters. Collections with `created`/`updated` use autodate fields. In the descriptions below, `—` means an empty rule, so only a superuser may perform that operation through the PocketBase Record API; this does not restrict internal server-side database/service access.
|
||||
|
||||
## Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
fh_servers ||--o{ fh_proxies : "serverId (no cascade)"
|
||||
fh_servers ||--o{ fh_metrics_targets : "serverId (optional, no cascade)"
|
||||
fh_proxies ||--o{ fh_metrics_targets : "proxyId (optional, no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_raw : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_hourly : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_daily : "targetId (no cascade)"
|
||||
```
|
||||
|
||||
All relation fields use `maxSelect: 1`. The schema neither guarantees that each metrics target is bound exclusively to a server or a proxy nor defines a unique `(serverId, proxyId)` index.
|
||||
|
||||
## Collection Design
|
||||
|
||||
### `fh_users` (auth)
|
||||
|
||||
Purpose: Podux login users. System fields: `password` (required, hidden, minimum 8 characters), `tokenKey` (required, hidden, 30–60 characters, automatically generated with 50 characters), `email` (required), `emailVisibility`, `verified`, `created`, and `updated`. Application fields: optional `nickname` text with max length 255; optional `avatar` file with at most one JPEG/PNG/SVG/GIF/WebP file; optional `passwordChangedAt` date.
|
||||
|
||||
Unique indexes: `tokenKey` and non-empty `email`. Password authentication is enabled with email as the identity; OAuth2, MFA, and OTP are disabled. The create rule is `@collection.fh_settings.initialized = false`; list/view/update/delete are restricted to `id = @request.auth.id`; the auth rule is empty, allowing authentication.
|
||||
|
||||
Mapping: `system.Service.InitializeSystem` creates the user; Login uses PocketBase `authWithPassword`; Settings/Profile reads and updates the user and avatar; ChangePasswordDialog updates the password.
|
||||
|
||||
### `fh_servers`
|
||||
|
||||
Purpose: remote frps connections and shared frpc configuration.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `serverName` | text | Required | Display name |
|
||||
| `serverAddr` | text | Required | frps address |
|
||||
| `serverPort` | text | Required | Read/edited as an integer by the service/frontend |
|
||||
| `description` | text | Optional | Description |
|
||||
| `auth` | json | Optional | frp authentication; may contain tokens/secrets |
|
||||
| `transport` | json | Optional | frp transport/TLS; may contain certificate private keys |
|
||||
| `metadatas` | json | Optional | frp metadata |
|
||||
| `log` | json | Optional | frp logging configuration |
|
||||
| `serverVersion` | text | Required, auto `built-in` | Current frp source marker |
|
||||
| `bootStatus` | text | Required, auto `stopped` | Runtime status; code uses running/stopped |
|
||||
| `autoConnection` | bool | Optional | Connect automatically after startup |
|
||||
| `geoLocation` | json | Optional | Populated by MonitorService |
|
||||
| `user` | text | Optional | frp user |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Index: non-unique `bootStatus`. All list/view/create/update/delete rules require authentication. Mapping: there is no complete Go domain model; `ServerRecord` covers only ID/name. The server repository, frpc service, monitor service, and custom `/api/servers` handler read it; React Servers, ServerDetail, and ServerForm use it.
|
||||
|
||||
### `fh_proxies`
|
||||
|
||||
Purpose: frpc proxy configuration under a server.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | text | Required | Proxy name; the record ID is appended to the runtime name |
|
||||
| `proxyType` | select | Required | One of tcp, udp, http, or https |
|
||||
| `serverId` | relation -> `fh_servers` | Required, N:1 | No cascading delete |
|
||||
| `localIP`,`localPort`,`remotePort`,`subdomain` | text | Optional | Endpoint configuration; Go maps ports with NullableInt |
|
||||
| `customDomains` | json | Optional | Domain array |
|
||||
| `transport`,`plugin` | json | Optional | Extended proxy configuration |
|
||||
| `status` | select | Required | enabled/disabled |
|
||||
| `bootStatus` | select | Required | online/offline |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Indexes: non-unique `serverId`, `proxyType`, and `status`. All CRUD/list/view rules require authentication. Mapping: `domain/proxy.Proxy`, the proxy repository/service, frpc configuration generation, and dashboard; used by React Proxies, ProxyForm, and ServerDetail. A successful update hook reloads a running server.
|
||||
|
||||
### `fh_settings`
|
||||
|
||||
Purpose: system initialization state and general settings. Fields are optional `initialized` bool, optional `general` JSON, and autodate `created`/`updated`; there are no application indexes. All list/view/create/update/delete rules require authentication, but the unauthenticated custom initialization API writes the fixed ID `wcstsqmz8hur331` inside a server-side transaction. Used `general` keys include `defaultLanguage`, `latencyCheckInterval`, and `locationCheckInterval`.
|
||||
|
||||
Mapping: `application/system.Service`, the system handler, React GeneralSettings, and the initialization flow.
|
||||
|
||||
### `fh_version`
|
||||
|
||||
Purpose: version name/path records. Optional text fields `version_name` and `version_path`, plus `created`/`updated`. It has no application indexes, and all Record API rules are `null`. The current version service returns the frp version from compile-time dependencies, while the system version uses buildinfo/an external release API. No application read/write path for this collection was found; its actual purpose remains to be confirmed.
|
||||
|
||||
### `fh_metrics_targets`
|
||||
|
||||
Purpose: bind a metric series to a server or proxy. `serverId` is an optional relation to `fh_servers`; `proxyId` is an optional relation to `fh_proxies`; neither cascades on deletion. There are no `created`/`updated` fields or indexes, and all Record API rules are `null`. `MetricsService` currently creates only targets with a populated `serverId` and empty `proxyId`, and caches server-to-target mappings in memory.
|
||||
|
||||
### `fh_metrics_raw`
|
||||
|
||||
Purpose: raw metric points. Required non-cascading `targetId` relation to `fh_metrics_targets`; optional `metricKey` select (currently only `frps_delay`); required `t` date; optional `val` number. The composite non-unique index is ordered `(targetId, t, metricKey)`. There are no autodate fields, and all Record API rules are `null`. MonitorService writes non-negative latency for reachable servers; the 01:05 daily job deletes data older than 7 days.
|
||||
|
||||
### `fh_metrics_hourly`
|
||||
|
||||
Purpose: hourly aggregates. Optional relation `targetId`, optional select `metricKey`, optional date `t`, and optional numbers `valAvg`/`valMax`/`valMin`. It has a composite non-unique `(metricKey, targetId, t)` index, no autodate fields, and `null` for all Record API rules. At minute 5 of every hour, the previous complete hour is aggregated and then updated or inserted after lookup by target/key/time. Data older than 30 days is deleted daily.
|
||||
|
||||
### `fh_metrics_daily`
|
||||
|
||||
Purpose: daily aggregates. Fields match hourly, and all three value fields are optional numbers. It has a composite non-unique `(targetId, metricKey, t)` index, no autodate fields, and `null` for all Record API rules. At 01:05 daily, the previous day's hourly values are aggregated and upserted; the code currently writes only `valAvg`. No retention policy for daily data was found.
|
||||
|
||||
## Lifecycle, Deletion, and Sensitivity
|
||||
|
||||
- Server/proxy runtime statuses are reset at startup. Status is a transient runtime projection; configuration itself is persistent.
|
||||
- Aggregation follows raw -> hourly -> daily. Raw data is retained for 7 days and hourly data for 30 days; no verified limit exists for daily data.
|
||||
- Every relation uses `cascadeDelete: false`. The schema does not automatically delete proxies/metrics targets with a server, and deleting proxies/targets may also leave related records. Although the UI shows a confirmation dialog, no server-side transactional cleanup was found; treat this as an orphaning risk.
|
||||
- PocketBase protects `fh_users.password/tokenKey`; `fh_servers.auth/transport` may contain tokens, OIDC secrets, and TLS private keys. Logs mask common JSON key names, but original values must still never be exported, committed, or echoed.
|
||||
- Migration workflow: identify callers -> add forward/down migrations -> update models/repositories/services/UI -> update this document -> verify upgrade and rollback against a temporary database -> run the full checks. Never rewrite the snapshot to falsify existing deployment history.
|
||||
|
||||
## Current Discrepancies / To Be Confirmed
|
||||
|
||||
- `domain/proxy.Proxy` declares and serializes `description`, but the `fh_proxies` migration has no such field; form payloads also include description. Do not assume here that the field exists.
|
||||
- The `/api/servers` handler reads and returns `sendRate` and `recvRate`, but the migration defines neither field.
|
||||
- ProfileSettings submits both `name` and `nickname`, while the migration defines only `nickname`.
|
||||
- The migration defines `serverPort/localPort/remotePort` as text; some Go/frontend paths treat them as numbers. Preserve conversion compatibility and confirm the long-term type strategy.
|
||||
- `fh_metrics_targets` has no uniqueness constraint. An in-process application lock only prevents concurrent duplicates within one process; multi-instance and pre-existing duplicate risks remain to be confirmed.
|
||||
- Metric aggregation performs application-level "lookup then write" operations. Composite indexes are non-unique, so the database does not guarantee idempotent uniqueness.
|
||||
- No caller for `fh_version` was found; its purpose remains to be confirmed.
|
||||
- The snapshot migration has an empty down function and cannot automatically restore the pre-import schema; rollback strategy remains technical debt.
|
||||
@@ -0,0 +1,67 @@
|
||||
# UI Specification
|
||||
|
||||
## Technology Stack, Entry Point, and Theme
|
||||
|
||||
The application UI under `site/` uses React 19, TypeScript, and Vite 7 together with Radix Themes, Tailwind CSS 4, Iconify, Framer Motion, Recharts, Sonner, and react-i18next; it does not use Vue. Vue is used only by the VitePress site under `docs/`.
|
||||
|
||||
`site/src/main.tsx` loads Radix CSS, `index.css`, and i18n in that order, then wraps the application in `ThemeProvider`, `LanguageProvider`, and Radix `<Theme>`. Theme settings are `accentColor="indigo"`, `grayColor="slate"`, and `radius="large"`. Appearance is light/dark, initially taken from the system `prefers-color-scheme` and then stored in `localStorage.theme`. `index.css` is the entry point for Tailwind and global status-dot styles. `App.css` is an unused Vite template remnant not imported by `App.tsx`; do not treat it as the current UI baseline.
|
||||
|
||||
## Design Tokens in Use
|
||||
|
||||
The project has no custom token file. It primarily consumes Radix CSS variables and component size/gap scales directly.
|
||||
|
||||
| Category | Verified values/usage |
|
||||
| --- | --- |
|
||||
| Brand/accent | Radix indigo mappings `--accent-2/3/4/6/9/10/11` and `--accent-a3`; do not hard-code a new "Podux blue" |
|
||||
| Neutrals/surfaces | Slate mappings `--gray-1..12`, alpha gray, `--color-background`, and `--color-panel-solid`; main page background is `--gray-2` |
|
||||
| Status colors | Radix green/red/amber/orange/blue/purple scales; online dot `--green-9`, offline dot `--red-9`, unknown dot `--gray-9` |
|
||||
| Typography | No project font family; inherits Radix/browser. Body text commonly uses `<Text size="1|2|3|4">`, page titles use `<Heading size="6">`, and section titles commonly use size 3/4 |
|
||||
| Spacing | Prefer Radix `gap/mb/px/py` scales and Tailwind (for example px-4, sm:px-6, lg:px-8); local values commonly include 8/12/16/20/24/32px |
|
||||
| Radius | Radix global `large`; variables `--radius-2/3`; local 8/12/16/24px and full circles |
|
||||
| Borders | Usually `1px solid var(--gray-5|6)`; highlighted areas use `--accent-6` |
|
||||
| Shadows | A few local `0 4px 12px rgba(0,0,0,.05/.2)` and `0 4px 16px rgba(0,0,0,.1)` values; prefer Card/Dialog defaults |
|
||||
| Stacking | Sticky top bar uses `z-50`; full-screen Loading uses `z-index: 9999`; otherwise prefer component overlay defaults |
|
||||
|
||||
Hard-coded values such as `#22c55e`, `#E5484D`, `#30A46C`, and `#6b7280` remain scattered through charts/status implementations. Prefer existing Radix tokens. Cleanup requires a separate task that verifies SVG chart compatibility; do not replace these values in bulk during ordinary feature work.
|
||||
|
||||
## Layout and Component Patterns
|
||||
|
||||
- Application shell: reuse `layouts/MainLayout.tsx`. Desktop uses a sticky top bar with logo, Dashboard/Servers/Proxies navigation, and controls on the right. Below `760px`, mobile uses bottom navigation. Content uses `max-w-7xl`, supports a minimum viewport width of 320px, and reserves space for the mobile bottom bar.
|
||||
- Page titles: reuse `components/PageHeader.tsx`, keeping title, description, and right-side actions at a consistent hierarchy. Reuse `SectionHeading` for section titles.
|
||||
- Forms: prefer Radix `TextField/Select/Switch/Button`; reuse `FormItem` for labels and required markers. Keep page state and submission logic in hooks/index files and layout in views.
|
||||
- Cards and statistics: use Radix `Card` for general content. Reuse `StatCard` and `AnimateNumber` for dashboard value cards rather than duplicating animation/color decisions.
|
||||
- Lists: Servers/Proxies establish the desktop-table + mobile-card, search, pagination, Badge, and DropdownMenu pattern. Prefer it for new resources of the same kind.
|
||||
- Dialogs: use Radix `AlertDialog` for delete confirmation and Radix `Dialog` for editing, passwords, and similar tasks. Mark dangerous actions red, separate cancel and confirm, and prevent duplicate submissions during async work.
|
||||
- Charts: reuse `LatencyChart/ProbeHistory` for latency trends and Dashboard `TopologyChart` for topology. Containers must be responsive, with sufficient contrast in both themes.
|
||||
- Notifications: prefer `sonner` toast for operation success/failure (global top-center with richColors). Do not add alerts; the existing `alert` in ProfileSettings is technical debt.
|
||||
- Empty/loading/error: reuse `EmptyState` for empty lists and `Loading` for route/page loading. Errors should explain the problem and offer a recovery action. There is no unified ErrorState/ErrorBoundary yet; before adding one, assess whether it should become a shared component.
|
||||
|
||||
## Reference Pages
|
||||
|
||||
- Dashboard: `site/src/pages/Dashboard/DashboardPage.view.tsx` combines `PageHeader`, `StatCard`, Radix Grid/Card, and `TopologyChart`; data orchestration is in `useDashboard.ts`.
|
||||
- Servers/Proxies: `site/src/pages/Servers/ServersPage.view.tsx` and `site/src/pages/Proxies/ProxiesPage.view.tsx` are the primary references for responsive lists, status badges, action menus, and AlertDialog. Their forms are under the corresponding `*FormPage` directories.
|
||||
- Settings: `site/src/pages/Settings/SettingsPage.view.tsx` and `SettingsPage.css` use a 240px sidebar, active accent state, and content area. `GeneralSettings.tsx` demonstrates `FormItem`, loading, and save toast; `ProfileSettings.tsx` demonstrates profile cards and security sections.
|
||||
|
||||
## Responsiveness, Themes, Internationalization, and Accessibility
|
||||
|
||||
- Responsiveness: the actual application-shell breakpoint is `max-width: 760px` (the 640px comment is stale). Test at least 320px mobile and desktop widths. On mobile, table content must use cards or controlled scrolling and must not require hover for actions.
|
||||
- Themes: new colors should use `var(--accent-*)`, `var(--gray-*)`, and semantic colors. Avoid fixed white backgrounds/black text. Check charts, overlays, borders, and focus states in light and dark themes.
|
||||
- Internationalization: route all user-facing text through `t()` and update both `locales/zh.json` and `en.json`. LanguageContext/localStorage owns language selection; do not use hard-coded Chinese or English as fallback UI.
|
||||
- Accessibility: use semantic Radix components. Icon-only buttons need accessible names/tooltips; images need alt text; form labels must associate with controls; keyboard focus must remain visible. `index.css` currently forces the Recharts surface outline off and must be limited to non-interactive charts; reassess it if keyboard chart interaction is added.
|
||||
- Motion: the standard page transition is `PageTransition` at 0.3s cubic-bezier; titles use 0.5s easeOut; status dots loop every 1.6–2.5s. Lightweight hover/tap effects are acceptable but must not block interaction. Only the unused Vite-template `App.css` currently observes `prefers-reduced-motion`; actual Framer/status-dot animations do not support it consistently and remain technical debt.
|
||||
|
||||
## Reuse and Addition Rules
|
||||
|
||||
1. Check Radix Themes first, then `site/src/components/`, then neighboring page view/hook patterns.
|
||||
2. Extract a shared component only when a semantically stable pattern spans at least two pages; keep page-specific compositions in the page directory.
|
||||
3. New shared components must use tokens, support `className` and necessary props, cover loading/disabled/error states, and be verified in both themes and mobile layouts.
|
||||
4. Local styles are acceptable for third-party charts, complex layouts, or states difficult to express with Radix props/Tailwind. Scope names to the page/component and avoid global selectors and `!important`. Existing `!important` usage in Settings CSS is a compatibility condition, not a pattern for new styles.
|
||||
5. Do not restore or extend unused `App.css` template styles. Put necessary global rules in `index.css` and document their impact.
|
||||
|
||||
## Technical Debt
|
||||
|
||||
- There is no centralized project-owned set of spacing, shadow, z-index, or motion tokens; the UI relies on Radix scales mixed with local pixel values.
|
||||
- Settings has only a desktop 240px sidebar, with no dedicated mobile adaptation rules found; verify on a real device.
|
||||
- Error state, ErrorBoundary, and form-error presentation do not yet follow a unified shared pattern.
|
||||
- ProfileSettings uses native `alert`, Loading defaults to English `Loading...`, and internationalization remains inconsistent.
|
||||
- Actual interaction animations do not yet systematically honor `prefers-reduced-motion`.
|
||||
@@ -8,7 +8,7 @@ export default defineConfig({
|
||||
head: [
|
||||
['link', { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
|
||||
['link', { rel: 'icon', type: 'image/svg+xml', href: '/logo.svg' }],
|
||||
['script', { defer: '', src: 'https://umami.jwinks.com/script.js', 'data-website-id': '8af0f36e-650c-45b5-a17e-e104b918f63f' }]
|
||||
['script', { defer: '', src: 'https://umami.jwinks.com:9443/script.js', 'data-website-id': '7a64c0ad-6d82-484c-88d3-5d9a6c2a1fff' }]
|
||||
],
|
||||
metaChunk: true,
|
||||
|
||||
@@ -55,6 +55,15 @@ export default defineConfig({
|
||||
items: [
|
||||
{ text: '常见问题', link: '/troubleshoot/faq' },
|
||||
]
|
||||
},
|
||||
{
|
||||
text: '开发设计',
|
||||
items: [
|
||||
{ text: '文档索引', link: '/development/' },
|
||||
{ text: '系统架构', link: '/development/architecture' },
|
||||
{ text: '数据库设计', link: '/development/database-design' },
|
||||
{ text: 'UI 规范', link: '/development/ui-spec' },
|
||||
]
|
||||
}
|
||||
],
|
||||
footer: {
|
||||
|
||||
@@ -170,6 +170,8 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error)
|
||||
if proxyMap.ProxyType == "http" || proxyMap.ProxyType == "https" {
|
||||
delete(proxyData, "remotePort")
|
||||
}
|
||||
proxyData["type"] = proxyMap.ProxyType
|
||||
delete(proxyData, "proxyType")
|
||||
proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id
|
||||
|
||||
// Remove empty plugin map so frp doesn't try to parse a typeless plugin
|
||||
|
||||
@@ -2,4 +2,4 @@ package buildinfo
|
||||
|
||||
// AppVersion is the single source of truth for the application version.
|
||||
// Update this value to release a new version.
|
||||
const AppVersion = "0.1.4"
|
||||
const AppVersion = "0.1.6"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 272 KiB |
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "podux-web",
|
||||
"private": true,
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -21,6 +21,11 @@ interface ProxiesViewProps {
|
||||
onDeleteProxy: (id: string) => Promise<void>;
|
||||
onToggleStatus: (proxy: Proxy) => Promise<void>;
|
||||
refreshProxies: () => void;
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
totalPages: number;
|
||||
search: string;
|
||||
setSearch: (value: string) => void;
|
||||
}
|
||||
|
||||
export function ProxiesView({
|
||||
@@ -31,6 +36,11 @@ export function ProxiesView({
|
||||
onDeleteProxy,
|
||||
onToggleStatus,
|
||||
refreshProxies,
|
||||
page,
|
||||
setPage,
|
||||
totalPages,
|
||||
search,
|
||||
setSearch,
|
||||
}: ProxiesViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -40,10 +50,23 @@ export function ProxiesView({
|
||||
const [togglingId, setTogglingId] = useState<string | null>(null);
|
||||
|
||||
const handleCopy = (text: string, id: string) => {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const done = () => {
|
||||
setCopiedId(id);
|
||||
setTimeout(() => setCopiedId(null), 1500);
|
||||
});
|
||||
};
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(text).then(done);
|
||||
} else {
|
||||
const el = document.createElement("textarea");
|
||||
el.value = text;
|
||||
el.style.position = "fixed";
|
||||
el.style.opacity = "0";
|
||||
document.body.appendChild(el);
|
||||
el.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(el);
|
||||
done();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -121,10 +144,21 @@ export function ProxiesView({
|
||||
size="2"
|
||||
placeholder={t("proxy.searchProxies")}
|
||||
className="min-w-32 flex-1"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
>
|
||||
<TextField.Slot>
|
||||
<Icon icon="lucide:search" width="16" height="16" />
|
||||
</TextField.Slot>
|
||||
{search && (
|
||||
<TextField.Slot
|
||||
pr="2"
|
||||
onClick={() => setSearch("")}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<Icon icon="lucide:x" width="16" height="16" />
|
||||
</TextField.Slot>
|
||||
)}
|
||||
</TextField.Root>
|
||||
<Button variant="soft" onClick={refreshProxies} disabled={refreshing}>
|
||||
<Icon
|
||||
@@ -155,6 +189,7 @@ export function ProxiesView({
|
||||
onAction={() => navigate("/proxies/new")}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<Table.Root>
|
||||
<Table.Header>
|
||||
@@ -172,6 +207,7 @@ export function ProxiesView({
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{proxies.map((proxy) => (
|
||||
|
||||
<Table.Row key={proxy.id}>
|
||||
<Table.Cell>
|
||||
<Text weight="medium">{proxy.name || <Text color="gray">-</Text>}</Text>
|
||||
@@ -278,8 +314,8 @@ export function ProxiesView({
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
const displayText = proxy.remotePort || "-";
|
||||
if (displayText === "-")
|
||||
const displayText = proxy.remotePort ? String(proxy.remotePort) : "";
|
||||
if (!displayText)
|
||||
return <Text size="2" color="gray">-</Text>;
|
||||
const copyKey = `${proxy.id}-port`;
|
||||
const isCopied = copiedId === copyKey;
|
||||
@@ -379,6 +415,66 @@ export function ProxiesView({
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
{totalPages > 1 && (
|
||||
<Flex justify="between" align="center" pt="4" px="1">
|
||||
<Text size="2" color="gray">
|
||||
{page} / {totalPages}
|
||||
</Text>
|
||||
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
|
||||
<button
|
||||
disabled={page === 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderRight: "1px solid var(--gray-6)",
|
||||
cursor: page === 1 ? "not-allowed" : "pointer",
|
||||
opacity: page === 1 ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-left" width="14" height="14" />
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPage(p)}
|
||||
style={{
|
||||
padding: "6px 12px",
|
||||
background: p === page ? "var(--accent-9)" : "none",
|
||||
color: p === page ? "white" : "inherit",
|
||||
border: "none",
|
||||
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
|
||||
cursor: "pointer",
|
||||
fontSize: "var(--font-size-2)",
|
||||
fontWeight: p === page ? 600 : 400,
|
||||
}}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
disabled={page === totalPages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderLeft: "1px solid var(--gray-6)",
|
||||
cursor: page === totalPages ? "not-allowed" : "pointer",
|
||||
opacity: page === totalPages ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-right" width="14" height="14" />
|
||||
</button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useProxies } from "./useProxies";
|
||||
import { ProxiesView } from "./ProxiesPage.view";
|
||||
|
||||
export function ProxiesPage() {
|
||||
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies } = useProxies();
|
||||
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies, page, setPage, totalPages, search, setSearch } = useProxies();
|
||||
|
||||
return (
|
||||
<ProxiesView
|
||||
@@ -13,6 +13,11 @@ export function ProxiesPage() {
|
||||
onDeleteProxy={deleteProxy}
|
||||
onToggleStatus={toggleStatus}
|
||||
refreshProxies={refreshProxies}
|
||||
page={page}
|
||||
setPage={setPage}
|
||||
totalPages={totalPages}
|
||||
search={search}
|
||||
setSearch={setSearch}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,8 +29,21 @@ export function useProxies() {
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [onlineCount, setOnlineCount] = useState(0);
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const PER_PAGE = 10;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedSearch(search), 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [debouncedSearch]);
|
||||
|
||||
const fetchProxies = useCallback(
|
||||
async (isRefresh = false) => {
|
||||
try {
|
||||
@@ -40,12 +53,24 @@ export function useProxies() {
|
||||
setRefreshing(true);
|
||||
}
|
||||
|
||||
const result = await pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
|
||||
sort: "-created",
|
||||
expand: "serverId",
|
||||
});
|
||||
const searchFilter = debouncedSearch
|
||||
? `name ~ "${debouncedSearch}" || localIP ~ "${debouncedSearch}" || remotePort ~ "${debouncedSearch}"`
|
||||
: "";
|
||||
|
||||
const [result, onlineResult] = await Promise.all([
|
||||
pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
|
||||
sort: "-created",
|
||||
expand: "serverId",
|
||||
filter: searchFilter,
|
||||
}),
|
||||
pb.collection("fh_proxies").getList(1, 1, {
|
||||
filter: 'bootStatus = "online"',
|
||||
}),
|
||||
]);
|
||||
setProxies(result.items);
|
||||
setTotalPages(result.totalPages);
|
||||
setTotalItems(result.totalItems);
|
||||
setOnlineCount(onlineResult.totalItems);
|
||||
initializedRef.current = true;
|
||||
} catch (err) {
|
||||
if ((err as Record<string, unknown>)?.isAbort) return;
|
||||
@@ -55,7 +80,7 @@ export function useProxies() {
|
||||
setRefreshing(false);
|
||||
}
|
||||
},
|
||||
[page]
|
||||
[page, debouncedSearch]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -104,9 +129,9 @@ export function useProxies() {
|
||||
};
|
||||
|
||||
const stats = {
|
||||
total: proxies.length,
|
||||
online: proxies.filter((p) => p.bootStatus === "online").length,
|
||||
offline: proxies.filter((p) => p.bootStatus === "offline").length,
|
||||
total: totalItems,
|
||||
online: onlineCount,
|
||||
offline: totalItems - onlineCount,
|
||||
};
|
||||
|
||||
const isEmpty = !loading && proxies.length === 0;
|
||||
@@ -122,6 +147,8 @@ export function useProxies() {
|
||||
setPage,
|
||||
totalPages,
|
||||
stats,
|
||||
search,
|
||||
setSearch,
|
||||
refreshProxies: () => fetchProxies(true),
|
||||
};
|
||||
}
|
||||
@@ -33,6 +33,9 @@ interface ServersViewProps {
|
||||
search: string;
|
||||
setSearch: (value: string) => void;
|
||||
refreshServers: () => void;
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export function ServersView({
|
||||
@@ -45,6 +48,9 @@ export function ServersView({
|
||||
search,
|
||||
setSearch,
|
||||
refreshServers,
|
||||
page,
|
||||
setPage,
|
||||
totalPages,
|
||||
}: ServersViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -411,6 +417,65 @@ export function ServersView({
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
{totalPages > 1 && (
|
||||
<Flex justify="between" align="center" pt="4" px="1">
|
||||
<Text size="2" color="gray">
|
||||
{page} / {totalPages}
|
||||
</Text>
|
||||
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
|
||||
<button
|
||||
disabled={page === 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderRight: "1px solid var(--gray-6)",
|
||||
cursor: page === 1 ? "not-allowed" : "pointer",
|
||||
opacity: page === 1 ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-left" width="14" height="14" />
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPage(p)}
|
||||
style={{
|
||||
padding: "6px 12px",
|
||||
background: p === page ? "var(--accent-9)" : "none",
|
||||
color: p === page ? "white" : "inherit",
|
||||
border: "none",
|
||||
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
|
||||
cursor: "pointer",
|
||||
fontSize: "var(--font-size-2)",
|
||||
fontWeight: p === page ? 600 : 400,
|
||||
}}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
disabled={page === totalPages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
style={{
|
||||
padding: "6px 10px",
|
||||
background: "none",
|
||||
border: "none",
|
||||
borderLeft: "1px solid var(--gray-6)",
|
||||
cursor: page === totalPages ? "not-allowed" : "pointer",
|
||||
opacity: page === totalPages ? 0.4 : 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Icon icon="lucide:chevron-right" width="14" height="14" />
|
||||
</button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
Reference in new issue
Block a user